summaryrefslogtreecommitdiffstats
path: root/Modules
diff options
context:
space:
mode:
authorAntoine Pitrou <solipsis@pitrou.net>2010-05-09 15:15:40 (GMT)
committerAntoine Pitrou <solipsis@pitrou.net>2010-05-09 15:15:40 (GMT)
commitc7c96a90bcf1366ac6f350f5506d0afee611e351 (patch)
tree4134c189d25fe972f2717f4b642a26e5f323a922 /Modules
parentba32864b2d97018c71ce90926c853a67e79becf7 (diff)
downloadcpython-c7c96a90bcf1366ac6f350f5506d0afee611e351.zip
cpython-c7c96a90bcf1366ac6f350f5506d0afee611e351.tar.gz
cpython-c7c96a90bcf1366ac6f350f5506d0afee611e351.tar.bz2
Recorded merge of revisions 81029 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk ........ r81029 | antoine.pitrou | 2010-05-09 16:46:46 +0200 (dim., 09 mai 2010) | 3 lines Untabify C files. Will watch buildbots. ........
Diffstat (limited to 'Modules')
-rw-r--r--Modules/_bisectmodule.c286
-rw-r--r--Modules/_bsddb.c356
-rw-r--r--Modules/_codecsmodule.c678
-rw-r--r--Modules/_collectionsmodule.c2176
-rw-r--r--Modules/_csv.c2188
-rw-r--r--Modules/_ctypes/_ctypes.c8596
-rw-r--r--Modules/_ctypes/_ctypes_test.c434
-rw-r--r--Modules/_ctypes/callbacks.c946
-rw-r--r--Modules/_ctypes/callproc.c2578
-rw-r--r--Modules/_ctypes/cfield.c2030
-rw-r--r--Modules/_ctypes/ctypes.h320
-rw-r--r--Modules/_ctypes/darwin/dlfcn_simple.c282
-rw-r--r--Modules/_ctypes/malloc_closure.c98
-rw-r--r--Modules/_ctypes/stgdict.c952
-rw-r--r--Modules/_curses_panel.c180
-rw-r--r--Modules/_functoolsmodule.c520
-rw-r--r--Modules/_heapqmodule.c892
-rw-r--r--Modules/_hotshot.c186
-rw-r--r--Modules/_localemodule.c130
-rw-r--r--Modules/_lsprof.c1152
-rw-r--r--Modules/_multiprocessing/connection.h736
-rw-r--r--Modules/_multiprocessing/multiprocessing.c388
-rw-r--r--Modules/_multiprocessing/pipe_connection.c188
-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.c774
-rw-r--r--Modules/_struct.c2628
-rw-r--r--Modules/_testcapimodule.c1568
-rw-r--r--Modules/_tkinter.c4054
-rw-r--r--Modules/addrinfo.h106
-rw-r--r--Modules/almodule.c4122
-rw-r--r--Modules/arraymodule.c3032
-rw-r--r--Modules/audioop.c2482
-rw-r--r--Modules/binascii.c1986
-rw-r--r--Modules/bsddbmodule.c1290
-rw-r--r--Modules/bz2module.c3290
-rw-r--r--Modules/cPickle.c8838
-rw-r--r--Modules/cStringIO.c738
-rw-r--r--Modules/cdmodule.c1048
-rw-r--r--Modules/cgensupport.c454
-rw-r--r--Modules/cgensupport.h28
-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.h550
-rw-r--r--Modules/cjkcodecs/emu_jisx0213_2000.h58
-rw-r--r--Modules/cjkcodecs/multibytecodec.c2824
-rw-r--r--Modules/cjkcodecs/multibytecodec.h132
-rw-r--r--Modules/clmodule.c3450
-rw-r--r--Modules/cmathmodule.c1600
-rw-r--r--Modules/cryptmodule.c22
-rw-r--r--Modules/datetimemodule.c6690
-rw-r--r--Modules/dbmmodule.c532
-rw-r--r--Modules/dlmodule.c344
-rw-r--r--Modules/errnomodule.c504
-rw-r--r--Modules/fcntlmodule.c680
-rw-r--r--Modules/flmodule.c1950
-rw-r--r--Modules/fmmodule.c268
-rw-r--r--Modules/fpectlmodule.c66
-rw-r--r--Modules/future_builtins.c54
-rw-r--r--Modules/gcmodule.c1698
-rw-r--r--Modules/getaddrinfo.c884
-rw-r--r--Modules/getbuildinfo.c26
-rw-r--r--Modules/getnameinfo.c254
-rw-r--r--Modules/getpath.c102
-rw-r--r--Modules/glmodule.c8980
-rw-r--r--Modules/imageop.c1264
-rw-r--r--Modules/imgfile.c776
-rw-r--r--Modules/itertoolsmodule.c5256
-rw-r--r--Modules/linuxaudiodev.c202
-rw-r--r--Modules/main.c910
-rw-r--r--Modules/mathmodule.c1314
-rw-r--r--Modules/md5.c130
-rw-r--r--Modules/md5module.c216
-rw-r--r--Modules/mmapmodule.c2112
-rw-r--r--Modules/nismodule.c546
-rw-r--r--Modules/operator.c780
-rw-r--r--Modules/parsermodule.c194
-rw-r--r--Modules/puremodule.c596
-rw-r--r--Modules/pwdmodule.c182
-rw-r--r--Modules/pyexpat.c380
-rw-r--r--Modules/readline.c1032
-rw-r--r--Modules/resource.c372
-rw-r--r--Modules/rotatingtree.c160
-rw-r--r--Modules/selectmodule.c2424
-rw-r--r--Modules/sgimodule.c52
-rw-r--r--Modules/sha256module.c110
-rw-r--r--Modules/sha512module.c130
-rw-r--r--Modules/shamodule.c116
-rw-r--r--Modules/signalmodule.c840
-rw-r--r--Modules/socketmodule.c6102
-rw-r--r--Modules/socketmodule.h140
-rw-r--r--Modules/spwdmodule.c150
-rw-r--r--Modules/stropmodule.c1830
-rw-r--r--Modules/sunaudiodev.c570
-rw-r--r--Modules/svmodule.c1232
-rw-r--r--Modules/symtablemodule.c122
-rw-r--r--Modules/syslogmodule.c256
-rw-r--r--Modules/termios.c886
-rw-r--r--Modules/testcapi_long.h316
-rw-r--r--Modules/threadmodule.c884
-rw-r--r--Modules/timemodule.c1138
-rw-r--r--Modules/timingmodule.c36
-rw-r--r--Modules/tkappinit.c170
-rw-r--r--Modules/unicodedata.c268
-rw-r--r--Modules/xxmodule.c496
-rw-r--r--Modules/xxsubtype.c394
-rw-r--r--Modules/yuv.h86
-rw-r--r--Modules/yuvconvert.c184
-rw-r--r--Modules/zipimport.c1720
-rw-r--r--Modules/zlibmodule.c474
116 files changed, 68971 insertions, 68971 deletions
diff --git a/Modules/_bisectmodule.c b/Modules/_bisectmodule.c
index fc54954..b51f3de 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 PyInt_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 PyInt_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 PyInt_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 PyInt_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,
@@ -237,7 +237,7 @@ common approach.\n");
PyMODINIT_FUNC
init_bisect(void)
{
- PyObject *m;
+ PyObject *m;
- m = Py_InitModule3("_bisect", bisect_methods, module_doc);
+ m = Py_InitModule3("_bisect", bisect_methods, module_doc);
}
diff --git a/Modules/_bsddb.c b/Modules/_bsddb.c
index 5aedfca..755242c 100644
--- a/Modules/_bsddb.c
+++ b/Modules/_bsddb.c
@@ -139,9 +139,9 @@ typedef int Py_ssize_t;
/* and these are for calling C --> Python */
#if defined(MYDB_USE_GILSTATE)
#define MYDB_BEGIN_BLOCK_THREADS \
- PyGILState_STATE __savestate = PyGILState_Ensure();
+ PyGILState_STATE __savestate = PyGILState_Ensure();
#define MYDB_END_BLOCK_THREADS \
- PyGILState_Release(__savestate);
+ PyGILState_Release(__savestate);
#else /* MYDB_USE_GILSTATE */
/* Pre GILState API - do it the long old way */
static PyInterpreterState* _db_interpreterState = NULL;
@@ -212,7 +212,7 @@ static PyObject* DBRepHandleDeadError; /* DB_REP_HANDLE_DEAD */
static PyObject* DBRepUnavailError; /* DB_REP_UNAVAIL */
#if (DBVER < 43)
-#define DB_BUFFER_SMALL ENOMEM
+#define DB_BUFFER_SMALL ENOMEM
#endif
@@ -537,7 +537,7 @@ unsigned int our_strlcpy(char* dest, const char* src, unsigned int n)
srclen = strlen(src);
if (n <= 0)
- return srclen;
+ return srclen;
copylen = (srclen > n-1) ? n-1 : srclen;
/* populate dest[0] thru dest[copylen-1] */
memcpy(dest, src, copylen);
@@ -554,7 +554,7 @@ static char _db_errmsg[1024];
static void _db_errorCallback(const char* prefix, char* msg)
#else
static void _db_errorCallback(const DB_ENV *db_env,
- const char* prefix, const char* msg)
+ const char* prefix, const char* msg)
#endif
{
our_strlcpy(_db_errmsg, msg, sizeof(_db_errmsg));
@@ -676,7 +676,7 @@ static int makeDBError(int err)
/* Ensure that bytes_left never goes negative */
if (_db_errmsg[0] && bytes_left < (sizeof(errTxt) - 4)) {
bytes_left = sizeof(errTxt) - bytes_left - 4 - 1;
- assert(bytes_left >= 0);
+ assert(bytes_left >= 0);
strcat(errTxt, " -- ");
strncat(errTxt, _db_errmsg, bytes_left);
}
@@ -705,8 +705,8 @@ static int makeDBError(int err)
case DB_BUFFER_SMALL: errObj = DBNoMemoryError; break;
#if (DBVER >= 43)
- /* ENOMEM and DB_BUFFER_SMALL were one and the same until 4.3 */
- case ENOMEM: errObj = PyExc_MemoryError; break;
+ /* ENOMEM and DB_BUFFER_SMALL were one and the same until 4.3 */
+ case ENOMEM: errObj = PyExc_MemoryError; break;
#endif
case EINVAL: errObj = DBInvalidArgError; break;
case EACCES: errObj = DBAccessError; break;
@@ -811,7 +811,7 @@ static int _DB_put(DBObject* self, DB_TXN *txn, DBT *key, DBT *data, int flags)
/* Get a key/data pair from a cursor */
static PyObject* _DBCursor_get(DBCursorObject* self, int extra_flags,
- PyObject *args, PyObject *kwargs, char *format)
+ PyObject *args, PyObject *kwargs, char *format)
{
int err;
PyObject* retval = NULL;
@@ -822,7 +822,7 @@ static PyObject* _DBCursor_get(DBCursorObject* self, int extra_flags,
static char* kwnames[] = { "flags", "dlen", "doff", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, format, kwnames,
- &flags, &dlen, &doff))
+ &flags, &dlen, &doff))
return NULL;
CHECK_CURSOR_NOT_CLOSED(self);
@@ -838,7 +838,7 @@ static PyObject* _DBCursor_get(DBCursorObject* self, int extra_flags,
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
- && self->mydb->moduleFlags.getReturnsNone) {
+ && self->mydb->moduleFlags.getReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@@ -882,13 +882,13 @@ static void _addIntToDict(PyObject* dict, char *name, int value)
static void _addTimeTToDict(PyObject* dict, char *name, time_t value)
{
PyObject* v;
- /* if the value fits in regular int, use that. */
+ /* if the value fits in regular int, use that. */
#ifdef PY_LONG_LONG
- if (sizeof(time_t) > sizeof(long))
- v = PyLong_FromLongLong((PY_LONG_LONG) value);
- else
+ if (sizeof(time_t) > sizeof(long))
+ v = PyLong_FromLongLong((PY_LONG_LONG) value);
+ else
#endif
- v = NUMBER_FromLong((long) value);
+ v = NUMBER_FromLong((long) value);
if (!v || PyDict_SetItemString(dict, name, v))
PyErr_Clear();
@@ -1038,10 +1038,10 @@ newDBCursorObject(DBC* dbc, DBTxnObject *txn, DBObject* db)
INSERT_IN_DOUBLE_LINKED_LIST(self->mydb->children_cursors,self);
if (txn && ((PyObject *)txn!=Py_None)) {
- INSERT_IN_DOUBLE_LINKED_LIST_TXN(txn->children_cursors,self);
- self->txn=txn;
+ INSERT_IN_DOUBLE_LINKED_LIST_TXN(txn->children_cursors,self);
+ self->txn=txn;
} else {
- self->txn=NULL;
+ self->txn=NULL;
}
self->in_weakreflist = NULL;
@@ -1406,16 +1406,16 @@ _db_associateCallback(DB* db, const DBT* priKey, const DBT* priData,
PyBytes_AsStringAndSize(result, &data, &size);
secKey->flags = DB_DBT_APPMALLOC; /* DB will free */
secKey->data = malloc(size); /* TODO, check this */
- if (secKey->data) {
- memcpy(secKey->data, data, size);
- secKey->size = size;
- retval = 0;
- }
- else {
- PyErr_SetString(PyExc_MemoryError,
+ if (secKey->data) {
+ memcpy(secKey->data, data, size);
+ secKey->size = size;
+ retval = 0;
+ }
+ else {
+ PyErr_SetString(PyExc_MemoryError,
"malloc failed in _db_associateCallback");
- PyErr_Print();
- }
+ PyErr_Print();
+ }
}
else {
PyErr_SetString(
@@ -1499,7 +1499,7 @@ DB_associate(DBObject* self, PyObject* args, PyObject* kwargs)
MYDB_BEGIN_ALLOW_THREADS;
#if (DBVER >= 41)
err = self->db->associate(self->db,
- txn,
+ txn,
secondaryDB->db,
_db_associateCallback,
flags);
@@ -1617,7 +1617,7 @@ _DB_consume(DBObject* self, PyObject* args, PyObject* kwargs, int consume_flag)
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
- && self->moduleFlags.getReturnsNone) {
+ && self->moduleFlags.getReturnsNone) {
err = 0;
Py_INCREF(Py_None);
retval = Py_None;
@@ -1764,7 +1764,7 @@ DB_get(DBObject* self, PyObject* args, PyObject* kwargs)
retval = dfltobj;
}
else if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
- && self->moduleFlags.getReturnsNone) {
+ && self->moduleFlags.getReturnsNone) {
err = 0;
Py_INCREF(Py_None);
retval = Py_None;
@@ -1833,7 +1833,7 @@ DB_pget(DBObject* self, PyObject* args, PyObject* kwargs)
retval = dfltobj;
}
else if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
- && self->moduleFlags.getReturnsNone) {
+ && self->moduleFlags.getReturnsNone) {
err = 0;
Py_INCREF(Py_None);
retval = Py_None;
@@ -1968,7 +1968,7 @@ DB_get_both(DBObject* self, PyObject* args, PyObject* kwargs)
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
- && self->moduleFlags.getReturnsNone) {
+ && self->moduleFlags.getReturnsNone) {
err = 0;
Py_INCREF(Py_None);
retval = Py_None;
@@ -2042,8 +2042,8 @@ DB_join(DBObject* self, PyObject* args)
length = PyObject_Length(cursorsObj);
cursors = malloc((length+1) * sizeof(DBC*));
if (!cursors) {
- PyErr_NoMemory();
- return NULL;
+ PyErr_NoMemory();
+ return NULL;
}
cursors[length] = NULL;
@@ -2134,28 +2134,28 @@ DB_open(DBObject* self, PyObject* args, PyObject* kwargs)
#if (DBVER >= 41)
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "z|ziiiO:open", kwnames,
- &filename, &dbname, &type, &flags, &mode,
+ &filename, &dbname, &type, &flags, &mode,
&txnobj))
#else
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "z|ziii:open", kwnames,
- &filename, &dbname, &type, &flags,
+ &filename, &dbname, &type, &flags,
&mode))
#endif
{
- PyErr_Clear();
- type = DB_UNKNOWN; flags = 0; mode = 0660;
- filename = NULL; dbname = NULL;
+ PyErr_Clear();
+ type = DB_UNKNOWN; flags = 0; mode = 0660;
+ filename = NULL; dbname = NULL;
#if (DBVER >= 41)
- if (!PyArg_ParseTupleAndKeywords(args, kwargs,"z|iiiO:open",
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs,"z|iiiO:open",
kwnames_basic,
- &filename, &type, &flags, &mode,
+ &filename, &type, &flags, &mode,
&txnobj))
- return NULL;
+ return NULL;
#else
- if (!PyArg_ParseTupleAndKeywords(args, kwargs,"z|iii:open",
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs,"z|iii:open",
kwnames_basic,
- &filename, &type, &flags, &mode))
- return NULL;
+ &filename, &type, &flags, &mode))
+ return NULL;
#endif
}
@@ -2338,20 +2338,20 @@ DB_set_bt_minkey(DBObject* self, PyObject* args)
static int
_default_cmp(const DBT *leftKey,
- const DBT *rightKey)
+ const DBT *rightKey)
{
int res;
int lsize = leftKey->size, rsize = rightKey->size;
res = memcmp(leftKey->data, rightKey->data,
- lsize < rsize ? lsize : rsize);
+ lsize < rsize ? lsize : rsize);
if (res == 0) {
if (lsize < rsize) {
- res = -1;
+ res = -1;
}
else if (lsize > rsize) {
- res = 1;
+ res = 1;
}
}
return res;
@@ -2359,8 +2359,8 @@ _default_cmp(const DBT *leftKey,
static int
_db_compareCallback(DB* db,
- const DBT *leftKey,
- const DBT *rightKey)
+ const DBT *leftKey,
+ const DBT *rightKey)
{
int res = 0;
PyObject *args;
@@ -2368,40 +2368,40 @@ _db_compareCallback(DB* db,
DBObject *self = (DBObject *)db->app_private;
if (self == NULL || self->btCompareCallback == NULL) {
- MYDB_BEGIN_BLOCK_THREADS;
- PyErr_SetString(PyExc_TypeError,
- (self == 0
- ? "DB_bt_compare db is NULL."
- : "DB_bt_compare callback is NULL."));
- /* we're in a callback within the DB code, we can't raise */
- PyErr_Print();
- res = _default_cmp(leftKey, rightKey);
- MYDB_END_BLOCK_THREADS;
+ MYDB_BEGIN_BLOCK_THREADS;
+ PyErr_SetString(PyExc_TypeError,
+ (self == 0
+ ? "DB_bt_compare db is NULL."
+ : "DB_bt_compare callback is NULL."));
+ /* we're in a callback within the DB code, we can't raise */
+ PyErr_Print();
+ res = _default_cmp(leftKey, rightKey);
+ MYDB_END_BLOCK_THREADS;
} else {
- MYDB_BEGIN_BLOCK_THREADS;
-
- args = BuildValue_SS(leftKey->data, leftKey->size, rightKey->data, rightKey->size);
- if (args != NULL) {
- result = PyEval_CallObject(self->btCompareCallback, args);
- }
- if (args == NULL || result == NULL) {
- /* we're in a callback within the DB code, we can't raise */
- PyErr_Print();
- res = _default_cmp(leftKey, rightKey);
- } else if (NUMBER_Check(result)) {
- res = NUMBER_AsLong(result);
- } else {
- PyErr_SetString(PyExc_TypeError,
- "DB_bt_compare callback MUST return an int.");
- /* we're in a callback within the DB code, we can't raise */
- PyErr_Print();
- res = _default_cmp(leftKey, rightKey);
- }
-
- Py_XDECREF(args);
- Py_XDECREF(result);
-
- MYDB_END_BLOCK_THREADS;
+ MYDB_BEGIN_BLOCK_THREADS;
+
+ args = BuildValue_SS(leftKey->data, leftKey->size, rightKey->data, rightKey->size);
+ if (args != NULL) {
+ result = PyEval_CallObject(self->btCompareCallback, args);
+ }
+ if (args == NULL || result == NULL) {
+ /* we're in a callback within the DB code, we can't raise */
+ PyErr_Print();
+ res = _default_cmp(leftKey, rightKey);
+ } else if (NUMBER_Check(result)) {
+ res = NUMBER_AsLong(result);
+ } else {
+ PyErr_SetString(PyExc_TypeError,
+ "DB_bt_compare callback MUST return an int.");
+ /* we're in a callback within the DB code, we can't raise */
+ PyErr_Print();
+ res = _default_cmp(leftKey, rightKey);
+ }
+
+ Py_XDECREF(args);
+ Py_XDECREF(result);
+
+ MYDB_END_BLOCK_THREADS;
}
return res;
}
@@ -2415,8 +2415,8 @@ DB_set_bt_compare(DBObject* self, PyObject* comparator)
CHECK_DB_NOT_CLOSED(self);
if (!PyCallable_Check(comparator)) {
- makeTypeError("Callable", comparator);
- return NULL;
+ makeTypeError("Callable", comparator);
+ return NULL;
}
/*
@@ -2430,15 +2430,15 @@ DB_set_bt_compare(DBObject* self, PyObject* comparator)
if (result == NULL)
return NULL;
if (!NUMBER_Check(result)) {
- Py_DECREF(result);
- PyErr_SetString(PyExc_TypeError,
- "callback MUST return an int");
- return NULL;
+ Py_DECREF(result);
+ PyErr_SetString(PyExc_TypeError,
+ "callback MUST return an int");
+ return NULL;
} else if (NUMBER_AsLong(result) != 0) {
- Py_DECREF(result);
- PyErr_SetString(PyExc_TypeError,
- "callback failed to return 0 on two empty strings");
- return NULL;
+ Py_DECREF(result);
+ PyErr_SetString(PyExc_TypeError,
+ "callback failed to return 0 on two empty strings");
+ return NULL;
}
Py_DECREF(result);
@@ -2446,8 +2446,8 @@ DB_set_bt_compare(DBObject* self, PyObject* comparator)
* simplify the code. This would have no real use, as one cannot
* change the function once the db is opened anyway */
if (self->btCompareCallback != NULL) {
- PyErr_SetString(PyExc_RuntimeError, "set_bt_compare() cannot be called more than once");
- return NULL;
+ PyErr_SetString(PyExc_RuntimeError, "set_bt_compare() cannot be called more than once");
+ return NULL;
}
Py_INCREF(comparator);
@@ -2462,9 +2462,9 @@ DB_set_bt_compare(DBObject* self, PyObject* comparator)
err = self->db->set_bt_compare(self->db, _db_compareCallback);
if (err) {
- /* restore the old state in case of error */
- Py_DECREF(comparator);
- self->btCompareCallback = NULL;
+ /* restore the old state in case of error */
+ Py_DECREF(comparator);
+ self->btCompareCallback = NULL;
}
RETURN_IF_ERR();
@@ -2885,8 +2885,8 @@ DB_verify(DBObject* self, PyObject* args, PyObject* kwargs)
CHECK_DB_NOT_CLOSED(self);
if (outFileName)
outFile = fopen(outFileName, "w");
- /* XXX(nnorwitz): it should probably be an exception if outFile
- can't be opened. */
+ /* XXX(nnorwitz): it should probably be an exception if outFile
+ can't be opened. */
{ /* DB.verify acts as a DB handle destructor (like close) */
PyObject *error;
@@ -2940,8 +2940,8 @@ DB_set_encrypt(DBObject* self, PyObject* args, PyObject* kwargs)
static char* kwnames[] = { "passwd", "flags", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|i:set_encrypt", kwnames,
- &passwd, &flags)) {
- return NULL;
+ &passwd, &flags)) {
+ return NULL;
}
MYDB_BEGIN_ALLOW_THREADS;
@@ -3414,12 +3414,12 @@ DBC_get(DBCursorObject* self, PyObject* args, PyObject *kwargs)
CLEAR_DBT(key);
CLEAR_DBT(data);
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|ii:get", &kwnames[2],
- &flags, &dlen, &doff))
+ &flags, &dlen, &doff))
{
PyErr_Clear();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi|ii:get",
&kwnames[1],
- &keyobj, &flags, &dlen, &doff))
+ &keyobj, &flags, &dlen, &doff))
{
PyErr_Clear();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOi|ii:get",
@@ -3427,8 +3427,8 @@ DBC_get(DBCursorObject* self, PyObject* args, PyObject *kwargs)
&flags, &dlen, &doff))
{
return NULL;
- }
- }
+ }
+ }
}
CHECK_CURSOR_NOT_CLOSED(self);
@@ -3447,7 +3447,7 @@ DBC_get(DBCursorObject* self, PyObject* args, PyObject *kwargs)
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
- && self->mydb->moduleFlags.getReturnsNone) {
+ && self->mydb->moduleFlags.getReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@@ -3490,12 +3490,12 @@ DBC_pget(DBCursorObject* self, PyObject* args, PyObject *kwargs)
CLEAR_DBT(key);
CLEAR_DBT(data);
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|ii:pget", &kwnames[2],
- &flags, &dlen, &doff))
+ &flags, &dlen, &doff))
{
PyErr_Clear();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi|ii:pget",
- kwnames_keyOnly,
- &keyobj, &flags, &dlen, &doff))
+ kwnames_keyOnly,
+ &keyobj, &flags, &dlen, &doff))
{
PyErr_Clear();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOi|ii:pget",
@@ -3503,8 +3503,8 @@ DBC_pget(DBCursorObject* self, PyObject* args, PyObject *kwargs)
&flags, &dlen, &doff))
{
return NULL;
- }
- }
+ }
+ }
}
CHECK_CURSOR_NOT_CLOSED(self);
@@ -3525,7 +3525,7 @@ DBC_pget(DBCursorObject* self, PyObject* args, PyObject *kwargs)
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
- && self->mydb->moduleFlags.getReturnsNone) {
+ && self->mydb->moduleFlags.getReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@@ -3636,7 +3636,7 @@ DBC_put(DBCursorObject* self, PyObject* args, PyObject* kwargs)
int doff = -1;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|iii:put", kwnames,
- &keyobj, &dataobj, &flags, &dlen, &doff))
+ &keyobj, &dataobj, &flags, &dlen, &doff))
return NULL;
CHECK_CURSOR_NOT_CLOSED(self);
@@ -3671,7 +3671,7 @@ DBC_set(DBCursorObject* self, PyObject* args, PyObject *kwargs)
int doff = -1;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|iii:set", kwnames,
- &keyobj, &flags, &dlen, &doff))
+ &keyobj, &flags, &dlen, &doff))
return NULL;
CHECK_CURSOR_NOT_CLOSED(self);
@@ -3689,7 +3689,7 @@ DBC_set(DBCursorObject* self, PyObject* args, PyObject *kwargs)
err = _DBC_get(self->dbc, &key, &data, flags|DB_SET);
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
- && self->mydb->moduleFlags.cursorSetReturnsNone) {
+ && self->mydb->moduleFlags.cursorSetReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@@ -3734,7 +3734,7 @@ DBC_set_range(DBCursorObject* self, PyObject* args, PyObject* kwargs)
int doff = -1;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|iii:set_range", kwnames,
- &keyobj, &flags, &dlen, &doff))
+ &keyobj, &flags, &dlen, &doff))
return NULL;
CHECK_CURSOR_NOT_CLOSED(self);
@@ -3751,7 +3751,7 @@ DBC_set_range(DBCursorObject* self, PyObject* args, PyObject* kwargs)
err = _DBC_get(self->dbc, &key, &data, flags|DB_SET_RANGE);
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
- && self->mydb->moduleFlags.cursorSetReturnsNone) {
+ && self->mydb->moduleFlags.cursorSetReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@@ -3905,7 +3905,7 @@ DBC_set_recno(DBCursorObject* self, PyObject* args, PyObject *kwargs)
static char* kwnames[] = { "recno","flags", "dlen", "doff", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|iii:set_recno", kwnames,
- &irecno, &flags, &dlen, &doff))
+ &irecno, &flags, &dlen, &doff))
return NULL;
CHECK_CURSOR_NOT_CLOSED(self);
@@ -3934,7 +3934,7 @@ DBC_set_recno(DBCursorObject* self, PyObject* args, PyObject *kwargs)
err = _DBC_get(self->dbc, &key, &data, flags|DB_SET_RECNO);
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
- && self->mydb->moduleFlags.cursorSetReturnsNone) {
+ && self->mydb->moduleFlags.cursorSetReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@@ -3997,7 +3997,7 @@ DBC_join_item(DBCursorObject* self, PyObject* args)
err = _DBC_get(self->dbc, &key, &data, flags | DB_JOIN_ITEM);
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
- && self->mydb->moduleFlags.getReturnsNone) {
+ && self->mydb->moduleFlags.getReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@@ -4109,8 +4109,8 @@ DBEnv_dbremove(DBEnvObject* self, PyObject* args, PyObject* kwargs)
NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|zOi:dbremove", kwnames,
- &file, &database, &txnobj, &flags)) {
- return NULL;
+ &file, &database, &txnobj, &flags)) {
+ return NULL;
}
if (!checkTxnObj(txnobj, &txn)) {
return NULL;
@@ -4137,8 +4137,8 @@ DBEnv_dbrename(DBEnvObject* self, PyObject* args, PyObject* kwargs)
"flags", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "szs|Oi:dbrename", kwnames,
- &file, &database, &newname, &txnobj, &flags)) {
- return NULL;
+ &file, &database, &newname, &txnobj, &flags)) {
+ return NULL;
}
if (!checkTxnObj(txnobj, &txn)) {
return NULL;
@@ -4161,8 +4161,8 @@ DBEnv_set_encrypt(DBEnvObject* self, PyObject* args, PyObject* kwargs)
static char* kwnames[] = { "passwd", "flags", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|i:set_encrypt", kwnames,
- &passwd, &flags)) {
- return NULL;
+ &passwd, &flags)) {
+ return NULL;
}
MYDB_BEGIN_ALLOW_THREADS;
@@ -4183,8 +4183,8 @@ DBEnv_set_timeout(DBEnvObject* self, PyObject* args, PyObject* kwargs)
static char* kwnames[] = { "timeout", "flags", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:set_timeout", kwnames,
- &timeout, &flags)) {
- return NULL;
+ &timeout, &flags)) {
+ return NULL;
}
MYDB_BEGIN_ALLOW_THREADS;
@@ -5146,8 +5146,8 @@ DBEnv_set_event_notify(DBEnvObject* self, PyObject* notifyFunc)
CHECK_ENV_NOT_CLOSED(self);
if (!PyCallable_Check(notifyFunc)) {
- makeTypeError("Callable", notifyFunc);
- return NULL;
+ makeTypeError("Callable", notifyFunc);
+ return NULL;
}
Py_XDECREF(self->event_notifyCallback);
@@ -5165,8 +5165,8 @@ DBEnv_set_event_notify(DBEnvObject* self, PyObject* notifyFunc)
MYDB_END_ALLOW_THREADS;
if (err) {
- Py_DECREF(notifyFunc);
- self->event_notifyCallback = NULL;
+ Py_DECREF(notifyFunc);
+ self->event_notifyCallback = NULL;
}
RETURN_IF_ERR();
@@ -5487,7 +5487,7 @@ DBEnv_rep_start(DBEnvObject* self, PyObject* args, PyObject* kwargs)
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"i|O:rep_start", kwnames, &flags, &cdata_py))
{
- return NULL;
+ return NULL;
}
CHECK_ENV_NOT_CLOSED(self);
@@ -5640,7 +5640,7 @@ DBEnv_repmgr_start(DBEnvObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"ii:repmgr_start", kwnames, &nthreads, &flags))
{
- return NULL;
+ return NULL;
}
CHECK_ENV_NOT_CLOSED(self);
MYDB_BEGIN_ALLOW_THREADS;
@@ -5663,7 +5663,7 @@ DBEnv_repmgr_set_local_site(DBEnvObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"si|i:repmgr_set_local_site", kwnames, &host, &port, &flags))
{
- return NULL;
+ return NULL;
}
CHECK_ENV_NOT_CLOSED(self);
MYDB_BEGIN_ALLOW_THREADS;
@@ -5687,7 +5687,7 @@ DBEnv_repmgr_add_remote_site(DBEnvObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"si|i:repmgr_add_remote_site", kwnames, &host, &port, &flags))
{
- return NULL;
+ return NULL;
}
CHECK_ENV_NOT_CLOSED(self);
MYDB_BEGIN_ALLOW_THREADS;
@@ -5705,7 +5705,7 @@ DBEnv_repmgr_set_ack_policy(DBEnvObject* self, PyObject* args)
if (!PyArg_ParseTuple(args, "i:repmgr_set_ack_policy", &ack_policy))
{
- return NULL;
+ return NULL;
}
CHECK_ENV_NOT_CLOSED(self);
MYDB_BEGIN_ALLOW_THREADS;
@@ -5880,7 +5880,7 @@ static void _promote_transaction_dbs_and_sequences(DBTxnObject *txn)
/* The db is already linked to its environment,
** so nothing to do.
*/
- db->txn=NULL;
+ db->txn=NULL;
}
}
@@ -6682,20 +6682,20 @@ statichere PyTypeObject DB_Type = {
0, /*tp_as_sequence*/
&DB_mapping,/*tp_as_mapping*/
0, /*tp_hash*/
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
0, /* tp_setattro */
- 0, /* tp_as_buffer */
+ 0, /* tp_as_buffer */
#if (PY_VERSION_HEX < 0x03000000)
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
#else
Py_TPFLAGS_DEFAULT, /* tp_flags */
#endif
0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
offsetof(DBObject, in_weakreflist), /* tp_weaklistoffset */
0, /*tp_iter*/
0, /*tp_iternext*/
@@ -6768,20 +6768,20 @@ statichere PyTypeObject DBEnv_Type = {
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
0, /* tp_setattro */
- 0, /* tp_as_buffer */
+ 0, /* tp_as_buffer */
#if (PY_VERSION_HEX < 0x03000000)
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
#else
Py_TPFLAGS_DEFAULT, /* tp_flags */
#endif
0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
offsetof(DBEnvObject, in_weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
@@ -6811,20 +6811,20 @@ statichere PyTypeObject DBTxn_Type = {
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
0, /* tp_setattro */
- 0, /* tp_as_buffer */
+ 0, /* tp_as_buffer */
#if (PY_VERSION_HEX < 0x03000000)
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
#else
Py_TPFLAGS_DEFAULT, /* tp_flags */
#endif
0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
offsetof(DBTxnObject, in_weakreflist), /* tp_weaklistoffset */
0, /*tp_iter*/
0, /*tp_iternext*/
@@ -6854,20 +6854,20 @@ statichere PyTypeObject DBLock_Type = {
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
0, /* tp_setattro */
- 0, /* tp_as_buffer */
+ 0, /* tp_as_buffer */
#if (PY_VERSION_HEX < 0x03000000)
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
#else
Py_TPFLAGS_DEFAULT, /* tp_flags */
#endif
0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
offsetof(DBLockObject, in_weakreflist), /* tp_weaklistoffset */
};
@@ -6893,20 +6893,20 @@ statichere PyTypeObject DBSequence_Type = {
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
0, /* tp_setattro */
- 0, /* tp_as_buffer */
+ 0, /* tp_as_buffer */
#if (PY_VERSION_HEX < 0x03000000)
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
#else
Py_TPFLAGS_DEFAULT, /* tp_flags */
#endif
0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
offsetof(DBSequenceObject, in_weakreflist), /* tp_weaklistoffset */
0, /*tp_iter*/
0, /*tp_iternext*/
@@ -7068,7 +7068,7 @@ PyMODINIT_FUNC PyInit__bsddb(void) /* Note the two underscores */
#if (PY_VERSION_HEX < 0x03000000)
return;
#else
- return NULL;
+ return NULL;
#endif
}
@@ -7473,7 +7473,7 @@ PyMODINIT_FUNC PyInit__bsddb(void) /* Note the two underscores */
* using one base class. */
PyDict_SetItemString(d, "KeyError", PyExc_KeyError);
PyRun_String("class DBNotFoundError(DBError, KeyError): pass\n"
- "class DBKeyEmptyError(DBError, KeyError): pass",
+ "class DBKeyEmptyError(DBError, KeyError): pass",
Py_file_input, d, d);
DBNotFoundError = PyDict_GetItemString(d, "DBNotFoundError");
DBKeyEmptyError = PyDict_GetItemString(d, "DBKeyEmptyError");
diff --git a/Modules/_codecsmodule.c b/Modules/_codecsmodule.c
index 6877238..9f22871 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)
@@ -96,11 +96,11 @@ codec_encode(PyObject *self, PyObject *args)
#ifdef Py_USING_UNICODE
if (encoding == NULL)
- encoding = PyUnicode_GetDefaultEncoding();
+ encoding = PyUnicode_GetDefaultEncoding();
#else
if (encoding == NULL) {
- PyErr_SetString(PyExc_ValueError, "no encoding specified");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "no encoding specified");
+ return NULL;
}
#endif
@@ -130,11 +130,11 @@ codec_decode(PyObject *self, PyObject *args)
#ifdef Py_USING_UNICODE
if (encoding == NULL)
- encoding = PyUnicode_GetDefaultEncoding();
+ encoding = PyUnicode_GetDefaultEncoding();
#else
if (encoding == NULL) {
- PyErr_SetString(PyExc_ValueError, "no encoding specified");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "no encoding specified");
+ return NULL;
}
#endif
@@ -146,7 +146,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)
@@ -159,44 +159,44 @@ 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(PyString_DecodeEscape(data, size, errors, 0, NULL),
- size);
+ size);
}
static PyObject *
escape_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- PyObject *str;
- const char *errors = NULL;
- char *buf;
- Py_ssize_t len;
-
- if (!PyArg_ParseTuple(args, "O!|z:escape_encode",
- &PyString_Type, &str, &errors))
- return NULL;
-
- str = PyString_Repr(str, 0);
- if (!str)
- return NULL;
-
- /* The string will be quoted. Unquote, similar to unicode-escape. */
- buf = PyString_AS_STRING (str);
- len = PyString_GET_SIZE (str);
- memmove(buf, buf+1, len-2);
- if (_PyString_Resize(&str, len-2) < 0)
- return NULL;
-
- return codec_tuple(str, PyString_Size(str));
+ PyObject *str;
+ const char *errors = NULL;
+ char *buf;
+ Py_ssize_t len;
+
+ if (!PyArg_ParseTuple(args, "O!|z:escape_encode",
+ &PyString_Type, &str, &errors))
+ return NULL;
+
+ str = PyString_Repr(str, 0);
+ if (!str)
+ return NULL;
+
+ /* The string will be quoted. Unquote, similar to unicode-escape. */
+ buf = PyString_AS_STRING (str);
+ len = PyString_GET_SIZE (str);
+ memmove(buf, buf+1, len-2);
+ if (_PyString_Resize(&str, len-2) < 0)
+ return NULL;
+
+ return codec_tuple(str, PyString_Size(str));
}
#ifdef Py_USING_UNICODE
@@ -204,7 +204,7 @@ escape_encode(PyObject *self,
static PyObject *
unicode_internal_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *obj;
const char *errors = NULL;
@@ -212,19 +212,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);
}
}
@@ -232,20 +232,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, "s*|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);
@@ -253,32 +253,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, "s*|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;
@@ -286,22 +286,22 @@ utf_16_decode(PyObject *self,
PyObject *decoded;
if (!PyArg_ParseTuple(args, "s*|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;
@@ -309,23 +309,23 @@ utf_16_le_decode(PyObject *self,
PyObject *decoded = NULL;
if (!PyArg_ParseTuple(args, "s*|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;
@@ -333,15 +333,15 @@ utf_16_be_decode(PyObject *self,
PyObject *decoded = NULL;
if (!PyArg_ParseTuple(args, "s*|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);
}
@@ -355,9 +355,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;
@@ -365,14 +365,14 @@ utf_16_ex_decode(PyObject *self,
Py_ssize_t consumed;
if (!PyArg_ParseTuple(args, "s*|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;
@@ -380,9 +380,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;
@@ -390,22 +390,22 @@ utf_32_decode(PyObject *self,
PyObject *decoded;
if (!PyArg_ParseTuple(args, "s*|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;
@@ -413,22 +413,22 @@ utf_32_le_decode(PyObject *self,
PyObject *decoded;
if (!PyArg_ParseTuple(args, "s*|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;
@@ -436,14 +436,14 @@ utf_32_be_decode(PyObject *self,
PyObject *decoded;
if (!PyArg_ParseTuple(args, "s*|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);
}
@@ -457,9 +457,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;
@@ -467,14 +467,14 @@ utf_32_ex_decode(PyObject *self,
Py_ssize_t consumed;
if (!PyArg_ParseTuple(args, "s*|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;
@@ -482,114 +482,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, "s*|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, "s*|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, "s*|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, "s*|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);
}
@@ -599,39 +599,39 @@ mbcs_decode(PyObject *self,
static PyObject *
readbuffer_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
const char *data;
Py_ssize_t size;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "s#|z:readbuffer_encode",
- &data, &size, &errors))
- return NULL;
+ &data, &size, &errors))
+ return NULL;
return codec_tuple(PyString_FromStringAndSize(data, size),
- size);
+ size);
}
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(PyString_FromStringAndSize(data, size),
- size);
+ size);
}
static PyObject *
unicode_internal_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *obj;
const char *errors = NULL;
@@ -639,65 +639,65 @@ 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(PyString_FromStringAndSize(data, size),
- size);
+ data = PyUnicode_AS_DATA(obj);
+ size = PyUnicode_GET_DATA_SIZE(obj);
+ return codec_tuple(PyString_FromStringAndSize(data, size),
+ size);
}
else {
- if (PyObject_AsReadBuffer(obj, (const void **)&data, &size))
- return NULL;
- return codec_tuple(PyString_FromStringAndSize(data, size),
- size);
+ if (PyObject_AsReadBuffer(obj, (const void **)&data, &size))
+ return NULL;
+ return codec_tuple(PyString_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;
}
@@ -711,70 +711,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;
}
@@ -788,186 +788,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;
}
@@ -985,23 +985,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;
}
@@ -1026,8 +1026,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;
@@ -1044,68 +1044,68 @@ 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},
+ {"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},
#ifdef Py_USING_UNICODE
- {"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},
+ {"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
#endif /* Py_USING_UNICODE */
- {"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 */
};
PyMODINIT_FUNC
diff --git a/Modules/_collectionsmodule.c b/Modules/_collectionsmodule.c
index 42cfe6b..6aadec1 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,22 +256,22 @@ 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.");
@@ -279,47 +279,47 @@ PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
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;
-
- 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;
+
+ 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,
@@ -328,47 +328,47 @@ 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;
-
- 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;
+
+ 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,
@@ -377,63 +377,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,
@@ -442,39 +442,39 @@ PyDoc_STRVAR(rotate_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,
@@ -483,56 +483,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
@@ -545,62 +545,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.");
@@ -608,49 +608,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.");
@@ -658,30 +658,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.");
@@ -689,210 +689,210 @@ PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
static PyObject *
deque_repr(PyObject *deque)
{
- PyObject *aslist, *result, *fmt;
- int i;
-
- i = Py_ReprEnter(deque);
- if (i != 0) {
- if (i < 0)
- return NULL;
- return PyString_FromString("[...]");
- }
-
- aslist = PySequence_List(deque);
- if (aslist == NULL) {
- Py_ReprLeave(deque);
- return NULL;
- }
- if (((dequeobject *)deque)->maxlen != -1)
- fmt = PyString_FromFormat("deque(%%r, maxlen=%zd)",
- ((dequeobject *)deque)->maxlen);
- else
- fmt = PyString_FromString("deque(%r)");
- if (fmt == NULL) {
- Py_DECREF(aslist);
- Py_ReprLeave(deque);
- return NULL;
- }
- result = PyString_Format(fmt, aslist);
- Py_DECREF(fmt);
- Py_DECREF(aslist);
- Py_ReprLeave(deque);
- return result;
+ PyObject *aslist, *result, *fmt;
+ int i;
+
+ i = Py_ReprEnter(deque);
+ if (i != 0) {
+ if (i < 0)
+ return NULL;
+ return PyString_FromString("[...]");
+ }
+
+ aslist = PySequence_List(deque);
+ if (aslist == NULL) {
+ Py_ReprLeave(deque);
+ return NULL;
+ }
+ if (((dequeobject *)deque)->maxlen != -1)
+ fmt = PyString_FromFormat("deque(%%r, maxlen=%zd)",
+ ((dequeobject *)deque)->maxlen);
+ else
+ fmt = PyString_FromString("deque(%r)");
+ if (fmt == NULL) {
+ Py_DECREF(aslist);
+ Py_ReprLeave(deque);
+ return NULL;
+ }
+ result = PyString_Format(fmt, aslist);
+ Py_DECREF(fmt);
+ Py_DECREF(aslist);
+ Py_ReprLeave(deque);
+ return result;
}
static int
deque_tp_print(PyObject *deque, FILE *fp, int flags)
{
- PyObject *it, *item;
- char *emit = ""; /* No separator emitted on first pass */
- char *separator = ", ";
- int i;
-
- i = Py_ReprEnter(deque);
- if (i != 0) {
- if (i < 0)
- return i;
- Py_BEGIN_ALLOW_THREADS
- fputs("[...]", fp);
- Py_END_ALLOW_THREADS
- return 0;
- }
-
- it = PyObject_GetIter(deque);
- if (it == NULL)
- return -1;
-
- Py_BEGIN_ALLOW_THREADS
- fputs("deque([", fp);
- Py_END_ALLOW_THREADS
- while ((item = PyIter_Next(it)) != NULL) {
- Py_BEGIN_ALLOW_THREADS
- fputs(emit, fp);
- Py_END_ALLOW_THREADS
- emit = separator;
- if (PyObject_Print(item, fp, 0) != 0) {
- Py_DECREF(item);
- Py_DECREF(it);
- Py_ReprLeave(deque);
- return -1;
- }
- Py_DECREF(item);
- }
- Py_ReprLeave(deque);
- Py_DECREF(it);
- if (PyErr_Occurred())
- return -1;
-
- Py_BEGIN_ALLOW_THREADS
- if (((dequeobject *)deque)->maxlen == -1)
- fputs("])", fp);
- else
- fprintf(fp, "], maxlen=%" PY_FORMAT_SIZE_T "d)", ((dequeobject *)deque)->maxlen);
- Py_END_ALLOW_THREADS
- return 0;
+ PyObject *it, *item;
+ char *emit = ""; /* No separator emitted on first pass */
+ char *separator = ", ";
+ int i;
+
+ i = Py_ReprEnter(deque);
+ if (i != 0) {
+ if (i < 0)
+ return i;
+ Py_BEGIN_ALLOW_THREADS
+ fputs("[...]", fp);
+ Py_END_ALLOW_THREADS
+ return 0;
+ }
+
+ it = PyObject_GetIter(deque);
+ if (it == NULL)
+ return -1;
+
+ Py_BEGIN_ALLOW_THREADS
+ fputs("deque([", fp);
+ Py_END_ALLOW_THREADS
+ while ((item = PyIter_Next(it)) != NULL) {
+ Py_BEGIN_ALLOW_THREADS
+ fputs(emit, fp);
+ Py_END_ALLOW_THREADS
+ emit = separator;
+ if (PyObject_Print(item, fp, 0) != 0) {
+ Py_DECREF(item);
+ Py_DECREF(it);
+ Py_ReprLeave(deque);
+ return -1;
+ }
+ Py_DECREF(item);
+ }
+ Py_ReprLeave(deque);
+ Py_DECREF(it);
+ if (PyErr_Occurred())
+ return -1;
+
+ Py_BEGIN_ALLOW_THREADS
+ if (((dequeobject *)deque)->maxlen == -1)
+ fputs("])", fp);
+ else
+ fprintf(fp, "], maxlen=%" PY_FORMAT_SIZE_T "d)", ((dequeobject *)deque)->maxlen);
+ Py_END_ALLOW_THREADS
+ return 0;
}
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 = PyInt_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 = PyInt_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 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 */
};
@@ -901,34 +901,34 @@ 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},
- {"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},
- {"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},
+ {"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},
+ {"rotate", (PyCFunction)deque_rotate,
+ METH_VARARGS, rotate_doc},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(deque_doc,
@@ -937,58 +937,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 */
- deque_tp_print, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 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 |
- Py_TPFLAGS_HAVE_WEAKREFS, /* 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 */
- 0, /* 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 */
+ deque_tp_print, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 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 |
+ Py_TPFLAGS_HAVE_WEAKREFS, /* 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 */
+ 0, /* 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;
@@ -996,107 +996,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 PyInt_FromLong(it->counter);
+ return PyInt_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_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 */
- 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_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 */
+ 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 **************************/
@@ -1106,87 +1106,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_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 */
- 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_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 */
+ 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 */
@@ -1201,25 +1201,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.");
@@ -1227,192 +1227,192 @@ 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 *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, "iteritems", "()");
- if (items == NULL) {
- Py_DECREF(args);
- return NULL;
- }
- result = PyTuple_Pack(5, Py_TYPE(dd), args,
- Py_None, Py_None, items);
- 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 *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, "iteritems", "()");
+ if (items == NULL) {
+ Py_DECREF(args);
+ return NULL;
+ }
+ result = PyTuple_Pack(5, Py_TYPE(dd), args,
+ Py_None, Py_None, items);
+ 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 int
defdict_print(defdictobject *dd, FILE *fp, int flags)
{
- int sts;
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "defaultdict(");
- Py_END_ALLOW_THREADS
- if (dd->default_factory == NULL) {
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "None");
- Py_END_ALLOW_THREADS
- } else {
- PyObject_Print(dd->default_factory, fp, 0);
- }
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, ", ");
- Py_END_ALLOW_THREADS
- sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, ")");
- Py_END_ALLOW_THREADS
- return sts;
+ int sts;
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "defaultdict(");
+ Py_END_ALLOW_THREADS
+ if (dd->default_factory == NULL) {
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "None");
+ Py_END_ALLOW_THREADS
+ } else {
+ PyObject_Print(dd->default_factory, fp, 0);
+ }
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, ", ");
+ Py_END_ALLOW_THREADS
+ sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, ")");
+ Py_END_ALLOW_THREADS
+ return sts;
}
static PyObject *
defdict_repr(defdictobject *dd)
{
- PyObject *defrepr;
- PyObject *baserepr;
- PyObject *result;
- baserepr = PyDict_Type.tp_repr((PyObject *)dd);
- if (baserepr == NULL)
- return NULL;
- if (dd->default_factory == NULL)
- defrepr = PyString_FromString("None");
- else
- {
- int status = Py_ReprEnter(dd->default_factory);
- if (status != 0) {
- if (status < 0)
- return NULL;
- defrepr = PyString_FromString("...");
- }
- else
- defrepr = PyObject_Repr(dd->default_factory);
- Py_ReprLeave(dd->default_factory);
- }
- if (defrepr == NULL) {
- Py_DECREF(baserepr);
- return NULL;
- }
- result = PyString_FromFormat("defaultdict(%s, %s)",
- PyString_AS_STRING(defrepr),
- PyString_AS_STRING(baserepr));
- Py_DECREF(defrepr);
- Py_DECREF(baserepr);
- return result;
+ PyObject *defrepr;
+ PyObject *baserepr;
+ PyObject *result;
+ baserepr = PyDict_Type.tp_repr((PyObject *)dd);
+ if (baserepr == NULL)
+ return NULL;
+ if (dd->default_factory == NULL)
+ defrepr = PyString_FromString("None");
+ else
+ {
+ int status = Py_ReprEnter(dd->default_factory);
+ if (status != 0) {
+ if (status < 0)
+ return NULL;
+ defrepr = PyString_FromString("...");
+ }
+ else
+ defrepr = PyObject_Repr(dd->default_factory);
+ Py_ReprLeave(dd->default_factory);
+ }
+ if (defrepr == NULL) {
+ Py_DECREF(baserepr);
+ return NULL;
+ }
+ result = PyString_FromFormat("defaultdict(%s, %s)",
+ PyString_AS_STRING(defrepr),
+ PyString_AS_STRING(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,
@@ -1427,47 +1427,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 */
- (printfunc)defdict_print, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (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 |
- Py_TPFLAGS_HAVE_WEAKREFS, /* 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 */
+ (printfunc)defdict_print, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (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 |
+ Py_TPFLAGS_HAVE_WEAKREFS, /* 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 ********************************************************/
@@ -1481,28 +1481,28 @@ PyDoc_STRVAR(module_doc,
PyMODINIT_FUNC
init_collections(void)
{
- PyObject *m;
+ PyObject *m;
- m = Py_InitModule3("_collections", NULL, module_doc);
- if (m == NULL)
- return;
+ m = Py_InitModule3("_collections", NULL, module_doc);
+ if (m == NULL)
+ return;
- if (PyType_Ready(&deque_type) < 0)
- return;
- Py_INCREF(&deque_type);
- PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
+ if (PyType_Ready(&deque_type) < 0)
+ return;
+ Py_INCREF(&deque_type);
+ PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
- defdict_type.tp_base = &PyDict_Type;
- if (PyType_Ready(&defdict_type) < 0)
- return;
- Py_INCREF(&defdict_type);
- PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
+ defdict_type.tp_base = &PyDict_Type;
+ if (PyType_Ready(&defdict_type) < 0)
+ return;
+ Py_INCREF(&defdict_type);
+ PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
- if (PyType_Ready(&dequeiter_type) < 0)
- return;
+ if (PyType_Ready(&dequeiter_type) < 0)
+ return;
- if (PyType_Ready(&dequereviter_type) < 0)
- return;
+ if (PyType_Ready(&dequereviter_type) < 0)
+ return;
- return;
+ return;
}
diff --git a/Modules/_csv.c b/Modules/_csv.c
index a5787d3..983f6a5 100644
--- a/Modules/_csv.c
+++ b/Modules/_csv.c
@@ -31,96 +31,96 @@ module instead.
#endif /* ifndef PyDoc_STRVAR */
#ifndef PyMODINIT_FUNC
-# if defined(__cplusplus)
-# define PyMODINIT_FUNC extern "C" void
-# else /* __cplusplus */
-# define PyMODINIT_FUNC void
-# endif /* __cplusplus */
+# if defined(__cplusplus)
+# define PyMODINIT_FUNC extern "C" void
+# else /* __cplusplus */
+# define PyMODINIT_FUNC void
+# endif /* __cplusplus */
#endif
#ifndef Py_CLEAR
-#define Py_CLEAR(op) \
- do { \
- if (op) { \
- PyObject *tmp = (PyObject *)(op); \
- (op) = NULL; \
- Py_DECREF(tmp); \
- } \
- } while (0)
+#define Py_CLEAR(op) \
+ do { \
+ if (op) { \
+ PyObject *tmp = (PyObject *)(op); \
+ (op) = NULL; \
+ Py_DECREF(tmp); \
+ } \
+ } while (0)
#endif
#ifndef Py_VISIT
-#define Py_VISIT(op) \
- do { \
- if (op) { \
- int vret = visit((PyObject *)(op), arg); \
- if (vret) \
- return vret; \
- } \
- } while (0)
+#define Py_VISIT(op) \
+ do { \
+ if (op) { \
+ int vret = visit((PyObject *)(op), arg); \
+ if (vret) \
+ return vret; \
+ } \
+ } while (0)
#endif
/* end 2.2 compatibility macros */
#define IS_BASESTRING(o) \
- PyObject_TypeCheck(o, &PyBaseString_Type)
+ PyObject_TypeCheck(o, &PyBaseString_Type)
-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
-
- int doublequote; /* is " represented by ""? */
- char delimiter; /* field separator */
- char quotechar; /* quote character */
- char 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 */
+ PyObject_HEAD
+
+ int doublequote; /* is " represented by ""? */
+ char delimiter; /* field separator */
+ char quotechar; /* quote character */
+ char 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 */
} DialectObj;
staticforward 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 */
- char *field; /* build current field in here */
- int field_size; /* size of allocated buffer */
- int 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 */
+ char *field; /* build current field in here */
+ int field_size; /* size of allocated buffer */
+ int field_len; /* length of current field */
+ int numeric_field; /* treat field as numeric */
+ unsigned long line_num; /* Source-file line number */
} ReaderObj;
staticforward PyTypeObject Reader_Type;
@@ -128,17 +128,17 @@ staticforward 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 */
- char *rec; /* buffer for parser.join */
- int rec_size; /* size of allocated record */
- int rec_len; /* length of record */
- int num_fields; /* number of fields in record */
-} WriterObj;
+ char *rec; /* buffer for parser.join */
+ int rec_size; /* size of allocated record */
+ int rec_len; /* length of record */
+ int num_fields; /* number of fields in record */
+} WriterObj;
staticforward PyTypeObject Writer_Type;
@@ -149,357 +149,357 @@ staticforward 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(char c)
{
- if (c == '\0') {
- Py_INCREF(Py_None);
- return Py_None;
- }
- else
- return PyString_FromStringAndSize((char*)&c, 1);
+ if (c == '\0') {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ else
+ return PyString_FromStringAndSize((char*)&c, 1);
}
static PyObject *
Dialect_get_lineterminator(DialectObj *self)
{
- return get_string(self->lineterminator);
+ return get_string(self->lineterminator);
}
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 PyInt_FromLong(self->quoting);
+ return PyInt_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 {
- if (!PyInt_Check(src)) {
- PyErr_Format(PyExc_TypeError,
- "\"%s\" must be an integer", name);
- return -1;
- }
- *target = PyInt_AsLong(src);
- }
- return 0;
+ if (src == NULL)
+ *target = dflt;
+ else {
+ if (!PyInt_Check(src)) {
+ PyErr_Format(PyExc_TypeError,
+ "\"%s\" must be an integer", name);
+ return -1;
+ }
+ *target = PyInt_AsLong(src);
+ }
+ return 0;
}
static int
_set_char(const char *name, char *target, PyObject *src, char dflt)
{
- if (src == NULL)
- *target = dflt;
- else {
- if (src == Py_None || PyString_Size(src) == 0)
- *target = '\0';
- else if (!PyString_Check(src) || PyString_Size(src) != 1) {
- PyErr_Format(PyExc_TypeError,
- "\"%s\" must be an 1-character string",
- name);
- return -1;
- }
- else {
- char *s = PyString_AsString(src);
- if (s == NULL)
- return -1;
- *target = s[0];
- }
- }
- return 0;
+ if (src == NULL)
+ *target = dflt;
+ else {
+ if (src == Py_None || PyString_Size(src) == 0)
+ *target = '\0';
+ else if (!PyString_Check(src) || PyString_Size(src) != 1) {
+ PyErr_Format(PyExc_TypeError,
+ "\"%s\" must be an 1-character string",
+ name);
+ return -1;
+ }
+ else {
+ char *s = PyString_AsString(src);
+ if (s == NULL)
+ return -1;
+ *target = s[0];
+ }
+ }
+ return 0;
}
static int
_set_str(const char *name, PyObject **target, PyObject *src, const char *dflt)
{
- if (src == NULL)
- *target = PyString_FromString(dflt);
- else {
- if (src == Py_None)
- *target = NULL;
- else if (!IS_BASESTRING(src)) {
- PyErr_Format(PyExc_TypeError,
- "\"%s\" must be an string", name);
- return -1;
- }
- else {
- Py_XDECREF(*target);
- Py_INCREF(src);
- *target = src;
- }
- }
- return 0;
+ if (src == NULL)
+ *target = PyString_FromString(dflt);
+ else {
+ if (src == Py_None)
+ *target = NULL;
+ else if (!IS_BASESTRING(src)) {
+ PyErr_Format(PyExc_TypeError,
+ "\"%s\" must be an 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[] = {
- { "delimiter", T_CHAR, D_OFF(delimiter), READONLY },
- { "skipinitialspace", T_INT, D_OFF(skipinitialspace), READONLY },
- { "doublequote", T_INT, D_OFF(doublequote), READONLY },
- { "strict", T_INT, D_OFF(strict), READONLY },
- { NULL }
+ { "delimiter", T_CHAR, D_OFF(delimiter), READONLY },
+ { "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[] = {
- { "escapechar", (getter)Dialect_get_escapechar},
- { "lineterminator", (getter)Dialect_get_lineterminator},
- { "quotechar", (getter)Dialect_get_quotechar},
- { "quoting", (getter)Dialect_get_quoting},
- {NULL},
+ { "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 */
- (cmpfunc)0, /* tp_compare */
- (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 */
+ (cmpfunc)0, /* tp_compare */
+ (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 */
};
/*
@@ -509,15 +509,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;
}
/*
@@ -526,330 +526,330 @@ _call_dialect(PyObject *dialect_inst, PyObject *kwargs)
static int
parse_save_field(ReaderObj *self)
{
- PyObject *field;
-
- field = PyString_FromStringAndSize(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 = PyString_FromStringAndSize(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_Malloc(self->field_size);
- }
- else {
- if (self->field_size > INT_MAX / 2) {
- PyErr_NoMemory();
- return 0;
- }
- self->field_size *= 2;
- self->field = PyMem_Realloc(self->field, 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_Malloc(self->field_size);
+ }
+ else {
+ if (self->field_size > INT_MAX / 2) {
+ PyErr_NoMemory();
+ return 0;
+ }
+ self->field_size *= 2;
+ self->field = PyMem_Realloc(self->field, self->field_size);
+ }
+ if (self->field == NULL) {
+ PyErr_NoMemory();
+ return 0;
+ }
+ return 1;
}
static int
parse_add_char(ReaderObj *self, char 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, char 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;
- char *line, c;
- int 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;
- }
- ++self->line_num;
+ PyObject *lineobj;
+ PyObject *fields = NULL;
+ char *line, c;
+ int 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;
+ }
+ ++self->line_num;
- line = PyString_AsString(lineobj);
- linelen = PyString_Size(lineobj);
+ line = PyString_AsString(lineobj);
+ linelen = PyString_Size(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;
- }
- }
+ 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,
@@ -860,93 +860,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), RO },
- { "line_num", T_ULONG, R_OFF(line_num), RO },
- { NULL }
+ { "dialect", T_OBJECT, R_OFF(dialect), RO },
+ { "line_num", T_ULONG, R_OFF(line_num), RO },
+ { 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*/
- (cmpfunc)0, /*tp_compare*/
- (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*/
+ (cmpfunc)0, /*tp_compare*/
+ (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;
}
/*
@@ -956,8 +956,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
@@ -967,90 +967,90 @@ join_reset(WriterObj *self)
*/
static int
join_append_data(WriterObj *self, char *field, int quote_empty,
- int *quoted, int copy_phase)
+ int *quoted, int copy_phase)
{
- DialectObj *dialect = self->dialect;
- int i, rec_len;
- char *lineterm;
+ DialectObj *dialect = self->dialect;
+ int i, rec_len;
+ char *lineterm;
#define ADDCH(c) \
- do {\
- if (copy_phase) \
- self->rec[rec_len] = c;\
- rec_len++;\
- } while(0)
-
- lineterm = PyString_AsString(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 */
- for (i = 0;; i++) {
- char c = field[i];
- int want_escape = 0;
-
- if (c == '\0')
- break;
-
- if (c == dialect->delimiter ||
- c == dialect->escapechar ||
- c == dialect->quotechar ||
- 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 = PyString_AsString(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 */
+ for (i = 0;; i++) {
+ char c = field[i];
+ int want_escape = 0;
+
+ if (c == '\0')
+ break;
+
+ if (c == dialect->delimiter ||
+ c == dialect->escapechar ||
+ c == dialect->quotechar ||
+ 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
}
@@ -1058,74 +1058,74 @@ 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_Malloc(self->rec_size);
- }
- else {
- char *old_rec = self->rec;
-
- self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR;
- self->rec = PyMem_Realloc(self->rec, 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_Malloc(self->rec_size);
+ }
+ else {
+ char *old_rec = self->rec;
+
+ self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR;
+ self->rec = PyMem_Realloc(self->rec, 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, char *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;
- char *terminator;
+ int terminator_len;
+ char *terminator;
- terminator_len = PyString_Size(self->dialect->lineterminator);
- if (terminator_len == -1)
- return 0;
+ terminator_len = PyString_Size(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 = PyString_AsString(self->dialect->lineterminator);
- if (terminator == NULL)
- return 0;
- memmove(self->rec + self->rec_len, terminator, terminator_len);
- self->rec_len += terminator_len;
+ terminator = PyString_AsString(self->dialect->lineterminator);
+ if (terminator == NULL)
+ return 0;
+ memmove(self->rec + self->rec_len, terminator, terminator_len);
+ self->rec_len += terminator_len;
- return 1;
+ return 1;
}
PyDoc_STRVAR(csv_writerow_doc,
@@ -1137,73 +1137,73 @@ 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 (PyString_Check(field)) {
- append_ok = join_append(self,
- PyString_AS_STRING(field),
- &quoted, len == 1);
- Py_DECREF(field);
- }
- else if (field == Py_None) {
- append_ok = join_append(self, "", &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, PyString_AS_STRING(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,
- "(s#)", self->rec, self->rec_len);
+ 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 (PyString_Check(field)) {
+ append_ok = join_append(self,
+ PyString_AS_STRING(field),
+ &quoted, len == 1);
+ Py_DECREF(field);
+ }
+ else if (field == Py_None) {
+ append_ok = join_append(self, "", &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, PyString_AS_STRING(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,
+ "(s#)", self->rec, self->rec_len);
}
PyDoc_STRVAR(csv_writerows_doc,
@@ -1215,72 +1215,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;
+ 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;
}
- 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);
- }
- 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), RO },
- { NULL }
+ { "dialect", T_OBJECT, W_OFF(dialect), RO },
+ { 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"
@@ -1288,75 +1288,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*/
- (cmpfunc)0, /*tp_compare*/
- (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*/
+ (cmpfunc)0, /*tp_compare*/
+ (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;
}
/*
@@ -1365,66 +1365,66 @@ 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 (!PyInt_Check(new_limit)) {
- PyErr_Format(PyExc_TypeError,
- "limit must be an integer");
- return NULL;
- }
- field_limit = PyInt_AsLong(new_limit);
- }
- return PyInt_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 (!PyInt_Check(new_limit)) {
+ PyErr_Format(PyExc_TypeError,
+ "limit must be an integer");
+ return NULL;
+ }
+ field_limit = PyInt_AsLong(new_limit);
+ }
+ return PyInt_FromLong(old_limit);
}
/*
@@ -1542,70 +1542,70 @@ 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 }
};
PyMODINIT_FUNC
init_csv(void)
{
- PyObject *module;
- StyleDesc *style;
-
- if (PyType_Ready(&Dialect_Type) < 0)
- return;
-
- if (PyType_Ready(&Reader_Type) < 0)
- return;
-
- if (PyType_Ready(&Writer_Type) < 0)
- return;
-
- /* Create the module and add the functions */
- module = Py_InitModule3("_csv", csv_methods, csv_module_doc);
- if (module == NULL)
- return;
-
- /* Add version to the module. */
- if (PyModule_AddStringConstant(module, "__version__",
- MODULE_VERSION) == -1)
- return;
-
- /* Add _dialects dictionary */
- dialects = PyDict_New();
- if (dialects == NULL)
- return;
- if (PyModule_AddObject(module, "_dialects", dialects))
- return;
-
- /* Add quote styles into dictionary */
- for (style = quote_styles; style->name; style++) {
- if (PyModule_AddIntConstant(module, style->name,
- style->style) == -1)
- return;
- }
-
- /* Add the Dialect type */
- Py_INCREF(&Dialect_Type);
- if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type))
- return;
-
- /* Add the CSV exception object to the module. */
- error_obj = PyErr_NewException("_csv.Error", NULL, NULL);
- if (error_obj == NULL)
- return;
- PyModule_AddObject(module, "Error", error_obj);
+ PyObject *module;
+ StyleDesc *style;
+
+ if (PyType_Ready(&Dialect_Type) < 0)
+ return;
+
+ if (PyType_Ready(&Reader_Type) < 0)
+ return;
+
+ if (PyType_Ready(&Writer_Type) < 0)
+ return;
+
+ /* Create the module and add the functions */
+ module = Py_InitModule3("_csv", csv_methods, csv_module_doc);
+ if (module == NULL)
+ return;
+
+ /* Add version to the module. */
+ if (PyModule_AddStringConstant(module, "__version__",
+ MODULE_VERSION) == -1)
+ return;
+
+ /* Add _dialects dictionary */
+ dialects = PyDict_New();
+ if (dialects == NULL)
+ return;
+ if (PyModule_AddObject(module, "_dialects", dialects))
+ return;
+
+ /* Add quote styles into dictionary */
+ for (style = quote_styles; style->name; style++) {
+ if (PyModule_AddIntConstant(module, style->name,
+ style->style) == -1)
+ return;
+ }
+
+ /* Add the Dialect type */
+ Py_INCREF(&Dialect_Type);
+ if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type))
+ return;
+
+ /* Add the CSV exception object to the module. */
+ error_obj = PyErr_NewException("_csv.Error", NULL, NULL);
+ if (error_obj == NULL)
+ return;
+ PyModule_AddObject(module, "Error", error_obj);
}
diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c
index c62cec5..af4ff49 100644
--- a/Modules/_ctypes/_ctypes.c
+++ b/Modules/_ctypes/_ctypes.c
@@ -25,20 +25,20 @@
/*
-Name methods, members, getsets
+Name methods, members, getsets
==============================================================================
-StructType_Type __new__(), from_address(), __mul__(), from_param()
-UnionType_Type __new__(), from_address(), __mul__(), from_param()
-PointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type()
-ArrayType_Type __new__(), from_address(), __mul__(), from_param()
-SimpleType_Type __new__(), from_address(), __mul__(), from_param()
+StructType_Type __new__(), from_address(), __mul__(), from_param()
+UnionType_Type __new__(), from_address(), __mul__(), from_param()
+PointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type()
+ArrayType_Type __new__(), from_address(), __mul__(), from_param()
+SimpleType_Type __new__(), from_address(), __mul__(), from_param()
CData_Type
- Struct_Type __new__(), __init__()
- Pointer_Type __new__(), __init__(), _as_parameter_, contents
- Array_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__()
- Simple_Type __new__(), __init__(), _as_parameter_
+ Struct_Type __new__(), __init__()
+ Pointer_Type __new__(), __init__(), _as_parameter_, contents
+ Array_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__()
+ Simple_Type __new__(), __init__(), _as_parameter_
CField_Type
StgDict_Type
@@ -50,28 +50,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)
@@ -82,7 +82,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)
*/
@@ -103,7 +103,7 @@ bytes(cdata)
* CField_Type
*
*/
-
+
#define PY_SSIZE_T_CLEAN
#include "Python.h"
@@ -140,7 +140,7 @@ static PyObject *_unpickle;
char *conversion_mode_encoding = NULL;
char *conversion_mode_errors = NULL;
-
+
/****************************************************************/
#if (PY_VERSION_HEX < 0x02040000)
@@ -148,148 +148,148 @@ char *conversion_mode_errors = NULL;
static PyObject *
PyTuple_Pack(int n, ...)
{
- int i;
- PyObject *o;
- PyObject *result;
- PyObject **items;
- va_list vargs;
-
- va_start(vargs, n);
- result = PyTuple_New(n);
- if (result == NULL)
- return NULL;
- items = ((PyTupleObject *)result)->ob_item;
- for (i = 0; i < n; i++) {
- o = va_arg(vargs, PyObject *);
- Py_INCREF(o);
- items[i] = o;
- }
- va_end(vargs);
- return result;
+ int i;
+ PyObject *o;
+ PyObject *result;
+ PyObject **items;
+ va_list vargs;
+
+ va_start(vargs, n);
+ result = PyTuple_New(n);
+ if (result == NULL)
+ return NULL;
+ items = ((PyTupleObject *)result)->ob_item;
+ for (i = 0; i < n; i++) {
+ o = va_arg(vargs, PyObject *);
+ Py_INCREF(o);
+ items[i] = o;
+ }
+ va_end(vargs);
+ return result;
}
#endif
/****************************************************************/
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_compare */
- 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_compare */
+ 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;
}
/******************************************************************/
@@ -302,25 +302,25 @@ PyDict_GetItemProxy(PyObject *dict, PyObject *key)
char *
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;
}
/*
@@ -333,100 +333,100 @@ alloc_format_string(const char *prefix, const char *suffix)
static PyCArgObject *
StructUnionType_paramfunc(CDataObject *self)
{
- PyCArgObject *parg;
- StgDictObject *stgdict;
-
- parg = new_CArgObject();
- 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 = new_CArgObject();
+ 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 *)&StgDict_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 = 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 == StgDict_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 *)&StgDict_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 = 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 == StgDict_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 *
StructType_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[] =
@@ -435,16 +435,16 @@ static char from_address_doc[] =
static PyObject *
CDataType_from_address(PyObject *type, PyObject *value)
{
- void *buf;
- if (!PyInt_Check(value) && !PyLong_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "integer expected");
- return NULL;
- }
- buf = (void *)PyLong_AsVoidPtr(value);
- if (PyErr_Occurred())
- return NULL;
- return CData_AtAddress(type, buf);
+ void *buf;
+ if (!PyInt_Check(value) && !PyLong_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "integer expected");
+ return NULL;
+ }
+ buf = (void *)PyLong_AsVoidPtr(value);
+ if (PyErr_Occurred())
+ return NULL;
+ return CData_AtAddress(type, buf);
}
static char from_buffer_doc[] =
@@ -456,51 +456,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 = CData_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 = CData_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[] =
@@ -512,48 +512,48 @@ GenericCData_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, &buffer, &buffer_len))
- return NULL;
+ if (-1 == PyObject_AsReadBuffer(obj, &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 = GenericCData_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 = GenericCData_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[] =
@@ -562,55 +562,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 (!PyInt_Check(obj) && !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 (!PyInt_Check(obj) && !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 CData_AtAddress(type, address);
+ return CData_AtAddress(type, address);
}
static char from_param_doc[] =
@@ -619,213 +619,213 @@ 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,
+ if (length < 0)
+ return PyErr_Format(PyExc_ValueError,
#if (PY_VERSION_HEX < 0x02050000)
- "Array length must be >= 0, not %d",
+ "Array length must be >= 0, not %d",
#else
- "Array length must be >= 0, not %zd",
+ "Array length must be >= 0, not %zd",
#endif
- length);
- return CreateArrayType(self, length);
+ length);
+ return CreateArrayType(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
StructType_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 && PyString_Check(key) &&
- 0 == strcmp(PyString_AS_STRING(key), "_fields_"))
- return StructUnionType_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 && PyString_Check(key) &&
+ 0 == strcmp(PyString_AS_STRING(key), "_fields_"))
+ return StructUnionType_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 (PyString_Check(key) &&
- 0 == strcmp(PyString_AS_STRING(key), "_fields_"))
- return StructUnionType_update_stgdict(self, value, 0);
- return 0;
+ /* XXX Should we disallow deleting _fields_? */
+ if (-1 == PyObject_GenericSetAttr(self, key, value))
+ return -1;
+
+ if (PyString_Check(key) &&
+ 0 == strcmp(PyString_AS_STRING(key), "_fields_"))
+ return StructUnionType_update_stgdict(self, value, 0);
+ return 0;
}
PyTypeObject StructType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.StructType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 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 */
- StructType_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 */
- StructType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.StructType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 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 */
+ StructType_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 */
+ StructType_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_compare */
- 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_compare */
+ 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 */
};
-
+
/******************************************************************/
/*
@@ -845,124 +845,124 @@ size property/method, and the sequence protocol.
static int
PointerType_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 *
PointerType_paramfunc(CDataObject *self)
{
- PyCArgObject *parg;
-
- parg = new_CArgObject();
- 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 = new_CArgObject();
+ 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 *
PointerType_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 *)&StgDict_Type, NULL);
- if (!stgdict)
- return NULL;
- stgdict->size = sizeof(void *);
- stgdict->align = getentry("P")->pffi_type->alignment;
- stgdict->length = 1;
- stgdict->ffi_type_pointer = ffi_type_pointer;
- stgdict->paramfunc = PointerType_paramfunc;
- stgdict->flags |= TYPEFLAG_ISPOINTER;
-
- proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
- if (proto && -1 == PointerType_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 = 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 *)&StgDict_Type, NULL);
+ if (!stgdict)
+ return NULL;
+ stgdict->size = sizeof(void *);
+ stgdict->align = getentry("P")->pffi_type->alignment;
+ stgdict->length = 1;
+ stgdict->ffi_type_pointer = ffi_type_pointer;
+ stgdict->paramfunc = PointerType_paramfunc;
+ stgdict->flags |= TYPEFLAG_ISPOINTER;
+
+ proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
+ if (proto && -1 == PointerType_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 = 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 *
PointerType_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 == PointerType_SetProto(dict, type))
- return NULL;
+ if (-1 == PointerType_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;
}
staticforward PyObject *_byref(PyObject *);
@@ -970,98 +970,98 @@ staticforward PyObject *_byref(PyObject *);
static PyObject *
PointerType_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 PointerType_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)PointerType_from_param, METH_O, from_param_doc},
- { "set_type", (PyCFunction)PointerType_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)PointerType_from_param, METH_O, from_param_doc},
+ { "set_type", (PyCFunction)PointerType_set_type, METH_O },
+ { NULL, NULL },
};
PyTypeObject PointerType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.PointerType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 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 */
- PointerType_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 */
- PointerType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.PointerType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 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 */
+ PointerType_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 */
+ PointerType_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
ArrayType_Type
@@ -1074,149 +1074,149 @@ PyTypeObject PointerType_Type = {
static int
CharArray_set_raw(CDataObject *self, PyObject *value)
{
- char *ptr;
- Py_ssize_t size;
- if (PyBuffer_Check(value)) {
- size = Py_TYPE(value)->tp_as_buffer->bf_getreadbuffer(value, 0, (void *)&ptr);
- if (size < 0)
- return -1;
- } else if (-1 == PyString_AsStringAndSize(value, &ptr, &size)) {
- return -1;
- }
- if (size > self->b_size) {
- PyErr_SetString(PyExc_ValueError,
- "string too long");
- return -1;
- }
-
- memcpy(self->b_ptr, ptr, size);
-
- return 0;
+ char *ptr;
+ Py_ssize_t size;
+ if (PyBuffer_Check(value)) {
+ size = Py_TYPE(value)->tp_as_buffer->bf_getreadbuffer(value, 0, (void *)&ptr);
+ if (size < 0)
+ return -1;
+ } else if (-1 == PyString_AsStringAndSize(value, &ptr, &size)) {
+ return -1;
+ }
+ if (size > self->b_size) {
+ PyErr_SetString(PyExc_ValueError,
+ "string too long");
+ return -1;
+ }
+
+ memcpy(self->b_ptr, ptr, size);
+
+ return 0;
}
static PyObject *
CharArray_get_raw(CDataObject *self)
{
- return PyString_FromStringAndSize(self->b_ptr, self->b_size);
+ return PyString_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 PyString_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 PyString_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,
- conversion_mode_encoding,
- conversion_mode_errors);
- if (!value)
- return -1;
- } else if (!PyString_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "string expected instead of %s instance",
- Py_TYPE(value)->tp_name);
- return -1;
- } else
- Py_INCREF(value);
- size = PyString_GET_SIZE(value);
- if (size > self->b_size) {
- PyErr_SetString(PyExc_ValueError,
- "string too long");
- Py_DECREF(value);
- return -1;
- }
-
- ptr = PyString_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,
+ conversion_mode_encoding,
+ conversion_mode_errors);
+ if (!value)
+ return -1;
+ } else if (!PyString_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "string expected instead of %s instance",
+ Py_TYPE(value)->tp_name);
+ return -1;
+ } else
+ Py_INCREF(value);
+ size = PyString_GET_SIZE(value);
+ if (size > self->b_size) {
+ PyErr_SetString(PyExc_ValueError,
+ "string too long");
+ Py_DECREF(value);
+ return -1;
+ }
+
+ ptr = PyString_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 (PyString_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- conversion_mode_encoding,
- conversion_mode_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 (PyString_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ conversion_mode_encoding,
+ conversion_mode_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
@@ -1231,231 +1231,231 @@ 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 *
ArrayType_paramfunc(CDataObject *self)
{
- PyCArgObject *p = new_CArgObject();
- 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 = new_CArgObject();
+ 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 *
ArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyTypeObject *result;
- StgDictObject *stgdict;
- StgDictObject *itemdict;
- PyObject *proto;
- PyObject *typedict;
- long length;
-
- 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 || !PyInt_Check(proto)) {
- PyErr_SetString(PyExc_AttributeError,
- "class must define a '_length_' attribute, "
- "which must be a positive integer");
- return NULL;
- }
- length = PyInt_AS_LONG(proto);
-
- 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 *)&StgDict_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 = alloc_format_string(buf, itemdict->format+1);
- } else {
- sprintf(buf, "(%ld)", length);
- stgdict->format = 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 = &ArrayType_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 == getentry("c")->getfunc) {
- if (-1 == add_getset(result, CharArray_getsets))
- return NULL;
+ PyTypeObject *result;
+ StgDictObject *stgdict;
+ StgDictObject *itemdict;
+ PyObject *proto;
+ PyObject *typedict;
+ long length;
+
+ 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 || !PyInt_Check(proto)) {
+ PyErr_SetString(PyExc_AttributeError,
+ "class must define a '_length_' attribute, "
+ "which must be a positive integer");
+ return NULL;
+ }
+ length = PyInt_AS_LONG(proto);
+
+ 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 *)&StgDict_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 = alloc_format_string(buf, itemdict->format+1);
+ } else {
+ sprintf(buf, "(%ld)", length);
+ stgdict->format = 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 = &ArrayType_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 == getentry("c")->getfunc) {
+ if (-1 == add_getset(result, CharArray_getsets))
+ return NULL;
#ifdef CTYPES_UNICODE
- } else if (itemdict->getfunc == getentry("u")->getfunc) {
- if (-1 == add_getset(result, WCharArray_getsets))
- return NULL;
+ } else if (itemdict->getfunc == getentry("u")->getfunc) {
+ if (-1 == add_getset(result, WCharArray_getsets))
+ return NULL;
#endif
- }
+ }
- return (PyObject *)result;
+ return (PyObject *)result;
}
PyTypeObject ArrayType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.ArrayType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 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 */
- ArrayType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.ArrayType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 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 */
+ ArrayType_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
SimpleType_Type
@@ -1472,264 +1472,264 @@ static char *SIMPLE_TYPE_CHARS = "cbBhHiIlLdfuzZqQPXOv?g";
static PyObject *
c_wchar_p_from_param(PyObject *type, PyObject *value)
{
- PyObject *as_parameter;
+ PyObject *as_parameter;
#if (PYTHON_API_VERSION < 1012)
# error not supported
#endif
- if (value == Py_None) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (PyUnicode_Check(value) || PyString_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = getentry("Z");
-
- parg = new_CArgObject();
- 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 == getentry("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 == getentry("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;
+ if (value == Py_None) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (PyUnicode_Check(value) || PyString_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = getentry("Z");
+
+ parg = new_CArgObject();
+ 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 == getentry("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 == getentry("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;
+ PyObject *as_parameter;
#if (PYTHON_API_VERSION < 1012)
# error not supported
#endif
- if (value == Py_None) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (PyString_Check(value) || PyUnicode_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = getentry("z");
-
- parg = new_CArgObject();
- 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 == getentry("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 == getentry("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;
+ if (value == Py_None) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (PyString_Check(value) || PyUnicode_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = getentry("z");
+
+ parg = new_CArgObject();
+ 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 == getentry("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 == getentry("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;
#if (PYTHON_API_VERSION < 1012)
# error not supported
#endif
/* 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 (PyInt_Check(value) || PyLong_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = getentry("P");
-
- parg = new_CArgObject();
- 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;
- }
+ if (PyInt_Check(value) || PyLong_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = getentry("P");
+
+ parg = new_CArgObject();
+ 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;
+ }
/* string */
- if (PyString_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = getentry("z");
-
- parg = new_CArgObject();
- 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 (PyString_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = getentry("z");
+
+ parg = new_CArgObject();
+ 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 = getentry("Z");
-
- parg = new_CArgObject();
- 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 = getentry("Z");
+
+ parg = new_CArgObject();
+ 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 (CFuncPtrObject_Check(value)) {
- PyCArgObject *parg;
- CFuncPtrObject *func;
- func = (CFuncPtrObject *)value;
- parg = new_CArgObject();
- 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 (CFuncPtrObject_Check(value)) {
+ PyCArgObject *parg;
+ CFuncPtrObject *func;
+ func = (CFuncPtrObject *)value;
+ parg = new_CArgObject();
+ 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 && PyString_Check(stgd->proto)) {
- PyCArgObject *parg;
-
- switch (PyString_AS_STRING(stgd->proto)[0]) {
- case 'z': /* c_char_p */
- case 'Z': /* c_wchar_p */
- parg = new_CArgObject();
- 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 && PyString_Check(stgd->proto)) {
+ PyCArgObject *parg;
+
+ switch (PyString_AS_STRING(stgd->proto)[0]) {
+ case 'z': /* c_char_p */
+ case 'Z': /* c_wchar_p */
+ parg = new_CArgObject();
+ 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;
}
#if (PYTHON_API_VERSION >= 1012)
@@ -1746,291 +1746,291 @@ static PyMethodDef c_wchar_p_method = { "from_param", c_wchar_p_from_param, METH
#endif
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 *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 *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 = PyString_InternFromString("_le");
+ suffix = PyString_InternFromString("_le");
#else
- suffix = PyString_InternFromString("_be");
+ suffix = PyString_InternFromString("_be");
#endif
- Py_INCREF(name);
- PyString_Concat(&name, suffix);
- if (name == NULL)
- return NULL;
-
- PyTuple_SET_ITEM(swapped_args, 0, name);
- 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 *)&StgDict_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;
+ Py_INCREF(name);
+ PyString_Concat(&name, suffix);
+ if (name == NULL)
+ return NULL;
+
+ PyTuple_SET_ITEM(swapped_args, 0, name);
+ 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 *)&StgDict_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 *
SimpleType_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 = PyString_AsString(dict->proto);
- assert(fmt);
-
- fd = getentry(fmt);
- assert(fd);
-
- parg = new_CArgObject();
- 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 = PyString_AsString(dict->proto);
+ assert(fmt);
+
+ fd = getentry(fmt);
+ assert(fd);
+
+ parg = new_CArgObject();
+ 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 *
SimpleType_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 (PyString_Check(proto)) {
- proto_str = PyString_AS_STRING(proto);
- proto_len = PyString_GET_SIZE(proto);
- } 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 = getentry(PyString_AS_STRING(proto));
- if (fmt == NULL) {
- PyErr_Format(PyExc_ValueError,
- "_type_ '%s' not supported",
- PyString_AS_STRING(proto));
- goto error;
- }
-
- stgdict = (StgDictObject *)PyObject_CallObject(
- (PyObject *)&StgDict_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 (PyString_Check(proto)) {
+ proto_str = PyString_AS_STRING(proto);
+ proto_len = PyString_GET_SIZE(proto);
+ } 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 = getentry(PyString_AS_STRING(proto));
+ if (fmt == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "_type_ '%s' not supported",
+ PyString_AS_STRING(proto));
+ goto error;
+ }
+
+ stgdict = (StgDictObject *)PyObject_CallObject(
+ (PyObject *)&StgDict_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 = alloc_format_string(">", proto_str);
+ stgdict->format = alloc_format_string(">", proto_str);
#else
- stgdict->format = alloc_format_string("<", proto_str);
+ stgdict->format = alloc_format_string("<", proto_str);
#endif
- if (stgdict->format == NULL) {
- Py_DECREF(result);
- Py_DECREF(proto);
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
-
- stgdict->paramfunc = SimpleType_paramfunc;
+ if (stgdict->format == NULL) {
+ Py_DECREF(result);
+ Py_DECREF(proto);
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+
+ stgdict->paramfunc = SimpleType_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 SimpleType_from_param generic method.
- */
- if (result->tp_base == &Simple_Type) {
- switch (PyString_AS_STRING(proto)[0]) {
- 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) {
+ /* 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 SimpleType_from_param generic method.
+ */
+ if (result->tp_base == &Simple_Type) {
+ switch (PyString_AS_STRING(proto)[0]) {
+ 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) {
#if (PYTHON_API_VERSION >= 1012)
- PyObject *meth;
- int x;
- meth = PyDescr_NewClassMethod(result, ml);
- if (!meth)
- return NULL;
+ PyObject *meth;
+ int x;
+ meth = PyDescr_NewClassMethod(result, ml);
+ if (!meth)
+ return NULL;
#else
#error
- PyObject *meth, *func;
- int x;
- func = PyCFunction_New(ml, NULL);
- if (!func)
- return NULL;
- meth = PyObject_CallFunctionObjArgs(
- (PyObject *)&PyClassMethod_Type,
- func, NULL);
- Py_DECREF(func);
- if (!meth) {
- return NULL;
- }
+ PyObject *meth, *func;
+ int x;
+ func = PyCFunction_New(ml, NULL);
+ if (!func)
+ return NULL;
+ meth = PyObject_CallFunctionObjArgs(
+ (PyObject *)&PyClassMethod_Type,
+ func, NULL);
+ Py_DECREF(func);
+ if (!meth) {
+ return NULL;
+ }
#endif
- x = PyDict_SetItemString(result->tp_dict,
- ml->ml_name,
- meth);
- Py_DECREF(meth);
- if (x == -1) {
- Py_DECREF(result);
- return NULL;
- }
- }
- }
-
- if (type == &SimpleType_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);
+ x = PyDict_SetItemString(result->tp_dict,
+ ml->ml_name,
+ meth);
+ Py_DECREF(meth);
+ if (x == -1) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ }
+
+ if (type == &SimpleType_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 = 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 = 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 = 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 = 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;
}
/*
@@ -2040,101 +2040,101 @@ SimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject *
SimpleType_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 = PyString_AsString(dict->proto);
- assert(fmt);
-
- fd = getentry(fmt);
- assert(fd);
-
- parg = new_CArgObject();
- 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 = SimpleType_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 = PyString_AsString(dict->proto);
+ assert(fmt);
+
+ fd = getentry(fmt);
+ assert(fd);
+
+ parg = new_CArgObject();
+ 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 = SimpleType_from_param(type, as_parameter);
+ Py_DECREF(as_parameter);
+ return value;
+ }
+ PyErr_SetString(PyExc_TypeError,
+ "wrong type");
+ return NULL;
}
static PyMethodDef SimpleType_methods[] = {
- { "from_param", SimpleType_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", SimpleType_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 SimpleType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.SimpleType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 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 SimpleType Objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- SimpleType_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 */
- SimpleType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.SimpleType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 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 SimpleType Objects", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ SimpleType_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 */
+ SimpleType_new, /* tp_new */
+ 0, /* tp_free */
};
/******************************************************************/
@@ -2145,221 +2145,221 @@ PyTypeObject SimpleType_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,
+ Py_XDECREF(converters);
+ Py_DECREF(ob);
+ PyErr_Format(PyExc_TypeError,
#if (PY_VERSION_HEX < 0x02050000)
- "item %d in _argtypes_ has no from_param method",
+ "item %d in _argtypes_ has no from_param method",
#else
- "item %zd in _argtypes_ has no from_param method",
+ "item %zd in _argtypes_ has no from_param method",
#endif
- i+1);
- return NULL;
+ i+1);
+ return NULL;
}
static int
make_funcptrtype_dict(StgDictObject *stgdict)
{
- PyObject *ob;
- PyObject *converters = NULL;
-
- stgdict->align = getentry("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 || !PyInt_Check(ob)) {
- PyErr_SetString(PyExc_TypeError,
- "class must define _flags_ which must be an integer");
- return -1;
- }
- stgdict->flags = PyInt_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 = getentry("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 || !PyInt_Check(ob)) {
+ PyErr_SetString(PyExc_TypeError,
+ "class must define _flags_ which must be an integer");
+ return -1;
+ }
+ stgdict->flags = PyInt_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 *
CFuncPtrType_paramfunc(CDataObject *self)
{
- PyCArgObject *parg;
-
- parg = new_CArgObject();
- 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 = new_CArgObject();
+ 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 *
CFuncPtrType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyTypeObject *result;
- StgDictObject *stgdict;
-
- stgdict = (StgDictObject *)PyObject_CallObject(
- (PyObject *)&StgDict_Type, NULL);
- if (!stgdict)
- return NULL;
-
- stgdict->paramfunc = CFuncPtrType_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 = 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 *)&StgDict_Type, NULL);
+ if (!stgdict)
+ return NULL;
+
+ stgdict->paramfunc = CFuncPtrType_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 = 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 CFuncPtrType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.CFuncPtrType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 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 */
- CFuncPtrType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.CFuncPtrType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 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 */
+ CFuncPtrType_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/*****************************************************************
* Code to keep needed objects alive
*/
@@ -2367,54 +2367,54 @@ PyTypeObject CFuncPtrType_Type = {
static CDataObject *
CData_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 CData_GetContainer(target)->b_objects;
+ return CData_GetContainer(target)->b_objects;
}
static PyObject *
unique_key(CDataObject *target, Py_ssize_t index)
{
- char string[256];
- char *cp = string;
- size_t bytes_left;
+ char string[256];
+ char *cp = string;
+ size_t bytes_left;
- assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2);
+ assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2);
#if (PY_VERSION_HEX < 0x02050000)
- cp += sprintf(cp, "%x", index);
+ cp += sprintf(cp, "%x", index);
#else
- cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
+ cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
#endif
- 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;
- }
+ 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;
+ }
#if (PY_VERSION_HEX < 0x02050000)
- cp += sprintf(cp, ":%x", (int)target->b_index);
+ cp += sprintf(cp, ":%x", (int)target->b_index);
#else
- cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int));
+ cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int));
#endif
- target = target->b_base;
- }
- return PyString_FromStringAndSize(string, cp-string);
+ target = target->b_base;
+ }
+ return PyString_FromStringAndSize(string, cp-string);
}
/*
@@ -2438,30 +2438,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 = CData_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 = CData_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;
}
/******************************************************************/
@@ -2471,100 +2471,100 @@ KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep)
static int
CData_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
CData_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
CData_dealloc(PyObject *self)
{
- CData_clear((CDataObject *)self);
- Py_TYPE(self)->tp_free(self);
+ CData_clear((CDataObject *)self);
+ Py_TYPE(self)->tp_free(self);
}
static PyMemberDef CData_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 },
};
#if (PY_VERSION_HEX >= 0x02060000)
static int CData_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;
}
#endif
static Py_ssize_t CData_GetSegcount(PyObject *_self, Py_ssize_t *lenp)
{
- if (lenp)
- *lenp = 1;
- return 1;
+ if (lenp)
+ *lenp = 1;
+ return 1;
}
static Py_ssize_t CData_GetBuffer(PyObject *_self, Py_ssize_t seg, void **pptr)
{
- CDataObject *self = (CDataObject *)_self;
- if (seg != 0) {
- /* Hm. Must this set an exception? */
- return -1;
- }
- *pptr = self->b_ptr;
- return self->b_size;
+ CDataObject *self = (CDataObject *)_self;
+ if (seg != 0) {
+ /* Hm. Must this set an exception? */
+ return -1;
+ }
+ *pptr = self->b_ptr;
+ return self->b_size;
}
static PyBufferProcs CData_as_buffer = {
- (readbufferproc)CData_GetBuffer,
- (writebufferproc)CData_GetBuffer,
- (segcountproc)CData_GetSegcount,
- (charbufferproc)NULL,
+ (readbufferproc)CData_GetBuffer,
+ (writebufferproc)CData_GetBuffer,
+ (segcountproc)CData_GetSegcount,
+ (charbufferproc)NULL,
#if (PY_VERSION_HEX >= 0x02060000)
- (getbufferproc)CData_NewGetBuffer,
- (releasebufferproc)NULL,
+ (getbufferproc)CData_NewGetBuffer,
+ (releasebufferproc)NULL,
#endif
};
@@ -2574,47 +2574,47 @@ static PyBufferProcs CData_as_buffer = {
static long
CData_nohash(PyObject *self)
{
- PyErr_SetString(PyExc_TypeError, "unhashable type");
- return -1;
+ PyErr_SetString(PyExc_TypeError, "unhashable type");
+ return -1;
}
static PyObject *
CData_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__"),
- PyString_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__"),
+ PyString_FromStringAndSize(self->b_ptr, self->b_size));
}
static PyObject *
CData_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;
}
/*
@@ -2623,124 +2623,124 @@ CData_setstate(PyObject *_self, PyObject *args)
static PyObject *
CData_from_outparam(PyObject *self, PyObject *args)
{
- Py_INCREF(self);
- return self;
+ Py_INCREF(self);
+ return self;
}
static PyMethodDef CData_methods[] = {
- { "__ctypes_from_outparam__", CData_from_outparam, METH_NOARGS, },
- { "__reduce__", CData_reduce, METH_NOARGS, },
- { "__setstate__", CData_setstate, METH_VARARGS, },
- { NULL, NULL },
+ { "__ctypes_from_outparam__", CData_from_outparam, METH_NOARGS, },
+ { "__reduce__", CData_reduce, METH_NOARGS, },
+ { "__setstate__", CData_setstate, METH_VARARGS, },
+ { NULL, NULL },
};
PyTypeObject CData_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes._CData",
- sizeof(CDataObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- CData_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- CData_nohash, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &CData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "XXX to be provided", /* tp_doc */
- (traverseproc)CData_traverse, /* tp_traverse */
- (inquiry)CData_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- CData_methods, /* tp_methods */
- CData_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 */
+ CData_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ CData_nohash, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &CData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "XXX to be provided", /* tp_doc */
+ (traverseproc)CData_traverse, /* tp_traverse */
+ (inquiry)CData_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ CData_methods, /* tp_methods */
+ CData_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 CData_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 *
CData_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 == CData_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 == CData_MallocBuffer(cmem, dict)) {
+ return NULL;
+ Py_DECREF(cmem);
+ }
+ memcpy(cmem->b_ptr, adr, dict->size);
+ cmem->b_index = index;
+ }
+ return (PyObject *)cmem;
}
/*
@@ -2749,26 +2749,26 @@ CData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr)
PyObject *
CData_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;
}
/*
@@ -2778,25 +2778,25 @@ CData_AtAddress(PyObject *type, void *buf)
*/
int IsSimpleSubType(PyObject *obj)
{
- PyTypeObject *type = (PyTypeObject *)obj;
+ PyTypeObject *type = (PyTypeObject *)obj;
- if (SimpleTypeObject_Check(type))
- return type->tp_base != &Simple_Type;
- return 0;
+ if (SimpleTypeObject_Check(type))
+ return type->tp_base != &Simple_Type;
+ return 0;
}
PyObject *
CData_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 && !IsSimpleSubType(type))
- return dict->getfunc(adr, size);
- return CData_FromBaseObj(type, src, index, adr);
+ StgDictObject *dict;
+ if (getfunc)
+ return getfunc(adr, size);
+ assert(type);
+ dict = PyType_stgdict(type);
+ if (dict && dict->getfunc && !IsSimpleSubType(type))
+ return dict->getfunc(adr, size);
+ return CData_FromBaseObj(type, src, index, adr);
}
/*
@@ -2804,96 +2804,96 @@ CData_get(PyObject *type, GETFUNC getfunc, PyObject *src,
*/
static PyObject *
_CData_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) {
- Extend_Error_Info(PyExc_RuntimeError, "(%s) ",
- ((PyTypeObject *)type)->tp_name);
- return NULL;
- }
- result = _CData_set(dst, type, setfunc, ob,
- size, ptr);
- Py_DECREF(ob);
- return result;
- } else if (value == Py_None && PointerTypeObject_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 (PointerTypeObject_Check(type))
- /* XXX */;
-
- value = GetKeepedObjects(src);
- Py_INCREF(value);
- return value;
- }
-
- if (PointerTypeObject_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) {
+ Extend_Error_Info(PyExc_RuntimeError, "(%s) ",
+ ((PyTypeObject *)type)->tp_name);
+ return NULL;
+ }
+ result = _CData_set(dst, type, setfunc, ob,
+ size, ptr);
+ Py_DECREF(ob);
+ return result;
+ } else if (value == Py_None && PointerTypeObject_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 (PointerTypeObject_Check(type))
+ /* XXX */;
+
+ value = GetKeepedObjects(src);
+ Py_INCREF(value);
+ return value;
+ }
+
+ if (PointerTypeObject_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;
}
/*
@@ -2902,58 +2902,58 @@ _CData_set(CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
*/
int
CData_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 = _CData_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 = _CData_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 *
GenericCData_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 == CData_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 == CData_MallocBuffer(obj, dict)) {
+ Py_DECREF(obj);
+ return NULL;
+ }
+ return (PyObject *)obj;
}
/*****************************************************************/
/*
@@ -2963,165 +2963,165 @@ GenericCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static int
CFuncPtr_set_errcheck(CFuncPtrObject *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 *
CFuncPtr_get_errcheck(CFuncPtrObject *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
CFuncPtr_set_restype(CFuncPtrObject *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 *
CFuncPtr_get_restype(CFuncPtrObject *self)
{
- StgDictObject *dict;
- if (self->restype) {
- Py_INCREF(self->restype);
- return self->restype;
- }
- dict = PyObject_stgdict((PyObject *)self);
- assert(dict); /* Cannot be NULL for CFuncPtrObject 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 CFuncPtrObject instances */
+ if (dict->restype) {
+ Py_INCREF(dict->restype);
+ return dict->restype;
+ } else {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
static int
CFuncPtr_set_argtypes(CFuncPtrObject *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 *
CFuncPtr_get_argtypes(CFuncPtrObject *self)
{
- StgDictObject *dict;
- if (self->argtypes) {
- Py_INCREF(self->argtypes);
- return self->argtypes;
- }
- dict = PyObject_stgdict((PyObject *)self);
- assert(dict); /* Cannot be NULL for CFuncPtrObject 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 CFuncPtrObject instances */
+ if (dict->argtypes) {
+ Py_INCREF(dict->argtypes);
+ return dict->argtypes;
+ } else {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
static PyGetSetDef CFuncPtr_getsets[] = {
- { "errcheck", (getter)CFuncPtr_get_errcheck, (setter)CFuncPtr_set_errcheck,
- "a function to check for errors", NULL },
- { "restype", (getter)CFuncPtr_get_restype, (setter)CFuncPtr_set_restype,
- "specify the result type", NULL },
- { "argtypes", (getter)CFuncPtr_get_argtypes,
- (setter)CFuncPtr_set_argtypes,
- "specify the argument types", NULL },
- { NULL, NULL }
+ { "errcheck", (getter)CFuncPtr_get_errcheck, (setter)CFuncPtr_set_errcheck,
+ "a function to check for errors", NULL },
+ { "restype", (getter)CFuncPtr_get_restype, (setter)CFuncPtr_set_restype,
+ "specify the result type", NULL },
+ { "argtypes", (getter)CFuncPtr_get_argtypes,
+ (setter)CFuncPtr_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
@@ -3130,223 +3130,223 @@ 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 (PointerTypeObject_Check(arg))
- return 1;
+ if (PointerTypeObject_Check(arg))
+ return 1;
- if (ArrayTypeObject_Check(arg))
- return 1;
+ if (ArrayTypeObject_Check(arg))
+ return 1;
- dict = PyType_stgdict(arg);
- if (dict
- /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
- && PyString_Check(dict->proto)
+ dict = PyType_stgdict(arg);
+ if (dict
+ /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
+ && PyString_Check(dict->proto)
/* We only allow c_void_p, c_char_p and c_wchar_p as a simple output parameter type */
- && (strchr("PzZ", PyString_AS_STRING(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", PyString_AS_STRING(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 CFuncPtr 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 CFuncPtr 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 (PyInt_Check(obj) || PyLong_Check(obj)) {
- /* We have to use MAKEINTRESOURCEA for Windows CE.
- Works on Windows as well, of course.
- */
- *pname = MAKEINTRESOURCEA(PyInt_AsUnsignedLongMask(obj) & 0xFFFF);
- return 1;
- }
+ if (PyInt_Check(obj) || PyLong_Check(obj)) {
+ /* We have to use MAKEINTRESOURCEA for Windows CE.
+ Works on Windows as well, of course.
+ */
+ *pname = MAKEINTRESOURCEA(PyInt_AsUnsignedLongMask(obj) & 0xFFFF);
+ return 1;
+ }
#endif
- if (PyString_Check(obj) || PyUnicode_Check(obj)) {
- *pname = PyString_AsString(obj);
- return *pname ? 1 : 0;
- }
- PyErr_SetString(PyExc_TypeError,
- "function name must be string or integer");
- return 0;
+ if (PyString_Check(obj) || PyUnicode_Check(obj)) {
+ *pname = PyString_AsString(obj);
+ return *pname ? 1 : 0;
+ }
+ PyErr_SetString(PyExc_TypeError,
+ "function name must be string or integer");
+ return 0;
}
static PyObject *
CFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- char *name;
- int (* address)(void);
- PyObject *dll;
- PyObject *obj;
- CFuncPtrObject *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 (!PyInt_Check(obj) && !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;
+ CFuncPtrObject *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 (!PyInt_Check(obj) && !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 = (CFuncPtrObject *)GenericCData_new(type, args, kwds);
- if (!self)
- return NULL;
+ self = (CFuncPtrObject *)GenericCData_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 *
CFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- CFuncPtrObject *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 = (CFuncPtrObject *)GenericCData_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;
+ CFuncPtrObject *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 = (CFuncPtrObject *)GenericCData_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
@@ -3366,91 +3366,91 @@ CFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject *
CFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- CFuncPtrObject *self;
- PyObject *callable;
- StgDictObject *dict;
- CThunkObject *thunk;
+ CFuncPtrObject *self;
+ PyObject *callable;
+ StgDictObject *dict;
+ CThunkObject *thunk;
- if (PyTuple_GET_SIZE(args) == 0)
- return GenericCData_new(type, args, kwds);
+ if (PyTuple_GET_SIZE(args) == 0)
+ return GenericCData_new(type, args, kwds);
- if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0)))
- return CFuncPtr_FromDll(type, args, kwds);
+ if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0)))
+ return CFuncPtr_FromDll(type, args, kwds);
#ifdef MS_WIN32
- if (2 <= PyTuple_GET_SIZE(args) && PyInt_Check(PyTuple_GET_ITEM(args, 0)))
- return CFuncPtr_FromVtblIndex(type, args, kwds);
+ if (2 <= PyTuple_GET_SIZE(args) && PyInt_Check(PyTuple_GET_ITEM(args, 0)))
+ return CFuncPtr_FromVtblIndex(type, args, kwds);
#endif
- if (1 == PyTuple_GET_SIZE(args)
- && (PyInt_Check(PyTuple_GET_ITEM(args, 0))
- || 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 *)GenericCData_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)
+ && (PyInt_Check(PyTuple_GET_ITEM(args, 0))
+ || 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 *)GenericCData_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: 'CFuncPtr(lambda x: x)' */
- if (!dict || !dict->argtypes) {
- PyErr_SetString(PyExc_TypeError,
- "cannot construct instance of this class:"
- " no argtypes");
- return NULL;
- }
-
- thunk = AllocFunctionCallback(callable,
- dict->argtypes,
- dict->restype,
- dict->flags);
- if (!thunk)
- return NULL;
-
- self = (CFuncPtrObject *)GenericCData_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: 'CFuncPtr(lambda x: x)' */
+ if (!dict || !dict->argtypes) {
+ PyErr_SetString(PyExc_TypeError,
+ "cannot construct instance of this class:"
+ " no argtypes");
+ return NULL;
+ }
+
+ thunk = AllocFunctionCallback(callable,
+ dict->argtypes,
+ dict->restype,
+ dict->flags);
+ if (!thunk)
+ return NULL;
+
+ self = (CFuncPtrObject *)GenericCData_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;
}
@@ -3460,54 +3460,54 @@ CFuncPtr_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 = new_CArgObject();
- 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 = new_CArgObject();
+ 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, char *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_GetItemString(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_GetItemString(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;
}
/*
@@ -3530,170 +3530,170 @@ _get_arg(int *pindex, char *name, PyObject *defval, PyObject *inargs, PyObject *
*/
static PyObject *
_build_callargs(CFuncPtrObject *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;
- char *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 = PyInt_AS_LONG(PyTuple_GET_ITEM(item, 0));
- name = tsize > 1 ? PyString_AS_STRING(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 = PyInt_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 (PyString_Check(dict->proto)) {
- PyErr_Format(
- PyExc_TypeError,
- "%s 'out' parameter must be passed as default value",
- ((PyTypeObject *)ob)->tp_name);
- goto error;
- }
- if (ArrayTypeObject_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,
+ for (i = 0; i < len; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(paramflags, i);
+ PyObject *ob;
+ int flag;
+ char *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 = PyInt_AS_LONG(PyTuple_GET_ITEM(item, 0));
+ name = tsize > 1 ? PyString_AS_STRING(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 = PyInt_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 (PyString_Check(dict->proto)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "%s 'out' parameter must be passed as default value",
+ ((PyTypeObject *)ob)->tp_name);
+ goto error;
+ }
+ if (ArrayTypeObject_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,
#if (PY_VERSION_HEX < 0x02050000)
- "call takes exactly %d arguments (%d given)",
+ "call takes exactly %d arguments (%d given)",
#else
- "call takes exactly %d arguments (%zd given)",
+ "call takes exactly %d arguments (%zd given)",
#endif
- inargs_index, actual_args);
- goto error;
- }
-
- /* outmask is a bitmask containing indexes into callargs. Items at
- these indexes contain values to return.
- */
- return callargs;
+ 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:
@@ -3706,308 +3706,308 @@ _build_callargs(CFuncPtrObject *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 *
CFuncPtr_call(CFuncPtrObject *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 CFuncPtrObject 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 CFuncPtrObject 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 = _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 = _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
CFuncPtr_traverse(CFuncPtrObject *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 CData_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 CData_traverse((CDataObject *)self, visit, arg);
}
static int
CFuncPtr_clear(CFuncPtrObject *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 CData_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 CData_clear((CDataObject *)self);
}
static void
CFuncPtr_dealloc(CFuncPtrObject *self)
{
- CFuncPtr_clear(self);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ CFuncPtr_clear(self);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
CFuncPtr_repr(CFuncPtrObject *self)
{
#ifdef MS_WIN32
- if (self->index)
- return PyString_FromFormat("<COM method offset %d: %s at %p>",
- self->index - 0x1000,
- Py_TYPE(self)->tp_name,
- self);
+ if (self->index)
+ return PyString_FromFormat("<COM method offset %d: %s at %p>",
+ self->index - 0x1000,
+ Py_TYPE(self)->tp_name,
+ self);
#endif
- return PyString_FromFormat("<%s object at %p>",
- Py_TYPE(self)->tp_name,
- self);
+ return PyString_FromFormat("<%s object at %p>",
+ Py_TYPE(self)->tp_name,
+ self);
}
static int
CFuncPtr_nonzero(CFuncPtrObject *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 CFuncPtr_as_number = {
- 0, /* nb_add */
- 0, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- (inquiry)CFuncPtr_nonzero, /* nb_nonzero */
+ 0, /* nb_add */
+ 0, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ (inquiry)CFuncPtr_nonzero, /* nb_nonzero */
};
PyTypeObject CFuncPtr_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.CFuncPtr",
- sizeof(CFuncPtrObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)CFuncPtr_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)CFuncPtr_repr, /* tp_repr */
- &CFuncPtr_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- (ternaryfunc)CFuncPtr_call, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &CData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "Function Pointer", /* tp_doc */
- (traverseproc)CFuncPtr_traverse, /* tp_traverse */
- (inquiry)CFuncPtr_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- CFuncPtr_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 */
- CFuncPtr_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.CFuncPtr",
+ sizeof(CFuncPtrObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)CFuncPtr_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)CFuncPtr_repr, /* tp_repr */
+ &CFuncPtr_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ (ternaryfunc)CFuncPtr_call, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &CData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "Function Pointer", /* tp_doc */
+ (traverseproc)CFuncPtr_traverse, /* tp_traverse */
+ (inquiry)CFuncPtr_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ CFuncPtr_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 */
+ CFuncPtr_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/*****************************************************************/
/*
Struct_Type
@@ -4022,61 +4022,61 @@ PyTypeObject CFuncPtr_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 = PyString_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 = PyString_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
@@ -4085,119 +4085,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_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &CData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "Structure base class", /* tp_doc */
- (traverseproc)CData_traverse, /* tp_traverse */
- (inquiry)CData_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 */
- GenericCData_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_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &CData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "Structure base class", /* tp_doc */
+ (traverseproc)CData_traverse, /* tp_traverse */
+ (inquiry)CData_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 */
+ GenericCData_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_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &CData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "Union base class", /* tp_doc */
- (traverseproc)CData_traverse, /* tp_traverse */
- (inquiry)CData_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 */
- GenericCData_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_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &CData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "Union base class", /* tp_doc */
+ (traverseproc)CData_traverse, /* tp_traverse */
+ (inquiry)CData_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 */
+ GenericCData_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
Array_Type
@@ -4205,463 +4205,463 @@ 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 CData_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 CData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self,
+ index, size, self->b_ptr + offset);
}
static PyObject *
Array_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh)
{
- CDataObject *self = (CDataObject *)_self;
- StgDictObject *stgdict, *itemdict;
- PyObject *proto;
- PyListObject *np;
- Py_ssize_t i, len;
-
- if (ilow < 0)
- ilow = 0;
- else if (ilow > self->b_length)
- ilow = self->b_length;
- if (ihigh < ilow)
- ihigh = ilow;
- else if (ihigh > self->b_length)
- ihigh = self->b_length;
- len = ihigh - ilow;
-
- 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 == getentry("c")->getfunc) {
- char *ptr = (char *)self->b_ptr;
- return PyString_FromStringAndSize(ptr + ilow, len);
+ CDataObject *self = (CDataObject *)_self;
+ StgDictObject *stgdict, *itemdict;
+ PyObject *proto;
+ PyListObject *np;
+ Py_ssize_t i, len;
+
+ if (ilow < 0)
+ ilow = 0;
+ else if (ilow > self->b_length)
+ ilow = self->b_length;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if (ihigh > self->b_length)
+ ihigh = self->b_length;
+ len = ihigh - ilow;
+
+ 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 == getentry("c")->getfunc) {
+ char *ptr = (char *)self->b_ptr;
+ return PyString_FromStringAndSize(ptr + ilow, len);
#ifdef CTYPES_UNICODE
- } else if (itemdict->getfunc == getentry("u")->getfunc) {
- wchar_t *ptr = (wchar_t *)self->b_ptr;
- return PyUnicode_FromWideChar(ptr + ilow, len);
+ } else if (itemdict->getfunc == getentry("u")->getfunc) {
+ wchar_t *ptr = (wchar_t *)self->b_ptr;
+ return PyUnicode_FromWideChar(ptr + ilow, len);
#endif
- }
+ }
- np = (PyListObject *) PyList_New(len);
- if (np == NULL)
- return NULL;
+ np = (PyListObject *) PyList_New(len);
+ if (np == NULL)
+ return NULL;
- for (i = 0; i < len; i++) {
- PyObject *v = Array_item(_self, i+ilow);
- PyList_SET_ITEM(np, i, v);
- }
- return (PyObject *)np;
+ for (i = 0; i < len; i++) {
+ PyObject *v = Array_item(_self, i+ilow);
+ PyList_SET_ITEM(np, i, v);
+ }
+ return (PyObject *)np;
}
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 == getentry("c")->getfunc) {
- char *ptr = (char *)self->b_ptr;
- char *dest;
-
- if (slicelen <= 0)
- return PyString_FromString("");
- if (step == 1) {
- return PyString_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 = PyString_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 == getentry("c")->getfunc) {
+ char *ptr = (char *)self->b_ptr;
+ char *dest;
+
+ if (slicelen <= 0)
+ return PyString_FromString("");
+ if (step == 1) {
+ return PyString_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 = PyString_FromStringAndSize(dest, slicelen);
+ PyMem_Free(dest);
+ return np;
+ }
#ifdef CTYPES_UNICODE
- if (itemdict->getfunc == getentry("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 == getentry("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 CData_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 CData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value,
+ index, size, ptr);
}
static int
Array_ass_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *value)
{
- CDataObject *self = (CDataObject *)_self;
- Py_ssize_t i, len;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "Array does not support item deletion");
- return -1;
- }
-
- if (ilow < 0)
- ilow = 0;
- else if (ilow > self->b_length)
- ilow = self->b_length;
- if (ihigh < 0)
- ihigh = 0;
- if (ihigh < ilow)
- ihigh = ilow;
- else if (ihigh > self->b_length)
- ihigh = self->b_length;
-
- len = PySequence_Length(value);
- if (len != ihigh - ilow) {
- PyErr_SetString(PyExc_ValueError,
- "Can only assign sequence of same size");
- return -1;
- }
- for (i = 0; i < len; i++) {
- PyObject *item = PySequence_GetItem(value, i);
- int result;
- if (item == NULL)
- return -1;
- result = Array_ass_item(_self, i+ilow, item);
- Py_DECREF(item);
- if (result == -1)
- return -1;
- }
- return 0;
+ CDataObject *self = (CDataObject *)_self;
+ Py_ssize_t i, len;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "Array does not support item deletion");
+ return -1;
+ }
+
+ if (ilow < 0)
+ ilow = 0;
+ else if (ilow > self->b_length)
+ ilow = self->b_length;
+ if (ihigh < 0)
+ ihigh = 0;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if (ihigh > self->b_length)
+ ihigh = self->b_length;
+
+ len = PySequence_Length(value);
+ if (len != ihigh - ilow) {
+ PyErr_SetString(PyExc_ValueError,
+ "Can only assign sequence of same size");
+ return -1;
+ }
+ for (i = 0; i < len; i++) {
+ PyObject *item = PySequence_GetItem(value, i);
+ int result;
+ if (item == NULL)
+ return -1;
+ result = Array_ass_item(_self, i+ilow, item);
+ Py_DECREF(item);
+ if (result == -1)
+ return -1;
+ }
+ return 0;
}
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; */
- Array_slice, /* sq_slice; */
- Array_ass_item, /* sq_ass_item; */
- Array_ass_slice, /* 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; */
+ Array_slice, /* sq_slice; */
+ Array_ass_item, /* sq_ass_item; */
+ Array_ass_slice, /* 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 Array_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_compare */
- 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 */
- &CData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "XXX to be provided", /* tp_doc */
- (traverseproc)CData_traverse, /* tp_traverse */
- (inquiry)CData_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 */
- GenericCData_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_compare */
+ 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 */
+ &CData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "XXX to be provided", /* tp_doc */
+ (traverseproc)CData_traverse, /* tp_traverse */
+ (inquiry)CData_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 */
+ GenericCData_new, /* tp_new */
+ 0, /* tp_free */
};
PyObject *
CreateArrayType(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 = PyInt_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 = PyInt_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 *)&ArrayType_Type,
+ result = PyObject_CallFunction((PyObject *)&ArrayType_Type,
#if (PY_VERSION_HEX < 0x02050000)
- "s(O){s:i,s:O}",
+ "s(O){s:i,s:O}",
#else
- "s(O){s:n,s:O}",
+ "s(O){s:n,s:O}",
#endif
- name,
- &Array_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;
+ name,
+ &Array_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
@@ -4670,167 +4670,167 @@ CreateArrayType(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 (IsSimpleSubType((PyObject *)Py_TYPE(self))) {
- Py_INCREF(self);
- return self;
- }
- /* call stgdict->getfunc */
- return Simple_get_value((CDataObject *)self);
+ if (IsSimpleSubType((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_nonzero(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_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- (inquiry)Simple_nonzero, /* nb_nonzero */
+ 0, /* nb_add */
+ 0, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ (inquiry)Simple_nonzero, /* nb_nonzero */
};
/* "%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 PyString_FromFormat("<%s object at %p>",
- Py_TYPE(self)->tp_name, self);
- }
-
- if (format == NULL) {
- format = PyString_InternFromString("%s(%r)");
- if (format == NULL)
- return NULL;
- }
-
- val = Simple_get_value(self);
- if (val == NULL)
- return NULL;
-
- name = PyString_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 = PyString_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 PyString_FromFormat("<%s object at %p>",
+ Py_TYPE(self)->tp_name, self);
+ }
+
+ if (format == NULL) {
+ format = PyString_InternFromString("%s(%r)");
+ if (format == NULL)
+ return NULL;
+ }
+
+ val = Simple_get_value(self);
+ if (val == NULL)
+ return NULL;
+
+ name = PyString_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 = PyString_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_compare */
- (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 */
- &CData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "XXX to be provided", /* tp_doc */
- (traverseproc)CData_traverse, /* tp_traverse */
- (inquiry)CData_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 */
- GenericCData_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_compare */
+ (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 */
+ &CData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "XXX to be provided", /* tp_doc */
+ (traverseproc)CData_traverse, /* tp_traverse */
+ (inquiry)CData_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 */
+ GenericCData_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
Pointer_Type
@@ -4838,420 +4838,420 @@ 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 CData_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 CData_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 CData_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 CData_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 CData_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 CData_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 GenericCData_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 GenericCData_new(type, args, kw);
}
static PyObject *
Pointer_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh)
{
- CDataObject *self = (CDataObject *)_self;
- PyListObject *np;
- StgDictObject *stgdict, *itemdict;
- PyObject *proto;
- Py_ssize_t i, len;
-
- if (ilow < 0)
- ilow = 0;
- if (ihigh < ilow)
- ihigh = ilow;
- len = ihigh - ilow;
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL fr pointer instances */
- proto = stgdict->proto;
- assert(proto);
- itemdict = PyType_stgdict(proto);
- assert(itemdict);
- if (itemdict->getfunc == getentry("c")->getfunc) {
- char *ptr = *(char **)self->b_ptr;
- return PyString_FromStringAndSize(ptr + ilow, len);
+ CDataObject *self = (CDataObject *)_self;
+ PyListObject *np;
+ StgDictObject *stgdict, *itemdict;
+ PyObject *proto;
+ Py_ssize_t i, len;
+
+ if (ilow < 0)
+ ilow = 0;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ len = ihigh - ilow;
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL fr pointer instances */
+ proto = stgdict->proto;
+ assert(proto);
+ itemdict = PyType_stgdict(proto);
+ assert(itemdict);
+ if (itemdict->getfunc == getentry("c")->getfunc) {
+ char *ptr = *(char **)self->b_ptr;
+ return PyString_FromStringAndSize(ptr + ilow, len);
#ifdef CTYPES_UNICODE
- } else if (itemdict->getfunc == getentry("u")->getfunc) {
- wchar_t *ptr = *(wchar_t **)self->b_ptr;
- return PyUnicode_FromWideChar(ptr + ilow, len);
+ } else if (itemdict->getfunc == getentry("u")->getfunc) {
+ wchar_t *ptr = *(wchar_t **)self->b_ptr;
+ return PyUnicode_FromWideChar(ptr + ilow, len);
#endif
- }
+ }
- np = (PyListObject *) PyList_New(len);
- if (np == NULL)
- return NULL;
+ np = (PyListObject *) PyList_New(len);
+ if (np == NULL)
+ return NULL;
- for (i = 0; i < len; i++) {
- PyObject *v = Pointer_item(_self, i+ilow);
- PyList_SET_ITEM(np, i, v);
- }
- return (PyObject *)np;
+ for (i = 0; i < len; i++) {
+ PyObject *v = Pointer_item(_self, i+ilow);
+ PyList_SET_ITEM(np, i, v);
+ }
+ return (PyObject *)np;
}
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 == getentry("c")->getfunc) {
- char *ptr = *(char **)self->b_ptr;
- char *dest;
-
- if (len <= 0)
- return PyString_FromString("");
- if (step == 1) {
- return PyString_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 = PyString_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 == getentry("c")->getfunc) {
+ char *ptr = *(char **)self->b_ptr;
+ char *dest;
+
+ if (len <= 0)
+ return PyString_FromString("");
+ if (step == 1) {
+ return PyString_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 = PyString_FromStringAndSize(dest, len);
+ PyMem_Free(dest);
+ return np;
+ }
#ifdef CTYPES_UNICODE
- if (itemdict->getfunc == getentry("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 == getentry("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; */
- Pointer_slice, /* 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; */
+ Pointer_slice, /* 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_nonzero(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_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- (inquiry)Pointer_nonzero, /* nb_nonzero */
+ 0, /* nb_add */
+ 0, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ (inquiry)Pointer_nonzero, /* nb_nonzero */
};
PyTypeObject Pointer_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_compare */
- 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 */
- &CData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "XXX to be provided", /* tp_doc */
- (traverseproc)CData_traverse, /* tp_traverse */
- (inquiry)CData_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_compare */
+ 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 */
+ &CData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "XXX to be provided", /* tp_doc */
+ (traverseproc)CData_traverse, /* tp_traverse */
+ (inquiry)CData_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.
@@ -5272,78 +5272,78 @@ comerror_init(PyObject *self, PyObject *args)
int status;
if (!PyArg_ParseTuple(args, "OOOO:COMError", &self, &hresult, &text, &details))
- return NULL;
+ return NULL;
a = PySequence_GetSlice(args, 1, PySequence_Size(args));
if (!a)
- return NULL;
+ return NULL;
status = PyObject_SetAttrString(self, "args", a);
Py_DECREF(a);
if (status < 0)
- return NULL;
+ return NULL;
if (PyObject_SetAttrString(self, "hresult", hresult) < 0)
- return NULL;
+ return NULL;
if (PyObject_SetAttrString(self, "text", text) < 0)
- return NULL;
+ return NULL;
if (PyObject_SetAttrString(self, "details", details) < 0)
- return NULL;
+ return NULL;
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef comerror_methods[] = {
- { "__init__", comerror_init, METH_VARARGS },
- { NULL, NULL },
+ { "__init__", comerror_init, METH_VARARGS },
+ { NULL, NULL },
};
static int
create_comerror(void)
{
- PyObject *dict = PyDict_New();
- PyMethodDef *methods = comerror_methods;
- PyObject *s;
- int status;
-
- if (dict == NULL)
- return -1;
-
- while (methods->ml_name) {
- /* get a wrapper for the built-in function */
- PyObject *func = PyCFunction_New(methods, NULL);
- PyObject *meth;
- if (func == NULL)
- goto error;
- meth = PyMethod_New(func, NULL, ComError);
- Py_DECREF(func);
- if (meth == NULL)
- goto error;
- PyDict_SetItemString(dict, methods->ml_name, meth);
- Py_DECREF(meth);
- ++methods;
- }
-
- s = PyString_FromString(comerror_doc);
- if (s == NULL)
- goto error;
- status = PyDict_SetItemString(dict, "__doc__", s);
- Py_DECREF(s);
- if (status == -1)
- goto error;
-
- ComError = PyErr_NewException("_ctypes.COMError",
- NULL,
- dict);
- if (ComError == NULL)
- goto error;
-
- return 0;
+ PyObject *dict = PyDict_New();
+ PyMethodDef *methods = comerror_methods;
+ PyObject *s;
+ int status;
+
+ if (dict == NULL)
+ return -1;
+
+ while (methods->ml_name) {
+ /* get a wrapper for the built-in function */
+ PyObject *func = PyCFunction_New(methods, NULL);
+ PyObject *meth;
+ if (func == NULL)
+ goto error;
+ meth = PyMethod_New(func, NULL, ComError);
+ Py_DECREF(func);
+ if (meth == NULL)
+ goto error;
+ PyDict_SetItemString(dict, methods->ml_name, meth);
+ Py_DECREF(meth);
+ ++methods;
+ }
+
+ s = PyString_FromString(comerror_doc);
+ if (s == NULL)
+ goto error;
+ status = PyDict_SetItemString(dict, "__doc__", s);
+ Py_DECREF(s);
+ if (status == -1)
+ goto error;
+
+ ComError = PyErr_NewException("_ctypes.COMError",
+ NULL,
+ dict);
+ if (ComError == NULL)
+ goto error;
+
+ return 0;
error:
- Py_DECREF(dict);
- return -1;
+ Py_DECREF(dict);
+ return -1;
}
#endif
@@ -5351,246 +5351,246 @@ create_comerror(void)
static PyObject *
string_at(const char *ptr, int size)
{
- if (size == -1)
- return PyString_FromString(ptr);
- return PyString_FromStringAndSize(ptr, size);
+ if (size == -1)
+ return PyString_FromString(ptr);
+ return PyString_FromStringAndSize(ptr, size);
}
static int
cast_check_pointertype(PyObject *arg)
{
- StgDictObject *dict;
-
- if (PointerTypeObject_Check(arg))
- return 1;
- if (CFuncPtrTypeObject_Check(arg))
- return 1;
- dict = PyType_stgdict(arg);
- if (dict) {
- if (PyString_Check(dict->proto)
- && (strchr("sPzUZXO", PyString_AS_STRING(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 (PointerTypeObject_Check(arg))
+ return 1;
+ if (CFuncPtrTypeObject_Check(arg))
+ return 1;
+ dict = PyType_stgdict(arg);
+ if (dict) {
+ if (PyString_Check(dict->proto)
+ && (strchr("sPzUZXO", PyString_AS_STRING(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;
- /* CData_GetContainer will initialize src.b_objects, we need
- this so it can be shared */
- CData_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;
+ /* CData_GetContainer will initialize src.b_objects, we need
+ this so it can be shared */
+ CData_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
PyMODINIT_FUNC
init_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 = Py_InitModule3("_ctypes", module_methods, module_docs);
- if (!m)
- return;
-
- _pointer_type_cache = PyDict_New();
- if (_pointer_type_cache == NULL)
- return;
-
- PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_pointer_type_cache);
-
- _unpickle = PyObject_GetAttrString(m, "_unpickle");
- if (_unpickle == NULL)
- return;
-
- if (PyType_Ready(&PyCArg_Type) < 0)
- return;
-
- if (PyType_Ready(&CThunk_Type) < 0)
- return;
-
- /* StgDict is derived from PyDict_Type */
- StgDict_Type.tp_base = &PyDict_Type;
- if (PyType_Ready(&StgDict_Type) < 0)
- return;
-
- /*************************************************
- *
- * Metaclasses
- */
-
- StructType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&StructType_Type) < 0)
- return;
-
- UnionType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&UnionType_Type) < 0)
- return;
-
- PointerType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&PointerType_Type) < 0)
- return;
-
- ArrayType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&ArrayType_Type) < 0)
- return;
-
- SimpleType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&SimpleType_Type) < 0)
- return;
-
- CFuncPtrType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&CFuncPtrType_Type) < 0)
- return;
-
- /*************************************************
- *
- * Classes using a custom metaclass
- */
-
- if (PyType_Ready(&CData_Type) < 0)
- return;
-
- Py_TYPE(&Struct_Type) = &StructType_Type;
- Struct_Type.tp_base = &CData_Type;
- if (PyType_Ready(&Struct_Type) < 0)
- return;
- PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type);
-
- Py_TYPE(&Union_Type) = &UnionType_Type;
- Union_Type.tp_base = &CData_Type;
- if (PyType_Ready(&Union_Type) < 0)
- return;
- PyModule_AddObject(m, "Union", (PyObject *)&Union_Type);
-
- Py_TYPE(&Pointer_Type) = &PointerType_Type;
- Pointer_Type.tp_base = &CData_Type;
- if (PyType_Ready(&Pointer_Type) < 0)
- return;
- PyModule_AddObject(m, "_Pointer", (PyObject *)&Pointer_Type);
-
- Py_TYPE(&Array_Type) = &ArrayType_Type;
- Array_Type.tp_base = &CData_Type;
- if (PyType_Ready(&Array_Type) < 0)
- return;
- PyModule_AddObject(m, "Array", (PyObject *)&Array_Type);
-
- Py_TYPE(&Simple_Type) = &SimpleType_Type;
- Simple_Type.tp_base = &CData_Type;
- if (PyType_Ready(&Simple_Type) < 0)
- return;
- PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type);
-
- Py_TYPE(&CFuncPtr_Type) = &CFuncPtrType_Type;
- CFuncPtr_Type.tp_base = &CData_Type;
- if (PyType_Ready(&CFuncPtr_Type) < 0)
- return;
- PyModule_AddObject(m, "CFuncPtr", (PyObject *)&CFuncPtr_Type);
-
- /*************************************************
- *
- * Simple classes
- */
-
- /* CField_Type is derived from PyBaseObject_Type */
- if (PyType_Ready(&CField_Type) < 0)
- return;
-
- /*************************************************
- *
- * Other stuff
- */
-
- DictRemover_Type.tp_new = PyType_GenericNew;
- if (PyType_Ready(&DictRemover_Type) < 0)
- return;
+ m = Py_InitModule3("_ctypes", module_methods, module_docs);
+ if (!m)
+ return;
+
+ _pointer_type_cache = PyDict_New();
+ if (_pointer_type_cache == NULL)
+ return;
+
+ PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_pointer_type_cache);
+
+ _unpickle = PyObject_GetAttrString(m, "_unpickle");
+ if (_unpickle == NULL)
+ return;
+
+ if (PyType_Ready(&PyCArg_Type) < 0)
+ return;
+
+ if (PyType_Ready(&CThunk_Type) < 0)
+ return;
+
+ /* StgDict is derived from PyDict_Type */
+ StgDict_Type.tp_base = &PyDict_Type;
+ if (PyType_Ready(&StgDict_Type) < 0)
+ return;
+
+ /*************************************************
+ *
+ * Metaclasses
+ */
+
+ StructType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&StructType_Type) < 0)
+ return;
+
+ UnionType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&UnionType_Type) < 0)
+ return;
+
+ PointerType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&PointerType_Type) < 0)
+ return;
+
+ ArrayType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&ArrayType_Type) < 0)
+ return;
+
+ SimpleType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&SimpleType_Type) < 0)
+ return;
+
+ CFuncPtrType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&CFuncPtrType_Type) < 0)
+ return;
+
+ /*************************************************
+ *
+ * Classes using a custom metaclass
+ */
+
+ if (PyType_Ready(&CData_Type) < 0)
+ return;
+
+ Py_TYPE(&Struct_Type) = &StructType_Type;
+ Struct_Type.tp_base = &CData_Type;
+ if (PyType_Ready(&Struct_Type) < 0)
+ return;
+ PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type);
+
+ Py_TYPE(&Union_Type) = &UnionType_Type;
+ Union_Type.tp_base = &CData_Type;
+ if (PyType_Ready(&Union_Type) < 0)
+ return;
+ PyModule_AddObject(m, "Union", (PyObject *)&Union_Type);
+
+ Py_TYPE(&Pointer_Type) = &PointerType_Type;
+ Pointer_Type.tp_base = &CData_Type;
+ if (PyType_Ready(&Pointer_Type) < 0)
+ return;
+ PyModule_AddObject(m, "_Pointer", (PyObject *)&Pointer_Type);
+
+ Py_TYPE(&Array_Type) = &ArrayType_Type;
+ Array_Type.tp_base = &CData_Type;
+ if (PyType_Ready(&Array_Type) < 0)
+ return;
+ PyModule_AddObject(m, "Array", (PyObject *)&Array_Type);
+
+ Py_TYPE(&Simple_Type) = &SimpleType_Type;
+ Simple_Type.tp_base = &CData_Type;
+ if (PyType_Ready(&Simple_Type) < 0)
+ return;
+ PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type);
+
+ Py_TYPE(&CFuncPtr_Type) = &CFuncPtrType_Type;
+ CFuncPtr_Type.tp_base = &CData_Type;
+ if (PyType_Ready(&CFuncPtr_Type) < 0)
+ return;
+ PyModule_AddObject(m, "CFuncPtr", (PyObject *)&CFuncPtr_Type);
+
+ /*************************************************
+ *
+ * Simple classes
+ */
+
+ /* CField_Type is derived from PyBaseObject_Type */
+ if (PyType_Ready(&CField_Type) < 0)
+ return;
+
+ /*************************************************
+ *
+ * Other stuff
+ */
+
+ DictRemover_Type.tp_new = PyType_GenericNew;
+ if (PyType_Ready(&DictRemover_Type) < 0)
+ return;
#ifdef MS_WIN32
- if (create_comerror() < 0)
- return;
- PyModule_AddObject(m, "COMError", ComError);
+ if (create_comerror() < 0)
+ return;
+ PyModule_AddObject(m, "COMError", ComError);
- PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyInt_FromLong(FUNCFLAG_HRESULT));
- PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyInt_FromLong(FUNCFLAG_STDCALL));
+ PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyInt_FromLong(FUNCFLAG_HRESULT));
+ PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyInt_FromLong(FUNCFLAG_STDCALL));
#endif
- PyModule_AddObject(m, "FUNCFLAG_CDECL", PyInt_FromLong(FUNCFLAG_CDECL));
- PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyInt_FromLong(FUNCFLAG_USE_ERRNO));
- PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyInt_FromLong(FUNCFLAG_USE_LASTERROR));
- PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyInt_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", PyInt_FromLong(FUNCFLAG_CDECL));
+ PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyInt_FromLong(FUNCFLAG_USE_ERRNO));
+ PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyInt_FromLong(FUNCFLAG_USE_LASTERROR));
+ PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyInt_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. */
@@ -5605,14 +5605,14 @@ init_ctypes(void)
#define RTLD_GLOBAL RTLD_LOCAL
#endif
- PyModule_AddObject(m, "RTLD_LOCAL", PyInt_FromLong(RTLD_LOCAL));
- PyModule_AddObject(m, "RTLD_GLOBAL", PyInt_FromLong(RTLD_GLOBAL));
-
- PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL);
- if (PyExc_ArgError) {
- Py_INCREF(PyExc_ArgError);
- PyModule_AddObject(m, "ArgumentError", PyExc_ArgError);
- }
+ PyModule_AddObject(m, "RTLD_LOCAL", PyInt_FromLong(RTLD_LOCAL));
+ PyModule_AddObject(m, "RTLD_GLOBAL", PyInt_FromLong(RTLD_GLOBAL));
+
+ PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL);
+ if (PyExc_ArgError) {
+ Py_INCREF(PyExc_ArgError);
+ PyModule_AddObject(m, "ArgumentError", PyExc_ArgError);
+ }
}
/*****************************************************************
@@ -5623,30 +5623,30 @@ init_ctypes(void)
#ifdef HAVE_WCHAR_H
PyObject *My_PyUnicode_FromWideChar(register const wchar_t *w,
- Py_ssize_t size)
+ Py_ssize_t size)
{
PyUnicodeObject *unicode;
if (w == NULL) {
- PyErr_BadInternalCall();
- return NULL;
+ PyErr_BadInternalCall();
+ return NULL;
}
unicode = (PyUnicodeObject *)PyUnicode_FromUnicode(NULL, size);
if (!unicode)
- return NULL;
+ return NULL;
/* Copy the wchar_t data into the new object */
#ifdef HAVE_USABLE_WCHAR_T
memcpy(unicode->str, w, size * sizeof(wchar_t));
#else
{
- register Py_UNICODE *u;
- register int i;
- u = PyUnicode_AS_UNICODE(unicode);
- /* In Python, the following line has a one-off error */
- for (i = size; i > 0; i--)
- *u++ = *w++;
+ register Py_UNICODE *u;
+ register int i;
+ u = PyUnicode_AS_UNICODE(unicode);
+ /* In Python, the following line has a one-off error */
+ for (i = size; i > 0; i--)
+ *u++ = *w++;
}
#endif
@@ -5654,25 +5654,25 @@ PyObject *My_PyUnicode_FromWideChar(register const wchar_t *w,
}
Py_ssize_t My_PyUnicode_AsWideChar(PyUnicodeObject *unicode,
- register wchar_t *w,
- Py_ssize_t size)
+ register wchar_t *w,
+ Py_ssize_t size)
{
if (unicode == NULL) {
- PyErr_BadInternalCall();
- return -1;
+ PyErr_BadInternalCall();
+ return -1;
}
if (size > PyUnicode_GET_SIZE(unicode))
- size = PyUnicode_GET_SIZE(unicode);
+ size = PyUnicode_GET_SIZE(unicode);
#ifdef HAVE_USABLE_WCHAR_T
memcpy(w, unicode->str, size * sizeof(wchar_t));
#else
{
- register Py_UNICODE *u;
- register int i;
- u = PyUnicode_AS_UNICODE(unicode);
- /* In Python, the following line has a one-off error */
- for (i = size; i > 0; i--)
- *w++ = *u++;
+ register Py_UNICODE *u;
+ register int i;
+ u = PyUnicode_AS_UNICODE(unicode);
+ /* In Python, the following line has a one-off error */
+ for (i = size; i > 0; i--)
+ *w++ = *u++;
}
#endif
diff --git a/Modules/_ctypes/_ctypes_test.c b/Modules/_ctypes/_ctypes_test.c
index 3f13180..46406a6 100644
--- a/Modules/_ctypes/_ctypes_test.c
+++ b/Modules/_ctypes/_ctypes_test.c
@@ -27,152 +27,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
@@ -183,158 +183,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
@@ -343,12 +343,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)
@@ -357,8 +357,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)
@@ -369,64 +369,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;
};
DL_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;
+ }
}
DL_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
@@ -496,80 +496,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
@@ -584,13 +584,13 @@ 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
@@ -598,5 +598,5 @@ EXPORT (HRESULT) KeepObject(IUnknown *punk)
DL_EXPORT(void)
init_ctypes_test(void)
{
- Py_InitModule("_ctypes_test", module_methods);
+ Py_InitModule("_ctypes_test", module_methods);
}
diff --git a/Modules/_ctypes/callbacks.c b/Modules/_ctypes/callbacks.c
index 58c0dca..b1b60ba 100644
--- a/Modules/_ctypes/callbacks.c
+++ b/Modules/_ctypes/callbacks.c
@@ -17,65 +17,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)
- FreeClosure(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)
+ FreeClosure(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 CThunk_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_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_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_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_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 */
};
/**************************************************************/
@@ -83,74 +83,74 @@ PyTypeObject CThunk_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)
- 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)
+ PyFile_WriteString(buf, f);
+ PyErr_Print();
}
/* after code that pyrex generates */
void _AddTraceback(char *funcname, char *filename, int lineno)
{
- PyObject *py_srcfile = 0;
- PyObject *py_funcname = 0;
- PyObject *py_globals = 0;
- PyObject *empty_tuple = 0;
- PyObject *empty_string = 0;
- PyCodeObject *py_code = 0;
- PyFrameObject *py_frame = 0;
-
- py_srcfile = PyString_FromString(filename);
- if (!py_srcfile) goto bad;
- py_funcname = PyString_FromString(funcname);
- if (!py_funcname) goto bad;
- py_globals = PyDict_New();
- if (!py_globals) goto bad;
- empty_tuple = PyTuple_New(0);
- if (!empty_tuple) goto bad;
- empty_string = PyString_FromString("");
- if (!empty_string) goto bad;
- py_code = PyCode_New(
- 0, /*int argcount,*/
- 0, /*int nlocals,*/
- 0, /*int stacksize,*/
- 0, /*int flags,*/
- empty_string, /*PyObject *code,*/
- empty_tuple, /*PyObject *consts,*/
- empty_tuple, /*PyObject *names,*/
- empty_tuple, /*PyObject *varnames,*/
- empty_tuple, /*PyObject *freevars,*/
- empty_tuple, /*PyObject *cellvars,*/
- py_srcfile, /*PyObject *filename,*/
- py_funcname, /*PyObject *name,*/
- lineno, /*int firstlineno,*/
- empty_string /*PyObject *lnotab*/
- );
- 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_srcfile = 0;
+ PyObject *py_funcname = 0;
+ PyObject *py_globals = 0;
+ PyObject *empty_tuple = 0;
+ PyObject *empty_string = 0;
+ PyCodeObject *py_code = 0;
+ PyFrameObject *py_frame = 0;
+
+ py_srcfile = PyString_FromString(filename);
+ if (!py_srcfile) goto bad;
+ py_funcname = PyString_FromString(funcname);
+ if (!py_funcname) goto bad;
+ py_globals = PyDict_New();
+ if (!py_globals) goto bad;
+ empty_tuple = PyTuple_New(0);
+ if (!empty_tuple) goto bad;
+ empty_string = PyString_FromString("");
+ if (!empty_string) goto bad;
+ py_code = PyCode_New(
+ 0, /*int argcount,*/
+ 0, /*int nlocals,*/
+ 0, /*int stacksize,*/
+ 0, /*int flags,*/
+ empty_string, /*PyObject *code,*/
+ empty_tuple, /*PyObject *consts,*/
+ empty_tuple, /*PyObject *names,*/
+ empty_tuple, /*PyObject *varnames,*/
+ empty_tuple, /*PyObject *freevars,*/
+ empty_tuple, /*PyObject *cellvars,*/
+ py_srcfile, /*PyObject *filename,*/
+ py_funcname, /*PyObject *name,*/
+ lineno, /*int firstlineno,*/
+ empty_string /*PyObject *lnotab*/
+ );
+ 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_srcfile);
- Py_XDECREF(py_funcname);
- Py_XDECREF(empty_tuple);
- Py_XDECREF(empty_string);
- Py_XDECREF(py_code);
- Py_XDECREF(py_frame);
+ Py_XDECREF(py_globals);
+ Py_XDECREF(py_srcfile);
+ Py_XDECREF(py_funcname);
+ Py_XDECREF(empty_tuple);
+ Py_XDECREF(empty_string);
+ Py_XDECREF(py_code);
+ Py_XDECREF(py_frame);
}
#ifdef MS_WIN32
@@ -167,15 +167,15 @@ void _AddTraceback(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
@@ -185,420 +185,420 @@ 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 && !IsSimpleSubType(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 CData_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 && !IsSimpleSubType(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 CData_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) _AddTraceback(what, "_ctypes/callbacks.c", __LINE__ - 1), PyErr_Print()
- if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
- error_object = get_error_object(&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 = get_error_object(&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 != getentry("O")->setfunc) {
- if (-1 == PyErr_Warn(PyExc_RuntimeWarning,
- "memory leak in callback function."))
- 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 != getentry("O")->setfunc) {
+ if (-1 == PyErr_Warn(PyExc_RuntimeWarning,
+ "memory leak in callback function."))
+ 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, &CThunk_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, &CThunk_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 *AllocFunctionCallback(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(p));
-
- p->pcl = MallocClosure();
- 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] = GetType(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(p));
+
+ p->pcl = MallocClosure();
+ 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] = GetType(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),
- GetType(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),
+ GetType(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 = PyString_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 = PyInt_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 = PyString_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 = PyInt_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 = PyString_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 = PyInt_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 = PyString_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 = PyInt_AsLong(result);
+ if (PyErr_Occurred()) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ retval = E_FAIL;
+ }
+ Py_DECREF(result);
+ return retval;
}
/*
@@ -607,26 +607,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 0c51f84..c84b4f3 100644
--- a/Modules/_ctypes/callproc.c
+++ b/Modules/_ctypes/callproc.c
@@ -9,9 +9,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.
*/
@@ -87,7 +87,7 @@
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'
@@ -120,82 +120,82 @@
PyObject *
get_error_object(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 = PyString_InternFromString("ctypes.error_object");
- if (error_object_name == NULL)
- return NULL;
- }
- errobj = PyDict_GetItem(dict, error_object_name);
- if (errobj)
- Py_INCREF(errobj);
- else {
- void *space = PyMem_Malloc(sizeof(int) * 2);
- if (space == NULL)
- return NULL;
- memset(space, 0, sizeof(int) * 2);
- errobj = PyCObject_FromVoidPtr(space, PyMem_Free);
- if (errobj == NULL)
- return NULL;
- if (-1 == PyDict_SetItem(dict, error_object_name,
- errobj)) {
- Py_DECREF(errobj);
- return NULL;
- }
- }
- *pspace = (int *)PyCObject_AsVoidPtr(errobj);
- 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 = PyString_InternFromString("ctypes.error_object");
+ if (error_object_name == NULL)
+ return NULL;
+ }
+ errobj = PyDict_GetItem(dict, error_object_name);
+ if (errobj)
+ Py_INCREF(errobj);
+ else {
+ void *space = PyMem_Malloc(sizeof(int) * 2);
+ if (space == NULL)
+ return NULL;
+ memset(space, 0, sizeof(int) * 2);
+ errobj = PyCObject_FromVoidPtr(space, PyMem_Free);
+ if (errobj == NULL)
+ return NULL;
+ if (-1 == PyDict_SetItem(dict, error_object_name,
+ errobj)) {
+ Py_DECREF(errobj);
+ return NULL;
+ }
+ }
+ *pspace = (int *)PyCObject_AsVoidPtr(errobj);
+ return errobj;
}
static PyObject *
get_error_internal(PyObject *self, PyObject *args, int index)
{
- int *space;
- PyObject *errobj = get_error_object(&space);
- PyObject *result;
-
- if (errobj == NULL)
- return NULL;
- result = PyInt_FromLong(space[index]);
- Py_DECREF(errobj);
- return result;
+ int *space;
+ PyObject *errobj = get_error_object(&space);
+ PyObject *result;
+
+ if (errobj == NULL)
+ return NULL;
+ result = PyInt_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 = get_error_object(&space);
- if (errobj == NULL)
- return NULL;
- old_errno = space[index];
- space[index] = new_errno;
- Py_DECREF(errobj);
- return PyInt_FromLong(old_errno);
+ int new_errno, old_errno;
+ PyObject *errobj;
+ int *space;
+
+ if (!PyArg_ParseTuple(args, "i", &new_errno))
+ return NULL;
+ errobj = get_error_object(&space);
+ if (errobj == NULL)
+ return NULL;
+ old_errno = space[index];
+ space[index] = new_errno;
+ Py_DECREF(errobj);
+ return PyInt_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
@@ -203,206 +203,206 @@ 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 TCHAR *FormatError(DWORD code)
{
- TCHAR *lpMsgBuf;
- DWORD n;
- n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
- NULL,
- code,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
- (LPTSTR) &lpMsgBuf,
- 0,
- NULL);
- if (n) {
- while (_istspace(lpMsgBuf[n-1]))
- --n;
- lpMsgBuf[n] = _T('\0'); /* rstrip() */
- }
- return lpMsgBuf;
+ TCHAR *lpMsgBuf;
+ DWORD n;
+ n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
+ NULL,
+ code,
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
+ (LPTSTR) &lpMsgBuf,
+ 0,
+ NULL);
+ if (n) {
+ while (_istspace(lpMsgBuf[n-1]))
+ --n;
+ lpMsgBuf[n] = _T('\0'); /* rstrip() */
+ }
+ return lpMsgBuf;
}
#ifndef DONT_USE_SEH
void SetException(DWORD code, EXCEPTION_RECORD *pr)
{
- TCHAR *lpMsgBuf;
- lpMsgBuf = FormatError(code);
- if(lpMsgBuf) {
- PyErr_SetFromWindowsErr(code);
- LocalFree(lpMsgBuf);
- } else {
- 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:
- printf("error %d\n", code);
- PyErr_Format(PyExc_WindowsError,
- "exception code 0x%08x",
- code);
- break;
- }
- }
+ TCHAR *lpMsgBuf;
+ lpMsgBuf = FormatError(code);
+ if(lpMsgBuf) {
+ PyErr_SetFromWindowsErr(code);
+ LocalFree(lpMsgBuf);
+ } else {
+ 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:
+ printf("error %d\n", code);
+ PyErr_Format(PyExc_WindowsError,
+ "exception code 0x%08x",
+ 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 PyInt_FromLong(hr);
+ HRESULT hr;
+ if (!PyArg_ParseTuple(args, "i", &hr))
+ return NULL;
+ if (FAILED(hr))
+ return PyErr_SetFromWindowsErr(hr);
+ return PyInt_FromLong(hr);
}
#endif
@@ -412,132 +412,132 @@ check_hresult(PyObject *self, PyObject *args)
PyCArgObject *
new_CArgObject(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 PyString_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 PyString_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_compare */
- (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_compare */
+ (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 */
};
/****************************************************************/
@@ -570,24 +570,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;
};
/*
@@ -595,140 +595,140 @@ 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 (PyInt_Check(obj)) {
- pa->ffi_type = &ffi_type_sint;
- pa->value.i = PyInt_AS_LONG(obj);
- 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 (PyString_Check(obj)) {
- pa->ffi_type = &ffi_type_pointer;
- pa->value.p = PyString_AS_STRING(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 (PyInt_Check(obj)) {
+ pa->ffi_type = &ffi_type_sint;
+ pa->value.i = PyInt_AS_LONG(obj);
+ 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 (PyString_Check(obj)) {
+ pa->ffi_type = &ffi_type_pointer;
+ pa->value.p = PyString_AS_STRING(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 = PyCObject_FromVoidPtr(pa->value.p, PyMem_Free);
- 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 = PyCObject_FromVoidPtr(pa->value.p, PyMem_Free);
+ 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 *GetType(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;
}
@@ -736,7 +736,7 @@ ffi_type *GetType(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);
*
@@ -745,139 +745,139 @@ ffi_type *GetType(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
- int delta;
+ int delta;
#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 = get_error_object(&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 = get_error_object(&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
- delta =
+ delta =
#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
#ifdef MS_WIN64
- if (delta != 0) {
- PyErr_Format(PyExc_RuntimeError,
- "ffi_call failed with code %d",
- delta);
- return -1;
- }
+ if (delta != 0) {
+ PyErr_Format(PyExc_RuntimeError,
+ "ffi_call failed with code %d",
+ delta);
+ return -1;
+ }
#else
- if (delta < 0) {
- if (flags & FUNCFLAG_CDECL)
- PyErr_Format(PyExc_ValueError,
- "Procedure called with not enough "
- "arguments (%d bytes missing) "
- "or wrong calling convention",
- -delta);
- else
- PyErr_Format(PyExc_ValueError,
- "Procedure probably called with not enough "
- "arguments (%d bytes missing)",
- -delta);
- return -1;
- } else if (delta > 0) {
- PyErr_Format(PyExc_ValueError,
- "Procedure probably called with too many "
- "arguments (%d bytes in excess)",
- delta);
- return -1;
- }
+ if (delta < 0) {
+ if (flags & FUNCFLAG_CDECL)
+ PyErr_Format(PyExc_ValueError,
+ "Procedure called with not enough "
+ "arguments (%d bytes missing) "
+ "or wrong calling convention",
+ -delta);
+ else
+ PyErr_Format(PyExc_ValueError,
+ "Procedure probably called with not enough "
+ "arguments (%d bytes missing)",
+ -delta);
+ return -1;
+ } else if (delta > 0) {
+ PyErr_Format(PyExc_ValueError,
+ "Procedure probably called with too many "
+ "arguments (%d bytes in excess)",
+ delta);
+ return -1;
+ }
#endif
#endif
- if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
- return -1;
- return 0;
+ if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
+ return -1;
+ return 0;
}
/*
@@ -892,41 +892,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 PyInt_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 && !IsSimpleSubType(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 == getentry("O")->getfunc) {
- Py_DECREF(retval);
- }
- } else
- retval = CData_FromBaseObj(restype, NULL, 0, result);
-
- if (!checker || !retval)
- return retval;
-
- v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
- if (v == NULL)
- _AddTraceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
- Py_DECREF(retval);
- return v;
+ StgDictObject *dict;
+ PyObject *retval, *v;
+
+ if (restype == NULL)
+ return PyInt_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 && !IsSimpleSubType(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 == getentry("O")->getfunc) {
+ Py_DECREF(retval);
+ }
+ } else
+ retval = CData_FromBaseObj(restype, NULL, 0, result);
+
+ if (!checker || !retval)
+ return retval;
+
+ v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
+ if (v == NULL)
+ _AddTraceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
+ Py_DECREF(retval);
+ return v;
}
/*
@@ -935,40 +935,40 @@ static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker)
*/
void Extend_Error_Info(PyObject *exc_class, char *fmt, ...)
{
- va_list vargs;
- PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;
-
- va_start(vargs, fmt);
- s = PyString_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) {
- PyString_ConcatAndDel(&s, cls_str);
- PyString_ConcatAndDel(&s, PyString_FromString(": "));
- if (s == NULL)
- goto error;
- } else
- PyErr_Clear();
- msg_str = PyObject_Str(v);
- if (msg_str)
- PyString_ConcatAndDel(&s, msg_str);
- else {
- PyErr_Clear();
- PyString_ConcatAndDel(&s, PyString_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 = PyString_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) {
+ PyString_ConcatAndDel(&s, cls_str);
+ PyString_ConcatAndDel(&s, PyString_FromString(": "));
+ if (s == NULL)
+ goto error;
+ } else
+ PyErr_Clear();
+ msg_str = PyObject_Str(v);
+ if (msg_str)
+ PyString_ConcatAndDel(&s, msg_str);
+ else {
+ PyErr_Clear();
+ PyString_ConcatAndDel(&s, PyString_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);
}
@@ -977,77 +977,77 @@ 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;
- TCHAR *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;
+ TCHAR *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);
+ progid = NULL;
+ ProgIDFromCLSID(&guid, &progid);
- text = FormatError(errcode);
- obj = Py_BuildValue(
+ text = FormatError(errcode);
+ obj = Py_BuildValue(
#ifdef _UNICODE
- "iu(uuuiu)",
+ "iu(uuuiu)",
#else
- "is(uuuiu)",
+ "is(uuuiu)",
#endif
- 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;
+ 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
@@ -1059,158 +1059,158 @@ GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk)
* - XXX various requirements for restype, not yet collected
*/
PyObject *_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::CFuncPtr_Call
- */
- if (argtypes && argtype_count > i) {
- PyObject *v;
- converter = PyTuple_GET_ITEM(argtypes, i);
- v = PyObject_CallFunctionObjArgs(converter,
- arg,
- NULL);
- if (v == NULL) {
- Extend_Error_Info(PyExc_ArgError, "argument %d: ", i+1);
- goto cleanup;
- }
-
- err = ConvParam(v, i+1, pa);
- Py_DECREF(v);
- if (-1 == err) {
- Extend_Error_Info(PyExc_ArgError, "argument %d: ", i+1);
- goto cleanup;
- }
- } else {
- err = ConvParam(arg, i+1, pa);
- if (-1 == err) {
- Extend_Error_Info(PyExc_ArgError, "argument %d: ", i+1);
- goto cleanup; /* leaking ? */
- }
- }
- }
-
- rtype = GetType(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
+ 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::CFuncPtr_Call
+ */
+ if (argtypes && argtype_count > i) {
+ PyObject *v;
+ converter = PyTuple_GET_ITEM(argtypes, i);
+ v = PyObject_CallFunctionObjArgs(converter,
+ arg,
+ NULL);
+ if (v == NULL) {
+ Extend_Error_Info(PyExc_ArgError, "argument %d: ", i+1);
+ goto cleanup;
+ }
+
+ err = ConvParam(v, i+1, pa);
+ Py_DECREF(v);
+ if (-1 == err) {
+ Extend_Error_Info(PyExc_ArgError, "argument %d: ", i+1);
+ goto cleanup;
+ }
+ } else {
+ err = ConvParam(arg, i+1, pa);
+ if (-1 == err) {
+ Extend_Error_Info(PyExc_ArgError, "argument %d: ", i+1);
+ goto cleanup; /* leaking ? */
+ }
+ }
+ }
+
+ rtype = GetType(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
#ifdef _WIN64
- && atypes[i]->size <= sizeof(void *)
+ && atypes[i]->size <= sizeof(void *)
#endif
- )
- 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;
+ )
+ 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 = PyInt_FromLong(*(int *)resbuf);
- } else if (flags & FUNCFLAG_HRESULT) {
- if (*(int *)resbuf & 0x80000000)
- retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
- else
- retval = PyInt_FromLong(*(int *)resbuf);
- } else
+ if (iid && pIunk) {
+ if (*(int *)resbuf & 0x80000000)
+ retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
+ else
+ retval = PyInt_FromLong(*(int *)resbuf);
+ } else if (flags & FUNCFLAG_HRESULT) {
+ if (*(int *)resbuf & 0x80000000)
+ retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
+ else
+ retval = PyInt_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
@@ -1231,21 +1231,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;
- TCHAR *lpMsgBuf;
- DWORD code = 0;
- if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
- return NULL;
- if (code == 0)
- code = GetLastError();
- lpMsgBuf = FormatError(code);
- if (lpMsgBuf) {
- result = Py_BuildValue(PYBUILD_TSTR, lpMsgBuf);
- LocalFree(lpMsgBuf);
- } else {
- result = Py_BuildValue("s", "<no description>");
- }
- return result;
+ PyObject *result;
+ TCHAR *lpMsgBuf;
+ DWORD code = 0;
+ if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
+ return NULL;
+ if (code == 0)
+ code = GetLastError();
+ lpMsgBuf = FormatError(code);
+ if (lpMsgBuf) {
+ result = Py_BuildValue(PYBUILD_TSTR, lpMsgBuf);
+ LocalFree(lpMsgBuf);
+ } else {
+ result = Py_BuildValue("s", "<no description>");
+ }
+ return result;
}
static char load_library_doc[] =
@@ -1256,40 +1256,40 @@ The handle may be used to locate exported functions in this\n\
module.\n";
static PyObject *load_library(PyObject *self, PyObject *args)
{
- TCHAR *name;
- PyObject *nameobj;
- PyObject *ignored;
- HMODULE hMod;
- if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
- return NULL;
+ TCHAR *name;
+ PyObject *nameobj;
+ PyObject *ignored;
+ HMODULE hMod;
+ if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
+ return NULL;
#ifdef _UNICODE
- name = alloca((PyString_Size(nameobj) + 1) * sizeof(WCHAR));
- if (!name) {
- PyErr_NoMemory();
- return NULL;
- }
-
- {
- int r;
- char *aname = PyString_AsString(nameobj);
- if(!aname)
- return NULL;
- r = MultiByteToWideChar(CP_ACP, 0, aname, -1, name, PyString_Size(nameobj) + 1);
- name[r] = 0;
- }
+ name = alloca((PyString_Size(nameobj) + 1) * sizeof(WCHAR));
+ if (!name) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ {
+ int r;
+ char *aname = PyString_AsString(nameobj);
+ if(!aname)
+ return NULL;
+ r = MultiByteToWideChar(CP_ACP, 0, aname, -1, name, PyString_Size(nameobj) + 1);
+ name[r] = 0;
+ }
#else
- name = PyString_AsString(nameobj);
- if(!name)
- return NULL;
+ name = PyString_AsString(nameobj);
+ if(!name)
+ return NULL;
#endif
- hMod = LoadLibrary(name);
- if (!hMod)
- return PyErr_SetFromWindowsErr(GetLastError());
+ hMod = LoadLibrary(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
}
@@ -1299,13 +1299,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 */
@@ -1313,55 +1313,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 = _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 = _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[] =
@@ -1370,89 +1370,89 @@ 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 = PyInt_FromLong(E_POINTER);
- else {
- if (src)
- src->lpVtbl->AddRef(src);
- *pdst = src;
- r = PyInt_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 = PyInt_FromLong(E_POINTER);
+ else {
+ if (src)
+ src->lpVtbl->AddRef(src);
+ *pdst = src;
+ r = PyInt_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)
{
- char *name;
- void * handle;
-#ifdef RTLD_LOCAL
- int mode = RTLD_NOW | RTLD_LOCAL;
+ char *name;
+ 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, "z|i:dlopen", &name, &mode))
- return NULL;
- mode |= RTLD_NOW;
- handle = ctypes_dlopen(name, mode);
- 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, "z|i:dlopen", &name, &mode))
+ return NULL;
+ mode |= RTLD_NOW;
+ handle = ctypes_dlopen(name, mode);
+ 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
@@ -1464,27 +1464,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 = _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 = _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;
}
/*
@@ -1495,27 +1495,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 = _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 = _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;
}
/*****************************************************************
@@ -1529,17 +1529,17 @@ static char sizeof_doc[] =
static PyObject *
sizeof_func(PyObject *self, PyObject *obj)
{
- StgDictObject *dict;
+ StgDictObject *dict;
- dict = PyType_stgdict(obj);
- if (dict)
- return PyInt_FromSsize_t(dict->size);
+ dict = PyType_stgdict(obj);
+ if (dict)
+ return PyInt_FromSsize_t(dict->size);
- if (CDataObject_Check(obj))
- return PyInt_FromSsize_t(((CDataObject *)obj)->b_size);
- PyErr_SetString(PyExc_TypeError,
- "this type has no size");
- return NULL;
+ if (CDataObject_Check(obj))
+ return PyInt_FromSsize_t(((CDataObject *)obj)->b_size);
+ PyErr_SetString(PyExc_TypeError,
+ "this type has no size");
+ return NULL;
}
static char alignment_doc[] =
@@ -1550,19 +1550,19 @@ static char alignment_doc[] =
static PyObject *
align_func(PyObject *self, PyObject *obj)
{
- StgDictObject *dict;
+ StgDictObject *dict;
- dict = PyType_stgdict(obj);
- if (dict)
- return PyInt_FromSsize_t(dict->align);
+ dict = PyType_stgdict(obj);
+ if (dict)
+ return PyInt_FromSsize_t(dict->align);
- dict = PyObject_stgdict(obj);
- if (dict)
- return PyInt_FromSsize_t(dict->align);
+ dict = PyObject_stgdict(obj);
+ if (dict)
+ return PyInt_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[] =
@@ -1577,36 +1577,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 = new_CArgObject();
- 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 = new_CArgObject();
+ 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[] =
@@ -1616,44 +1616,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
@@ -1667,242 +1667,242 @@ 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)", conversion_mode_encoding, conversion_mode_errors);
- if (coding) {
- PyMem_Free(conversion_mode_encoding);
- conversion_mode_encoding = PyMem_Malloc(strlen(coding) + 1);
- strcpy(conversion_mode_encoding, coding);
- } else {
- conversion_mode_encoding = NULL;
- }
- PyMem_Free(conversion_mode_errors);
- conversion_mode_errors = PyMem_Malloc(strlen(mode) + 1);
- strcpy(conversion_mode_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)", conversion_mode_encoding, conversion_mode_errors);
+ if (coding) {
+ PyMem_Free(conversion_mode_encoding);
+ conversion_mode_encoding = PyMem_Malloc(strlen(coding) + 1);
+ strcpy(conversion_mode_encoding, coding);
+ } else {
+ conversion_mode_encoding = NULL;
+ }
+ PyMem_Free(conversion_mode_errors);
+ conversion_mode_errors = PyMem_Malloc(strlen(mode) + 1);
+ strcpy(conversion_mode_errors, mode);
+ return result;
}
#endif
static PyObject *
resize(PyObject *self, PyObject *args)
{
- CDataObject *obj;
- StgDictObject *dict;
- Py_ssize_t size;
+ CDataObject *obj;
+ StgDictObject *dict;
+ Py_ssize_t size;
- if (!PyArg_ParseTuple(args,
+ if (!PyArg_ParseTuple(args,
#if (PY_VERSION_HEX < 0x02050000)
- "Oi:resize",
+ "Oi:resize",
#else
- "On:resize",
+ "On:resize",
#endif
- &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,
+ &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,
#if PY_VERSION_HEX < 0x02050000
- "minimum size is %d",
+ "minimum size is %d",
#else
- "minimum size is %zd",
+ "minimum size is %zd",
#endif
- 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;
- }
+ 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(_pointer_type_cache, cls);
- if (result) {
- Py_INCREF(result);
- return result;
- }
- if (PyString_CheckExact(cls)) {
- buf = alloca(strlen(PyString_AS_STRING(cls)) + 3 + 1);
- sprintf(buf, "LP_%s", PyString_AS_STRING(cls));
- result = PyObject_CallFunction((PyObject *)Py_TYPE(&Pointer_Type),
- "s(O){}",
- buf,
- &Pointer_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(&Pointer_Type),
- "s(O){sO}",
- buf,
- &Pointer_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(_pointer_type_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(_pointer_type_cache, cls);
+ if (result) {
+ Py_INCREF(result);
+ return result;
+ }
+ if (PyString_CheckExact(cls)) {
+ buf = alloca(strlen(PyString_AS_STRING(cls)) + 3 + 1);
+ sprintf(buf, "LP_%s", PyString_AS_STRING(cls));
+ result = PyObject_CallFunction((PyObject *)Py_TYPE(&Pointer_Type),
+ "s(O){}",
+ buf,
+ &Pointer_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(&Pointer_Type),
+ "s(O){sO}",
+ buf,
+ &Pointer_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(_pointer_type_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(_pointer_type_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(_pointer_type_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 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 (for testing only)"},
- {"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 (for testing only)"},
+ {"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 4037e93..46053b8 100644
--- a/Modules/_ctypes/cfield.c
+++ b/Modules/_ctypes/cfield.c
@@ -17,9 +17,9 @@
static PyObject *
CField_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;
}
/*
@@ -36,305 +36,305 @@ CField_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
*/
PyObject *
CField_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 *)&CField_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 *)&CField_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 (ArrayTypeObject_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 == getentry("c")->getfunc) {
- struct fielddesc *fd = getentry("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 (ArrayTypeObject_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 == getentry("c")->getfunc) {
+ struct fielddesc *fd = getentry("s");
+ getfunc = fd->getfunc;
+ setfunc = fd->setfunc;
+ }
#ifdef CTYPES_UNICODE
- if (idict->getfunc == getentry("u")->getfunc) {
- struct fielddesc *fd = getentry("U");
- getfunc = fd->getfunc;
- setfunc = fd->setfunc;
- }
+ if (idict->getfunc == getentry("u")->getfunc) {
+ struct fielddesc *fd = getentry("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
CField_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 CData_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 CData_set(inst, self->proto, self->setfunc, value,
+ self->index, self->size, ptr);
}
static PyObject *
CField_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 CData_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 CData_get(self->proto, self->getfunc, inst,
+ self->index, self->size, src->b_ptr + self->offset);
}
static PyObject *
CField_get_offset(PyObject *self, void *data)
{
- return PyInt_FromSsize_t(((CFieldObject *)self)->offset);
+ return PyInt_FromSsize_t(((CFieldObject *)self)->offset);
}
static PyObject *
CField_get_size(PyObject *self, void *data)
{
- return PyInt_FromSsize_t(((CFieldObject *)self)->size);
+ return PyInt_FromSsize_t(((CFieldObject *)self)->size);
}
static PyGetSetDef CField_getset[] = {
- { "offset", CField_get_offset, NULL, "offset in bytes of this field" },
- { "size", CField_get_size, NULL, "size in bytes of this field" },
- { NULL, NULL, NULL, NULL },
+ { "offset", CField_get_offset, NULL, "offset in bytes of this field" },
+ { "size", CField_get_size, NULL, "size in bytes of this field" },
+ { NULL, NULL, NULL, NULL },
};
static int
CField_traverse(CFieldObject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->proto);
- return 0;
+ Py_VISIT(self->proto);
+ return 0;
}
static int
CField_clear(CFieldObject *self)
{
- Py_CLEAR(self->proto);
- return 0;
+ Py_CLEAR(self->proto);
+ return 0;
}
static void
CField_dealloc(PyObject *self)
{
- CField_clear((CFieldObject *)self);
- self->ob_type->tp_free((PyObject *)self);
+ CField_clear((CFieldObject *)self);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *
CField_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 = PyString_FromFormat(
+ if (bits)
+ result = PyString_FromFormat(
#if (PY_VERSION_HEX < 0x02050000)
- "<Field type=%s, ofs=%d:%d, bits=%d>",
+ "<Field type=%s, ofs=%d:%d, bits=%d>",
#else
- "<Field type=%s, ofs=%zd:%zd, bits=%zd>",
+ "<Field type=%s, ofs=%zd:%zd, bits=%zd>",
#endif
- name, self->offset, size, bits);
- else
- result = PyString_FromFormat(
+ name, self->offset, size, bits);
+ else
+ result = PyString_FromFormat(
#if (PY_VERSION_HEX < 0x02050000)
- "<Field type=%s, ofs=%d, size=%d>",
+ "<Field type=%s, ofs=%d, size=%d>",
#else
- "<Field type=%s, ofs=%zd, size=%zd>",
+ "<Field type=%s, ofs=%zd, size=%zd>",
#endif
- name, self->offset, size);
- return result;
+ name, self->offset, size);
+ return result;
}
PyTypeObject CField_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.CField", /* tp_name */
- sizeof(CFieldObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- CField_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)CField_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)CField_traverse, /* tp_traverse */
- (inquiry)CField_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- CField_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- (descrgetfunc)CField_get, /* tp_descr_get */
- (descrsetfunc)CField_set, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- CField_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.CField", /* tp_name */
+ sizeof(CFieldObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ CField_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)CField_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)CField_traverse, /* tp_traverse */
+ (inquiry)CField_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ CField_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ (descrgetfunc)CField_get, /* tp_descr_get */
+ (descrsetfunc)CField_set, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ CField_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
Accessor functions
@@ -347,17 +347,17 @@ PyTypeObject CField_Type = {
static int
get_long(PyObject *v, long *p)
{
- long x;
- if (PyFloat_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "int expected instead of float");
- return -1;
- }
- x = PyInt_AsUnsignedLongMask(v);
- if (x == -1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ long x;
+ if (PyFloat_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "int expected instead of float");
+ return -1;
+ }
+ x = PyInt_AsUnsignedLongMask(v);
+ if (x == -1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
/* Same, but handling unsigned long */
@@ -365,17 +365,17 @@ get_long(PyObject *v, long *p)
static int
get_ulong(PyObject *v, unsigned long *p)
{
- unsigned long x;
- if (PyFloat_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "int expected instead of float");
- return -1;
- }
- x = PyInt_AsUnsignedLongMask(v);
- if (x == (unsigned long)-1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ unsigned long x;
+ if (PyFloat_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "int expected instead of float");
+ return -1;
+ }
+ x = PyInt_AsUnsignedLongMask(v);
+ if (x == (unsigned long)-1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
#ifdef HAVE_LONG_LONG
@@ -385,17 +385,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 = PyInt_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 = PyInt_AsUnsignedLongLongMask(v);
+ if (x == -1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
/* Same, but handling native unsigned long long. */
@@ -403,17 +403,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 = PyInt_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 = PyInt_AsUnsignedLongLongMask(v);
+ if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
#endif
@@ -436,49 +436,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
@@ -515,184 +515,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 PyInt_FromLong(val);
+ signed char val = *(signed char *)ptr;
+ GET_BITFIELD(val, size);
+ return PyInt_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 PyInt_FromLong(val);
+ unsigned char val = *(unsigned char *)ptr;
+ GET_BITFIELD(val, size);
+ return PyInt_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 PyInt_FromLong((long)val);
+ short val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyInt_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 PyInt_FromLong(val);
+ short val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_2(val);
+ GET_BITFIELD(val, size);
+ return PyInt_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 PyInt_FromLong(val);
+ unsigned short val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyInt_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 PyInt_FromLong(val);
+ unsigned short val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_2(val);
+ GET_BITFIELD(val, size);
+ return PyInt_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 PyInt_FromLong(val);
+ int val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyInt_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 PyInt_FromLong(val);
+ int val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_INT(val);
+ GET_BITFIELD(val, size);
+ return PyInt_FromLong(val);
}
#ifdef MS_WIN32
@@ -700,22 +700,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
@@ -730,260 +730,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 PyInt_FromLong(val);
+ long val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyInt_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 PyInt_FromLong(val);
+ long val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_LONG(val);
+ GET_BITFIELD(val, size);
+ return PyInt_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
@@ -995,136 +995,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
}
@@ -1141,45 +1141,45 @@ 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 (!PyString_Check(value) || (1 != PyString_Size(value))) {
- PyErr_Format(PyExc_TypeError,
- "one character string expected");
- return NULL;
- }
- *(char *)ptr = PyString_AS_STRING(value)[0];
- _RET(value);
+ if (!PyString_Check(value) || (1 != PyString_Size(value))) {
+ PyErr_Format(PyExc_TypeError,
+ "one character string expected");
+ return NULL;
+ }
+ *(char *)ptr = PyString_AS_STRING(value)[0];
+ _RET(value);
}
static PyObject *
c_get(void *ptr, Py_ssize_t size)
{
- return PyString_FromStringAndSize((char *)ptr, 1);
+ return PyString_FromStringAndSize((char *)ptr, 1);
}
#ifdef CTYPES_UNICODE
@@ -1187,112 +1187,112 @@ c_get(void *ptr, Py_ssize_t size)
static PyObject *
u_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- Py_ssize_t len;
+ Py_ssize_t len;
- if (PyString_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- conversion_mode_encoding,
- conversion_mode_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);
+ if (PyString_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ conversion_mode_encoding,
+ conversion_mode_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 (PyString_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- conversion_mode_encoding,
- conversion_mode_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,
+ Py_ssize_t size;
+
+ /* It's easier to calculate in characters than in bytes */
+ length /= sizeof(wchar_t);
+
+ if (PyString_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ conversion_mode_encoding,
+ conversion_mode_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,
#if (PY_VERSION_HEX < 0x02050000)
- "string too long (%d, maximum length %d)",
+ "string too long (%d, maximum length %d)",
#else
- "string too long (%zd, maximum length %zd)",
+ "string too long (%zd, maximum length %zd)",
#endif
- 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;
+ 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
@@ -1300,201 +1300,201 @@ U_set(void *ptr, PyObject *value, Py_ssize_t length)
static PyObject *
s_get(void *ptr, Py_ssize_t size)
{
- PyObject *result;
- size_t slen;
+ PyObject *result;
+ size_t slen;
- result = PyString_FromString((char *)ptr);
- if (!result)
- return NULL;
- /* chop off at the first NUL character, if any.
- * On error, result will be deallocated and set to NULL.
- */
- slen = strlen(PyString_AS_STRING(result));
- size = min(size, (Py_ssize_t)slen);
- if (result->ob_refcnt == 1) {
- /* shorten the result */
- _PyString_Resize(&result, size);
- return result;
- } else
- /* cannot shorten the result */
- return PyString_FromStringAndSize(ptr, size);
+ result = PyString_FromString((char *)ptr);
+ if (!result)
+ return NULL;
+ /* chop off at the first NUL character, if any.
+ * On error, result will be deallocated and set to NULL.
+ */
+ slen = strlen(PyString_AS_STRING(result));
+ size = min(size, (Py_ssize_t)slen);
+ if (result->ob_refcnt == 1) {
+ /* shorten the result */
+ _PyString_Resize(&result, size);
+ return result;
+ } else
+ /* cannot shorten the result */
+ return PyString_FromStringAndSize(ptr, size);
}
static PyObject *
s_set(void *ptr, PyObject *value, Py_ssize_t length)
{
- char *data;
- Py_ssize_t size;
-
- data = PyString_AsString(value);
- if (!data)
- return NULL;
- size = strlen(data);
- 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,
+ char *data;
+ Py_ssize_t size;
+
+ data = PyString_AsString(value);
+ if (!data)
+ return NULL;
+ size = strlen(data);
+ 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,
#if (PY_VERSION_HEX < 0x02050000)
- "string too long (%d, maximum length %d)",
+ "string too long (%d, maximum length %d)",
#else
- "string too long (%zd, maximum length %zd)",
+ "string too long (%zd, maximum length %zd)",
#endif
- size, length);
- return NULL;
- }
- /* Also copy the terminating NUL character if there is space */
- memcpy((char *)ptr, data, size);
- _RET(value);
+ size, length);
+ return NULL;
+ }
+ /* Also copy the terminating NUL character if there is space */
+ memcpy((char *)ptr, data, size);
+ _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 (PyString_Check(value)) {
- *(char **)ptr = PyString_AS_STRING(value);
- Py_INCREF(value);
- return value;
- } else if (PyUnicode_Check(value)) {
- PyObject *str = PyUnicode_AsEncodedString(value,
- conversion_mode_encoding,
- conversion_mode_errors);
- if (str == NULL)
- return NULL;
- *(char **)ptr = PyString_AS_STRING(str);
- return str;
- } else if (PyInt_Check(value) || PyLong_Check(value)) {
+ if (value == Py_None) {
+ *(char **)ptr = NULL;
+ Py_INCREF(value);
+ return value;
+ }
+ if (PyString_Check(value)) {
+ *(char **)ptr = PyString_AS_STRING(value);
+ Py_INCREF(value);
+ return value;
+ } else if (PyUnicode_Check(value)) {
+ PyObject *str = PyUnicode_AsEncodedString(value,
+ conversion_mode_encoding,
+ conversion_mode_errors);
+ if (str == NULL)
+ return NULL;
+ *(char **)ptr = PyString_AS_STRING(str);
+ return str;
+ } else if (PyInt_Check(value) || PyLong_Check(value)) {
#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
- *(char **)ptr = (char *)PyInt_AsUnsignedLongLongMask(value);
+ *(char **)ptr = (char *)PyInt_AsUnsignedLongLongMask(value);
#else
- *(char **)ptr = (char *)PyInt_AsUnsignedLongMask(value);
+ *(char **)ptr = (char *)PyInt_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 PyString_FromString(*(char **)ptr);
- } else {
- Py_INCREF(Py_None);
- return Py_None;
- }
+ return PyString_FromString(*(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 (PyString_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- conversion_mode_encoding,
- conversion_mode_errors);
- if (!value)
- return NULL;
- } else if (PyInt_Check(value) || PyLong_Check(value)) {
+ if (value == Py_None) {
+ *(wchar_t **)ptr = NULL;
+ Py_INCREF(value);
+ return value;
+ }
+ if (PyString_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ conversion_mode_encoding,
+ conversion_mode_errors);
+ if (!value)
+ return NULL;
+ } else if (PyInt_Check(value) || PyLong_Check(value)) {
#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
- *(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongLongMask(value);
+ *(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongLongMask(value);
#else
- *(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongMask(value);
+ *(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongMask(value);
#endif
- Py_INCREF(Py_None);
- return Py_None;
- } 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;
+ } 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 = PyCObject_FromVoidPtr(buffer, PyMem_Free);
- 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 = PyCObject_FromVoidPtr(buffer, PyMem_Free);
+ 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
@@ -1502,166 +1502,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 (PyString_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- conversion_mode_encoding,
- conversion_mode_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 (PyString_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ conversion_mode_encoding,
+ conversion_mode_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 (!PyInt_Check(value) && !PyLong_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "cannot be converted to pointer");
- return NULL;
- }
+ if (!PyInt_Check(value) && !PyLong_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "cannot be converted to pointer");
+ return NULL;
+ }
#if SIZEOF_VOID_P <= SIZEOF_LONG
- v = (void *)PyInt_AsUnsignedLongMask(value);
+ v = (void *)PyInt_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 *)PyInt_AsUnsignedLongLongMask(value);
+ v = (void *)PyInt_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},
};
/*
@@ -1672,26 +1672,26 @@ static struct fielddesc formattable[] = {
struct fielddesc *
getentry(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))
- getentry("u")->pffi_type = &ffi_type_sshort;
- else if (sizeof(wchar_t) == sizeof(int))
- getentry("u")->pffi_type = &ffi_type_sint;
- else if (sizeof(wchar_t) == sizeof(long))
- getentry("u")->pffi_type = &ffi_type_slong;
+ if (sizeof(wchar_t) == sizeof(short))
+ getentry("u")->pffi_type = &ffi_type_sshort;
+ else if (sizeof(wchar_t) == sizeof(int))
+ getentry("u")->pffi_type = &ffi_type_sint;
+ else if (sizeof(wchar_t) == sizeof(long))
+ getentry("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;
@@ -1735,10 +1735,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;
*/
@@ -1765,7 +1765,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 6de9a81..37f470d 100644
--- a/Modules/_ctypes/ctypes.h
+++ b/Modules/_ctypes/ctypes.h
@@ -24,7 +24,7 @@ typedef Py_ssize_t (*charbufferproc)(PyObject *, Py_ssize_t, char **);
#if (PY_VERSION_HEX < 0x02060000)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#define PyVarObject_HEAD_INIT(type, size) \
- PyObject_HEAD_INIT(type) size,
+ PyObject_HEAD_INIT(type) size,
#define PyImport_ImportModuleNoBlock PyImport_ImportModule
#define PyLong_FromSsize_t PyInt_FromLong
#define Py_TPFLAGS_HAVE_NEWBUFFER 0
@@ -62,16 +62,16 @@ Making CDataObject a variable size object would be a better solution, but more
difficult in the presence of CFuncPtrObject. 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;
};
/*
@@ -81,67 +81,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 CThunk_Type;
-#define CThunk_CheckExact(v) ((v)->ob_type == &CThunk_Type)
+#define CThunk_CheckExact(v) ((v)->ob_type == &CThunk_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;
} CFuncPtrObject;
extern PyTypeObject StgDict_Type;
-#define StgDict_CheckExact(v) ((v)->ob_type == &StgDict_Type)
-#define StgDict_Check(v) PyObject_TypeCheck(v, &StgDict_Type)
+#define StgDict_CheckExact(v) ((v)->ob_type == &StgDict_Type)
+#define StgDict_Check(v) PyObject_TypeCheck(v, &StgDict_Type)
extern int StructUnionType_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);
@@ -150,12 +150,12 @@ extern int PyObject_stginfo(PyObject *self, Py_ssize_t *psize, Py_ssize_t *palig
extern PyTypeObject CData_Type;
-#define CDataObject_CheckExact(v) ((v)->ob_type == &CData_Type)
-#define CDataObject_Check(v) PyObject_TypeCheck(v, &CData_Type)
+#define CDataObject_CheckExact(v) ((v)->ob_type == &CData_Type)
+#define CDataObject_Check(v) PyObject_TypeCheck(v, &CData_Type)
extern PyTypeObject SimpleType_Type;
-#define SimpleTypeObject_CheckExact(v) ((v)->ob_type == &SimpleType_Type)
-#define SimpleTypeObject_Check(v) PyObject_TypeCheck(v, &SimpleType_Type)
+#define SimpleTypeObject_CheckExact(v) ((v)->ob_type == &SimpleType_Type)
+#define SimpleTypeObject_Check(v) PyObject_TypeCheck(v, &SimpleType_Type)
extern PyTypeObject CField_Type;
extern struct fielddesc *getentry(char *fmt);
@@ -163,9 +163,9 @@ extern struct fielddesc *getentry(char *fmt);
extern PyObject *
CField_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 *CData_AtAddress(PyObject *type, void *buf);
extern PyObject *CData_FromBytes(PyObject *type, char *data, Py_ssize_t length);
@@ -178,13 +178,13 @@ extern PyTypeObject CFuncPtr_Type;
extern PyTypeObject CFuncPtrType_Type;
extern PyTypeObject StructType_Type;
-#define ArrayTypeObject_Check(v) PyObject_TypeCheck(v, &ArrayType_Type)
-#define ArrayObject_Check(v) PyObject_TypeCheck(v, &Array_Type)
-#define PointerObject_Check(v) PyObject_TypeCheck(v, &Pointer_Type)
-#define PointerTypeObject_Check(v) PyObject_TypeCheck(v, &PointerType_Type)
-#define CFuncPtrObject_Check(v) PyObject_TypeCheck(v, &CFuncPtr_Type)
-#define CFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &CFuncPtrType_Type)
-#define StructTypeObject_Check(v) PyObject_TypeCheck(v, &StructType_Type)
+#define ArrayTypeObject_Check(v) PyObject_TypeCheck(v, &ArrayType_Type)
+#define ArrayObject_Check(v) PyObject_TypeCheck(v, &Array_Type)
+#define PointerObject_Check(v) PyObject_TypeCheck(v, &Pointer_Type)
+#define PointerTypeObject_Check(v) PyObject_TypeCheck(v, &PointerType_Type)
+#define CFuncPtrObject_Check(v) PyObject_TypeCheck(v, &CFuncPtr_Type)
+#define CFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &CFuncPtrType_Type)
+#define StructTypeObject_Check(v) PyObject_TypeCheck(v, &StructType_Type)
extern PyObject *
CreateArrayType(PyObject *itemtype, Py_ssize_t length);
@@ -192,35 +192,35 @@ CreateArrayType(PyObject *itemtype, Py_ssize_t length);
extern PyMethodDef module_methods[];
extern CThunkObject *AllocFunctionCallback(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 ArrayType_new the ffi_type fields must be filled in -
@@ -229,28 +229,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 CFuncPtrType_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 CFuncPtrType_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;
@@ -305,16 +305,16 @@ extern int StgDict_clone(StgDictObject *src, StgDictObject *dst);
typedef int(* PPROC)(void);
PyObject *_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
@@ -329,45 +329,45 @@ PyObject *_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 *new_CArgObject(void);
extern PyObject *
CData_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
CData_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 Extend_Error_Info(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[];
@@ -383,14 +383,14 @@ extern char *conversion_mode_errors;
/* Python 2.4 macros, which are not available in Python 2.3 */
#ifndef Py_CLEAR
-#define Py_CLEAR(op) \
- do { \
- if (op) { \
- PyObject *tmp = (PyObject *)(op); \
- (op) = NULL; \
- Py_DECREF(tmp); \
- } \
- } while (0)
+#define Py_CLEAR(op) \
+ do { \
+ if (op) { \
+ PyObject *tmp = (PyObject *)(op); \
+ (op) = NULL; \
+ Py_DECREF(tmp); \
+ } \
+ } while (0)
#endif
#ifndef Py_VISIT
@@ -399,14 +399,14 @@ extern char *conversion_mode_errors;
* "visit" and "arg". This is intended to keep tp_traverse functions
* looking as much alike as possible.
*/
-#define Py_VISIT(op) \
- do { \
- if (op) { \
- int vret = visit((op), arg); \
- if (vret) \
- return vret; \
- } \
- } while (0)
+#define Py_VISIT(op) \
+ do { \
+ if (op) { \
+ int vret = visit((op), arg); \
+ if (vret) \
+ return vret; \
+ } \
+ } while (0)
#endif
/* Python's PyUnicode_*WideChar functions are broken ... */
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 105935e..c50d53e 100644
--- a/Modules/_ctypes/malloc_closure.c
+++ b/Modules/_ctypes/malloc_closure.c
@@ -27,8 +27,8 @@
/******************************************************************/
typedef union _tagITEM {
- ffi_closure closure;
- union _tagITEM *next;
+ ffi_closure closure;
+ union _tagITEM *next;
} ITEM;
static ITEM *free_list;
@@ -36,58 +36,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;
+ }
}
/******************************************************************/
@@ -95,20 +95,20 @@ static void more_core(void)
/* put the item back into the free list */
void FreeClosure(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 *MallocClosure(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 dabf9f1..8ae09bf 100644
--- a/Modules/_ctypes/stgdict.c
+++ b/Modules/_ctypes/stgdict.c
@@ -23,145 +23,145 @@
static int
StgDict_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
StgDict_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
StgDict_dealloc(StgDictObject *self)
{
- StgDict_clear(self);
- PyMem_Free(self->format);
- PyMem_Free(self->shape);
- PyMem_Free(self->ffi_type_pointer.elements);
- PyDict_Type.tp_dealloc((PyObject *)self);
+ StgDict_clear(self);
+ PyMem_Free(self->format);
+ PyMem_Free(self->shape);
+ PyMem_Free(self->ffi_type_pointer.elements);
+ PyDict_Type.tp_dealloc((PyObject *)self);
}
int
StgDict_clone(StgDictObject *dst, StgDictObject *src)
{
- char *d, *s;
- Py_ssize_t size;
-
- StgDict_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;
+
+ StgDict_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 StgDict_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "StgDict",
- sizeof(StgDictObject),
- 0,
- (destructor)StgDict_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- 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)StgDict_init, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "StgDict",
+ sizeof(StgDictObject),
+ 0,
+ (destructor)StgDict_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 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)StgDict_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 (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS))
- return NULL;
- if (!type->tp_dict || !StgDict_CheckExact(type->tp_dict))
- return NULL;
- return (StgDictObject *)type->tp_dict;
+ PyTypeObject *type;
+
+ if (!PyType_Check(obj))
+ return NULL;
+ type = (PyTypeObject *)obj;
+ if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS))
+ return NULL;
+ if (!type->tp_dict || !StgDict_CheckExact(type->tp_dict))
+ return NULL;
+ return (StgDictObject *)type->tp_dict;
}
/* May return NULL, but does not set an exception! */
@@ -172,12 +172,12 @@ PyType_stgdict(PyObject *obj)
StgDictObject *
PyObject_stgdict(PyObject *self)
{
- PyTypeObject *type = self->ob_type;
- if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS))
- return NULL;
- if (!type->tp_dict || !StgDict_CheckExact(type->tp_dict))
- return NULL;
- return (StgDictObject *)type->tp_dict;
+ PyTypeObject *type = self->ob_type;
+ if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS))
+ return NULL;
+ if (!type->tp_dict || !StgDict_CheckExact(type->tp_dict))
+ return NULL;
+ return (StgDictObject *)type->tp_dict;
}
/* descr is the descriptor for a field marked as anonymous. Get all the
@@ -186,78 +186,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) != &CField_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 *)&CField_Type, NULL);
- if (new_descr == NULL) {
- Py_DECREF(fdescr);
- Py_DECREF(fieldlist);
- return -1;
- }
- assert(Py_TYPE(new_descr) == &CField_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) != &CField_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 *)&CField_Type, NULL);
+ if (new_descr == NULL) {
+ Py_DECREF(fdescr);
+ Py_DECREF(fieldlist);
+ return -1;
+ }
+ assert(Py_TYPE(new_descr) == &CField_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,
@@ -265,43 +265,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) == &CField_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) == &CField_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;
}
/*
@@ -311,265 +311,265 @@ MakeAnonFields(PyObject *type)
int
StructUnionType_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 = PyInt_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 = 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 = 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 = PyInt_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 = 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 = 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,
+ 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,
#if (PY_VERSION_HEX < 0x02050000)
- "second item in _fields_ tuple (index %d) must be a C type",
+ "second item in _fields_ tuple (index %d) must be a C type",
#else
- "second item in _fields_ tuple (index %zd) must be a C type",
+ "second item in _fields_ tuple (index %zd) must be a C type",
#endif
- 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 != getentry("c")->getfunc
+ 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 != getentry("c")->getfunc
#ifdef CTYPES_UNICODE
- && dict->getfunc != getentry("u")->getfunc
+ && dict->getfunc != getentry("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 = PyString_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 = alloc_format_string(stgdict->format, buf);
- PyMem_Free(ptr);
-
- if (stgdict->format == NULL) {
- Py_DECREF(pair);
- return -1;
- }
- }
- if (isStruct) {
- prop = CField_FromDesc(desc, i,
- &field_size, bitsize, &bitofs,
- &size, &offset, &align,
- pack, big_endian);
- } else /* union */ {
- size = 0;
- offset = 0;
- align = 0;
- prop = CField_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 = PyString_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 = alloc_format_string(stgdict->format, buf);
+ PyMem_Free(ptr);
+
+ if (stgdict->format == NULL) {
+ Py_DECREF(pair);
+ return -1;
+ }
+ }
+ if (isStruct) {
+ prop = CField_FromDesc(desc, i,
+ &field_size, bitsize, &bitofs,
+ &size, &offset, &align,
+ pack, big_endian);
+ } else /* union */ {
+ size = 0;
+ offset = 0;
+ align = 0;
+ prop = CField_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 = 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 = 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 74e6bfa..04a0a28 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,7 +329,7 @@ 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 */
};
static PyObject *
@@ -342,20 +342,20 @@ PyCursesPanel_GetAttr(PyCursesPanelObject *self, char *name)
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_print*/
(getattrfunc)PyCursesPanel_GetAttr, /*tp_getattr*/
(setattrfunc)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_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
};
/* Wrapper for panel_above(NULL). This function returns the bottom
@@ -372,16 +372,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;
@@ -397,8 +397,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);
}
@@ -413,28 +413,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);
@@ -449,7 +449,7 @@ 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 */
@@ -467,7 +467,7 @@ init_curses_panel(void)
/* Create the module and add the functions */
m = Py_InitModule("_curses_panel", PyCurses_methods);
if (m == NULL)
- return;
+ return;
d = PyModule_GetDict(m);
/* For exception _curses_panel.error */
diff --git a/Modules/_functoolsmodule.c b/Modules/_functoolsmodule.c
index 5dfbc15..3e0e077 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.
@@ -14,64 +14,64 @@
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(reduce_doc,
@@ -90,12 +90,12 @@ sequence is empty.");
/* 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;
@@ -103,219 +103,219 @@ 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 */
};
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_compare */
- 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 | Py_TPFLAGS_HAVE_WEAKREFS, /* 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 */
- 0, /* 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_compare */
+ 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 | Py_TPFLAGS_HAVE_WEAKREFS, /* 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 */
+ 0, /* 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 */
};
@@ -325,31 +325,31 @@ PyDoc_STRVAR(module_doc,
"Tools that operate on functions.");
static PyMethodDef module_methods[] = {
- {"reduce", functools_reduce, METH_VARARGS, reduce_doc},
- {NULL, NULL} /* sentinel */
+ {"reduce", functools_reduce, METH_VARARGS, reduce_doc},
+ {NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
init_functools(void)
{
- int i;
- PyObject *m;
- char *name;
- PyTypeObject *typelist[] = {
- &partial_type,
- NULL
- };
-
- m = Py_InitModule3("_functools", module_methods, module_doc);
- if (m == NULL)
- return;
-
- for (i=0 ; typelist[i] != NULL ; i++) {
- if (PyType_Ready(typelist[i]) < 0)
- return;
- name = strchr(typelist[i]->tp_name, '.');
- assert (name != NULL);
- Py_INCREF(typelist[i]);
- PyModule_AddObject(m, name+1, (PyObject *)typelist[i]);
- }
+ int i;
+ PyObject *m;
+ char *name;
+ PyTypeObject *typelist[] = {
+ &partial_type,
+ NULL
+ };
+
+ m = Py_InitModule3("_functools", module_methods, module_doc);
+ if (m == NULL)
+ return;
+
+ for (i=0 ; typelist[i] != NULL ; i++) {
+ if (PyType_Ready(typelist[i]) < 0)
+ return;
+ name = strchr(typelist[i]->tp_name, '.');
+ assert (name != NULL);
+ Py_INCREF(typelist[i]);
+ PyModule_AddObject(m, name+1, (PyObject *)typelist[i]);
+ }
}
diff --git a/Modules/_heapqmodule.c b/Modules/_heapqmodule.c
index 4fd0dd5..f705ec1 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,
@@ -16,128 +16,128 @@ annotated by François Pinard, and converted to C by Raymond Hettinger.
static int
cmp_lt(PyObject *x, PyObject *y)
{
- int cmp;
- static PyObject *lt = NULL;
-
- if (lt == NULL) {
- lt = PyString_FromString("__lt__");
- if (lt == NULL)
- return -1;
- }
- if (PyObject_HasAttr(x, lt))
- return PyObject_RichCompareBool(x, y, Py_LT);
- cmp = PyObject_RichCompareBool(y, x, Py_LE);
- if (cmp != -1)
- cmp = 1 - cmp;
- return cmp;
+ int cmp;
+ static PyObject *lt = NULL;
+
+ if (lt == NULL) {
+ lt = PyString_FromString("__lt__");
+ if (lt == NULL)
+ return -1;
+ }
+ if (PyObject_HasAttr(x, lt))
+ return PyObject_RichCompareBool(x, y, Py_LT);
+ cmp = PyObject_RichCompareBool(y, x, Py_LE);
+ if (cmp != -1)
+ cmp = 1 - cmp;
+ return cmp;
}
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,
@@ -146,35 +146,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,
@@ -183,29 +183,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,
@@ -215,44 +215,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,
@@ -263,26 +263,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,
@@ -291,79 +291,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,
@@ -374,166 +374,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,
@@ -542,21 +542,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,
@@ -687,11 +687,11 @@ From all times, sorting has always been a Great Art! :-)\n");
PyMODINIT_FUNC
init_heapq(void)
{
- PyObject *m;
+ PyObject *m;
- m = Py_InitModule3("_heapq", heapq_methods, module_doc);
- if (m == NULL)
- return;
- PyModule_AddObject(m, "__about__", PyString_FromString(__about__));
+ m = Py_InitModule3("_heapq", heapq_methods, module_doc);
+ if (m == NULL)
+ return;
+ PyModule_AddObject(m, "__about__", PyString_FromString(__about__));
}
diff --git a/Modules/_hotshot.c b/Modules/_hotshot.c
index a36cd50..df8a7f9 100644
--- a/Modules/_hotshot.c
+++ b/Modules/_hotshot.c
@@ -21,10 +21,10 @@
typedef __int64 hs_time;
#define GETTIMEOFDAY(P_HS_TIME) \
- { LARGE_INTEGER _temp; \
- QueryPerformanceCounter(&_temp); \
- *(P_HS_TIME) = _temp.QuadPart; }
-
+ { LARGE_INTEGER _temp; \
+ QueryPerformanceCounter(&_temp); \
+ *(P_HS_TIME) = _temp.QuadPart; }
+
#else
#ifndef HAVE_GETTIMEOFDAY
@@ -284,7 +284,7 @@ unpack_packed_int(LogReaderObject *self, int *pvalue, int discard)
do {
/* read byte */
- if ((c = fgetc(self->logfp)) == EOF)
+ if ((c = fgetc(self->logfp)) == EOF)
return ERR_EOF;
accum |= ((c & 0x7F) >> discard) << bits;
bits += (7 - discard);
@@ -308,19 +308,19 @@ unpack_string(LogReaderObject *self, PyObject **pvalue)
int err;
int ch;
char *buf;
-
+
if ((err = unpack_packed_int(self, &len, 0)))
return err;
buf = (char *)malloc(len);
if (!buf) {
- PyErr_NoMemory();
- return ERR_EXCEPTION;
+ PyErr_NoMemory();
+ return ERR_EXCEPTION;
}
for (i=0; i < len; i++) {
ch = fgetc(self->logfp);
- buf[i] = ch;
+ buf[i] = ch;
if (ch == EOF) {
free(buf);
return ERR_EOF;
@@ -459,16 +459,16 @@ restart:
err = ERR_EOF;
else {
self->linetimings = c ? 1 : 0;
- goto restart;
- }
+ goto restart;
+ }
break;
case WHAT_FRAME_TIMES:
if ((c = fgetc(self->logfp)) == EOF)
err = ERR_EOF;
else {
self->frametimings = c ? 1 : 0;
- goto restart;
- }
+ goto restart;
+ }
break;
default:
err = ERR_BAD_RECTYPE;
@@ -876,7 +876,7 @@ tracer_callback(ProfilerObject *self, PyFrameObject *frame, int what,
case PyTrace_LINE: /* we only get these events if we asked for them */
if (self->linetimings)
return pack_lineno_tdelta(self, frame->f_lineno,
- get_tdelta(self));
+ get_tdelta(self));
else
return pack_lineno(self, frame->f_lineno);
@@ -1221,39 +1221,39 @@ PyDoc_STRVAR(profiler_object__doc__,
static PyTypeObject ProfilerType = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_hotshot.ProfilerType", /* tp_name */
- (int) sizeof(ProfilerObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)profiler_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- profiler_object__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 */
- profiler_members, /* tp_members */
- profiler_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
+ "_hotshot.ProfilerType", /* tp_name */
+ (int) sizeof(ProfilerObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)profiler_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ profiler_object__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 */
+ profiler_members, /* tp_members */
+ profiler_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
};
@@ -1277,16 +1277,16 @@ PyDoc_STRVAR(logreader__doc__,
Create a log-reader for the timing information file.");
static PySequenceMethods logreader_as_sequence = {
- 0, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- (ssizeargfunc)logreader_sq_item, /* sq_item */
- 0, /* sq_slice */
- 0, /* sq_ass_item */
- 0, /* sq_ass_slice */
- 0, /* sq_contains */
- 0, /* sq_inplace_concat */
- 0, /* sq_inplace_repeat */
+ 0, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ (ssizeargfunc)logreader_sq_item, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ 0, /* sq_contains */
+ 0, /* sq_inplace_concat */
+ 0, /* sq_inplace_repeat */
};
static PyObject *
@@ -1305,39 +1305,39 @@ static PyGetSetDef logreader_getsets[] = {
static PyTypeObject LogReaderType = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_hotshot.LogReaderType", /* tp_name */
- (int) sizeof(LogReaderObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)logreader_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &logreader_as_sequence, /* 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 */
- logreader__doc__, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)logreader_tp_iternext,/* tp_iternext */
- logreader_methods, /* tp_methods */
- logreader_members, /* tp_members */
- logreader_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
+ "_hotshot.LogReaderType", /* tp_name */
+ (int) sizeof(LogReaderObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)logreader_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &logreader_as_sequence, /* 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 */
+ logreader__doc__, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)logreader_tp_iternext,/* tp_iternext */
+ logreader_methods, /* tp_methods */
+ logreader_members, /* tp_members */
+ logreader_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
};
static PyObject *
@@ -1463,8 +1463,8 @@ write_header(ProfilerObject *self)
temp = PySys_GetObject("path");
if (temp == NULL || !PyList_Check(temp)) {
- PyErr_SetString(PyExc_RuntimeError, "sys.path must be a list");
- return -1;
+ PyErr_SetString(PyExc_RuntimeError, "sys.path must be a list");
+ return -1;
}
len = PyList_GET_SIZE(temp);
for (i = 0; i < len; ++i) {
@@ -1562,7 +1562,7 @@ hotshot_coverage(PyObject *unused, PyObject *args)
return result;
}
-PyDoc_VAR(resolution__doc__) =
+PyDoc_VAR(resolution__doc__) =
#ifdef MS_WINDOWS
PyDoc_STR(
"resolution() -> (performance-counter-ticks, update-frequency)\n"
diff --git a/Modules/_localemodule.c b/Modules/_localemodule.c
index bf5d58d..7e475da 100644
--- a/Modules/_localemodule.c
+++ b/Modules/_localemodule.c
@@ -165,7 +165,7 @@ PyLocale_setlocale(PyObject* self, PyObject* args)
PyObject *result_object;
if (!PyArg_ParseTuple(args, "i|z:setlocale", &category, &locale))
- return NULL;
+ return NULL;
if (locale) {
/* set locale */
@@ -272,7 +272,7 @@ PyLocale_strcoll(PyObject* self, PyObject* args)
{
#if !defined(HAVE_WCSCOLL) || !defined(Py_USING_UNICODE)
char *s1,*s2;
-
+
if (!PyArg_ParseTuple(args, "ss:strcoll", &s1, &s2))
return NULL;
return PyInt_FromLong(strcoll(s1, s2));
@@ -280,7 +280,7 @@ PyLocale_strcoll(PyObject* self, PyObject* args)
PyObject *os1, *os2, *result = NULL;
wchar_t *ws1 = NULL, *ws2 = NULL;
int rel1 = 0, rel2 = 0, len1, len2;
-
+
if (!PyArg_UnpackTuple(args, "strcoll", 2, 2, &os1, &os2))
return NULL;
/* If both arguments are byte strings, use strcoll. */
@@ -305,7 +305,7 @@ PyLocale_strcoll(PyObject* self, PyObject* args)
Py_DECREF(os1);
}
return NULL;
- }
+ }
rel2 = 1;
}
/* Convert the unicode strings to wchar[]. */
@@ -434,7 +434,7 @@ static char *mac_getscript(void)
/* This leaks an object. */
name = CFStringConvertEncodingToIANACharSetName(enc);
}
- return (char *)CFStringGetCStringPtr(name, 0);
+ return (char *)CFStringGetCStringPtr(name, 0);
}
static PyObject*
@@ -447,9 +447,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),
@@ -567,12 +567,12 @@ PyLocale_nl_langinfo(PyObject* self, PyObject* args)
returns numeric values in the char* return value, which would
crash PyString_FromString. */
for (i = 0; langinfo_constants[i].name; i++)
- if (langinfo_constants[i].value == item) {
- /* Check NULL as a workaround for GNU libc's returning NULL
- instead of an empty string for nl_langinfo(ERA). */
- const char *result = nl_langinfo(item);
- return PyString_FromString(result != NULL ? result : "");
- }
+ if (langinfo_constants[i].value == item) {
+ /* Check NULL as a workaround for GNU libc's returning NULL
+ instead of an empty string for nl_langinfo(ERA). */
+ const char *result = nl_langinfo(item);
+ return PyString_FromString(result != NULL ? result : "");
+ }
PyErr_SetString(PyExc_ValueError, "unsupported langinfo constant");
return NULL;
}
@@ -587,10 +587,10 @@ PyDoc_STRVAR(gettext__doc__,
static PyObject*
PyIntl_gettext(PyObject* self, PyObject *args)
{
- char *in;
- if (!PyArg_ParseTuple(args, "s", &in))
- return 0;
- return PyString_FromString(gettext(in));
+ char *in;
+ if (!PyArg_ParseTuple(args, "s", &in))
+ return 0;
+ return PyString_FromString(gettext(in));
}
PyDoc_STRVAR(dgettext__doc__,
@@ -600,10 +600,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 PyString_FromString(dgettext(domain, in));
+ char *domain, *in;
+ if (!PyArg_ParseTuple(args, "zs", &domain, &in))
+ return 0;
+ return PyString_FromString(dgettext(domain, in));
}
PyDoc_STRVAR(dcgettext__doc__,
@@ -613,11 +613,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 PyString_FromString(dcgettext(domain,msgid,category));
+ char *domain, *msgid;
+ int category;
+ if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category))
+ return 0;
+ return PyString_FromString(dcgettext(domain,msgid,category));
}
PyDoc_STRVAR(textdomain__doc__,
@@ -627,15 +627,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 PyString_FromString(domain);
+ char *domain;
+ if (!PyArg_ParseTuple(args, "z", &domain))
+ return 0;
+ domain = textdomain(domain);
+ if (!domain) {
+ PyErr_SetFromErrno(PyExc_OSError);
+ return NULL;
+ }
+ return PyString_FromString(domain);
}
PyDoc_STRVAR(bindtextdomain__doc__,
@@ -645,19 +645,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 PyString_FromString(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 PyString_FromString(dirname);
}
#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
@@ -668,26 +668,26 @@ 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 PyString_FromString(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 PyString_FromString(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__},
- {"strcoll", (PyCFunction) PyLocale_strcoll,
+ {"strcoll", (PyCFunction) PyLocale_strcoll,
METH_VARARGS, strcoll__doc__},
- {"strxfrm", (PyCFunction) PyLocale_strxfrm,
+ {"strxfrm", (PyCFunction) PyLocale_strxfrm,
METH_VARARGS, strxfrm__doc__},
#if defined(MS_WINDOWS) || defined(__APPLE__)
{"_getdefaultlocale", (PyCFunction) PyLocale_getdefaultlocale, METH_NOARGS},
@@ -711,7 +711,7 @@ static struct PyMethodDef PyLocale_Methods[] = {
{"bind_textdomain_codeset",(PyCFunction)PyIntl_bind_textdomain_codeset,
METH_VARARGS, bind_textdomain_codeset__doc__},
#endif
-#endif
+#endif
{NULL, NULL}
};
@@ -725,7 +725,7 @@ init_locale(void)
m = Py_InitModule("_locale", PyLocale_Methods);
if (m == NULL)
- return;
+ return;
d = PyModule_GetDict(m);
@@ -772,13 +772,13 @@ init_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
}
-/*
+/*
Local variables:
c-basic-offset: 4
indent-tabs-mode: nil
diff --git a/Modules/_lsprof.c b/Modules/_lsprof.c
index 8820fcf..049c94d 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;
- char *modname;
- if (mod && PyString_Check(mod)) {
- modname = PyString_AS_STRING(mod);
- }
- else if (mod && PyModule_Check(mod)) {
- modname = PyModule_GetName(mod);
- if (modname == NULL) {
- PyErr_Clear();
- modname = "__builtin__";
- }
- }
- else {
- modname = "__builtin__";
- }
- if (strcmp(modname, "__builtin__") != 0)
- return PyString_FromFormat("<%s.%s>",
- modname,
- fn->m_ml->ml_name);
- else
- return PyString_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 = PyString_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 PyString_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;
+ char *modname;
+ if (mod && PyString_Check(mod)) {
+ modname = PyString_AS_STRING(mod);
+ }
+ else if (mod && PyModule_Check(mod)) {
+ modname = PyModule_GetName(mod);
+ if (modname == NULL) {
+ PyErr_Clear();
+ modname = "__builtin__";
+ }
+ }
+ else {
+ modname = "__builtin__";
+ }
+ if (strcmp(modname, "__builtin__") != 0)
+ return PyString_FromFormat("<%s.%s>",
+ modname,
+ fn->m_ml->ml_name);
+ else
+ return PyString_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 = PyString_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 PyString_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,76 +817,76 @@ Profiler(custom_timer=None, time_unit=None, subcalls=True, builtins=True)\n\
");
statichere PyTypeObject PyProfiler_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /* ob_size */
- "_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_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- 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 */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* ob_size */
+ "_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_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 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}
};
PyMODINIT_FUNC
init_lsprof(void)
{
- PyObject *module, *d;
- module = Py_InitModule3("_lsprof", moduleMethods, "Fast profiler");
- if (module == NULL)
- return;
- d = PyModule_GetDict(module);
- if (PyType_Ready(&PyProfiler_Type) < 0)
- return;
- 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;
+ PyObject *module, *d;
+ module = Py_InitModule3("_lsprof", moduleMethods, "Fast profiler");
+ if (module == NULL)
+ return;
+ d = PyModule_GetDict(module);
+ if (PyType_Ready(&PyProfiler_Type) < 0)
+ return;
+ 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;
}
diff --git a/Modules/_multiprocessing/connection.h b/Modules/_multiprocessing/connection.h
index 458d1d3..f6db851 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,156 +96,156 @@ connection_dealloc(ConnectionObject* self)
static PyObject *
connection_sendbytes(ConnectionObject *self, PyObject *args)
{
- 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,
- &buffer, &length, &offset, &size))
- return NULL;
-
- CHECK_WRITABLE(self);
-
- if (offset < 0) {
- PyErr_SetString(PyExc_ValueError, "offset is negative");
- return NULL;
- }
- if (length < offset) {
- PyErr_SetString(PyExc_ValueError, "buffer length < offset");
- return NULL;
- }
-
- if (size == PY_SSIZE_T_MIN) {
- size = length - offset;
- } else {
- if (size < 0) {
- PyErr_SetString(PyExc_ValueError, "size is negative");
- return NULL;
- }
- if (offset + size > length) {
- PyErr_SetString(PyExc_ValueError,
- "buffer length < offset + size");
- return NULL;
- }
- }
-
- res = conn_send_string(self, buffer + offset, size);
-
- if (res < 0)
- return mp_SetError(PyExc_IOError, res);
-
- Py_RETURN_NONE;
+ 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,
+ &buffer, &length, &offset, &size))
+ return NULL;
+
+ CHECK_WRITABLE(self);
+
+ if (offset < 0) {
+ PyErr_SetString(PyExc_ValueError, "offset is negative");
+ return NULL;
+ }
+ if (length < offset) {
+ PyErr_SetString(PyExc_ValueError, "buffer length < offset");
+ return NULL;
+ }
+
+ if (size == PY_SSIZE_T_MIN) {
+ size = length - offset;
+ } else {
+ if (size < 0) {
+ PyErr_SetString(PyExc_ValueError, "size is negative");
+ return NULL;
+ }
+ if (offset + size > length) {
+ PyErr_SetString(PyExc_ValueError,
+ "buffer length < offset + size");
+ return NULL;
+ }
+ }
+
+ res = conn_send_string(self, buffer + offset, size);
+
+ if (res < 0)
+ 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 = PyString_FromStringAndSize(self->buffer, res);
- } else {
- result = PyString_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 = PyString_FromStringAndSize(self->buffer, res);
+ } else {
+ result = PyString_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;
}
/*
@@ -255,74 +255,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 (PyString_AsStringAndSize(pickled_string, &buffer, &length) < 0)
- goto failure;
+ if (PyString_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 = PyString_FromStringAndSize(self->buffer, res);
- } else {
- temp = PyString_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 = PyString_FromStringAndSize(self->buffer, res);
+ } else {
+ temp = PyString_FromStringAndSize(freeme, res);
+ PyMem_Free(freeme);
+ }
+ }
+
+ if (temp)
+ result = PyObject_CallFunctionObjArgs(pickle_loads,
+ temp, NULL);
+ Py_XDECREF(temp);
+ return result;
}
/*
@@ -332,73 +332,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);
}
/*
@@ -408,19 +408,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));
}
/*
@@ -428,37 +428,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}
};
/*
@@ -466,50 +466,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_compare */ 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_compare */ 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 48049c7..e593950 100644
--- a/Modules/_multiprocessing/multiprocessing.c
+++ b/Modules/_multiprocessing/multiprocessing.c
@@ -20,46 +20,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;
}
@@ -76,8 +76,8 @@ HANDLE sigint_event = NULL;
static BOOL WINAPI
ProcessingCtrlHandler(DWORD dwCtrlType)
{
- SetEvent(sigint_event);
- return FALSE;
+ SetEvent(sigint_event);
+ return FALSE;
}
/*
@@ -95,72 +95,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 */
@@ -175,14 +175,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);
}
@@ -191,20 +191,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}
};
@@ -215,97 +215,97 @@ static PyMethodDef module_methods[] = {
PyMODINIT_FUNC
init_multiprocessing(void)
{
- PyObject *module, *temp, *value;
-
- /* Initialize module */
- module = Py_InitModule("_multiprocessing", module_methods);
- if (!module)
- return;
-
- /* Get copy of objects from pickle */
- temp = PyImport_ImportModule(PICKLE_MODULE);
- if (!temp)
- return;
- 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;
- BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort");
- Py_XDECREF(temp);
-
- /* Add connection type to module */
- if (PyType_Ready(&ConnectionType) < 0)
- return;
- Py_INCREF(&ConnectionType);
- PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType);
+ PyObject *module, *temp, *value;
+
+ /* Initialize module */
+ module = Py_InitModule("_multiprocessing", module_methods);
+ if (!module)
+ return;
+
+ /* Get copy of objects from pickle */
+ temp = PyImport_ImportModule(PICKLE_MODULE);
+ if (!temp)
+ return;
+ 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;
+ BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort");
+ Py_XDECREF(temp);
+
+ /* Add connection type to module */
+ if (PyType_Ready(&ConnectionType) < 0)
+ return;
+ Py_INCREF(&ConnectionType);
+ PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType);
#if defined(MS_WINDOWS) || HAVE_SEM_OPEN
- /* Add SemLock type to module */
- if (PyType_Ready(&SemLockType) < 0)
- return;
- 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;
+ 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;
- Py_INCREF(&PipeConnectionType);
- PyModule_AddObject(module, "PipeConnection",
- (PyObject*)&PipeConnectionType);
-
- /* Initialize win32 class and add to multiprocessing */
- temp = create_win32_namespace();
- if (!temp)
- return;
- 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;
- }
- if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) {
- PyErr_SetFromWindowsErr(0);
- return;
- }
+ /* Add PipeConnection to module */
+ if (PyType_Ready(&PipeConnectionType) < 0)
+ return;
+ Py_INCREF(&PipeConnectionType);
+ PyModule_AddObject(module, "PipeConnection",
+ (PyObject*)&PipeConnectionType);
+
+ /* Initialize win32 class and add to multiprocessing */
+ temp = create_win32_namespace();
+ if (!temp)
+ return;
+ 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;
+ }
+ if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) {
+ PyErr_SetFromWindowsErr(0);
+ return;
+ }
#endif
- /* Add configuration macros */
- temp = PyDict_New();
- if (!temp)
- return;
-#define ADD_FLAG(name) \
- value = Py_BuildValue("i", name); \
- if (value == NULL) { Py_DECREF(temp); return; } \
- if (PyDict_SetItemString(temp, #name, value) < 0) { \
- Py_DECREF(temp); Py_DECREF(value); return; } \
- Py_DECREF(value)
-
+ /* Add configuration macros */
+ temp = PyDict_New();
+ if (!temp)
+ return;
+#define ADD_FLAG(name) \
+ value = Py_BuildValue("i", name); \
+ if (value == NULL) { Py_DECREF(temp); return; } \
+ if (PyDict_SetItemString(temp, #name, value) < 0) { \
+ Py_DECREF(temp); Py_DECREF(value); return; } \
+ Py_DECREF(value)
+
#ifdef HAVE_SEM_OPEN
- 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;
+ if (PyModule_AddObject(module, "flags", temp) < 0)
+ return;
}
diff --git a/Modules/_multiprocessing/pipe_connection.c b/Modules/_multiprocessing/pipe_connection.c
index 27e79dd..ee5836f 100644
--- a/Modules/_multiprocessing/pipe_connection.c
+++ b/Modules/_multiprocessing/pipe_connection.c
@@ -17,13 +17,13 @@
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
- return ret ? MP_SUCCESS : MP_STANDARD_ERROR;
+ Py_BEGIN_ALLOW_THREADS
+ ret = WriteFile(conn->handle, string, length, &amount_written, NULL);
+ Py_END_ALLOW_THREADS
+ return ret ? MP_SUCCESS : MP_STANDARD_ERROR;
}
/*
@@ -33,50 +33,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;
+ }
}
/*
@@ -86,51 +86,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 2c2fb10..261e67c 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 {
#if 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)
{
#if 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)
{
#if 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_compare */ 0,
- /* tp_repr */ 0,
- /* tp_as_number */ 0,
- /* tp_as_sequence */ 0,
- /* tp_as_mapping */ 0,
- /* tp_hash */ 0,
- /* tp_call */ 0,
- /* tp_str */ 0,
- /* tp_getattro */ 0,
- /* tp_setattro */ 0,
- /* tp_as_buffer */ 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_compare */ 0,
+ /* tp_repr */ 0,
+ /* tp_as_number */ 0,
+ /* tp_as_sequence */ 0,
+ /* tp_as_mapping */ 0,
+ /* tp_hash */ 0,
+ /* tp_call */ 0,
+ /* tp_str */ 0,
+ /* tp_getattro */ 0,
+ /* tp_setattro */ 0,
+ /* tp_as_buffer */ 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 549c151..1666aa9 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] = PyInt_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] = PyInt_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 b45f243..2d81daf 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,167 +206,167 @@ 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 (PyInt_Check(arg) || 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 = PyInt_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 (PyInt_Check(arg) || 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 = PyInt_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;
}
/*
@@ -389,7 +389,7 @@ each element at position i. Successive calls are then guaranteed to
have changing (growing) values as well as shuffled positions.
Finally, the self->index value is set to N so that the generator itself
-kicks in on the next call to random(). This assures that all results
+kicks in on the next call to random(). This assures that all results
have been through the generator and do not just reflect alterations to
the underlying state.
*/
@@ -397,169 +397,169 @@ the underlying state.
static PyObject *
random_jumpahead(RandomObject *self, PyObject *n)
{
- long i, j;
- PyObject *iobj;
- PyObject *remobj;
- unsigned long *mt, tmp;
-
- if (!PyInt_Check(n) && !PyLong_Check(n)) {
- PyErr_Format(PyExc_TypeError, "jumpahead requires an "
- "integer, not '%s'",
- Py_TYPE(n)->tp_name);
- return NULL;
- }
-
- mt = self->state;
- for (i = N-1; i > 1; i--) {
- iobj = PyInt_FromLong(i);
- if (iobj == NULL)
- return NULL;
- remobj = PyNumber_Remainder(n, iobj);
- Py_DECREF(iobj);
- if (remobj == NULL)
- return NULL;
- j = PyInt_AsLong(remobj);
- Py_DECREF(remobj);
- if (j == -1L && PyErr_Occurred())
- return NULL;
- tmp = mt[i];
- mt[i] = mt[j];
- mt[j] = tmp;
- }
-
- for (i = 0; i < N; i++)
- mt[i] += i+1;
-
- self->index = N;
- Py_INCREF(Py_None);
- return Py_None;
+ long i, j;
+ PyObject *iobj;
+ PyObject *remobj;
+ unsigned long *mt, tmp;
+
+ if (!PyInt_Check(n) && !PyLong_Check(n)) {
+ PyErr_Format(PyExc_TypeError, "jumpahead requires an "
+ "integer, not '%s'",
+ Py_TYPE(n)->tp_name);
+ return NULL;
+ }
+
+ mt = self->state;
+ for (i = N-1; i > 1; i--) {
+ iobj = PyInt_FromLong(i);
+ if (iobj == NULL)
+ return NULL;
+ remobj = PyNumber_Remainder(n, iobj);
+ Py_DECREF(iobj);
+ if (remobj == NULL)
+ return NULL;
+ j = PyInt_AsLong(remobj);
+ Py_DECREF(remobj);
+ if (j == -1L && PyErr_Occurred())
+ return NULL;
+ tmp = mt[i];
+ mt[i] = mt[j];
+ mt[j] = tmp;
+ }
+
+ for (i = 0; i < N; i++)
+ mt[i] += i+1;
+
+ self->index = N;
+ 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.")},
- {"jumpahead", (PyCFunction)random_jumpahead, METH_O,
- PyDoc_STR("jumpahead(int) -> None. Create new state from "
- "existing state and integer.")},
- {"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.")},
+ {"jumpahead", (PyCFunction)random_jumpahead, METH_O,
+ PyDoc_STR("jumpahead(int) -> None. Create new state from "
+ "existing state and integer.")},
+ {"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_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*/
- 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_Del, /*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_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*/
+ 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_Del, /*tp_free*/
+ 0, /*tp_is_gc*/
};
PyDoc_STRVAR(module_doc,
@@ -568,13 +568,13 @@ PyDoc_STRVAR(module_doc,
PyMODINIT_FUNC
init_random(void)
{
- PyObject *m;
-
- if (PyType_Ready(&Random_Type) < 0)
- return;
- m = Py_InitModule3("_random", NULL, module_doc);
- if (m == NULL)
- return;
- Py_INCREF(&Random_Type);
- PyModule_AddObject(m, "Random", (PyObject *)&Random_Type);
+ PyObject *m;
+
+ if (PyType_Ready(&Random_Type) < 0)
+ return;
+ m = Py_InitModule3("_random", NULL, module_doc);
+ if (m == NULL)
+ return;
+ Py_INCREF(&Random_Type);
+ PyModule_AddObject(m, "Random", (PyObject *)&Random_Type);
}
diff --git a/Modules/_struct.c b/Modules/_struct.c
index d924cad..6d2452b 100644
--- a/Modules/_struct.c
+++ b/Modules/_struct.c
@@ -44,30 +44,30 @@ static PyObject *pyint_zero = NULL;
/* 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;
@@ -124,27 +124,27 @@ typedef struct { char c; _Bool x; } s_bool;
static PyObject *
get_pylong(PyObject *v)
{
- PyNumberMethods *m;
-
- assert(v != NULL);
- if (PyInt_Check(v))
- return PyLong_FromLong(PyInt_AS_LONG(v));
- if (PyLong_Check(v)) {
- Py_INCREF(v);
- return v;
- }
- m = Py_TYPE(v)->tp_as_number;
- if (m != NULL && m->nb_long != NULL) {
- v = m->nb_long(v);
- if (v == NULL)
- return NULL;
- if (PyLong_Check(v))
- return v;
- Py_DECREF(v);
- }
- PyErr_SetString(StructError,
- "cannot convert argument to long");
- return NULL;
+ PyNumberMethods *m;
+
+ assert(v != NULL);
+ if (PyInt_Check(v))
+ return PyLong_FromLong(PyInt_AS_LONG(v));
+ if (PyLong_Check(v)) {
+ Py_INCREF(v);
+ return v;
+ }
+ m = Py_TYPE(v)->tp_as_number;
+ if (m != NULL && m->nb_long != NULL) {
+ v = m->nb_long(v);
+ if (v == NULL)
+ return NULL;
+ if (PyLong_Check(v))
+ return v;
+ Py_DECREF(v);
+ }
+ PyErr_SetString(StructError,
+ "cannot convert argument to long");
+ return NULL;
}
/* Helper routine to get a Python integer and raise the appropriate error
@@ -153,30 +153,30 @@ get_pylong(PyObject *v)
static int
get_long(PyObject *v, long *p)
{
- long x = PyInt_AsLong(v);
- if (x == -1 && PyErr_Occurred()) {
+ long x = PyInt_AsLong(v);
+ if (x == -1 && PyErr_Occurred()) {
#ifdef PY_STRUCT_FLOAT_COERCE
- if (PyFloat_Check(v)) {
- PyObject *o;
- int res;
- PyErr_Clear();
- if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 1) < 0)
- return -1;
- o = PyNumber_Int(v);
- if (o == NULL)
- return -1;
- res = get_long(o, p);
- Py_DECREF(o);
- return res;
- }
+ if (PyFloat_Check(v)) {
+ PyObject *o;
+ int res;
+ PyErr_Clear();
+ if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 1) < 0)
+ return -1;
+ o = PyNumber_Int(v);
+ if (o == NULL)
+ return -1;
+ res = get_long(o, p);
+ Py_DECREF(o);
+ return res;
+ }
#endif
- if (PyErr_ExceptionMatches(PyExc_TypeError))
- PyErr_SetString(StructError,
- "required argument is not an integer");
- return -1;
- }
- *p = x;
- return 0;
+ if (PyErr_ExceptionMatches(PyExc_TypeError))
+ PyErr_SetString(StructError,
+ "required argument is not an integer");
+ return -1;
+ }
+ *p = x;
+ return 0;
}
@@ -187,21 +187,21 @@ get_long(PyObject *v, long *p)
static int
get_ulong(PyObject *v, unsigned long *p)
{
- if (PyLong_Check(v)) {
- unsigned long x = PyLong_AsUnsignedLong(v);
- if (x == (unsigned long)(-1) && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
- }
- if (get_long(v, (long *)p) < 0)
- return -1;
- if (((long)*p) < 0) {
- PyErr_SetString(StructError,
- "unsigned argument is < 0");
- return -1;
- }
- return 0;
+ if (PyLong_Check(v)) {
+ unsigned long x = PyLong_AsUnsignedLong(v);
+ if (x == (unsigned long)(-1) && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
+ }
+ if (get_long(v, (long *)p) < 0)
+ return -1;
+ if (((long)*p) < 0) {
+ PyErr_SetString(StructError,
+ "unsigned argument is < 0");
+ return -1;
+ }
+ return 0;
}
#endif /* PY_STRUCT_OVERFLOW_MASKING */
@@ -213,18 +213,18 @@ 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())
- 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())
+ return -1;
+ *p = x;
+ return 0;
}
/* Same, but handling native unsigned long long. */
@@ -232,18 +232,18 @@ 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())
- 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())
+ return -1;
+ *p = x;
+ return 0;
}
#endif
@@ -258,89 +258,89 @@ get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
static int
get_wrapped_long(PyObject *v, long *p)
{
- if (get_long(v, p) < 0) {
- if (PyLong_Check(v) &&
- PyErr_ExceptionMatches(PyExc_OverflowError)) {
- PyObject *wrapped;
- long x;
- PyErr_Clear();
+ if (get_long(v, p) < 0) {
+ if (PyLong_Check(v) &&
+ PyErr_ExceptionMatches(PyExc_OverflowError)) {
+ PyObject *wrapped;
+ long x;
+ PyErr_Clear();
#ifdef PY_STRUCT_FLOAT_COERCE
- if (PyFloat_Check(v)) {
- PyObject *o;
- int res;
- PyErr_Clear();
- if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 1) < 0)
- return -1;
- o = PyNumber_Int(v);
- if (o == NULL)
- return -1;
- res = get_wrapped_long(o, p);
- Py_DECREF(o);
- return res;
- }
+ if (PyFloat_Check(v)) {
+ PyObject *o;
+ int res;
+ PyErr_Clear();
+ if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 1) < 0)
+ return -1;
+ o = PyNumber_Int(v);
+ if (o == NULL)
+ return -1;
+ res = get_wrapped_long(o, p);
+ Py_DECREF(o);
+ return res;
+ }
#endif
- if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 1) < 0)
- return -1;
- wrapped = PyNumber_And(v, pylong_ulong_mask);
- if (wrapped == NULL)
- return -1;
- x = (long)PyLong_AsUnsignedLong(wrapped);
- Py_DECREF(wrapped);
- if (x == -1 && PyErr_Occurred())
- return -1;
- *p = x;
- } else {
- return -1;
- }
- }
- return 0;
+ if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 1) < 0)
+ return -1;
+ wrapped = PyNumber_And(v, pylong_ulong_mask);
+ if (wrapped == NULL)
+ return -1;
+ x = (long)PyLong_AsUnsignedLong(wrapped);
+ Py_DECREF(wrapped);
+ if (x == -1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ } else {
+ return -1;
+ }
+ }
+ return 0;
}
static int
get_wrapped_ulong(PyObject *v, unsigned long *p)
{
- long x = (long)PyLong_AsUnsignedLong(v);
- if (x == -1 && PyErr_Occurred()) {
- PyObject *wrapped;
- PyErr_Clear();
+ long x = (long)PyLong_AsUnsignedLong(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyObject *wrapped;
+ PyErr_Clear();
#ifdef PY_STRUCT_FLOAT_COERCE
- if (PyFloat_Check(v)) {
- PyObject *o;
- int res;
- PyErr_Clear();
- if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 1) < 0)
- return -1;
- o = PyNumber_Int(v);
- if (o == NULL)
- return -1;
- res = get_wrapped_ulong(o, p);
- Py_DECREF(o);
- return res;
- }
+ if (PyFloat_Check(v)) {
+ PyObject *o;
+ int res;
+ PyErr_Clear();
+ if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 1) < 0)
+ return -1;
+ o = PyNumber_Int(v);
+ if (o == NULL)
+ return -1;
+ res = get_wrapped_ulong(o, p);
+ Py_DECREF(o);
+ return res;
+ }
#endif
- wrapped = PyNumber_And(v, pylong_ulong_mask);
- if (wrapped == NULL)
- return -1;
- if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 1) < 0) {
- Py_DECREF(wrapped);
- return -1;
- }
- x = (long)PyLong_AsUnsignedLong(wrapped);
- Py_DECREF(wrapped);
- if (x == -1 && PyErr_Occurred())
- return -1;
- }
- *p = (unsigned long)x;
- return 0;
+ wrapped = PyNumber_And(v, pylong_ulong_mask);
+ if (wrapped == NULL)
+ return -1;
+ if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 1) < 0) {
+ Py_DECREF(wrapped);
+ return -1;
+ }
+ x = (long)PyLong_AsUnsignedLong(wrapped);
+ Py_DECREF(wrapped);
+ if (x == -1 && PyErr_Occurred())
+ return -1;
+ }
+ *p = (unsigned long)x;
+ return 0;
}
#define RANGE_ERROR(x, f, flag, mask) \
- do { \
- if (_range_error(f, flag) < 0) \
- return -1; \
- else \
- (x) &= (mask); \
- } while (0)
+ do { \
+ if (_range_error(f, flag) < 0) \
+ return -1; \
+ else \
+ (x) &= (mask); \
+ } while (0)
#else
@@ -354,76 +354,76 @@ get_wrapped_ulong(PyObject *v, unsigned 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);
- }
+ /* 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);
+ }
#ifdef PY_STRUCT_OVERFLOW_MASKING
- {
- PyObject *ptype, *pvalue, *ptraceback;
- PyObject *msg;
- int rval;
- PyErr_Fetch(&ptype, &pvalue, &ptraceback);
- assert(pvalue != NULL);
- msg = PyObject_Str(pvalue);
- Py_XDECREF(ptype);
- Py_XDECREF(pvalue);
- Py_XDECREF(ptraceback);
- if (msg == NULL)
- return -1;
- rval = PyErr_WarnEx(PyExc_DeprecationWarning,
- PyString_AS_STRING(msg), 1);
- Py_DECREF(msg);
- if (rval == 0)
- return 0;
- }
+ {
+ PyObject *ptype, *pvalue, *ptraceback;
+ PyObject *msg;
+ int rval;
+ PyErr_Fetch(&ptype, &pvalue, &ptraceback);
+ assert(pvalue != NULL);
+ msg = PyObject_Str(pvalue);
+ Py_XDECREF(ptype);
+ Py_XDECREF(pvalue);
+ Py_XDECREF(ptraceback);
+ if (msg == NULL)
+ return -1;
+ rval = PyErr_WarnEx(PyExc_DeprecationWarning,
+ PyString_AS_STRING(msg), 1);
+ Py_DECREF(msg);
+ if (rval == 0)
+ return 0;
+ }
#endif
- return -1;
+ return -1;
}
@@ -450,75 +450,75 @@ _range_error(const formatdef *f, int is_unsigned)
static PyObject *
nu_char(const char *p, const formatdef *f)
{
- return PyString_FromStringAndSize(p, 1);
+ return PyString_FromStringAndSize(p, 1);
}
static PyObject *
nu_byte(const char *p, const formatdef *f)
{
- return PyInt_FromLong((long) *(signed char *)p);
+ return PyInt_FromLong((long) *(signed char *)p);
}
static PyObject *
nu_ubyte(const char *p, const formatdef *f)
{
- return PyInt_FromLong((long) *(unsigned char *)p);
+ return PyInt_FromLong((long) *(unsigned char *)p);
}
static PyObject *
nu_short(const char *p, const formatdef *f)
{
- short x;
- memcpy((char *)&x, p, sizeof x);
- return PyInt_FromLong((long)x);
+ short x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyInt_FromLong((long)x);
}
static PyObject *
nu_ushort(const char *p, const formatdef *f)
{
- unsigned short x;
- memcpy((char *)&x, p, sizeof x);
- return PyInt_FromLong((long)x);
+ unsigned short x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyInt_FromLong((long)x);
}
static PyObject *
nu_int(const char *p, const formatdef *f)
{
- int x;
- memcpy((char *)&x, p, sizeof x);
- return PyInt_FromLong((long)x);
+ int x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyInt_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 PyInt_FromLong((long)x);
+ return PyInt_FromLong((long)x);
#else
- if (x <= ((unsigned int)LONG_MAX))
- return PyInt_FromLong((long)x);
- return PyLong_FromUnsignedLong((unsigned long)x);
+ if (x <= ((unsigned int)LONG_MAX))
+ return PyInt_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 PyInt_FromLong(x);
+ long x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyInt_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 PyInt_FromLong((long)x);
- return PyLong_FromUnsignedLong(x);
+ unsigned long x;
+ memcpy((char *)&x, p, sizeof x);
+ if (x <= LONG_MAX)
+ return PyInt_FromLong((long)x);
+ return PyLong_FromUnsignedLong(x);
}
/* Native mode doesn't support q or Q unless the platform C supports
@@ -529,21 +529,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 PyInt_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 PyInt_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 PyInt_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 PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
+ return PyLong_FromUnsignedLongLong(x);
}
#endif
@@ -551,163 +551,163 @@ 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 (!PyString_Check(v) || PyString_Size(v) != 1) {
- PyErr_SetString(StructError,
- "char format require string of length 1");
- return -1;
- }
- *p = *PyString_AsString(v);
- return 0;
+ if (!PyString_Check(v) || PyString_Size(v) != 1) {
+ PyErr_SetString(StructError,
+ "char format require string of length 1");
+ return -1;
+ }
+ *p = *PyString_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_wrapped_ulong(v, &x) < 0)
- return -1;
- y = (unsigned int)x;
+ unsigned long x;
+ unsigned int y;
+ if (get_wrapped_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_wrapped_ulong(v, &x) < 0)
- return -1;
- memcpy(p, (char *)&x, sizeof x);
- return 0;
+ unsigned long x;
+ if (get_wrapped_ulong(v, &x) < 0)
+ return -1;
+ memcpy(p, (char *)&x, sizeof x);
+ return 0;
}
#ifdef HAVE_LONG_LONG
@@ -715,21 +715,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
@@ -737,77 +737,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. *****************************************************/
@@ -815,53 +815,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 PyInt_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 PyInt_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 PyInt_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 PyInt_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 PyInt_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 PyInt_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
}
@@ -869,181 +869,181 @@ 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 PyInt_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 PyInt_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_wrapped_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_wrapped_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
#ifdef PY_STRUCT_OVERFLOW_MASKING
- else if ((i == 1) && (x < -128 || x > 127))
- RANGE_ERROR(x, f, 0, 0xffL);
+ else if ((i == 1) && (x < -128 || x > 127))
+ RANGE_ERROR(x, f, 0, 0xffL);
#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_wrapped_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_wrapped_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},
+ {'x', 1, 0, NULL},
#ifdef PY_STRUCT_OVERFLOW_MASKING
- /* Native packers do range checking without overflow masking. */
- {'b', 1, 0, nu_byte, bp_int},
- {'B', 1, 0, nu_ubyte, bp_uint},
+ /* Native packers do range checking without overflow masking. */
+ {'b', 1, 0, nu_byte, bp_int},
+ {'B', 1, 0, nu_ubyte, bp_uint},
#else
- {'b', 1, 0, nu_byte, np_byte},
- {'B', 1, 0, nu_ubyte, np_ubyte},
+ {'b', 1, 0, nu_byte, np_byte},
+ {'B', 1, 0, nu_ubyte, np_ubyte},
#endif
- {'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}
+ {'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. *****************************************************/
@@ -1051,53 +1051,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 PyInt_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 PyInt_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 PyInt_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 PyInt_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 PyInt_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 PyInt_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
}
@@ -1105,192 +1105,192 @@ 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 PyInt_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 PyInt_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_wrapped_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_wrapped_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
#ifdef PY_STRUCT_OVERFLOW_MASKING
- else if ((i == 1) && (x < -128 || x > 127))
- RANGE_ERROR(x, f, 0, 0xffL);
+ else if ((i == 1) && (x < -128 || x > 127))
+ RANGE_ERROR(x, f, 0, 0xffL);
#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_wrapped_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_wrapped_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},
+ {'x', 1, 0, NULL},
#ifdef PY_STRUCT_OVERFLOW_MASKING
- /* Native packers do range checking without overflow masking. */
- {'b', 1, 0, nu_byte, lp_int},
- {'B', 1, 0, nu_ubyte, lp_uint},
+ /* Native packers do range checking without overflow masking. */
+ {'b', 1, 0, nu_byte, lp_int},
+ {'B', 1, 0, nu_ubyte, lp_uint},
#else
- {'b', 1, 0, nu_byte, np_byte},
- {'B', 1, 0, nu_ubyte, np_ubyte},
+ {'b', 1, 0, nu_byte, np_byte},
+ {'B', 1, 0, nu_ubyte, np_ubyte},
#endif
- {'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}
+ {'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;
+ }
}
@@ -1299,13 +1299,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;
}
@@ -1314,14 +1314,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;
}
@@ -1330,207 +1330,207 @@ 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 = PyString_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 = PyString_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, "S:Struct", kwlist,
- &o_format))
- return -1;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
+ &o_format))
+ return -1;
- Py_INCREF(o_format);
- Py_CLEAR(soself->s_format);
- soself->s_format = o_format;
+ Py_INCREF(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 = PyString_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 = PyString_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 = PyString_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 = PyString_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;
}
@@ -1544,35 +1544,35 @@ strings.");
static PyObject *
s_unpack(PyObject *self, PyObject *inputstr)
{
- char *start;
- Py_ssize_t len;
- PyObject *args=NULL, *result;
- PyStructObject *soself = (PyStructObject *)self;
- assert(PyStruct_Check(self));
- assert(soself->s_codes != NULL);
- if (inputstr == NULL)
- goto fail;
- if (PyString_Check(inputstr) &&
- PyString_GET_SIZE(inputstr) == soself->s_size) {
- return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
- }
- args = PyTuple_Pack(1, inputstr);
- if (args == NULL)
- return NULL;
- if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
- goto fail;
- if (soself->s_size != len)
- goto fail;
- result = s_unpack_internal(soself, start);
- Py_DECREF(args);
- return result;
+ char *start;
+ Py_ssize_t len;
+ PyObject *args=NULL, *result;
+ PyStructObject *soself = (PyStructObject *)self;
+ assert(PyStruct_Check(self));
+ assert(soself->s_codes != NULL);
+ if (inputstr == NULL)
+ goto fail;
+ if (PyString_Check(inputstr) &&
+ PyString_GET_SIZE(inputstr) == soself->s_size) {
+ return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
+ }
+ args = PyTuple_Pack(1, inputstr);
+ if (args == NULL)
+ return NULL;
+ if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
+ goto fail;
+ if (soself->s_size != len)
+ goto fail;
+ result = s_unpack_internal(soself, start);
+ Py_DECREF(args);
+ return result;
fail:
- Py_XDECREF(args);
- PyErr_Format(StructError,
- "unpack requires a string argument of length %zd",
- soself->s_size);
- return NULL;
+ Py_XDECREF(args);
+ PyErr_Format(StructError,
+ "unpack requires a string argument of length %zd",
+ soself->s_size);
+ return NULL;
}
PyDoc_STRVAR(s_unpack_from__doc__,
@@ -1586,38 +1586,38 @@ 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};
+ static char *kwlist[] = {"buffer", "offset", 0};
#if (PY_VERSION_HEX < 0x02050000)
- static char *fmt = "z#|i:unpack_from";
+ static char *fmt = "z#|i:unpack_from";
#else
- static char *fmt = "z#|n:unpack_from";
+ static char *fmt = "z#|n:unpack_from";
#endif
- Py_ssize_t buffer_len = 0, offset = 0;
- char *buffer = NULL;
- PyStructObject *soself = (PyStructObject *)self;
- assert(PyStruct_Check(self));
- assert(soself->s_codes != NULL);
+ Py_ssize_t buffer_len = 0, offset = 0;
+ char *buffer = NULL;
+ PyStructObject *soself = (PyStructObject *)self;
+ assert(PyStruct_Check(self));
+ assert(soself->s_codes != NULL);
- if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
- &buffer, &buffer_len, &offset))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
+ &buffer, &buffer_len, &offset))
+ return NULL;
- if (buffer == NULL) {
- PyErr_Format(StructError,
- "unpack_from requires a buffer argument");
- return NULL;
- }
+ if (buffer == NULL) {
+ PyErr_Format(StructError,
+ "unpack_from requires a buffer argument");
+ return NULL;
+ }
- if (offset < 0)
- offset += buffer_len;
+ if (offset < 0)
+ offset += buffer_len;
- if (offset < 0 || (buffer_len - offset) < soself->s_size) {
- PyErr_Format(StructError,
- "unpack_from requires a buffer of at least %zd bytes",
- soself->s_size);
- return NULL;
- }
- return s_unpack_internal(soself, buffer + offset);
+ if (offset < 0 || (buffer_len - offset) < soself->s_size) {
+ PyErr_Format(StructError,
+ "unpack_from requires a buffer of at least %zd bytes",
+ soself->s_size);
+ return NULL;
+ }
+ return s_unpack_internal(soself, buffer + offset);
}
@@ -1634,55 +1634,55 @@ 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') {
- if (!PyString_Check(v)) {
- PyErr_SetString(StructError,
- "argument for 's' must be a string");
- return -1;
- }
- n = PyString_GET_SIZE(v);
- if (n > code->size)
- n = code->size;
- if (n > 0)
- memcpy(res, PyString_AS_STRING(v), n);
- } else if (e->format == 'p') {
- if (!PyString_Check(v)) {
- PyErr_SetString(StructError,
- "argument for 'p' must be a string");
- return -1;
- }
- n = PyString_GET_SIZE(v);
- if (n > (code->size - 1))
- n = code->size - 1;
- if (n > 0)
- memcpy(res + 1, PyString_AS_STRING(v), 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') {
+ if (!PyString_Check(v)) {
+ PyErr_SetString(StructError,
+ "argument for 's' must be a string");
+ return -1;
+ }
+ n = PyString_GET_SIZE(v);
+ if (n > code->size)
+ n = code->size;
+ if (n > 0)
+ memcpy(res, PyString_AS_STRING(v), n);
+ } else if (e->format == 'p') {
+ if (!PyString_Check(v)) {
+ PyErr_SetString(StructError,
+ "argument for 'p' must be a string");
+ return -1;
+ }
+ n = PyString_GET_SIZE(v);
+ if (n > (code->size - 1))
+ n = code->size - 1;
+ if (n > 0)
+ memcpy(res + 1, PyString_AS_STRING(v), 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;
}
@@ -1695,32 +1695,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 = PyString_FromStringAndSize((char *)NULL, soself->s_size);
- if (result == NULL)
- return NULL;
+ /* Allocate a new string */
+ result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
+ if (result == NULL)
+ return NULL;
- /* Call the guts */
- if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
- Py_DECREF(result);
- return NULL;
- }
+ /* Call the guts */
+ if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
+ Py_DECREF(result);
+ return NULL;
+ }
- return result;
+ return result;
}
PyDoc_STRVAR(s_pack_into__doc__,
@@ -1734,59 +1734,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 = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
- 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 = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
+ 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 *
@@ -1798,12 +1798,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");
@@ -1811,52 +1811,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_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 */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* 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_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 */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* 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 */
};
@@ -1868,29 +1868,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,
@@ -1899,8 +1899,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,
@@ -1909,13 +1909,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 PyInt_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 PyInt_FromSsize_t(n);
}
PyDoc_STRVAR(pack_doc,
@@ -1924,27 +1924,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,
@@ -1954,27 +1954,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,
@@ -1984,17 +1984,17 @@ Requires len(string) == 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,
@@ -2004,38 +2004,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 */
};
@@ -2073,101 +2073,101 @@ The variable struct.error is an exception raised on errors.\n");
PyMODINIT_FUNC
init_struct(void)
{
- PyObject *ver, *m;
+ PyObject *ver, *m;
- ver = PyString_FromString("0.2");
- if (ver == NULL)
- return;
+ ver = PyString_FromString("0.2");
+ if (ver == NULL)
+ return;
- m = Py_InitModule3("_struct", module_functions, module_doc);
- if (m == NULL)
- return;
+ m = Py_InitModule3("_struct", module_functions, module_doc);
+ if (m == NULL)
+ return;
- Py_TYPE(&PyStructType) = &PyType_Type;
- if (PyType_Ready(&PyStructType) < 0)
- return;
+ Py_TYPE(&PyStructType) = &PyType_Type;
+ if (PyType_Ready(&PyStructType) < 0)
+ return;
#ifdef PY_STRUCT_OVERFLOW_MASKING
- if (pyint_zero == NULL) {
- pyint_zero = PyInt_FromLong(0);
- if (pyint_zero == NULL)
- return;
- }
- if (pylong_ulong_mask == NULL) {
+ if (pyint_zero == NULL) {
+ pyint_zero = PyInt_FromLong(0);
+ if (pyint_zero == NULL)
+ return;
+ }
+ if (pylong_ulong_mask == NULL) {
#if (SIZEOF_LONG == 4)
- pylong_ulong_mask = PyLong_FromString("FFFFFFFF", NULL, 16);
+ pylong_ulong_mask = PyLong_FromString("FFFFFFFF", NULL, 16);
#else
- pylong_ulong_mask = PyLong_FromString("FFFFFFFFFFFFFFFF", NULL, 16);
+ pylong_ulong_mask = PyLong_FromString("FFFFFFFFFFFFFFFF", NULL, 16);
#endif
- if (pylong_ulong_mask == NULL)
- return;
- }
+ if (pylong_ulong_mask == NULL)
+ return;
+ }
#else
- /* This speed trick can't be used until overflow masking goes away, because
- native endian always raises exceptions instead of overflow masking. */
-
- /* 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++;
- }
- }
+ /* This speed trick can't be used until overflow masking goes away, because
+ native endian always raises exceptions instead of overflow masking. */
+
+ /* 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++;
+ }
+ }
#endif
- /* Add some symbolic constants to the module */
- if (StructError == NULL) {
- StructError = PyErr_NewException("struct.error", NULL, NULL);
- if (StructError == NULL)
- return;
- }
+ /* Add some symbolic constants to the module */
+ if (StructError == NULL) {
+ StructError = PyErr_NewException("struct.error", NULL, NULL);
+ if (StructError == NULL)
+ return;
+ }
- Py_INCREF(StructError);
- PyModule_AddObject(m, "error", StructError);
+ Py_INCREF(StructError);
+ PyModule_AddObject(m, "error", StructError);
- Py_INCREF((PyObject*)&PyStructType);
- PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
+ Py_INCREF((PyObject*)&PyStructType);
+ PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
- PyModule_AddObject(m, "__version__", ver);
+ PyModule_AddObject(m, "__version__", ver);
- PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
+ PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
#ifdef PY_STRUCT_OVERFLOW_MASKING
- PyModule_AddIntConstant(m, "_PY_STRUCT_OVERFLOW_MASKING", 1);
+ PyModule_AddIntConstant(m, "_PY_STRUCT_OVERFLOW_MASKING", 1);
#endif
#ifdef PY_STRUCT_FLOAT_COERCE
- PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
+ PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
#endif
}
diff --git a/Modules/_testcapimodule.c b/Modules/_testcapimodule.c
index 0996145..ee5ae48 100644
--- a/Modules/_testcapimodule.c
+++ b/Modules/_testcapimodule.c
@@ -12,22 +12,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];
-
- 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;
+ 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;
}
/* Test #defines from pyconfig.h (particularly the SIZEOF_* defines).
@@ -38,138 +38,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 = PyInt_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 (PyInt_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 = PyInt_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 (PyInt_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 = PyInt_FromLong(i);
- PyDict_SetItem(dict, v, v);
- Py_DECREF(v);
- }
-
- while (PyDict_Next(dict, &pos, &k, &v)) {
- PyObject *o;
- iterations++;
-
- i = PyInt_AS_LONG(v) + 1;
- o = PyInt_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 = PyInt_FromLong(i);
+ PyDict_SetItem(dict, v, v);
+ Py_DECREF(v);
+ }
+
+ while (PyDict_Next(dict, &pos, &k, &v)) {
+ PyObject *o;
+ iterations++;
+
+ i = PyInt_AS_LONG(v) + 1;
+ o = PyInt_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;
}
@@ -177,108 +177,108 @@ test_dict_iteration(PyObject* self)
* PyType_Ready if it hasn't already been called
*/
static PyTypeObject _HashInheritanceTester_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /* Number of items for varobject */
- "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_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 */
- 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 */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* Number of items for varobject */
+ "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_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 */
+ 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;
}
@@ -302,22 +302,22 @@ test_lazy_hash_inheritance(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
@@ -332,22 +332,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
@@ -364,71 +364,71 @@ test_longlong_api(PyObject* self, PyObject *args)
static PyObject *
test_L_code(PyObject *self)
{
- PyObject *tuple, *num;
- PY_LONG_LONG value;
-
- tuple = PyTuple_New(1);
- if (tuple == NULL)
- return NULL;
-
- num = PyLong_FromLong(42);
- if (num == NULL)
- return NULL;
-
- 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");
-
- Py_DECREF(num);
- num = PyInt_FromLong(42);
- if (num == NULL)
- return NULL;
-
- 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");
-
- Py_DECREF(tuple);
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *tuple, *num;
+ PY_LONG_LONG value;
+
+ tuple = PyTuple_New(1);
+ if (tuple == NULL)
+ return NULL;
+
+ num = PyLong_FromLong(42);
+ if (num == NULL)
+ return NULL;
+
+ 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");
+
+ Py_DECREF(num);
+ num = PyInt_FromLong(42);
+ if (num == NULL)
+ return NULL;
+
+ 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");
+
+ 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};
-
- 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]);
+ 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]);
}
/* Functions to call PyArg_ParseTuple with integer format codes,
@@ -437,92 +437,92 @@ 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)
{
- 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 PyInt_FromSsize_t(value);
+ Py_ssize_t value;
+ if (!PyArg_ParseTuple(args, "n", &value))
+ return NULL;
+ return PyInt_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
@@ -531,54 +531,54 @@ getargs_K(PyObject *self, PyObject *args)
static PyObject *
test_k_code(PyObject *self)
{
- PyObject *tuple, *num;
- unsigned long value;
-
- 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;
-
- value = PyInt_AsUnsignedLongMask(num);
- if (value != ULONG_MAX)
- return raiseTestError("test_k_code",
- "PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
-
- 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");
-
- Py_DECREF(num);
- num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16);
- if (num == NULL)
- return NULL;
-
- value = PyInt_AsUnsignedLongMask(num);
- if (value != (unsigned long)-0x42)
- return raiseTestError("test_k_code",
- "PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
-
- 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");
-
- Py_DECREF(tuple);
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *tuple, *num;
+ unsigned long value;
+
+ 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;
+
+ value = PyInt_AsUnsignedLongMask(num);
+ if (value != ULONG_MAX)
+ return raiseTestError("test_k_code",
+ "PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
+
+ 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");
+
+ Py_DECREF(num);
+ num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16);
+ if (num == NULL)
+ return NULL;
+
+ value = PyInt_AsUnsignedLongMask(num);
+ if (value != (unsigned long)-0x42)
+ return raiseTestError("test_k_code",
+ "PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
+
+ 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");
+
+ Py_DECREF(tuple);
+ Py_INCREF(Py_None);
+ return Py_None;
}
#ifdef Py_USING_UNICODE
@@ -591,88 +591,88 @@ static volatile int x;
static PyObject *
test_u_code(PyObject *self)
{
- PyObject *tuple, *obj;
- Py_UNICODE *value;
- int 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;
+ int 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;
}
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);
}
#endif
@@ -681,42 +681,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) and PyObject_Unicode(NULL). */
@@ -724,42 +724,42 @@ test_long_numbits(PyObject *self)
static PyObject *
test_null_strings(PyObject *self)
{
- PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Unicode(NULL);
- PyObject *tuple = PyTuple_Pack(2, o1, o2);
- Py_XDECREF(o1);
- Py_XDECREF(o2);
- return tuple;
+ PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Unicode(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;
- if (!PyExceptionClass_Check(exc)) {
- PyErr_Format(PyExc_TypeError, "an exception class is required");
- return NULL;
- }
-
- exc_args = PyTuple_New(num_args);
- if (exc_args == NULL)
- return NULL;
- for (i = 0; i < num_args; ++i) {
- v = PyInt_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;
+ if (!PyExceptionClass_Check(exc)) {
+ PyErr_Format(PyExc_TypeError, "an exception class is required");
+ return NULL;
+ }
+
+ exc_args = PyTuple_New(num_args);
+ if (exc_args == NULL)
+ return NULL;
+ for (i = 0; i < num_args; ++i) {
+ v = PyInt_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;
}
#ifdef WITH_THREAD
@@ -776,14 +776,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
@@ -792,59 +792,59 @@ _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;
}
#endif
@@ -852,34 +852,34 @@ test_thread_state(PyObject *self, PyObject *args)
static PyObject *
test_string_from_format(PyObject *self, PyObject *args)
{
- PyObject *result;
- char *msg;
-
-#define CHECK_1_FORMAT(FORMAT, TYPE) \
- result = PyString_FromFormat(FORMAT, (TYPE)1); \
- if (result == NULL) \
- return NULL; \
- if (strcmp(PyString_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);
-
- Py_RETURN_NONE;
+ PyObject *result;
+ char *msg;
+
+#define CHECK_1_FORMAT(FORMAT, TYPE) \
+ result = PyString_FromFormat(FORMAT, (TYPE)1); \
+ if (result == NULL) \
+ return NULL; \
+ if (strcmp(PyString_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);
+
+ 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
}
@@ -888,267 +888,267 @@ test_string_from_format(PyObject *self, PyObject *args)
static PyObject *
test_with_docstring(PyObject *self)
{
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
/* To test the format of tracebacks as printed out. */
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;
}
static PyMethodDef TestMethods[] = {
- {"raise_exception", raise_exception, METH_VARARGS},
- {"test_config", (PyCFunction)test_config, 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_long_api", (PyCFunction)test_long_api, 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_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.")},
-
- {"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_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},
+ {"test_config", (PyCFunction)test_config, 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_long_api", (PyCFunction)test_long_api, 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_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.")},
+
+ {"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_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_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_L_code", (PyCFunction)test_L_code, METH_NOARGS},
+ {"codec_incrementalencoder",
+ (PyCFunction)codec_incrementalencoder, METH_VARARGS},
+ {"codec_incrementaldecoder",
+ (PyCFunction)codec_incrementaldecoder, METH_VARARGS},
#endif
#ifdef Py_USING_UNICODE
- {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS},
+ {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS},
#endif
#ifdef WITH_THREAD
- {"_test_thread_state", test_thread_state, METH_VARARGS},
+ {"_test_thread_state", test_thread_state, METH_VARARGS},
#endif
- {"traceback_print", traceback_print, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"traceback_print", traceback_print, METH_VARARGS},
+ {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;
- 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;
+ 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_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_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_FLOAT", "T_DOUBLE", "T_STRING_INPLACE",
-#ifdef HAVE_LONG_LONG
- "T_LONGLONG", "T_ULONGLONG",
+ static char *keywords[] = {
+ "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT",
+ "T_INT", "T_UINT", "T_LONG", "T_ULONG",
+ "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE",
+#ifdef HAVE_LONG_LONG
+ "T_LONGLONG", "T_ULONGLONG",
#endif
- NULL};
- static char *fmt = "|bbBhHiIlkfds#"
+ NULL};
+ static char *fmt = "|bbBhHiIlkfds#"
#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.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.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_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 */
- 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_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 */
+ 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 */
};
PyMODINIT_FUNC
init_testcapi(void)
{
- PyObject *m;
-
- m = Py_InitModule("_testcapi", TestMethods);
- if (m == NULL)
- return;
-
- Py_TYPE(&_HashInheritanceTester_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", PyInt_FromLong(CHAR_MAX));
- PyModule_AddObject(m, "CHAR_MIN", PyInt_FromLong(CHAR_MIN));
- PyModule_AddObject(m, "UCHAR_MAX", PyInt_FromLong(UCHAR_MAX));
- PyModule_AddObject(m, "SHRT_MAX", PyInt_FromLong(SHRT_MAX));
- PyModule_AddObject(m, "SHRT_MIN", PyInt_FromLong(SHRT_MIN));
- PyModule_AddObject(m, "USHRT_MAX", PyInt_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", PyInt_FromLong(LONG_MAX));
- PyModule_AddObject(m, "LONG_MIN", PyInt_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", PyInt_FromSsize_t(PY_SSIZE_T_MAX));
- PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyInt_FromSsize_t(PY_SSIZE_T_MIN));
- PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyInt_FromSsize_t(sizeof(PyGC_Head)));
-
- TestError = PyErr_NewException("_testcapi.error", NULL, NULL);
- Py_INCREF(TestError);
- PyModule_AddObject(m, "error", TestError);
+ PyObject *m;
+
+ m = Py_InitModule("_testcapi", TestMethods);
+ if (m == NULL)
+ return;
+
+ Py_TYPE(&_HashInheritanceTester_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", PyInt_FromLong(CHAR_MAX));
+ PyModule_AddObject(m, "CHAR_MIN", PyInt_FromLong(CHAR_MIN));
+ PyModule_AddObject(m, "UCHAR_MAX", PyInt_FromLong(UCHAR_MAX));
+ PyModule_AddObject(m, "SHRT_MAX", PyInt_FromLong(SHRT_MAX));
+ PyModule_AddObject(m, "SHRT_MIN", PyInt_FromLong(SHRT_MIN));
+ PyModule_AddObject(m, "USHRT_MAX", PyInt_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", PyInt_FromLong(LONG_MAX));
+ PyModule_AddObject(m, "LONG_MIN", PyInt_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", PyInt_FromSsize_t(PY_SSIZE_T_MAX));
+ PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyInt_FromSsize_t(PY_SSIZE_T_MIN));
+ PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyInt_FromSsize_t(sizeof(PyGC_Head)));
+
+ TestError = PyErr_NewException("_testcapi.error", NULL, NULL);
+ Py_INCREF(TestError);
+ PyModule_AddObject(m, "error", TestError);
}
diff --git a/Modules/_tkinter.c b/Modules/_tkinter.c
index 83501bf..b8929b6 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.2 and later are supported. Older versions are not
- supported. (Use Python 2.2 if you cannot upgrade your Tcl/Tk
- libraries.)
+ Only Tcl/Tk 8.2 and later are supported. Older versions are not
+ supported. (Use Python 2.2 if you cannot upgrade your Tcl/Tk
+ libraries.)
*/
/* XXX Further speed-up ideas, involving Tcl 8.0 features:
@@ -83,8 +83,8 @@ Copyright (C) 1994 Steen Lumholt.
/* Unicode conversion assumes that Tcl_UniChar is two bytes.
We cannot test this directly, so we test UTF-8 size instead,
expecting that TCL_UTF_MAX is changed if Tcl ever supports
- either UTF-16 or UCS-4.
- Redhat 8 sets TCL_UTF_MAX to 6, and uses wchar_t for
+ either UTF-16 or UCS-4.
+ Redhat 8 sets TCL_UTF_MAX to 6, and uses wchar_t for
Tcl_Unichar. This is also ok as long as Python uses UCS-4,
as well.
*/
@@ -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;
@@ -281,16 +281,16 @@ static PyObject *valInCmd;
static PyObject *trbInCmd;
-
+
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;
@@ -303,11 +303,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 */
@@ -316,174 +316,174 @@ 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 (PyString_Check(value))
- return PyString_AsString(value);
+ if (PyString_Check(value))
+ return PyString_AsString(value);
#ifdef Py_USING_UNICODE
- 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 PyString_AsString(v);
- }
+ 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 PyString_AsString(v);
+ }
#endif
- 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 PyString_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 PyString_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 PyString_FromString(list);
- }
-
- if (argc == 0)
- v = PyString_FromString("");
- else if (argc == 1)
- v = PyString_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 PyString_FromString(list);
+ }
+
+ if (argc == 0)
+ v = PyString_FromString("");
+ else if (argc == 1)
+ v = PyString_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
@@ -493,89 +493,89 @@ 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 (PyString_Check(arg)) {
- int argc;
- char **argv;
- char *list = PyString_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(PyString_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 (PyString_Check(arg)) {
+ int argc;
+ char **argv;
+ char *list = PyString_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(PyString_AsString(arg));
+ /* Fall through, returning arg. */
+ }
+ Py_INCREF(arg);
+ return arg;
+}
+
+
/**** Tkapp Object ****/
#ifndef WITH_APPINIT
int
Tcl_AppInit(Tcl_Interp *interp)
{
- Tk_Window main;
- 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;
- }
- _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) {
- main = Tk_MainWindow(interp);
- if (Tk_Init(interp) == TCL_ERROR) {
- PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp));
- return TCL_ERROR;
- }
- }
- return TCL_OK;
+ Tk_Window main;
+ 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;
+ }
+ _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) {
+ main = Tk_MainWindow(interp);
+ if (Tk_Init(interp) == TCL_ERROR) {
+ PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp));
+ return TCL_ERROR;
+ }
+ }
+ return TCL_OK;
}
#endif /* !WITH_APPINIT */
-
+
/* Initialize the Tk application; see the `main' function in
* `tkMain.c'.
@@ -586,214 +586,214 @@ static void DisableEventHook(void); /* Forward */
static TkappObject *
Tkapp_New(char *screenName, char *baseName, 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);
- }
-
- /* 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);
- Py_DECREF((PyObject *)v);
- return (TkappObject *)result;
- }
-
- EnableEventHook();
-
- return v;
+ 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);
+ }
+
+ /* 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);
+ Py_DECREF((PyObject *)v);
+ return (TkappObject *)result;
+ }
+
+ EnableEventHook();
+
+ return v;
}
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
}
-
+
/** 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;
staticforward 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 PyObject *
PyTclObject_str(PyTclObject *self)
{
- if (self->string && PyString_Check(self->string)) {
- Py_INCREF(self->string);
- return self->string;
- }
- /* XXX Could cache value if it is an ASCII string. */
- return PyString_FromString(Tcl_GetString(self->value));
+ if (self->string && PyString_Check(self->string)) {
+ Py_INCREF(self->string);
+ return self->string;
+ }
+ /* XXX Could cache value if it is an ASCII string. */
+ return PyString_FromString(Tcl_GetString(self->value));
}
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. */
-PyDoc_STRVAR(PyTclObject_string__doc__,
+PyDoc_STRVAR(PyTclObject_string__doc__,
"the string representation of this object, either as string or Unicode");
static PyObject *
PyTclObject_string(PyTclObject *self, void *ignored)
{
- char *s;
- int i, len;
- if (!self->string) {
- s = Tcl_GetStringFromObj(self->value, &len);
- for (i = 0; i < len; i++)
- if (s[i] & 0x80)
- break;
+ char *s;
+ int i, len;
+ if (!self->string) {
+ s = Tcl_GetStringFromObj(self->value, &len);
+ for (i = 0; i < len; i++)
+ if (s[i] & 0x80)
+ break;
#ifdef Py_USING_UNICODE
- if (i == len)
- /* It is an ASCII string. */
- self->string = PyString_FromStringAndSize(s, len);
- else {
- self->string = PyUnicode_DecodeUTF8(s, len, "strict");
- if (!self->string) {
- PyErr_Clear();
- self->string = PyString_FromStringAndSize(s, len);
- }
- }
+ if (i == len)
+ /* It is an ASCII string. */
+ self->string = PyString_FromStringAndSize(s, len);
+ else {
+ self->string = PyUnicode_DecodeUTF8(s, len, "strict");
+ if (!self->string) {
+ PyErr_Clear();
+ self->string = PyString_FromStringAndSize(s, len);
+ }
+ }
#else
- self->string = PyString_FromStringAndSize(s, len);
+ self->string = PyString_FromStringAndSize(s, len);
#endif
- if (!self->string)
- return NULL;
- }
- Py_INCREF(self->string);
- return self->string;
+ if (!self->string)
+ return NULL;
+ }
+ Py_INCREF(self->string);
+ return self->string;
}
#ifdef Py_USING_UNICODE
@@ -802,36 +802,36 @@ PyDoc_STRVAR(PyTclObject_unicode__doc__, "convert argument to unicode");
static PyObject *
PyTclObject_unicode(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");
}
#endif
static PyObject *
PyTclObject_repr(PyTclObject *self)
{
- char buf[50];
- PyOS_snprintf(buf, 50, "<%s object at %p>",
- self->value->typePtr->name, self->value);
- return PyString_FromString(buf);
+ char buf[50];
+ PyOS_snprintf(buf, 50, "<%s object at %p>",
+ self->value->typePtr->name, self->value);
+ return PyString_FromString(buf);
}
static int
PyTclObject_cmp(PyTclObject *self, PyTclObject *other)
{
- int res;
- res = strcmp(Tcl_GetString(self->value),
- Tcl_GetString(other->value));
- if (res < 0) return -1;
- if (res > 0) return 1;
- return 0;
+ int res;
+ res = strcmp(Tcl_GetString(self->value),
+ Tcl_GetString(other->value));
+ if (res < 0) return -1;
+ if (res > 0) return 1;
+ return 0;
}
PyDoc_STRVAR(get_typename__doc__, "name of the Tcl type");
@@ -839,264 +839,264 @@ PyDoc_STRVAR(get_typename__doc__, "name of the Tcl type");
static PyObject*
get_typename(PyTclObject* obj, void* ignored)
{
- return PyString_FromString(obj->value->typePtr->name);
+ return PyString_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 PyMethodDef PyTclObject_methods[] = {
#ifdef Py_USING_UNICODE
- {"__unicode__", (PyCFunction)PyTclObject_unicode, METH_NOARGS,
- PyTclObject_unicode__doc__},
+ {"__unicode__", (PyCFunction)PyTclObject_unicode, METH_NOARGS,
+ PyTclObject_unicode__doc__},
#endif
- {0}
+ {0}
};
statichere PyTypeObject PyTclObject_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_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*/
- (cmpfunc)PyTclObject_cmp, /*tp_compare*/
- (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*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- PyTclObject_methods, /*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*/
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_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*/
+ (cmpfunc)PyTclObject_cmp, /*tp_compare*/
+ (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*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ PyTclObject_methods, /*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;
-
- if (PyString_Check(value))
- return Tcl_NewStringObj(PyString_AS_STRING(value),
- PyString_GET_SIZE(value));
- else if (PyBool_Check(value))
- return Tcl_NewBooleanObj(PyObject_IsTrue(value));
- else if (PyInt_Check(value))
- return Tcl_NewLongObj(PyInt_AS_LONG(value));
- 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;
- }
+ Tcl_Obj *result;
+
+ if (PyString_Check(value))
+ return Tcl_NewStringObj(PyString_AS_STRING(value),
+ PyString_GET_SIZE(value));
+ else if (PyBool_Check(value))
+ return Tcl_NewBooleanObj(PyObject_IsTrue(value));
+ else if (PyInt_Check(value))
+ return Tcl_NewLongObj(PyInt_AS_LONG(value));
+ 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;
+ }
#ifdef Py_USING_UNICODE
- 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. */
+ 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
- }
+ }
#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;
+ PyObject *result = NULL;
+ TkappObject *app = (TkappObject*)tkapp;
- if (value->typePtr == NULL) {
- /* If the result contains any bytes with the top bit set,
- it's UTF-8 and we should decode it to Unicode */
+ if (value->typePtr == NULL) {
+ /* If the result contains any bytes with the top bit set,
+ it's UTF-8 and we should decode it to Unicode */
#ifdef Py_USING_UNICODE
- int i;
- char *s = value->bytes;
- int len = value->length;
- for (i = 0; i < len; i++) {
- if (value->bytes[i] & 0x80)
- break;
- }
-
- if (i == value->length)
- result = PyString_FromStringAndSize(s, len);
- else {
- /* Convert UTF-8 to Unicode string */
- result = PyUnicode_DecodeUTF8(s, len, "strict");
- if (result == NULL) {
- PyErr_Clear();
- result = PyString_FromStringAndSize(s, len);
- }
- }
+ int i;
+ char *s = value->bytes;
+ int len = value->length;
+ for (i = 0; i < len; i++) {
+ if (value->bytes[i] & 0x80)
+ break;
+ }
+
+ if (i == value->length)
+ result = PyString_FromStringAndSize(s, len);
+ else {
+ /* Convert UTF-8 to Unicode string */
+ result = PyUnicode_DecodeUTF8(s, len, "strict");
+ if (result == NULL) {
+ PyErr_Clear();
+ result = PyString_FromStringAndSize(s, len);
+ }
+ }
#else
- result = PyString_FromStringAndSize(value->bytes, value->length);
+ result = PyString_FromStringAndSize(value->bytes, value->length);
#endif
- return result;
- }
-
- 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 PyString_FromStringAndSize(data, size);
- }
-
- if (value->typePtr == app->DoubleType) {
- return PyFloat_FromDouble(value->internalRep.doubleValue);
- }
-
- if (value->typePtr == app->IntType) {
- return PyInt_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) {
+ return result;
+ }
+
+ 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 PyString_FromStringAndSize(data, size);
+ }
+
+ if (value->typePtr == app->DoubleType) {
+ return PyFloat_FromDouble(value->internalRep.doubleValue);
+ }
+
+ if (value->typePtr == app->IntType) {
+ return PyInt_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) {
#ifdef Py_USING_UNICODE
#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
#else
- int size;
- char *c;
- c = Tcl_GetStringFromObj(value, &size);
- return PyString_FromStringAndSize(c, size);
+ int size;
+ char *c;
+ c = Tcl_GetStringFromObj(value, &size);
+ return PyString_FromStringAndSize(c, size);
#endif
- }
+ }
- return newPyTclObject(value);
+ return newPyTclObject(value);
}
/* This mutex synchronizes inter-thread command calls. */
@@ -1104,23 +1104,23 @@ 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;
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
@@ -1129,51 +1129,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. */
@@ -1181,45 +1181,45 @@ 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;
-
- /* If the result contains any bytes with the top bit set,
- it's UTF-8 and we should decode it to Unicode */
+ 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;
+
+ /* If the result contains any bytes with the top bit set,
+ it's UTF-8 and we should decode it to Unicode */
#ifdef Py_USING_UNICODE
- while (*p != '\0') {
- if (*p & 0x80)
- break;
- p++;
- }
-
- if (*p == '\0')
- res = PyString_FromStringAndSize(s, (int)(p-s));
- else {
- /* Convert UTF-8 to Unicode string */
- p = strchr(p, '\0');
- res = PyUnicode_DecodeUTF8(s, (int)(p-s), "strict");
- if (res == NULL) {
- PyErr_Clear();
- res = PyString_FromStringAndSize(s, (int)(p-s));
- }
- }
+ while (*p != '\0') {
+ if (*p & 0x80)
+ break;
+ p++;
+ }
+
+ if (*p == '\0')
+ res = PyString_FromStringAndSize(s, (int)(p-s));
+ else {
+ /* Convert UTF-8 to Unicode string */
+ p = strchr(p, '\0');
+ res = PyUnicode_DecodeUTF8(s, (int)(p-s), "strict");
+ if (res == NULL) {
+ PyErr_Clear();
+ res = PyString_FromStringAndSize(s, (int)(p-s));
+ }
+ }
#else
- p = strchr(p, '\0');
- res = PyString_FromStringAndSize(s, (int)(p-s));
+ p = strchr(p, '\0');
+ res = PyString_FromStringAndSize(s, (int)(p-s));
#endif
- }
- return res;
+ }
+ return res;
}
/* Tkapp_CallProc is the event procedure that is executed in the context of
@@ -1229,41 +1229,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;
}
/* This is the main entry point for calling a Tcl command.
@@ -1281,711 +1281,711 @@ 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;
- 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 = (Tcl_Condition)0;
-
- Tkapp_ThreadSend(self, (Tcl_Event*)ev, &ev->done, &call_mutex);
-
- if (res == NULL) {
- if (exc_type)
- PyErr_Restore(exc_type, exc_value, exc_tb);
- else
- PyErr_SetObject(Tkinter_TclError, exc_value);
- }
- }
- 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;
+ 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 = (Tcl_Condition)0;
+
+ Tkapp_ThreadSend(self, (Tcl_Event*)ev, &ev->done, &call_mutex);
+
+ if (res == NULL) {
+ if (exc_type)
+ PyErr_Restore(exc_type, exc_value, exc_tb);
+ else
+ PyErr_SetObject(Tkinter_TclError, exc_value);
+ }
+ }
+ 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 = PyString_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 = PyString_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 = PyString_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 = PyString_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 = PyString_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 = PyString_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 = PyString_FromString(Tkapp_Result(self));
- LEAVE_OVERLAP_TCL
- return res;
+ else
+ res = PyString_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 = PyString_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 = PyString_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 **/
TCL_DECLARE_MUTEX(var_mutex)
typedef PyObject* (*EventFunc)(PyObject*, PyObject *args, int flags);
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;
static int
varname_converter(PyObject *in, void *_out)
{
- char **out = (char**)_out;
- if (PyString_Check(in)) {
- *out = PyString_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 (PyString_Check(in)) {
+ *out = PyString_AsString(in);
+ return 1;
+ }
+ if (PyTclObject_Check(in)) {
+ *out = PyTclObject_TclString(in);
+ return 1;
+ }
+ /* XXX: Should give diagnostics. */
+ return 0;
+}
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;
}
static PyObject*
var_invoke(EventFunc func, PyObject *selfptr, PyObject *args, int flags)
{
- TkappObject *self = (TkappObject*)selfptr;
+ TkappObject *self = (TkappObject*)selfptr;
#ifdef WITH_THREAD
- if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
- TkappObject *self = (TkappObject*)selfptr;
- VarEvent *ev;
- PyObject *res, *exc_type, *exc_val;
-
- /* 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 = NULL;
- ev->ev.proc = (Tcl_EventProc*)var_proc;
- Tkapp_ThreadSend(self, (Tcl_Event*)ev, &ev->cond, &var_mutex);
- if (!res) {
- PyErr_SetObject(exc_type, exc_val);
- Py_DECREF(exc_type);
- Py_DECREF(exc_val);
- return NULL;
- }
- return res;
- }
+ if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
+ TkappObject *self = (TkappObject*)selfptr;
+ VarEvent *ev;
+ PyObject *res, *exc_type, *exc_val;
+
+ /* 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 = NULL;
+ ev->ev.proc = (Tcl_EventProc*)var_proc;
+ Tkapp_ThreadSend(self, (Tcl_Event*)ev, &ev->cond, &var_mutex);
+ 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 = PyString_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 = PyString_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 (PyInt_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 (PyInt_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 (PyInt_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 (PyInt_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 = PyString_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 = PyString_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 = PyString_FromString(s);
- ckfree(s);
- }
+ if (s) {
+ res = PyString_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
@@ -1994,199 +1994,199 @@ 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 = PyString_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 = PyString_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
}
-
+
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;
}
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;
-
- if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
- 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 = NULL;
- Tkapp_ThreadSend(self, (Tcl_Event*)ev, &ev->done, &command_mutex);
- }
- else {
- 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;
-}
-
-
-
+ data = PyMem_NEW(PythonCmd_ClientData, 1);
+ if (!data)
+ return PyErr_NoMemory();
+ Py_INCREF(self);
+ Py_INCREF(func);
+ data->self = selfptr;
+ data->func = func;
+
+ if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
+ 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 = NULL;
+ Tkapp_ThreadSend(self, (Tcl_Event*)ev, &ev->done, &command_mutex);
+ }
+ else {
+ 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;
+}
+
+
+
static PyObject *
Tkapp_DeleteCommand(PyObject *selfptr, PyObject *args)
{
- TkappObject *self = (TkappObject*)selfptr;
- char *cmdName;
- int err;
-
- if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName))
- return NULL;
- if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
- 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 = NULL;
- Tkapp_ThreadSend(self, (Tcl_Event*)ev, &ev->done,
- &command_mutex);
- }
- else {
- 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;
-}
-
-
-
+ TkappObject *self = (TkappObject*)selfptr;
+ char *cmdName;
+ int err;
+
+ if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName))
+ return NULL;
+ if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
+ 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 = NULL;
+ Tkapp_ThreadSend(self, (Tcl_Event*)ev, &ev->done,
+ &command_mutex);
+ }
+ else {
+ 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;
@@ -2194,747 +2194,747 @@ 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;
#ifdef WITH_THREAD
- if (!self && !tcl_lock) {
- /* We don't have the Tcl lock since Tcl is threaded. */
- PyErr_SetString(PyExc_RuntimeError,
- "_tkinter.createfilehandler not supported "
- "for threaded Tcl");
- return NULL;
- }
+ if (!self && !tcl_lock) {
+ /* We don't have the Tcl lock since Tcl is threaded. */
+ PyErr_SetString(PyExc_RuntimeError,
+ "_tkinter.createfilehandler not supported "
+ "for threaded Tcl");
+ return NULL;
+ }
#endif
- if (self) {
- CHECK_TCL_APPARTMENT;
- }
+ if (self) {
+ 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;
#ifdef WITH_THREAD
- if (!self && !tcl_lock) {
- /* We don't have the Tcl lock since Tcl is threaded. */
- PyErr_SetString(PyExc_RuntimeError,
- "_tkinter.deletefilehandler not supported "
- "for threaded Tcl");
- return NULL;
- }
+ if (!self && !tcl_lock) {
+ /* We don't have the Tcl lock since Tcl is threaded. */
+ PyErr_SetString(PyExc_RuntimeError,
+ "_tkinter.deletefilehandler not supported "
+ "for threaded Tcl");
+ return NULL;
+ }
#endif
- if (self) {
- CHECK_TCL_APPARTMENT;
- }
+ if (self) {
+ 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;
-
- v = PyObject_New(TkttObject, &Tktt_Type);
- if (v == NULL)
- return NULL;
+ TkttObject *v;
- Py_INCREF(func);
- v->token = NULL;
- v->func = func;
+ v = PyObject_New(TkttObject, &Tktt_Type);
+ if (v == NULL)
+ return NULL;
- /* Extra reference, deleted when called or when handler is deleted */
- Py_INCREF(v);
- return v;
+ Py_INCREF(func);
+ v->token = NULL;
+ v->func = func;
+
+ /* 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 PyString_FromString(buf);
+ PyOS_snprintf(buf, sizeof(buf), "<tktimertoken at %p%s>", v,
+ v->func == NULL ? ", handler deleted" : "");
+ return PyString_FromString(buf);
}
static PyObject *
Tktt_GetAttr(PyObject *self, char *name)
{
- return Py_FindMethod(Tktt_methods, self, name);
+ return Py_FindMethod(Tktt_methods, self, name);
}
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 */
- Tktt_GetAttr, /*tp_getattr */
- 0, /*tp_setattr */
- 0, /*tp_compare */
- Tktt_Repr, /*tp_repr */
- 0, /*tp_as_number */
- 0, /*tp_as_sequence */
- 0, /*tp_as_mapping */
- 0, /*tp_hash */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "tktimertoken", /*tp_name */
+ sizeof(TkttObject), /*tp_basicsize */
+ 0, /*tp_itemsize */
+ Tktt_Dealloc, /*tp_dealloc */
+ 0, /*tp_print */
+ Tktt_GetAttr, /*tp_getattr */
+ 0, /*tp_setattr */
+ 0, /*tp_compare */
+ Tktt_Repr, /*tp_repr */
+ 0, /*tp_as_number */
+ 0, /*tp_as_sequence */
+ 0, /*tp_as_mapping */
+ 0, /*tp_hash */
};
-
+
/** 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;
+ }
#ifdef WITH_THREAD
- if (!self && !tcl_lock) {
- /* We don't have the Tcl lock since Tcl is threaded. */
- PyErr_SetString(PyExc_RuntimeError,
- "_tkinter.createtimerhandler not supported "
- "for threaded Tcl");
- return NULL;
- }
+ if (!self && !tcl_lock) {
+ /* We don't have the Tcl lock since Tcl is threaded. */
+ PyErr_SetString(PyExc_RuntimeError,
+ "_tkinter.createtimerhandler not supported "
+ "for threaded Tcl");
+ return NULL;
+ }
#endif
- if (self) {
- CHECK_TCL_APPARTMENT;
- }
+ if (self) {
+ 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;
#ifdef WITH_THREAD
- if (!self && !tcl_lock) {
- /* We don't have the Tcl lock since Tcl is threaded. */
- PyErr_SetString(PyExc_RuntimeError,
- "_tkinter.mainloop not supported "
- "for threaded Tcl");
- return NULL;
- }
+ if (!self && !tcl_lock) {
+ /* We don't have the Tcl lock since Tcl is threaded. */
+ PyErr_SetString(PyExc_RuntimeError,
+ "_tkinter.mainloop not supported "
+ "for threaded Tcl");
+ return NULL;
+ }
#endif
- if (self) {
- CHECK_TCL_APPARTMENT;
- self->dispatching = 1;
- }
+ if (self) {
+ 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 && 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 && 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) {
- if (self)
- self->dispatching = 0;
- return NULL;
- }
- if (result < 0)
- break;
- }
- if (self)
- 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) {
+ if (self)
+ self->dispatching = 0;
+ return NULL;
+ }
+ if (result < 0)
+ break;
+ }
+ if (self)
+ 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 PyInt_FromLong((long)Tkapp_Interp(self));
+ return PyInt_FromLong((long)Tkapp_Interp(self));
}
-static PyObject *
+static PyObject *
Tkapp_TkInit(PyObject *self, PyObject *args)
{
- static int has_failed;
- Tcl_Interp *interp = Tkapp_Interp(self);
- Tk_Window main_window;
- const char * _tk_exists = NULL;
- int err;
- main_window = Tk_MainWindow(interp);
-
- /* In all current versions of Tk (including 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 (has_failed) {
- PyErr_SetString(Tkinter_TclError,
- "Calling Tk_Init again after a previous call failed might deadlock");
- return NULL;
- }
-
- /* 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)));
- has_failed = 1;
- return NULL;
- }
- }
- Py_INCREF(Py_None);
- return Py_None;
+ static int has_failed;
+ Tcl_Interp *interp = Tkapp_Interp(self);
+ Tk_Window main_window;
+ const char * _tk_exists = NULL;
+ int err;
+ main_window = Tk_MainWindow(interp);
+
+ /* In all current versions of Tk (including 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 (has_failed) {
+ PyErr_SetString(Tkinter_TclError,
+ "Calling Tk_Init again after a previous call failed might deadlock");
+ return NULL;
+ }
+
+ /* 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)));
+ has_failed = 1;
+ 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 PyObject *
Tkapp_GetAttr(PyObject *self, char *name)
{
- return Py_FindMethod(Tkapp_methods, self, name);
+ return Py_FindMethod(Tkapp_methods, self, name);
}
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 */
- Tkapp_GetAttr, /*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 */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "tkapp", /*tp_name */
+ sizeof(TkappObject), /*tp_basicsize */
+ 0, /*tp_itemsize */
+ Tkapp_Dealloc, /*tp_dealloc */
+ 0, /*tp_print */
+ Tkapp_GetAttr, /*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 */
};
-
+
/**** 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;
+
+ context.maxsize = PySequence_Size(item);
+ if (context.maxsize <= 0)
+ return PyTuple_New(0);
- if (!PyArg_ParseTuple(args, "O:_flatten", &item))
- return NULL;
+ context.tuple = PyTuple_New(context.maxsize);
+ if (!context.tuple)
+ return NULL;
- context.maxsize = PySequence_Size(item);
- if (context.maxsize <= 0)
- return PyTuple_New(0);
-
- 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;
- 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 */
-
- baseName = strrchr(Py_GetProgramName(), '/');
- if (baseName != NULL)
- baseName++;
- else
- baseName = Py_GetProgramName();
- className = "Tk";
-
- if (!PyArg_ParseTuple(args, "|zssiiiiz:create",
- &screenName, &baseName, &className,
- &interactive, &wantobjects, &wantTk,
- &sync, &use))
- return NULL;
-
- return (PyObject *) Tkapp_New(screenName, baseName, className,
- interactive, wantobjects, wantTk,
- sync, use);
+ char *screenName = NULL;
+ char *baseName = NULL;
+ 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 */
+
+ baseName = strrchr(Py_GetProgramName(), '/');
+ if (baseName != NULL)
+ baseName++;
+ else
+ baseName = Py_GetProgramName();
+ className = "Tk";
+
+ if (!PyArg_ParseTuple(args, "|zssiiiiz:create",
+ &screenName, &baseName, &className,
+ &interactive, &wantobjects, &wantTk,
+ &sync, &use))
+ return NULL;
+
+ return (PyObject *) Tkapp_New(screenName, baseName, 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[] =
@@ -2948,7 +2948,7 @@ frames in an animation.";
static PyObject *
Tkinter_getbusywaitinterval(PyObject *self, PyObject *args)
{
- return PyInt_FromLong(Tkinter_busywaitinterval);
+ return PyInt_FromLong(Tkinter_busywaitinterval);
}
static char getbusywaitinterval_doc[] =
@@ -2959,21 +2959,21 @@ calls to Tcl_DoOneEvent in a threaded Python interpreter.";
static PyMethodDef moduleMethods[] =
{
- {"_flatten", Tkinter_Flatten, METH_VARARGS},
- {"create", Tkinter_Create, METH_VARARGS},
+ {"_flatten", Tkinter_Flatten, METH_VARARGS},
+ {"create", Tkinter_Create, 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},
- {"setbusywaitinterval",Tkinter_setbusywaitinterval, METH_VARARGS,
- setbusywaitinterval_doc},
- {"getbusywaitinterval",(PyCFunction)Tkinter_getbusywaitinterval,
- METH_NOARGS, getbusywaitinterval_doc},
- {NULL, NULL}
+ {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS},
+ {"mainloop", Tkapp_MainLoop, METH_VARARGS},
+ {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS},
+ {"quit", Tkapp_Quit, METH_VARARGS},
+ {"setbusywaitinterval",Tkinter_setbusywaitinterval, METH_VARARGS,
+ setbusywaitinterval_doc},
+ {"getbusywaitinterval",(PyCFunction)Tkinter_getbusywaitinterval,
+ METH_NOARGS, getbusywaitinterval_doc},
+ {NULL, NULL}
};
#ifdef WAIT_FOR_STDIN
@@ -2984,7 +2984,7 @@ static int stdin_ready = 0;
static void
MyFileProc(void *clientData, int mask)
{
- stdin_ready = 1;
+ stdin_ready = 1;
}
#endif
@@ -2996,57 +2996,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
@@ -3055,12 +3055,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
}
@@ -3068,9 +3068,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
}
@@ -3079,89 +3079,89 @@ DisableEventHook(void)
static void
ins_long(PyObject *d, char *name, long val)
{
- PyObject *v = PyInt_FromLong(val);
- if (v) {
- PyDict_SetItemString(d, name, v);
- Py_DECREF(v);
- }
+ PyObject *v = PyInt_FromLong(val);
+ if (v) {
+ PyDict_SetItemString(d, name, v);
+ Py_DECREF(v);
+ }
}
static void
ins_string(PyObject *d, char *name, char *val)
{
- PyObject *v = PyString_FromString(val);
- if (v) {
- PyDict_SetItemString(d, name, v);
- Py_DECREF(v);
- }
+ PyObject *v = PyString_FromString(val);
+ if (v) {
+ PyDict_SetItemString(d, name, v);
+ Py_DECREF(v);
+ }
}
PyMODINIT_FUNC
init_tkinter(void)
{
- PyObject *m, *d;
+ PyObject *m, *d;
- Py_TYPE(&Tkapp_Type) = &PyType_Type;
+ Py_TYPE(&Tkapp_Type) = &PyType_Type;
#ifdef WITH_THREAD
- tcl_lock = PyThread_allocate_lock();
+ tcl_lock = PyThread_allocate_lock();
#endif
- m = Py_InitModule("_tkinter", moduleMethods);
- if (m == NULL)
- return;
+ m = Py_InitModule("_tkinter", moduleMethods);
+ if (m == NULL)
+ return;
- 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);
- Py_TYPE(&Tktt_Type) = &PyType_Type;
- PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type);
+ Py_TYPE(&Tktt_Type) = &PyType_Type;
+ 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. */
- Tcl_FindExecutable(Py_GetProgramName());
+ /* This helps the dynamic loader; in Unicode aware Tcl versions
+ it also helps Tcl find its encodings. */
+ Tcl_FindExecutable(Py_GetProgramName());
- if (PyErr_Occurred())
- return;
+ if (PyErr_Occurred())
+ return;
#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
}
diff --git a/Modules/addrinfo.h b/Modules/addrinfo.h
index 6f67a2e..670b173 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/almodule.c b/Modules/almodule.c
index 93f26bd..691175e 100644
--- a/Modules/almodule.c
+++ b/Modules/almodule.c
@@ -1,5 +1,5 @@
-#define OLD_INTERFACE /* define for pre-Irix 6 interface */
+#define OLD_INTERFACE /* define for pre-Irix 6 interface */
#include "Python.h"
#include "stringobject.h"
@@ -19,9 +19,9 @@ static PyObject *ErrorObject;
/* Declarations for objects of type port */
typedef struct {
- PyObject_HEAD
- /* XXXX Add your own stuff here */
- ALport port;
+ PyObject_HEAD
+ /* XXXX Add your own stuff here */
+ ALport port;
} alpobject;
static PyTypeObject Alptype;
@@ -33,9 +33,9 @@ static PyTypeObject Alptype;
/* Declarations for objects of type config */
typedef struct {
- PyObject_HEAD
- /* XXXX Add your own stuff here */
- ALconfig config;
+ PyObject_HEAD
+ /* XXXX Add your own stuff here */
+ ALconfig config;
} alcobject;
static PyTypeObject Alctype;
@@ -44,199 +44,199 @@ static PyTypeObject Alctype;
static void
ErrorHandler(long code, const char *fmt, ...)
{
- va_list args;
- char buf[128];
+ va_list args;
+ char buf[128];
- va_start(args, fmt);
- vsprintf(buf, fmt, args);
- va_end(args);
- PyErr_SetString(ErrorObject, buf);
+ va_start(args, fmt);
+ vsprintf(buf, fmt, args);
+ va_end(args);
+ PyErr_SetString(ErrorObject, buf);
}
-#ifdef AL_NO_ELEM /* IRIX 6 */
+#ifdef AL_NO_ELEM /* IRIX 6 */
static PyObject *
param2python(int resource, int param, ALvalue value, ALparamInfo *pinfo)
{
- ALparamInfo info;
-
- if (pinfo == NULL) {
- pinfo = &info;
- if (alGetParamInfo(resource, param, &info) < 0)
- return NULL;
- }
- switch (pinfo->elementType) {
- case AL_PTR_ELEM:
- /* XXXX don't know how to handle this */
- case AL_NO_ELEM:
- Py_INCREF(Py_None);
- return Py_None;
- case AL_INT32_ELEM:
- case AL_RESOURCE_ELEM:
- case AL_ENUM_ELEM:
- return PyInt_FromLong((long) value.i);
- case AL_INT64_ELEM:
- return PyLong_FromLongLong(value.ll);
- case AL_FIXED_ELEM:
- return PyFloat_FromDouble(alFixedToDouble(value.ll));
- case AL_CHAR_ELEM:
- if (value.ptr == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString((char *) value.ptr);
- default:
- PyErr_SetString(ErrorObject, "unknown element type");
- return NULL;
- }
+ ALparamInfo info;
+
+ if (pinfo == NULL) {
+ pinfo = &info;
+ if (alGetParamInfo(resource, param, &info) < 0)
+ return NULL;
+ }
+ switch (pinfo->elementType) {
+ case AL_PTR_ELEM:
+ /* XXXX don't know how to handle this */
+ case AL_NO_ELEM:
+ Py_INCREF(Py_None);
+ return Py_None;
+ case AL_INT32_ELEM:
+ case AL_RESOURCE_ELEM:
+ case AL_ENUM_ELEM:
+ return PyInt_FromLong((long) value.i);
+ case AL_INT64_ELEM:
+ return PyLong_FromLongLong(value.ll);
+ case AL_FIXED_ELEM:
+ return PyFloat_FromDouble(alFixedToDouble(value.ll));
+ case AL_CHAR_ELEM:
+ if (value.ptr == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString((char *) value.ptr);
+ default:
+ PyErr_SetString(ErrorObject, "unknown element type");
+ return NULL;
+ }
}
static int
python2elem(PyObject *item, void *ptr, int elementType)
{
- switch (elementType) {
- case AL_INT32_ELEM:
- case AL_RESOURCE_ELEM:
- case AL_ENUM_ELEM:
- if (!PyInt_Check(item)) {
- PyErr_BadArgument();
- return -1;
- }
- *((int *) ptr) = PyInt_AsLong(item);
- break;
- case AL_INT64_ELEM:
- if (PyInt_Check(item))
- *((long long *) ptr) = PyInt_AsLong(item);
- else if (PyLong_Check(item))
- *((long long *) ptr) = PyLong_AsLongLong(item);
- else {
- PyErr_BadArgument();
- return -1;
- }
- break;
- case AL_FIXED_ELEM:
- if (PyInt_Check(item))
- *((long long *) ptr) = alDoubleToFixed((double) PyInt_AsLong(item));
- else if (PyFloat_Check(item))
- *((long long *) ptr) = alDoubleToFixed(PyFloat_AsDouble(item));
- else {
- PyErr_BadArgument();
- return -1;
- }
- break;
- default:
- PyErr_SetString(ErrorObject, "unknown element type");
- return -1;
- }
- return 0;
+ switch (elementType) {
+ case AL_INT32_ELEM:
+ case AL_RESOURCE_ELEM:
+ case AL_ENUM_ELEM:
+ if (!PyInt_Check(item)) {
+ PyErr_BadArgument();
+ return -1;
+ }
+ *((int *) ptr) = PyInt_AsLong(item);
+ break;
+ case AL_INT64_ELEM:
+ if (PyInt_Check(item))
+ *((long long *) ptr) = PyInt_AsLong(item);
+ else if (PyLong_Check(item))
+ *((long long *) ptr) = PyLong_AsLongLong(item);
+ else {
+ PyErr_BadArgument();
+ return -1;
+ }
+ break;
+ case AL_FIXED_ELEM:
+ if (PyInt_Check(item))
+ *((long long *) ptr) = alDoubleToFixed((double) PyInt_AsLong(item));
+ else if (PyFloat_Check(item))
+ *((long long *) ptr) = alDoubleToFixed(PyFloat_AsDouble(item));
+ else {
+ PyErr_BadArgument();
+ return -1;
+ }
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "unknown element type");
+ return -1;
+ }
+ return 0;
}
static int
python2param(int resource, ALpv *param, PyObject *value, ALparamInfo *pinfo)
{
- ALparamInfo info;
- int i, stepsize;
- PyObject *item;
-
- if (pinfo == NULL) {
- pinfo = &info;
- if (alGetParamInfo(resource, param->param, &info) < 0)
- return -1;
- }
- switch (pinfo->valueType) {
- case AL_STRING_VAL:
- if (pinfo->elementType != AL_CHAR_ELEM) {
- PyErr_SetString(ErrorObject, "unknown element type");
- return -1;
- }
- if (!PyString_Check(value)) {
- PyErr_BadArgument();
- return -1;
- }
- param->value.ptr = PyString_AS_STRING(value);
- param->sizeIn = PyString_GET_SIZE(value)+1; /*account for NUL*/
- break;
- case AL_SET_VAL:
- case AL_VECTOR_VAL:
- if (!PyList_Check(value) && !PyTuple_Check(value)) {
- PyErr_BadArgument();
- return -1;
- }
- switch (pinfo->elementType) {
- case AL_INT32_ELEM:
- case AL_RESOURCE_ELEM:
- case AL_ENUM_ELEM:
- param->sizeIn = PySequence_Size(value);
- param->value.ptr = PyMem_NEW(int, param->sizeIn);
- stepsize = sizeof(int);
- break;
- case AL_INT64_ELEM:
- case AL_FIXED_ELEM:
- param->sizeIn = PySequence_Size(value);
- param->value.ptr = PyMem_NEW(long long, param->sizeIn);
- stepsize = sizeof(long long);
- break;
- }
- for (i = 0; i < param->sizeIn; i++) {
- item = PySequence_GetItem(value, i);
- if (python2elem(item, (void *) ((char *) param->value.ptr + i*stepsize), pinfo->elementType) < 0) {
- PyMem_DEL(param->value.ptr);
- return -1;
- }
- }
- break;
- case AL_SCALAR_VAL:
- switch (pinfo->elementType) {
- case AL_INT32_ELEM:
- case AL_RESOURCE_ELEM:
- case AL_ENUM_ELEM:
- return python2elem(value, (void *) &param->value.i,
- pinfo->elementType);
- case AL_INT64_ELEM:
- case AL_FIXED_ELEM:
- return python2elem(value, (void *) &param->value.ll,
- pinfo->elementType);
- default:
- PyErr_SetString(ErrorObject, "unknown element type");
- return -1;
- }
- }
- return 0;
+ ALparamInfo info;
+ int i, stepsize;
+ PyObject *item;
+
+ if (pinfo == NULL) {
+ pinfo = &info;
+ if (alGetParamInfo(resource, param->param, &info) < 0)
+ return -1;
+ }
+ switch (pinfo->valueType) {
+ case AL_STRING_VAL:
+ if (pinfo->elementType != AL_CHAR_ELEM) {
+ PyErr_SetString(ErrorObject, "unknown element type");
+ return -1;
+ }
+ if (!PyString_Check(value)) {
+ PyErr_BadArgument();
+ return -1;
+ }
+ param->value.ptr = PyString_AS_STRING(value);
+ param->sizeIn = PyString_GET_SIZE(value)+1; /*account for NUL*/
+ break;
+ case AL_SET_VAL:
+ case AL_VECTOR_VAL:
+ if (!PyList_Check(value) && !PyTuple_Check(value)) {
+ PyErr_BadArgument();
+ return -1;
+ }
+ switch (pinfo->elementType) {
+ case AL_INT32_ELEM:
+ case AL_RESOURCE_ELEM:
+ case AL_ENUM_ELEM:
+ param->sizeIn = PySequence_Size(value);
+ param->value.ptr = PyMem_NEW(int, param->sizeIn);
+ stepsize = sizeof(int);
+ break;
+ case AL_INT64_ELEM:
+ case AL_FIXED_ELEM:
+ param->sizeIn = PySequence_Size(value);
+ param->value.ptr = PyMem_NEW(long long, param->sizeIn);
+ stepsize = sizeof(long long);
+ break;
+ }
+ for (i = 0; i < param->sizeIn; i++) {
+ item = PySequence_GetItem(value, i);
+ if (python2elem(item, (void *) ((char *) param->value.ptr + i*stepsize), pinfo->elementType) < 0) {
+ PyMem_DEL(param->value.ptr);
+ return -1;
+ }
+ }
+ break;
+ case AL_SCALAR_VAL:
+ switch (pinfo->elementType) {
+ case AL_INT32_ELEM:
+ case AL_RESOURCE_ELEM:
+ case AL_ENUM_ELEM:
+ return python2elem(value, (void *) &param->value.i,
+ pinfo->elementType);
+ case AL_INT64_ELEM:
+ case AL_FIXED_ELEM:
+ return python2elem(value, (void *) &param->value.ll,
+ pinfo->elementType);
+ default:
+ PyErr_SetString(ErrorObject, "unknown element type");
+ return -1;
+ }
+ }
+ return 0;
}
static int
python2params(int resource1, int resource2, PyObject *list, ALpv **pvsp, ALparamInfo **pinfop)
{
- PyObject *item;
- ALpv *pvs;
- ALparamInfo *pinfo;
- int npvs, i;
-
- npvs = PyList_Size(list);
- pvs = PyMem_NEW(ALpv, npvs);
- pinfo = PyMem_NEW(ALparamInfo, npvs);
- for (i = 0; i < npvs; i++) {
- item = PyList_GetItem(list, i);
- if (!PyArg_ParseTuple(item, "iO", &pvs[i].param, &item))
- goto error;
- if (alGetParamInfo(resource1, pvs[i].param, &pinfo[i]) < 0 &&
- alGetParamInfo(resource2, pvs[i].param, &pinfo[i]) < 0)
- goto error;
- if (python2param(resource1, &pvs[i], item, &pinfo[i]) < 0)
- goto error;
- }
-
- *pvsp = pvs;
- *pinfop = pinfo;
- return npvs;
+ PyObject *item;
+ ALpv *pvs;
+ ALparamInfo *pinfo;
+ int npvs, i;
+
+ npvs = PyList_Size(list);
+ pvs = PyMem_NEW(ALpv, npvs);
+ pinfo = PyMem_NEW(ALparamInfo, npvs);
+ for (i = 0; i < npvs; i++) {
+ item = PyList_GetItem(list, i);
+ if (!PyArg_ParseTuple(item, "iO", &pvs[i].param, &item))
+ goto error;
+ if (alGetParamInfo(resource1, pvs[i].param, &pinfo[i]) < 0 &&
+ alGetParamInfo(resource2, pvs[i].param, &pinfo[i]) < 0)
+ goto error;
+ if (python2param(resource1, &pvs[i], item, &pinfo[i]) < 0)
+ goto error;
+ }
+
+ *pvsp = pvs;
+ *pinfop = pinfo;
+ return npvs;
error:
- /* XXXX we should clean up everything */
- if (pvs)
- PyMem_DEL(pvs);
- if (pinfo)
- PyMem_DEL(pinfo);
- return -1;
+ /* XXXX we should clean up everything */
+ if (pvs)
+ PyMem_DEL(pvs);
+ if (pinfo)
+ PyMem_DEL(pinfo);
+ return -1;
}
/* -------------------------------------------------------- */
@@ -245,30 +245,30 @@ python2params(int resource1, int resource2, PyObject *list, ALpv **pvsp, ALparam
static PyObject *
SetConfig(alcobject *self, PyObject *args, int (*func)(ALconfig, int))
{
- int par;
+ int par;
- if (!PyArg_ParseTuple(args, "i:SetConfig", &par))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:SetConfig", &par))
+ return NULL;
- if ((*func)(self->config, par) == -1)
- return NULL;
+ if ((*func)(self->config, par) == -1)
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
GetConfig(alcobject *self, PyObject *args, int (*func)(ALconfig))
-{
- int par;
+{
+ int par;
+
+ if (!PyArg_ParseTuple(args, ":GetConfig"))
+ return NULL;
- if (!PyArg_ParseTuple(args, ":GetConfig"))
- return NULL;
-
- if ((par = (*func)(self->config)) == -1)
- return NULL;
+ if ((par = (*func)(self->config)) == -1)
+ return NULL;
- return PyInt_FromLong((long) par);
+ return PyInt_FromLong((long) par);
}
PyDoc_STRVAR(alc_SetWidth__doc__,
@@ -277,7 +277,7 @@ PyDoc_STRVAR(alc_SetWidth__doc__,
static PyObject *
alc_SetWidth(alcobject *self, PyObject *args)
{
- return SetConfig(self, args, alSetWidth);
+ return SetConfig(self, args, alSetWidth);
}
@@ -287,7 +287,7 @@ PyDoc_STRVAR(alc_GetWidth__doc__,
static PyObject *
alc_GetWidth(alcobject *self, PyObject *args)
{
- return GetConfig(self, args, alGetWidth);
+ return GetConfig(self, args, alGetWidth);
}
@@ -298,7 +298,7 @@ PyDoc_STRVAR(alc_SetSampFmt__doc__,
static PyObject *
alc_SetSampFmt(alcobject *self, PyObject *args)
{
- return SetConfig(self, args, alSetSampFmt);
+ return SetConfig(self, args, alSetSampFmt);
}
@@ -309,7 +309,7 @@ PyDoc_STRVAR(alc_GetSampFmt__doc__,
static PyObject *
alc_GetSampFmt(alcobject *self, PyObject *args)
{
- return GetConfig(self, args, alGetSampFmt);
+ return GetConfig(self, args, alGetSampFmt);
}
@@ -319,7 +319,7 @@ PyDoc_STRVAR(alc_SetChannels__doc__,
static PyObject *
alc_SetChannels(alcobject *self, PyObject *args)
{
- return SetConfig(self, args, alSetChannels);
+ return SetConfig(self, args, alSetChannels);
}
@@ -329,7 +329,7 @@ PyDoc_STRVAR(alc_GetChannels__doc__,
static PyObject *
alc_GetChannels(alcobject *self, PyObject *args)
{
- return GetConfig(self, args, alGetChannels);
+ return GetConfig(self, args, alGetChannels);
}
@@ -339,14 +339,14 @@ PyDoc_STRVAR(alc_SetFloatMax__doc__,
static PyObject *
alc_SetFloatMax(alcobject *self, PyObject *args)
{
- double maximum_value;
+ double maximum_value;
- if (!PyArg_ParseTuple(args, "d:SetFloatMax", &maximum_value))
- return NULL;
- if (alSetFloatMax(self->config, maximum_value) < 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "d:SetFloatMax", &maximum_value))
+ return NULL;
+ if (alSetFloatMax(self->config, maximum_value) < 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -356,13 +356,13 @@ PyDoc_STRVAR(alc_GetFloatMax__doc__,
static PyObject *
alc_GetFloatMax(alcobject *self, PyObject *args)
{
- double maximum_value;
+ double maximum_value;
- if (!PyArg_ParseTuple(args, ":GetFloatMax"))
- return NULL;
- if ((maximum_value = alGetFloatMax(self->config)) == 0)
- return NULL;
- return PyFloat_FromDouble(maximum_value);
+ if (!PyArg_ParseTuple(args, ":GetFloatMax"))
+ return NULL;
+ if ((maximum_value = alGetFloatMax(self->config)) == 0)
+ return NULL;
+ return PyFloat_FromDouble(maximum_value);
}
@@ -372,7 +372,7 @@ PyDoc_STRVAR(alc_SetDevice__doc__,
static PyObject *
alc_SetDevice(alcobject *self, PyObject *args)
{
- return SetConfig(self, args, alSetDevice);
+ return SetConfig(self, args, alSetDevice);
}
@@ -382,7 +382,7 @@ PyDoc_STRVAR(alc_GetDevice__doc__,
static PyObject *
alc_GetDevice(alcobject *self, PyObject *args)
{
- return GetConfig(self, args, alGetDevice);
+ return GetConfig(self, args, alGetDevice);
}
@@ -392,7 +392,7 @@ PyDoc_STRVAR(alc_SetQueueSize__doc__,
static PyObject *
alc_SetQueueSize(alcobject *self, PyObject *args)
{
- return SetConfig(self, args, alSetQueueSize);
+ return SetConfig(self, args, alSetQueueSize);
}
@@ -402,7 +402,7 @@ PyDoc_STRVAR(alc_GetQueueSize__doc__,
static PyObject *
alc_GetQueueSize(alcobject *self, PyObject *args)
{
- return GetConfig(self, args, alGetQueueSize);
+ return GetConfig(self, args, alGetQueueSize);
}
#endif /* AL_NO_ELEM */
@@ -410,66 +410,66 @@ alc_GetQueueSize(alcobject *self, PyObject *args)
static PyObject *
setconfig(alcobject *self, PyObject *args, int (*func)(ALconfig, long))
{
- long par;
+ long par;
- if (!PyArg_ParseTuple(args, "l:SetConfig", &par))
- return NULL;
+ if (!PyArg_ParseTuple(args, "l:SetConfig", &par))
+ return NULL;
- if ((*func)(self->config, par) == -1)
- return NULL;
+ if ((*func)(self->config, par) == -1)
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
getconfig(alcobject *self, PyObject *args, long (*func)(ALconfig))
-{
- long par;
+{
+ long par;
- if (!PyArg_ParseTuple(args, ":GetConfig"))
- return NULL;
-
- if ((par = (*func)(self->config)) == -1)
- return NULL;
+ if (!PyArg_ParseTuple(args, ":GetConfig"))
+ return NULL;
- return PyInt_FromLong((long) par);
+ if ((par = (*func)(self->config)) == -1)
+ return NULL;
+
+ return PyInt_FromLong((long) par);
}
static PyObject *
alc_setqueuesize (alcobject *self, PyObject *args)
{
- return setconfig(self, args, ALsetqueuesize);
+ return setconfig(self, args, ALsetqueuesize);
}
static PyObject *
alc_getqueuesize (alcobject *self, PyObject *args)
{
- return getconfig(self, args, ALgetqueuesize);
+ return getconfig(self, args, ALgetqueuesize);
}
static PyObject *
alc_setwidth (alcobject *self, PyObject *args)
{
- return setconfig(self, args, ALsetwidth);
+ return setconfig(self, args, ALsetwidth);
}
static PyObject *
alc_getwidth (alcobject *self, PyObject *args)
{
- return getconfig(self, args, ALgetwidth);
+ return getconfig(self, args, ALgetwidth);
}
static PyObject *
alc_getchannels (alcobject *self, PyObject *args)
{
- return getconfig(self, args, ALgetchannels);
+ return getconfig(self, args, ALgetchannels);
}
static PyObject *
alc_setchannels (alcobject *self, PyObject *args)
{
- return setconfig(self, args, ALsetchannels);
+ return setconfig(self, args, ALsetchannels);
}
#ifdef AL_405
@@ -477,70 +477,70 @@ alc_setchannels (alcobject *self, PyObject *args)
static PyObject *
alc_getsampfmt (alcobject *self, PyObject *args)
{
- return getconfig(self, args, ALgetsampfmt);
+ return getconfig(self, args, ALgetsampfmt);
}
static PyObject *
alc_setsampfmt (alcobject *self, PyObject *args)
{
- return setconfig(self, args, ALsetsampfmt);
+ return setconfig(self, args, ALsetsampfmt);
}
static PyObject *
alc_getfloatmax(alcobject *self, PyObject *args)
{
- double arg;
+ double arg;
- if (!PyArg_ParseTuple(args, ":GetFloatMax"))
- return 0;
- if ((arg = ALgetfloatmax(self->config)) == 0)
- return NULL;
- return PyFloat_FromDouble(arg);
+ if (!PyArg_ParseTuple(args, ":GetFloatMax"))
+ return 0;
+ if ((arg = ALgetfloatmax(self->config)) == 0)
+ return NULL;
+ return PyFloat_FromDouble(arg);
}
static PyObject *
alc_setfloatmax(alcobject *self, PyObject *args)
{
- double arg;
+ double arg;
- if (!PyArg_ParseTuple(args, "d:SetFloatMax", &arg))
- return 0;
- if (ALsetfloatmax(self->config, arg) == -1)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "d:SetFloatMax", &arg))
+ return 0;
+ if (ALsetfloatmax(self->config, arg) == -1)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* AL_405 */
-
+
static struct PyMethodDef alc_methods[] = {
-#ifdef AL_NO_ELEM /* IRIX 6 */
- {"SetWidth", (PyCFunction)alc_SetWidth, METH_VARARGS, alc_SetWidth__doc__},
- {"GetWidth", (PyCFunction)alc_GetWidth, METH_VARARGS, alc_GetWidth__doc__},
- {"SetSampFmt", (PyCFunction)alc_SetSampFmt, METH_VARARGS, alc_SetSampFmt__doc__},
- {"GetSampFmt", (PyCFunction)alc_GetSampFmt, METH_VARARGS, alc_GetSampFmt__doc__},
- {"SetChannels", (PyCFunction)alc_SetChannels, METH_VARARGS, alc_SetChannels__doc__},
- {"GetChannels", (PyCFunction)alc_GetChannels, METH_VARARGS, alc_GetChannels__doc__},
- {"SetFloatMax", (PyCFunction)alc_SetFloatMax, METH_VARARGS, alc_SetFloatMax__doc__},
- {"GetFloatMax", (PyCFunction)alc_GetFloatMax, METH_VARARGS, alc_GetFloatMax__doc__},
- {"SetDevice", (PyCFunction)alc_SetDevice, METH_VARARGS, alc_SetDevice__doc__},
- {"GetDevice", (PyCFunction)alc_GetDevice, METH_VARARGS, alc_GetDevice__doc__},
- {"SetQueueSize", (PyCFunction)alc_SetQueueSize, METH_VARARGS, alc_SetQueueSize__doc__},
- {"GetQueueSize", (PyCFunction)alc_GetQueueSize, METH_VARARGS, alc_GetQueueSize__doc__},
+#ifdef AL_NO_ELEM /* IRIX 6 */
+ {"SetWidth", (PyCFunction)alc_SetWidth, METH_VARARGS, alc_SetWidth__doc__},
+ {"GetWidth", (PyCFunction)alc_GetWidth, METH_VARARGS, alc_GetWidth__doc__},
+ {"SetSampFmt", (PyCFunction)alc_SetSampFmt, METH_VARARGS, alc_SetSampFmt__doc__},
+ {"GetSampFmt", (PyCFunction)alc_GetSampFmt, METH_VARARGS, alc_GetSampFmt__doc__},
+ {"SetChannels", (PyCFunction)alc_SetChannels, METH_VARARGS, alc_SetChannels__doc__},
+ {"GetChannels", (PyCFunction)alc_GetChannels, METH_VARARGS, alc_GetChannels__doc__},
+ {"SetFloatMax", (PyCFunction)alc_SetFloatMax, METH_VARARGS, alc_SetFloatMax__doc__},
+ {"GetFloatMax", (PyCFunction)alc_GetFloatMax, METH_VARARGS, alc_GetFloatMax__doc__},
+ {"SetDevice", (PyCFunction)alc_SetDevice, METH_VARARGS, alc_SetDevice__doc__},
+ {"GetDevice", (PyCFunction)alc_GetDevice, METH_VARARGS, alc_GetDevice__doc__},
+ {"SetQueueSize", (PyCFunction)alc_SetQueueSize, METH_VARARGS, alc_SetQueueSize__doc__},
+ {"GetQueueSize", (PyCFunction)alc_GetQueueSize, METH_VARARGS, alc_GetQueueSize__doc__},
#endif /* AL_NO_ELEM */
- {"getqueuesize", (PyCFunction)alc_getqueuesize, METH_VARARGS},
- {"setqueuesize", (PyCFunction)alc_setqueuesize, METH_VARARGS},
- {"getwidth", (PyCFunction)alc_getwidth, METH_VARARGS},
- {"setwidth", (PyCFunction)alc_setwidth, METH_VARARGS},
- {"getchannels", (PyCFunction)alc_getchannels, METH_VARARGS},
- {"setchannels", (PyCFunction)alc_setchannels, METH_VARARGS},
+ {"getqueuesize", (PyCFunction)alc_getqueuesize, METH_VARARGS},
+ {"setqueuesize", (PyCFunction)alc_setqueuesize, METH_VARARGS},
+ {"getwidth", (PyCFunction)alc_getwidth, METH_VARARGS},
+ {"setwidth", (PyCFunction)alc_setwidth, METH_VARARGS},
+ {"getchannels", (PyCFunction)alc_getchannels, METH_VARARGS},
+ {"setchannels", (PyCFunction)alc_setchannels, METH_VARARGS},
#ifdef AL_405
- {"getsampfmt", (PyCFunction)alc_getsampfmt, METH_VARARGS},
- {"setsampfmt", (PyCFunction)alc_setsampfmt, METH_VARARGS},
- {"getfloatmax", (PyCFunction)alc_getfloatmax, METH_VARARGS},
- {"setfloatmax", (PyCFunction)alc_setfloatmax, METH_VARARGS},
+ {"getsampfmt", (PyCFunction)alc_getsampfmt, METH_VARARGS},
+ {"setsampfmt", (PyCFunction)alc_setsampfmt, METH_VARARGS},
+ {"getfloatmax", (PyCFunction)alc_getfloatmax, METH_VARARGS},
+ {"setfloatmax", (PyCFunction)alc_setfloatmax, METH_VARARGS},
#endif /* AL_405 */
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
/* ---------- */
@@ -549,67 +549,67 @@ static struct PyMethodDef alc_methods[] = {
static PyObject *
newalcobject(ALconfig config)
{
- alcobject *self;
-
- self = PyObject_New(alcobject, &Alctype);
- if (self == NULL)
- return NULL;
- /* XXXX Add your own initializers here */
- self->config = config;
- return (PyObject *) self;
+ alcobject *self;
+
+ self = PyObject_New(alcobject, &Alctype);
+ if (self == NULL)
+ return NULL;
+ /* XXXX Add your own initializers here */
+ self->config = config;
+ return (PyObject *) self;
}
static void
alc_dealloc(alcobject *self)
{
- /* XXXX Add your own cleanup code here */
-#ifdef AL_NO_ELEM /* IRIX 6 */
- (void) alFreeConfig(self->config); /* ignore errors */
+ /* XXXX Add your own cleanup code here */
+#ifdef AL_NO_ELEM /* IRIX 6 */
+ (void) alFreeConfig(self->config); /* ignore errors */
#else
- (void) ALfreeconfig(self->config); /* ignore errors */
+ (void) ALfreeconfig(self->config); /* ignore errors */
#endif
- PyObject_Del(self);
+ PyObject_Del(self);
}
static PyObject *
alc_getattr(alcobject *self, char *name)
{
- /* XXXX Add your own getattr code here */
- return Py_FindMethod(alc_methods, (PyObject *)self, name);
+ /* XXXX Add your own getattr code here */
+ return Py_FindMethod(alc_methods, (PyObject *)self, name);
}
PyDoc_STRVAR(Alctype__doc__, "");
static PyTypeObject Alctype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "al.config", /*tp_name*/
- sizeof(alcobject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)alc_dealloc, /*tp_dealloc*/
- (printfunc)0, /*tp_print*/
- (getattrfunc)alc_getattr, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc)0, /*tp_compare*/
- (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*/
-
- /* Space for future expansion */
- 0L,0L,0L,0L,
- Alctype__doc__ /* Documentation string */
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "al.config", /*tp_name*/
+ sizeof(alcobject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)alc_dealloc, /*tp_dealloc*/
+ (printfunc)0, /*tp_print*/
+ (getattrfunc)alc_getattr, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc)0, /*tp_compare*/
+ (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*/
+
+ /* Space for future expansion */
+ 0L,0L,0L,0L,
+ Alctype__doc__ /* Documentation string */
};
/* End of code for config objects */
/* ---------------------------------------------------------------- */
-#ifdef AL_NO_ELEM /* IRIX 6 */
+#ifdef AL_NO_ELEM /* IRIX 6 */
PyDoc_STRVAR(alp_SetConfig__doc__,
"alSetConfig: set the ALconfig of an audio ALport.");
@@ -617,13 +617,13 @@ PyDoc_STRVAR(alp_SetConfig__doc__,
static PyObject *
alp_SetConfig(alpobject *self, PyObject *args)
{
- alcobject *config;
- if (!PyArg_ParseTuple(args, "O!:SetConfig", &Alctype, &config))
- return NULL;
- if (alSetConfig(self->port, config->config) < 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ alcobject *config;
+ if (!PyArg_ParseTuple(args, "O!:SetConfig", &Alctype, &config))
+ return NULL;
+ if (alSetConfig(self->port, config->config) < 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -633,12 +633,12 @@ PyDoc_STRVAR(alp_GetConfig__doc__,
static PyObject *
alp_GetConfig(alpobject *self, PyObject *args)
{
- ALconfig config;
- if (!PyArg_ParseTuple(args, ":GetConfig"))
- return NULL;
- if ((config = alGetConfig(self->port)) == NULL)
- return NULL;
- return newalcobject(config);
+ ALconfig config;
+ if (!PyArg_ParseTuple(args, ":GetConfig"))
+ return NULL;
+ if ((config = alGetConfig(self->port)) == NULL)
+ return NULL;
+ return newalcobject(config);
}
@@ -648,13 +648,13 @@ PyDoc_STRVAR(alp_GetResource__doc__,
static PyObject *
alp_GetResource(alpobject *self, PyObject *args)
{
- int resource;
+ int resource;
- if (!PyArg_ParseTuple(args, ":GetResource"))
- return NULL;
- if ((resource = alGetResource(self->port)) == 0)
- return NULL;
- return PyInt_FromLong((long) resource);
+ if (!PyArg_ParseTuple(args, ":GetResource"))
+ return NULL;
+ if ((resource = alGetResource(self->port)) == 0)
+ return NULL;
+ return PyInt_FromLong((long) resource);
}
@@ -664,15 +664,15 @@ PyDoc_STRVAR(alp_GetFD__doc__,
static PyObject *
alp_GetFD(alpobject *self, PyObject *args)
{
- int fd;
+ int fd;
- if (!PyArg_ParseTuple(args, ":GetFD"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":GetFD"))
+ return NULL;
- if ((fd = alGetFD(self->port)) < 0)
- return NULL;
+ if ((fd = alGetFD(self->port)) < 0)
+ return NULL;
- return PyInt_FromLong((long) fd);
+ return PyInt_FromLong((long) fd);
}
@@ -683,13 +683,13 @@ PyDoc_STRVAR(alp_GetFilled__doc__,
static PyObject *
alp_GetFilled(alpobject *self, PyObject *args)
{
- int filled;
+ int filled;
- if (!PyArg_ParseTuple(args, ":GetFilled"))
- return NULL;
- if ((filled = alGetFilled(self->port)) < 0)
- return NULL;
- return PyInt_FromLong((long) filled);
+ if (!PyArg_ParseTuple(args, ":GetFilled"))
+ return NULL;
+ if ((filled = alGetFilled(self->port)) < 0)
+ return NULL;
+ return PyInt_FromLong((long) filled);
}
@@ -700,13 +700,13 @@ PyDoc_STRVAR(alp_GetFillable__doc__,
static PyObject *
alp_GetFillable(alpobject *self, PyObject *args)
{
- int fillable;
+ int fillable;
- if (!PyArg_ParseTuple(args, ":GetFillable"))
- return NULL;
- if ((fillable = alGetFillable(self->port)) < 0)
- return NULL;
- return PyInt_FromLong((long) fillable);
+ if (!PyArg_ParseTuple(args, ":GetFillable"))
+ return NULL;
+ if ((fillable = alGetFillable(self->port)) < 0)
+ return NULL;
+ return PyInt_FromLong((long) fillable);
}
@@ -716,64 +716,64 @@ PyDoc_STRVAR(alp_ReadFrames__doc__,
static PyObject *
alp_ReadFrames(alpobject *self, PyObject *args)
{
- int framecount;
- PyObject *v;
- int size;
- int ch;
- ALconfig c;
-
- if (!PyArg_ParseTuple(args, "i:ReadFrames", &framecount))
- return NULL;
- if (framecount < 0) {
- PyErr_SetString(ErrorObject, "negative framecount");
- return NULL;
- }
- c = alGetConfig(self->port);
- switch (alGetSampFmt(c)) {
- case AL_SAMPFMT_TWOSCOMP:
- switch (alGetWidth(c)) {
- case AL_SAMPLE_8:
- size = 1;
- break;
- case AL_SAMPLE_16:
- size = 2;
- break;
- case AL_SAMPLE_24:
- size = 4;
- break;
- default:
- PyErr_SetString(ErrorObject, "can't determine width");
- alFreeConfig(c);
- return NULL;
- }
- break;
- case AL_SAMPFMT_FLOAT:
- size = 4;
- break;
- case AL_SAMPFMT_DOUBLE:
- size = 8;
- break;
- default:
- PyErr_SetString(ErrorObject, "can't determine format");
- alFreeConfig(c);
- return NULL;
- }
- ch = alGetChannels(c);
- alFreeConfig(c);
- if (ch < 0) {
- PyErr_SetString(ErrorObject, "can't determine # of channels");
- return NULL;
- }
- size *= ch;
- v = PyString_FromStringAndSize((char *) NULL, size * framecount);
- if (v == NULL)
- return NULL;
-
- Py_BEGIN_ALLOW_THREADS
- alReadFrames(self->port, (void *) PyString_AS_STRING(v), framecount);
- Py_END_ALLOW_THREADS
-
- return v;
+ int framecount;
+ PyObject *v;
+ int size;
+ int ch;
+ ALconfig c;
+
+ if (!PyArg_ParseTuple(args, "i:ReadFrames", &framecount))
+ return NULL;
+ if (framecount < 0) {
+ PyErr_SetString(ErrorObject, "negative framecount");
+ return NULL;
+ }
+ c = alGetConfig(self->port);
+ switch (alGetSampFmt(c)) {
+ case AL_SAMPFMT_TWOSCOMP:
+ switch (alGetWidth(c)) {
+ case AL_SAMPLE_8:
+ size = 1;
+ break;
+ case AL_SAMPLE_16:
+ size = 2;
+ break;
+ case AL_SAMPLE_24:
+ size = 4;
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "can't determine width");
+ alFreeConfig(c);
+ return NULL;
+ }
+ break;
+ case AL_SAMPFMT_FLOAT:
+ size = 4;
+ break;
+ case AL_SAMPFMT_DOUBLE:
+ size = 8;
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "can't determine format");
+ alFreeConfig(c);
+ return NULL;
+ }
+ ch = alGetChannels(c);
+ alFreeConfig(c);
+ if (ch < 0) {
+ PyErr_SetString(ErrorObject, "can't determine # of channels");
+ return NULL;
+ }
+ size *= ch;
+ v = PyString_FromStringAndSize((char *) NULL, size * framecount);
+ if (v == NULL)
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ alReadFrames(self->port, (void *) PyString_AS_STRING(v), framecount);
+ Py_END_ALLOW_THREADS
+
+ return v;
}
@@ -783,19 +783,19 @@ PyDoc_STRVAR(alp_DiscardFrames__doc__,
static PyObject *
alp_DiscardFrames(alpobject *self, PyObject *args)
{
- int framecount;
+ int framecount;
- if (!PyArg_ParseTuple(args, "i:DiscardFrames", &framecount))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:DiscardFrames", &framecount))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- framecount = alDiscardFrames(self->port, framecount);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ framecount = alDiscardFrames(self->port, framecount);
+ Py_END_ALLOW_THREADS
- if (framecount < 0)
- return NULL;
+ if (framecount < 0)
+ return NULL;
- return PyInt_FromLong((long) framecount);
+ return PyInt_FromLong((long) framecount);
}
@@ -805,22 +805,22 @@ PyDoc_STRVAR(alp_ZeroFrames__doc__,
static PyObject *
alp_ZeroFrames(alpobject *self, PyObject *args)
{
- int framecount;
+ int framecount;
- if (!PyArg_ParseTuple(args, "i:ZeroFrames", &framecount))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:ZeroFrames", &framecount))
+ return NULL;
- if (framecount < 0) {
- PyErr_SetString(ErrorObject, "negative framecount");
- return NULL;
- }
+ if (framecount < 0) {
+ PyErr_SetString(ErrorObject, "negative framecount");
+ return NULL;
+ }
- Py_BEGIN_ALLOW_THREADS
- alZeroFrames(self->port, framecount);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ alZeroFrames(self->port, framecount);
+ Py_END_ALLOW_THREADS
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -830,16 +830,16 @@ PyDoc_STRVAR(alp_SetFillPoint__doc__,
static PyObject *
alp_SetFillPoint(alpobject *self, PyObject *args)
{
- int fillpoint;
+ int fillpoint;
- if (!PyArg_ParseTuple(args, "i:SetFillPoint", &fillpoint))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:SetFillPoint", &fillpoint))
+ return NULL;
- if (alSetFillPoint(self->port, fillpoint) < 0)
- return NULL;
+ if (alSetFillPoint(self->port, fillpoint) < 0)
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -849,15 +849,15 @@ PyDoc_STRVAR(alp_GetFillPoint__doc__,
static PyObject *
alp_GetFillPoint(alpobject *self, PyObject *args)
{
- int fillpoint;
+ int fillpoint;
- if (!PyArg_ParseTuple(args, ":GetFillPoint"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":GetFillPoint"))
+ return NULL;
- if ((fillpoint = alGetFillPoint(self->port)) < 0)
- return NULL;
+ if ((fillpoint = alGetFillPoint(self->port)) < 0)
+ return NULL;
- return PyInt_FromLong((long) fillpoint);
+ return PyInt_FromLong((long) fillpoint);
}
@@ -868,15 +868,15 @@ PyDoc_STRVAR(alp_GetFrameNumber__doc__,
static PyObject *
alp_GetFrameNumber(alpobject *self, PyObject *args)
{
- stamp_t fnum;
+ stamp_t fnum;
- if (!PyArg_ParseTuple(args, ":GetFrameNumber"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":GetFrameNumber"))
+ return NULL;
- if (alGetFrameNumber(self->port, &fnum) < 0)
- return NULL;
+ if (alGetFrameNumber(self->port, &fnum) < 0)
+ return NULL;
- return PyLong_FromLongLong((long long) fnum);
+ return PyLong_FromLongLong((long long) fnum);
}
@@ -887,24 +887,24 @@ PyDoc_STRVAR(alp_GetFrameTime__doc__,
static PyObject *
alp_GetFrameTime(alpobject *self, PyObject *args)
{
- stamp_t fnum, time;
- PyObject *ret, *v0, *v1;
+ stamp_t fnum, time;
+ PyObject *ret, *v0, *v1;
- if (!PyArg_ParseTuple(args, ":GetFrameTime"))
- return NULL;
- if (alGetFrameTime(self->port, &fnum, &time) < 0)
- return NULL;
- v0 = PyLong_FromLongLong((long long) fnum);
- v1 = PyLong_FromLongLong((long long) time);
- if (PyErr_Occurred()) {
- Py_XDECREF(v0);
- Py_XDECREF(v1);
- return NULL;
- }
- ret = PyTuple_Pack(2, v0, v1);
- Py_DECREF(v0);
- Py_DECREF(v1);
- return ret;
+ if (!PyArg_ParseTuple(args, ":GetFrameTime"))
+ return NULL;
+ if (alGetFrameTime(self->port, &fnum, &time) < 0)
+ return NULL;
+ v0 = PyLong_FromLongLong((long long) fnum);
+ v1 = PyLong_FromLongLong((long long) time);
+ if (PyErr_Occurred()) {
+ Py_XDECREF(v0);
+ Py_XDECREF(v1);
+ return NULL;
+ }
+ ret = PyTuple_Pack(2, v0, v1);
+ Py_DECREF(v0);
+ Py_DECREF(v1);
+ return ret;
}
@@ -914,62 +914,62 @@ PyDoc_STRVAR(alp_WriteFrames__doc__,
static PyObject *
alp_WriteFrames(alpobject *self, PyObject *args)
{
- char *samples;
- int length;
- int size, ch;
- ALconfig c;
-
- if (!PyArg_ParseTuple(args, "s#:WriteFrames", &samples, &length))
- return NULL;
- c = alGetConfig(self->port);
- switch (alGetSampFmt(c)) {
- case AL_SAMPFMT_TWOSCOMP:
- switch (alGetWidth(c)) {
- case AL_SAMPLE_8:
- size = 1;
- break;
- case AL_SAMPLE_16:
- size = 2;
- break;
- case AL_SAMPLE_24:
- size = 4;
- break;
- default:
- PyErr_SetString(ErrorObject, "can't determine width");
- alFreeConfig(c);
- return NULL;
- }
- break;
- case AL_SAMPFMT_FLOAT:
- size = 4;
- break;
- case AL_SAMPFMT_DOUBLE:
- size = 8;
- break;
- default:
- PyErr_SetString(ErrorObject, "can't determine format");
- alFreeConfig(c);
- return NULL;
- }
- ch = alGetChannels(c);
- alFreeConfig(c);
- if (ch < 0) {
- PyErr_SetString(ErrorObject, "can't determine # of channels");
- return NULL;
- }
- size *= ch;
- if (length % size != 0) {
- PyErr_SetString(ErrorObject,
- "buffer length not whole number of frames");
- return NULL;
- }
-
- Py_BEGIN_ALLOW_THREADS
- alWriteFrames(self->port, (void *) samples, length / size);
- Py_END_ALLOW_THREADS
-
- Py_INCREF(Py_None);
- return Py_None;
+ char *samples;
+ int length;
+ int size, ch;
+ ALconfig c;
+
+ if (!PyArg_ParseTuple(args, "s#:WriteFrames", &samples, &length))
+ return NULL;
+ c = alGetConfig(self->port);
+ switch (alGetSampFmt(c)) {
+ case AL_SAMPFMT_TWOSCOMP:
+ switch (alGetWidth(c)) {
+ case AL_SAMPLE_8:
+ size = 1;
+ break;
+ case AL_SAMPLE_16:
+ size = 2;
+ break;
+ case AL_SAMPLE_24:
+ size = 4;
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "can't determine width");
+ alFreeConfig(c);
+ return NULL;
+ }
+ break;
+ case AL_SAMPFMT_FLOAT:
+ size = 4;
+ break;
+ case AL_SAMPFMT_DOUBLE:
+ size = 8;
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "can't determine format");
+ alFreeConfig(c);
+ return NULL;
+ }
+ ch = alGetChannels(c);
+ alFreeConfig(c);
+ if (ch < 0) {
+ PyErr_SetString(ErrorObject, "can't determine # of channels");
+ return NULL;
+ }
+ size *= ch;
+ if (length % size != 0) {
+ PyErr_SetString(ErrorObject,
+ "buffer length not whole number of frames");
+ return NULL;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ alWriteFrames(self->port, (void *) samples, length / size);
+ Py_END_ALLOW_THREADS
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -978,13 +978,13 @@ PyDoc_STRVAR(alp_ClosePort__doc__, "alClosePort: close an audio port.");
static PyObject *
alp_ClosePort(alpobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":ClosePort"))
- return NULL;
- if (alClosePort(self->port) < 0)
- return NULL;
- self->port = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ":ClosePort"))
+ return NULL;
+ if (alClosePort(self->port) < 0)
+ return NULL;
+ self->port = NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* AL_NO_ELEM */
@@ -993,257 +993,257 @@ alp_ClosePort(alpobject *self, PyObject *args)
static PyObject *
alp_closeport(alpobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":ClosePort"))
- return NULL;
- if (ALcloseport(self->port) < 0)
- return NULL;
- self->port = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ":ClosePort"))
+ return NULL;
+ if (ALcloseport(self->port) < 0)
+ return NULL;
+ self->port = NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
alp_getfd(alpobject *self, PyObject *args)
{
- int fd;
+ int fd;
- if (!PyArg_ParseTuple(args, ":GetFD"))
- return NULL;
- if ((fd = ALgetfd(self-> port)) == -1)
- return NULL;
- return PyInt_FromLong(fd);
+ if (!PyArg_ParseTuple(args, ":GetFD"))
+ return NULL;
+ if ((fd = ALgetfd(self-> port)) == -1)
+ return NULL;
+ return PyInt_FromLong(fd);
}
static PyObject *
alp_getfilled(alpobject *self, PyObject *args)
{
- long count;
+ long count;
- if (!PyArg_ParseTuple(args, ":GetFilled"))
- return NULL;
- if ((count = ALgetfilled(self-> port)) == -1)
- return NULL;
- return PyInt_FromLong(count);
+ if (!PyArg_ParseTuple(args, ":GetFilled"))
+ return NULL;
+ if ((count = ALgetfilled(self-> port)) == -1)
+ return NULL;
+ return PyInt_FromLong(count);
}
static PyObject *
alp_getfillable(alpobject *self, PyObject *args)
{
- long count;
+ long count;
- if (!PyArg_ParseTuple(args, ":GetFillable"))
- return NULL;
- if ((count = ALgetfillable(self-> port)) == -1)
- return NULL;
- return PyInt_FromLong (count);
+ if (!PyArg_ParseTuple(args, ":GetFillable"))
+ return NULL;
+ if ((count = ALgetfillable(self-> port)) == -1)
+ return NULL;
+ return PyInt_FromLong (count);
}
static PyObject *
alp_readsamps(alpobject *self, PyObject *args)
{
- long count;
- PyObject *v;
- ALconfig c;
- int width;
- int ret;
+ long count;
+ PyObject *v;
+ ALconfig c;
+ int width;
+ int ret;
- if (!PyArg_ParseTuple(args, "l:readsamps", &count))
- return NULL;
+ if (!PyArg_ParseTuple(args, "l:readsamps", &count))
+ return NULL;
- if (count <= 0) {
- PyErr_SetString(ErrorObject, "al.readsamps : arg <= 0");
- return NULL;
- }
+ if (count <= 0) {
+ PyErr_SetString(ErrorObject, "al.readsamps : arg <= 0");
+ return NULL;
+ }
- c = ALgetconfig(self->port);
+ c = ALgetconfig(self->port);
#ifdef AL_405
- width = ALgetsampfmt(c);
- if (width == AL_SAMPFMT_FLOAT)
- width = sizeof(float);
- else if (width == AL_SAMPFMT_DOUBLE)
- width = sizeof(double);
- else
- width = ALgetwidth(c);
+ width = ALgetsampfmt(c);
+ if (width == AL_SAMPFMT_FLOAT)
+ width = sizeof(float);
+ else if (width == AL_SAMPFMT_DOUBLE)
+ width = sizeof(double);
+ else
+ width = ALgetwidth(c);
#else
- width = ALgetwidth(c);
+ width = ALgetwidth(c);
#endif /* AL_405 */
- ALfreeconfig(c);
- v = PyString_FromStringAndSize((char *)NULL, width * count);
- if (v == NULL)
- return NULL;
+ ALfreeconfig(c);
+ v = PyString_FromStringAndSize((char *)NULL, width * count);
+ if (v == NULL)
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- ret = ALreadsamps(self->port, (void *) PyString_AsString(v), count);
- Py_END_ALLOW_THREADS
- if (ret == -1) {
- Py_DECREF(v);
- return NULL;
- }
+ Py_BEGIN_ALLOW_THREADS
+ ret = ALreadsamps(self->port, (void *) PyString_AsString(v), count);
+ Py_END_ALLOW_THREADS
+ if (ret == -1) {
+ Py_DECREF(v);
+ return NULL;
+ }
- return (v);
+ return (v);
}
static PyObject *
alp_writesamps(alpobject *self, PyObject *args)
{
- char *buf;
- int size, width;
- ALconfig c;
- int ret;
+ char *buf;
+ int size, width;
+ ALconfig c;
+ int ret;
- if (!PyArg_ParseTuple(args, "s#:writesamps", &buf, &size))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s#:writesamps", &buf, &size))
+ return NULL;
- c = ALgetconfig(self->port);
+ c = ALgetconfig(self->port);
#ifdef AL_405
- width = ALgetsampfmt(c);
- if (width == AL_SAMPFMT_FLOAT)
- width = sizeof(float);
- else if (width == AL_SAMPFMT_DOUBLE)
- width = sizeof(double);
- else
- width = ALgetwidth(c);
+ width = ALgetsampfmt(c);
+ if (width == AL_SAMPFMT_FLOAT)
+ width = sizeof(float);
+ else if (width == AL_SAMPFMT_DOUBLE)
+ width = sizeof(double);
+ else
+ width = ALgetwidth(c);
#else
- width = ALgetwidth(c);
+ width = ALgetwidth(c);
#endif /* AL_405 */
- ALfreeconfig(c);
- Py_BEGIN_ALLOW_THREADS
- ret = ALwritesamps (self->port, (void *) buf, (long) size / width);
- Py_END_ALLOW_THREADS
- if (ret == -1)
- return NULL;
+ ALfreeconfig(c);
+ Py_BEGIN_ALLOW_THREADS
+ ret = ALwritesamps (self->port, (void *) buf, (long) size / width);
+ Py_END_ALLOW_THREADS
+ if (ret == -1)
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
alp_getfillpoint(alpobject *self, PyObject *args)
{
- long count;
+ long count;
- if (!PyArg_ParseTuple(args, ":GetFillPoint"))
- return NULL;
- if ((count = ALgetfillpoint(self->port)) == -1)
- return NULL;
- return PyInt_FromLong(count);
+ if (!PyArg_ParseTuple(args, ":GetFillPoint"))
+ return NULL;
+ if ((count = ALgetfillpoint(self->port)) == -1)
+ return NULL;
+ return PyInt_FromLong(count);
}
static PyObject *
alp_setfillpoint(alpobject *self, PyObject *args)
{
- long count;
+ long count;
- if (!PyArg_ParseTuple(args, "l:SetFillPoint", &count))
- return NULL;
- if (ALsetfillpoint(self->port, count) == -1)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "l:SetFillPoint", &count))
+ return NULL;
+ if (ALsetfillpoint(self->port, count) == -1)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
alp_setconfig(alpobject *self, PyObject *args)
{
- alcobject *config;
+ alcobject *config;
- if (!PyArg_ParseTuple(args, "O!:SetConfig", &Alctype, &config))
- return NULL;
- if (ALsetconfig(self->port, config->config) == -1)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "O!:SetConfig", &Alctype, &config))
+ return NULL;
+ if (ALsetconfig(self->port, config->config) == -1)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
alp_getconfig(alpobject *self, PyObject *args)
{
- ALconfig config;
+ ALconfig config;
- if (!PyArg_ParseTuple(args, ":GetConfig"))
- return NULL;
- config = ALgetconfig(self->port);
- if (config == NULL)
- return NULL;
- return newalcobject(config);
+ if (!PyArg_ParseTuple(args, ":GetConfig"))
+ return NULL;
+ config = ALgetconfig(self->port);
+ if (config == NULL)
+ return NULL;
+ return newalcobject(config);
}
#ifdef AL_405
static PyObject *
alp_getstatus(alpobject *self, PyObject *args)
{
- PyObject *list, *v;
- long *PVbuffer;
- long length;
- int i;
-
- if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &list))
- return NULL;
- length = PyList_Size(list);
- PVbuffer = PyMem_NEW(long, length);
- if (PVbuffer == NULL)
- return PyErr_NoMemory();
- for (i = 0; i < length; i++) {
- v = PyList_GetItem(list, i);
- if (!PyInt_Check(v)) {
- PyMem_DEL(PVbuffer);
- PyErr_BadArgument();
- return NULL;
- }
- PVbuffer[i] = PyInt_AsLong(v);
- }
-
- if (ALgetstatus(self->port, PVbuffer, length) == -1)
- return NULL;
-
- for (i = 0; i < length; i++)
- PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
-
- PyMem_DEL(PVbuffer);
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *list, *v;
+ long *PVbuffer;
+ long length;
+ int i;
+
+ if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &list))
+ return NULL;
+ length = PyList_Size(list);
+ PVbuffer = PyMem_NEW(long, length);
+ if (PVbuffer == NULL)
+ return PyErr_NoMemory();
+ for (i = 0; i < length; i++) {
+ v = PyList_GetItem(list, i);
+ if (!PyInt_Check(v)) {
+ PyMem_DEL(PVbuffer);
+ PyErr_BadArgument();
+ return NULL;
+ }
+ PVbuffer[i] = PyInt_AsLong(v);
+ }
+
+ if (ALgetstatus(self->port, PVbuffer, length) == -1)
+ return NULL;
+
+ for (i = 0; i < length; i++)
+ PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
+
+ PyMem_DEL(PVbuffer);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* AL_405 */
#endif /* OLD_INTERFACE */
static struct PyMethodDef alp_methods[] = {
-#ifdef AL_NO_ELEM /* IRIX 6 */
- {"SetConfig", (PyCFunction)alp_SetConfig, METH_VARARGS, alp_SetConfig__doc__},
- {"GetConfig", (PyCFunction)alp_GetConfig, METH_VARARGS, alp_GetConfig__doc__},
- {"GetResource", (PyCFunction)alp_GetResource, METH_VARARGS, alp_GetResource__doc__},
- {"GetFD", (PyCFunction)alp_GetFD, METH_VARARGS, alp_GetFD__doc__},
- {"GetFilled", (PyCFunction)alp_GetFilled, METH_VARARGS, alp_GetFilled__doc__},
- {"GetFillable", (PyCFunction)alp_GetFillable, METH_VARARGS, alp_GetFillable__doc__},
- {"ReadFrames", (PyCFunction)alp_ReadFrames, METH_VARARGS, alp_ReadFrames__doc__},
- {"DiscardFrames", (PyCFunction)alp_DiscardFrames, METH_VARARGS, alp_DiscardFrames__doc__},
- {"ZeroFrames", (PyCFunction)alp_ZeroFrames, METH_VARARGS, alp_ZeroFrames__doc__},
- {"SetFillPoint", (PyCFunction)alp_SetFillPoint, METH_VARARGS, alp_SetFillPoint__doc__},
- {"GetFillPoint", (PyCFunction)alp_GetFillPoint, METH_VARARGS, alp_GetFillPoint__doc__},
- {"GetFrameNumber", (PyCFunction)alp_GetFrameNumber, METH_VARARGS, alp_GetFrameNumber__doc__},
- {"GetFrameTime", (PyCFunction)alp_GetFrameTime, METH_VARARGS, alp_GetFrameTime__doc__},
- {"WriteFrames", (PyCFunction)alp_WriteFrames, METH_VARARGS, alp_WriteFrames__doc__},
- {"ClosePort", (PyCFunction)alp_ClosePort, METH_VARARGS, alp_ClosePort__doc__},
+#ifdef AL_NO_ELEM /* IRIX 6 */
+ {"SetConfig", (PyCFunction)alp_SetConfig, METH_VARARGS, alp_SetConfig__doc__},
+ {"GetConfig", (PyCFunction)alp_GetConfig, METH_VARARGS, alp_GetConfig__doc__},
+ {"GetResource", (PyCFunction)alp_GetResource, METH_VARARGS, alp_GetResource__doc__},
+ {"GetFD", (PyCFunction)alp_GetFD, METH_VARARGS, alp_GetFD__doc__},
+ {"GetFilled", (PyCFunction)alp_GetFilled, METH_VARARGS, alp_GetFilled__doc__},
+ {"GetFillable", (PyCFunction)alp_GetFillable, METH_VARARGS, alp_GetFillable__doc__},
+ {"ReadFrames", (PyCFunction)alp_ReadFrames, METH_VARARGS, alp_ReadFrames__doc__},
+ {"DiscardFrames", (PyCFunction)alp_DiscardFrames, METH_VARARGS, alp_DiscardFrames__doc__},
+ {"ZeroFrames", (PyCFunction)alp_ZeroFrames, METH_VARARGS, alp_ZeroFrames__doc__},
+ {"SetFillPoint", (PyCFunction)alp_SetFillPoint, METH_VARARGS, alp_SetFillPoint__doc__},
+ {"GetFillPoint", (PyCFunction)alp_GetFillPoint, METH_VARARGS, alp_GetFillPoint__doc__},
+ {"GetFrameNumber", (PyCFunction)alp_GetFrameNumber, METH_VARARGS, alp_GetFrameNumber__doc__},
+ {"GetFrameTime", (PyCFunction)alp_GetFrameTime, METH_VARARGS, alp_GetFrameTime__doc__},
+ {"WriteFrames", (PyCFunction)alp_WriteFrames, METH_VARARGS, alp_WriteFrames__doc__},
+ {"ClosePort", (PyCFunction)alp_ClosePort, METH_VARARGS, alp_ClosePort__doc__},
#endif /* AL_NO_ELEM */
#ifdef OLD_INTERFACE
- {"closeport", (PyCFunction)alp_closeport, METH_VARARGS},
- {"getfd", (PyCFunction)alp_getfd, METH_VARARGS},
- {"fileno", (PyCFunction)alp_getfd, METH_VARARGS},
- {"getfilled", (PyCFunction)alp_getfilled, METH_VARARGS},
- {"getfillable", (PyCFunction)alp_getfillable, METH_VARARGS},
- {"readsamps", (PyCFunction)alp_readsamps, METH_VARARGS},
- {"writesamps", (PyCFunction)alp_writesamps, METH_VARARGS},
- {"setfillpoint", (PyCFunction)alp_setfillpoint, METH_VARARGS},
- {"getfillpoint", (PyCFunction)alp_getfillpoint, METH_VARARGS},
- {"setconfig", (PyCFunction)alp_setconfig, METH_VARARGS},
- {"getconfig", (PyCFunction)alp_getconfig, METH_VARARGS},
+ {"closeport", (PyCFunction)alp_closeport, METH_VARARGS},
+ {"getfd", (PyCFunction)alp_getfd, METH_VARARGS},
+ {"fileno", (PyCFunction)alp_getfd, METH_VARARGS},
+ {"getfilled", (PyCFunction)alp_getfilled, METH_VARARGS},
+ {"getfillable", (PyCFunction)alp_getfillable, METH_VARARGS},
+ {"readsamps", (PyCFunction)alp_readsamps, METH_VARARGS},
+ {"writesamps", (PyCFunction)alp_writesamps, METH_VARARGS},
+ {"setfillpoint", (PyCFunction)alp_setfillpoint, METH_VARARGS},
+ {"getfillpoint", (PyCFunction)alp_getfillpoint, METH_VARARGS},
+ {"setconfig", (PyCFunction)alp_setconfig, METH_VARARGS},
+ {"getconfig", (PyCFunction)alp_getconfig, METH_VARARGS},
#ifdef AL_405
- {"getstatus", (PyCFunction)alp_getstatus, METH_VARARGS},
-#endif /* AL_405 */
+ {"getstatus", (PyCFunction)alp_getstatus, METH_VARARGS},
+#endif /* AL_405 */
#endif /* OLD_INTERFACE */
-
- {NULL, NULL} /* sentinel */
+
+ {NULL, NULL} /* sentinel */
};
/* ---------- */
@@ -1252,74 +1252,74 @@ static struct PyMethodDef alp_methods[] = {
static PyObject *
newalpobject(ALport port)
{
- alpobject *self;
-
- self = PyObject_New(alpobject, &Alptype);
- if (self == NULL)
- return NULL;
- /* XXXX Add your own initializers here */
- self->port = port;
- return (PyObject *) self;
+ alpobject *self;
+
+ self = PyObject_New(alpobject, &Alptype);
+ if (self == NULL)
+ return NULL;
+ /* XXXX Add your own initializers here */
+ self->port = port;
+ return (PyObject *) self;
}
static void
alp_dealloc(alpobject *self)
{
- /* XXXX Add your own cleanup code here */
- if (self->port) {
-#ifdef AL_NO_ELEM /* IRIX 6 */
- alClosePort(self->port);
+ /* XXXX Add your own cleanup code here */
+ if (self->port) {
+#ifdef AL_NO_ELEM /* IRIX 6 */
+ alClosePort(self->port);
#else
- ALcloseport(self->port);
+ ALcloseport(self->port);
#endif
- }
- PyObject_Del(self);
+ }
+ PyObject_Del(self);
}
static PyObject *
alp_getattr(alpobject *self, char *name)
{
- /* XXXX Add your own getattr code here */
- if (self->port == NULL) {
- PyErr_SetString(ErrorObject, "port already closed");
- return NULL;
- }
- return Py_FindMethod(alp_methods, (PyObject *)self, name);
+ /* XXXX Add your own getattr code here */
+ if (self->port == NULL) {
+ PyErr_SetString(ErrorObject, "port already closed");
+ return NULL;
+ }
+ return Py_FindMethod(alp_methods, (PyObject *)self, name);
}
PyDoc_STRVAR(Alptype__doc__, "");
static PyTypeObject Alptype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "al.port", /*tp_name*/
- sizeof(alpobject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)alp_dealloc, /*tp_dealloc*/
- (printfunc)0, /*tp_print*/
- (getattrfunc)alp_getattr, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc)0, /*tp_compare*/
- (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*/
-
- /* Space for future expansion */
- 0L,0L,0L,0L,
- Alptype__doc__ /* Documentation string */
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "al.port", /*tp_name*/
+ sizeof(alpobject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)alp_dealloc, /*tp_dealloc*/
+ (printfunc)0, /*tp_print*/
+ (getattrfunc)alp_getattr, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc)0, /*tp_compare*/
+ (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*/
+
+ /* Space for future expansion */
+ 0L,0L,0L,0L,
+ Alptype__doc__ /* Documentation string */
};
/* End of code for port objects */
/* -------------------------------------------------------- */
-#ifdef AL_NO_ELEM /* IRIX 6 */
+#ifdef AL_NO_ELEM /* IRIX 6 */
PyDoc_STRVAR(al_NewConfig__doc__,
"alNewConfig: create and initialize an audio ALconfig structure.");
@@ -1327,13 +1327,13 @@ PyDoc_STRVAR(al_NewConfig__doc__,
static PyObject *
al_NewConfig(PyObject *self, PyObject *args)
{
- ALconfig config;
+ ALconfig config;
- if (!PyArg_ParseTuple(args, ":NewConfig"))
- return NULL;
- if ((config = alNewConfig()) == NULL)
- return NULL;
- return newalcobject(config);
+ if (!PyArg_ParseTuple(args, ":NewConfig"))
+ return NULL;
+ if ((config = alNewConfig()) == NULL)
+ return NULL;
+ return newalcobject(config);
}
PyDoc_STRVAR(al_OpenPort__doc__,
@@ -1342,15 +1342,15 @@ PyDoc_STRVAR(al_OpenPort__doc__,
static PyObject *
al_OpenPort(PyObject *self, PyObject *args)
{
- ALport port;
- char *name, *dir;
- alcobject *config = NULL;
+ ALport port;
+ char *name, *dir;
+ alcobject *config = NULL;
- if (!PyArg_ParseTuple(args, "ss|O!:OpenPort", &name, &dir, &Alctype, &config))
- return NULL;
- if ((port = alOpenPort(name, dir, config ? config->config : NULL)) == NULL)
- return NULL;
- return newalpobject(port);
+ if (!PyArg_ParseTuple(args, "ss|O!:OpenPort", &name, &dir, &Alctype, &config))
+ return NULL;
+ if ((port = alOpenPort(name, dir, config ? config->config : NULL)) == NULL)
+ return NULL;
+ return newalpobject(port);
}
PyDoc_STRVAR(al_Connect__doc__,
@@ -1359,37 +1359,37 @@ PyDoc_STRVAR(al_Connect__doc__,
static PyObject *
al_Connect(PyObject *self, PyObject *args)
{
- int source, dest, nprops = 0, id, i;
- ALpv *props = NULL;
- ALparamInfo *propinfo = NULL;
- PyObject *propobj = NULL;
-
- if (!PyArg_ParseTuple(args, "ii|O!:Connect", &source, &dest, &PyList_Type, &propobj))
- return NULL;
- if (propobj != NULL) {
- nprops = python2params(source, dest, propobj, &props, &propinfo);
- if (nprops < 0)
- return NULL;
- }
-
- id = alConnect(source, dest, props, nprops);
-
- if (props) {
- for (i = 0; i < nprops; i++) {
- switch (propinfo[i].valueType) {
- case AL_SET_VAL:
- case AL_VECTOR_VAL:
- PyMem_DEL(props[i].value.ptr);
- break;
- }
- }
- PyMem_DEL(props);
- PyMem_DEL(propinfo);
- }
-
- if (id < 0)
- return NULL;
- return PyInt_FromLong((long) id);
+ int source, dest, nprops = 0, id, i;
+ ALpv *props = NULL;
+ ALparamInfo *propinfo = NULL;
+ PyObject *propobj = NULL;
+
+ if (!PyArg_ParseTuple(args, "ii|O!:Connect", &source, &dest, &PyList_Type, &propobj))
+ return NULL;
+ if (propobj != NULL) {
+ nprops = python2params(source, dest, propobj, &props, &propinfo);
+ if (nprops < 0)
+ return NULL;
+ }
+
+ id = alConnect(source, dest, props, nprops);
+
+ if (props) {
+ for (i = 0; i < nprops; i++) {
+ switch (propinfo[i].valueType) {
+ case AL_SET_VAL:
+ case AL_VECTOR_VAL:
+ PyMem_DEL(props[i].value.ptr);
+ break;
+ }
+ }
+ PyMem_DEL(props);
+ PyMem_DEL(propinfo);
+ }
+
+ if (id < 0)
+ return NULL;
+ return PyInt_FromLong((long) id);
}
PyDoc_STRVAR(al_Disconnect__doc__,
@@ -1398,14 +1398,14 @@ PyDoc_STRVAR(al_Disconnect__doc__,
static PyObject *
al_Disconnect(PyObject *self, PyObject *args)
{
- int res;
+ int res;
- if (!PyArg_ParseTuple(args, "i:Disconnect", &res))
- return NULL;
- if (alDisconnect(res) < 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "i:Disconnect", &res))
+ return NULL;
+ if (alDisconnect(res) < 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(al_GetParams__doc__,
@@ -1414,143 +1414,143 @@ PyDoc_STRVAR(al_GetParams__doc__,
static PyObject *
al_GetParams(PyObject *self, PyObject *args)
{
- int resource;
- PyObject *pvslist, *item = NULL, *v = NULL;
- ALpv *pvs;
- int i, j, npvs;
- ALparamInfo *pinfo;
-
- if (!PyArg_ParseTuple(args, "iO!:GetParams", &resource, &PyList_Type, &pvslist))
- return NULL;
- npvs = PyList_Size(pvslist);
- pvs = PyMem_NEW(ALpv, npvs);
- pinfo = PyMem_NEW(ALparamInfo, npvs);
- for (i = 0; i < npvs; i++) {
- item = PyList_GetItem(pvslist, i);
- if (!PyInt_Check(item)) {
- item = NULL;
- PyErr_SetString(ErrorObject, "list of integers expected");
- goto error;
- }
- pvs[i].param = (int) PyInt_AsLong(item);
- item = NULL; /* not needed anymore */
- if (alGetParamInfo(resource, pvs[i].param, &pinfo[i]) < 0)
- goto error;
- switch (pinfo[i].valueType) {
- case AL_NO_VAL:
- break;
- case AL_MATRIX_VAL:
- pinfo[i].maxElems *= pinfo[i].maxElems2;
- /* fall through */
- case AL_STRING_VAL:
- case AL_SET_VAL:
- case AL_VECTOR_VAL:
- switch (pinfo[i].elementType) {
- case AL_INT32_ELEM:
- case AL_RESOURCE_ELEM:
- case AL_ENUM_ELEM:
- pvs[i].value.ptr = PyMem_NEW(int, pinfo[i].maxElems);
- pvs[i].sizeIn = pinfo[i].maxElems;
- break;
- case AL_INT64_ELEM:
- case AL_FIXED_ELEM:
- pvs[i].value.ptr = PyMem_NEW(long long, pinfo[i].maxElems);
- pvs[i].sizeIn = pinfo[i].maxElems;
- break;
- case AL_CHAR_ELEM:
- pvs[i].value.ptr = PyMem_NEW(char, 32);
- pvs[i].sizeIn = 32;
- break;
- case AL_NO_ELEM:
- case AL_PTR_ELEM:
- default:
- PyErr_SetString(ErrorObject, "internal error");
- goto error;
- }
- break;
- case AL_SCALAR_VAL:
- break;
- default:
- PyErr_SetString(ErrorObject, "internal error");
- goto error;
- }
- if (pinfo[i].valueType == AL_MATRIX_VAL) {
- pinfo[i].maxElems /= pinfo[i].maxElems2;
- pvs[i].sizeIn /= pinfo[i].maxElems2;
- pvs[i].size2In = pinfo[i].maxElems2;
- }
- }
- if (alGetParams(resource, pvs, npvs) < 0)
- goto error;
- if (!(v = PyList_New(npvs)))
- goto error;
- for (i = 0; i < npvs; i++) {
- if (pvs[i].sizeOut < 0) {
- char buf[32];
- PyOS_snprintf(buf, sizeof(buf),
- "problem with param %d", i);
- PyErr_SetString(ErrorObject, buf);
- goto error;
- }
- switch (pinfo[i].valueType) {
- case AL_NO_VAL:
- item = Py_None;
- Py_INCREF(item);
- break;
- case AL_STRING_VAL:
- item = PyString_FromString(pvs[i].value.ptr);
- PyMem_DEL(pvs[i].value.ptr);
- break;
- case AL_MATRIX_VAL:
- /* XXXX this is not right */
- pvs[i].sizeOut *= pvs[i].size2Out;
- /* fall through */
- case AL_SET_VAL:
- case AL_VECTOR_VAL:
- item = PyList_New(pvs[i].sizeOut);
- for (j = 0; j < pvs[i].sizeOut; j++) {
- switch (pinfo[i].elementType) {
- case AL_INT32_ELEM:
- case AL_RESOURCE_ELEM:
- case AL_ENUM_ELEM:
- PyList_SetItem(item, j, PyInt_FromLong((long) ((int *) pvs[i].value.ptr)[j]));
- break;
- case AL_INT64_ELEM:
- PyList_SetItem(item, j, PyLong_FromLongLong(((long long *) pvs[i].value.ptr)[j]));
- break;
- case AL_FIXED_ELEM:
- PyList_SetItem(item, j, PyFloat_FromDouble(alFixedToDouble(((long long *) pvs[i].value.ptr)[j])));
- break;
- default:
- PyErr_SetString(ErrorObject, "internal error");
- goto error;
- }
- }
- PyMem_DEL(pvs[i].value.ptr);
- break;
- case AL_SCALAR_VAL:
- item = param2python(resource, pvs[i].param, pvs[i].value, &pinfo[i]);
- break;
- }
- if (PyErr_Occurred() ||
- PyList_SetItem(v, i, Py_BuildValue("(iO)", pvs[i].param,
- item)) < 0 ||
- PyErr_Occurred())
- goto error;
- Py_DECREF(item);
- }
- PyMem_DEL(pvs);
- PyMem_DEL(pinfo);
- return v;
+ int resource;
+ PyObject *pvslist, *item = NULL, *v = NULL;
+ ALpv *pvs;
+ int i, j, npvs;
+ ALparamInfo *pinfo;
+
+ if (!PyArg_ParseTuple(args, "iO!:GetParams", &resource, &PyList_Type, &pvslist))
+ return NULL;
+ npvs = PyList_Size(pvslist);
+ pvs = PyMem_NEW(ALpv, npvs);
+ pinfo = PyMem_NEW(ALparamInfo, npvs);
+ for (i = 0; i < npvs; i++) {
+ item = PyList_GetItem(pvslist, i);
+ if (!PyInt_Check(item)) {
+ item = NULL;
+ PyErr_SetString(ErrorObject, "list of integers expected");
+ goto error;
+ }
+ pvs[i].param = (int) PyInt_AsLong(item);
+ item = NULL; /* not needed anymore */
+ if (alGetParamInfo(resource, pvs[i].param, &pinfo[i]) < 0)
+ goto error;
+ switch (pinfo[i].valueType) {
+ case AL_NO_VAL:
+ break;
+ case AL_MATRIX_VAL:
+ pinfo[i].maxElems *= pinfo[i].maxElems2;
+ /* fall through */
+ case AL_STRING_VAL:
+ case AL_SET_VAL:
+ case AL_VECTOR_VAL:
+ switch (pinfo[i].elementType) {
+ case AL_INT32_ELEM:
+ case AL_RESOURCE_ELEM:
+ case AL_ENUM_ELEM:
+ pvs[i].value.ptr = PyMem_NEW(int, pinfo[i].maxElems);
+ pvs[i].sizeIn = pinfo[i].maxElems;
+ break;
+ case AL_INT64_ELEM:
+ case AL_FIXED_ELEM:
+ pvs[i].value.ptr = PyMem_NEW(long long, pinfo[i].maxElems);
+ pvs[i].sizeIn = pinfo[i].maxElems;
+ break;
+ case AL_CHAR_ELEM:
+ pvs[i].value.ptr = PyMem_NEW(char, 32);
+ pvs[i].sizeIn = 32;
+ break;
+ case AL_NO_ELEM:
+ case AL_PTR_ELEM:
+ default:
+ PyErr_SetString(ErrorObject, "internal error");
+ goto error;
+ }
+ break;
+ case AL_SCALAR_VAL:
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "internal error");
+ goto error;
+ }
+ if (pinfo[i].valueType == AL_MATRIX_VAL) {
+ pinfo[i].maxElems /= pinfo[i].maxElems2;
+ pvs[i].sizeIn /= pinfo[i].maxElems2;
+ pvs[i].size2In = pinfo[i].maxElems2;
+ }
+ }
+ if (alGetParams(resource, pvs, npvs) < 0)
+ goto error;
+ if (!(v = PyList_New(npvs)))
+ goto error;
+ for (i = 0; i < npvs; i++) {
+ if (pvs[i].sizeOut < 0) {
+ char buf[32];
+ PyOS_snprintf(buf, sizeof(buf),
+ "problem with param %d", i);
+ PyErr_SetString(ErrorObject, buf);
+ goto error;
+ }
+ switch (pinfo[i].valueType) {
+ case AL_NO_VAL:
+ item = Py_None;
+ Py_INCREF(item);
+ break;
+ case AL_STRING_VAL:
+ item = PyString_FromString(pvs[i].value.ptr);
+ PyMem_DEL(pvs[i].value.ptr);
+ break;
+ case AL_MATRIX_VAL:
+ /* XXXX this is not right */
+ pvs[i].sizeOut *= pvs[i].size2Out;
+ /* fall through */
+ case AL_SET_VAL:
+ case AL_VECTOR_VAL:
+ item = PyList_New(pvs[i].sizeOut);
+ for (j = 0; j < pvs[i].sizeOut; j++) {
+ switch (pinfo[i].elementType) {
+ case AL_INT32_ELEM:
+ case AL_RESOURCE_ELEM:
+ case AL_ENUM_ELEM:
+ PyList_SetItem(item, j, PyInt_FromLong((long) ((int *) pvs[i].value.ptr)[j]));
+ break;
+ case AL_INT64_ELEM:
+ PyList_SetItem(item, j, PyLong_FromLongLong(((long long *) pvs[i].value.ptr)[j]));
+ break;
+ case AL_FIXED_ELEM:
+ PyList_SetItem(item, j, PyFloat_FromDouble(alFixedToDouble(((long long *) pvs[i].value.ptr)[j])));
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "internal error");
+ goto error;
+ }
+ }
+ PyMem_DEL(pvs[i].value.ptr);
+ break;
+ case AL_SCALAR_VAL:
+ item = param2python(resource, pvs[i].param, pvs[i].value, &pinfo[i]);
+ break;
+ }
+ if (PyErr_Occurred() ||
+ PyList_SetItem(v, i, Py_BuildValue("(iO)", pvs[i].param,
+ item)) < 0 ||
+ PyErr_Occurred())
+ goto error;
+ Py_DECREF(item);
+ }
+ PyMem_DEL(pvs);
+ PyMem_DEL(pinfo);
+ return v;
error:
- Py_XDECREF(v);
- Py_XDECREF(item);
- if (pvs)
- PyMem_DEL(pvs);
- if (pinfo)
- PyMem_DEL(pinfo);
- return NULL;
+ Py_XDECREF(v);
+ Py_XDECREF(item);
+ if (pvs)
+ PyMem_DEL(pvs);
+ if (pinfo)
+ PyMem_DEL(pinfo);
+ return NULL;
}
PyDoc_STRVAR(al_SetParams__doc__,
@@ -1559,43 +1559,43 @@ PyDoc_STRVAR(al_SetParams__doc__,
static PyObject *
al_SetParams(PyObject *self, PyObject *args)
{
- int resource;
- PyObject *pvslist;
- ALpv *pvs;
- ALparamInfo *pinfo;
- int npvs, i;
-
- if (!PyArg_ParseTuple(args, "iO!:SetParams", &resource, &PyList_Type, &pvslist))
- return NULL;
- npvs = python2params(resource, -1, pvslist, &pvs, &pinfo);
- if (npvs < 0)
- return NULL;
-
- if (alSetParams(resource, pvs, npvs) < 0)
- goto error;
-
- /* cleanup */
- for (i = 0; i < npvs; i++) {
- switch (pinfo[i].valueType) {
- case AL_SET_VAL:
- case AL_VECTOR_VAL:
- PyMem_DEL(pvs[i].value.ptr);
- break;
- }
- }
- PyMem_DEL(pvs);
- PyMem_DEL(pinfo);
-
- Py_INCREF(Py_None);
- return Py_None;
+ int resource;
+ PyObject *pvslist;
+ ALpv *pvs;
+ ALparamInfo *pinfo;
+ int npvs, i;
+
+ if (!PyArg_ParseTuple(args, "iO!:SetParams", &resource, &PyList_Type, &pvslist))
+ return NULL;
+ npvs = python2params(resource, -1, pvslist, &pvs, &pinfo);
+ if (npvs < 0)
+ return NULL;
+
+ if (alSetParams(resource, pvs, npvs) < 0)
+ goto error;
+
+ /* cleanup */
+ for (i = 0; i < npvs; i++) {
+ switch (pinfo[i].valueType) {
+ case AL_SET_VAL:
+ case AL_VECTOR_VAL:
+ PyMem_DEL(pvs[i].value.ptr);
+ break;
+ }
+ }
+ PyMem_DEL(pvs);
+ PyMem_DEL(pinfo);
+
+ Py_INCREF(Py_None);
+ return Py_None;
error:
- /* XXXX we should clean up everything */
- if (pvs)
- PyMem_DEL(pvs);
- if (pinfo)
- PyMem_DEL(pinfo);
- return NULL;
+ /* XXXX we should clean up everything */
+ if (pvs)
+ PyMem_DEL(pvs);
+ if (pinfo)
+ PyMem_DEL(pinfo);
+ return NULL;
}
PyDoc_STRVAR(al_QueryValues__doc__,
@@ -1604,79 +1604,79 @@ PyDoc_STRVAR(al_QueryValues__doc__,
static PyObject *
al_QueryValues(PyObject *self, PyObject *args)
{
- int resource, param;
- ALvalue *return_set = NULL;
- int setsize = 32, qualsize = 0, nvals, i;
- ALpv *quals = NULL;
- ALparamInfo pinfo;
- ALparamInfo *qualinfo = NULL;
- PyObject *qualobj = NULL;
- PyObject *res = NULL, *item;
-
- if (!PyArg_ParseTuple(args, "ii|O!:QueryValues", &resource, &param,
- &PyList_Type, &qualobj))
- return NULL;
- if (qualobj != NULL) {
- qualsize = python2params(resource, param, qualobj, &quals, &qualinfo);
- if (qualsize < 0)
- return NULL;
- }
- setsize = 32;
- return_set = PyMem_NEW(ALvalue, setsize);
- if (return_set == NULL) {
- PyErr_NoMemory();
- goto cleanup;
- }
+ int resource, param;
+ ALvalue *return_set = NULL;
+ int setsize = 32, qualsize = 0, nvals, i;
+ ALpv *quals = NULL;
+ ALparamInfo pinfo;
+ ALparamInfo *qualinfo = NULL;
+ PyObject *qualobj = NULL;
+ PyObject *res = NULL, *item;
+
+ if (!PyArg_ParseTuple(args, "ii|O!:QueryValues", &resource, &param,
+ &PyList_Type, &qualobj))
+ return NULL;
+ if (qualobj != NULL) {
+ qualsize = python2params(resource, param, qualobj, &quals, &qualinfo);
+ if (qualsize < 0)
+ return NULL;
+ }
+ setsize = 32;
+ return_set = PyMem_NEW(ALvalue, setsize);
+ if (return_set == NULL) {
+ PyErr_NoMemory();
+ goto cleanup;
+ }
retry:
- nvals = alQueryValues(resource, param, return_set, setsize, quals, qualsize);
- if (nvals < 0)
- goto cleanup;
- if (nvals > setsize) {
- ALvalue *old_return_set = return_set;
- setsize = nvals;
- PyMem_RESIZE(return_set, ALvalue, setsize);
- if (return_set == NULL) {
- return_set = old_return_set;
- PyErr_NoMemory();
- goto cleanup;
- }
- goto retry;
- }
-
- if (alGetParamInfo(resource, param, &pinfo) < 0)
- goto cleanup;
-
- res = PyList_New(nvals);
- if (res == NULL)
- goto cleanup;
- for (i = 0; i < nvals; i++) {
- item = param2python(resource, param, return_set[i], &pinfo);
- if (item == NULL ||
- PyList_SetItem(res, i, item) < 0) {
- Py_DECREF(res);
- res = NULL;
- goto cleanup;
- }
- }
+ nvals = alQueryValues(resource, param, return_set, setsize, quals, qualsize);
+ if (nvals < 0)
+ goto cleanup;
+ if (nvals > setsize) {
+ ALvalue *old_return_set = return_set;
+ setsize = nvals;
+ PyMem_RESIZE(return_set, ALvalue, setsize);
+ if (return_set == NULL) {
+ return_set = old_return_set;
+ PyErr_NoMemory();
+ goto cleanup;
+ }
+ goto retry;
+ }
+
+ if (alGetParamInfo(resource, param, &pinfo) < 0)
+ goto cleanup;
+
+ res = PyList_New(nvals);
+ if (res == NULL)
+ goto cleanup;
+ for (i = 0; i < nvals; i++) {
+ item = param2python(resource, param, return_set[i], &pinfo);
+ if (item == NULL ||
+ PyList_SetItem(res, i, item) < 0) {
+ Py_DECREF(res);
+ res = NULL;
+ goto cleanup;
+ }
+ }
cleanup:
- if (return_set)
- PyMem_DEL(return_set);
- if (quals) {
- for (i = 0; i < qualsize; i++) {
- switch (qualinfo[i].valueType) {
- case AL_SET_VAL:
- case AL_VECTOR_VAL:
- PyMem_DEL(quals[i].value.ptr);
- break;
- }
- }
- PyMem_DEL(quals);
- PyMem_DEL(qualinfo);
- }
-
- return res;
+ if (return_set)
+ PyMem_DEL(return_set);
+ if (quals) {
+ for (i = 0; i < qualsize; i++) {
+ switch (qualinfo[i].valueType) {
+ case AL_SET_VAL:
+ case AL_VECTOR_VAL:
+ PyMem_DEL(quals[i].value.ptr);
+ break;
+ }
+ }
+ PyMem_DEL(quals);
+ PyMem_DEL(qualinfo);
+ }
+
+ return res;
}
PyDoc_STRVAR(al_GetParamInfo__doc__,
@@ -1686,81 +1686,81 @@ PyDoc_STRVAR(al_GetParamInfo__doc__,
static PyObject *
al_GetParamInfo(PyObject *self, PyObject *args)
{
- int res, param;
- ALparamInfo pinfo;
- PyObject *v, *item;
-
- if (!PyArg_ParseTuple(args, "ii:GetParamInfo", &res, &param))
- return NULL;
- if (alGetParamInfo(res, param, &pinfo) < 0)
- return NULL;
- v = PyDict_New();
- if (!v) return NULL;
-
- item = PyInt_FromLong((long) pinfo.resource);
- PyDict_SetItemString(v, "resource", item);
- Py_DECREF(item);
-
- item = PyInt_FromLong((long) pinfo.param);
- PyDict_SetItemString(v, "param", item);
- Py_DECREF(item);
-
- item = PyInt_FromLong((long) pinfo.valueType);
- PyDict_SetItemString(v, "valueType", item);
- Py_DECREF(item);
-
- if (pinfo.valueType != AL_NO_VAL && pinfo.valueType != AL_SCALAR_VAL) {
- /* multiple values */
- item = PyInt_FromLong((long) pinfo.maxElems);
- PyDict_SetItemString(v, "maxElems", item);
- Py_DECREF(item);
-
- if (pinfo.valueType == AL_MATRIX_VAL) {
- /* 2 dimensional */
- item = PyInt_FromLong((long) pinfo.maxElems2);
- PyDict_SetItemString(v, "maxElems2", item);
- Py_DECREF(item);
- }
- }
-
- item = PyInt_FromLong((long) pinfo.elementType);
- PyDict_SetItemString(v, "elementType", item);
- Py_DECREF(item);
-
- item = PyString_FromString(pinfo.name);
- PyDict_SetItemString(v, "name", item);
- Py_DECREF(item);
-
- item = param2python(res, param, pinfo.initial, &pinfo);
- PyDict_SetItemString(v, "initial", item);
- Py_DECREF(item);
-
- if (pinfo.elementType != AL_ENUM_ELEM &&
- pinfo.elementType != AL_RESOURCE_ELEM &&
- pinfo.elementType != AL_CHAR_ELEM) {
- /* range param */
- item = param2python(res, param, pinfo.min, &pinfo);
- PyDict_SetItemString(v, "min", item);
- Py_DECREF(item);
-
- item = param2python(res, param, pinfo.max, &pinfo);
- PyDict_SetItemString(v, "max", item);
- Py_DECREF(item);
-
- item = param2python(res, param, pinfo.minDelta, &pinfo);
- PyDict_SetItemString(v, "minDelta", item);
- Py_DECREF(item);
-
- item = param2python(res, param, pinfo.maxDelta, &pinfo);
- PyDict_SetItemString(v, "maxDelta", item);
- Py_DECREF(item);
-
- item = PyInt_FromLong((long) pinfo.specialVals);
- PyDict_SetItemString(v, "specialVals", item);
- Py_DECREF(item);
- }
-
- return v;
+ int res, param;
+ ALparamInfo pinfo;
+ PyObject *v, *item;
+
+ if (!PyArg_ParseTuple(args, "ii:GetParamInfo", &res, &param))
+ return NULL;
+ if (alGetParamInfo(res, param, &pinfo) < 0)
+ return NULL;
+ v = PyDict_New();
+ if (!v) return NULL;
+
+ item = PyInt_FromLong((long) pinfo.resource);
+ PyDict_SetItemString(v, "resource", item);
+ Py_DECREF(item);
+
+ item = PyInt_FromLong((long) pinfo.param);
+ PyDict_SetItemString(v, "param", item);
+ Py_DECREF(item);
+
+ item = PyInt_FromLong((long) pinfo.valueType);
+ PyDict_SetItemString(v, "valueType", item);
+ Py_DECREF(item);
+
+ if (pinfo.valueType != AL_NO_VAL && pinfo.valueType != AL_SCALAR_VAL) {
+ /* multiple values */
+ item = PyInt_FromLong((long) pinfo.maxElems);
+ PyDict_SetItemString(v, "maxElems", item);
+ Py_DECREF(item);
+
+ if (pinfo.valueType == AL_MATRIX_VAL) {
+ /* 2 dimensional */
+ item = PyInt_FromLong((long) pinfo.maxElems2);
+ PyDict_SetItemString(v, "maxElems2", item);
+ Py_DECREF(item);
+ }
+ }
+
+ item = PyInt_FromLong((long) pinfo.elementType);
+ PyDict_SetItemString(v, "elementType", item);
+ Py_DECREF(item);
+
+ item = PyString_FromString(pinfo.name);
+ PyDict_SetItemString(v, "name", item);
+ Py_DECREF(item);
+
+ item = param2python(res, param, pinfo.initial, &pinfo);
+ PyDict_SetItemString(v, "initial", item);
+ Py_DECREF(item);
+
+ if (pinfo.elementType != AL_ENUM_ELEM &&
+ pinfo.elementType != AL_RESOURCE_ELEM &&
+ pinfo.elementType != AL_CHAR_ELEM) {
+ /* range param */
+ item = param2python(res, param, pinfo.min, &pinfo);
+ PyDict_SetItemString(v, "min", item);
+ Py_DECREF(item);
+
+ item = param2python(res, param, pinfo.max, &pinfo);
+ PyDict_SetItemString(v, "max", item);
+ Py_DECREF(item);
+
+ item = param2python(res, param, pinfo.minDelta, &pinfo);
+ PyDict_SetItemString(v, "minDelta", item);
+ Py_DECREF(item);
+
+ item = param2python(res, param, pinfo.maxDelta, &pinfo);
+ PyDict_SetItemString(v, "maxDelta", item);
+ Py_DECREF(item);
+
+ item = PyInt_FromLong((long) pinfo.specialVals);
+ PyDict_SetItemString(v, "specialVals", item);
+ Py_DECREF(item);
+ }
+
+ return v;
}
PyDoc_STRVAR(al_GetResourceByName__doc__,
@@ -1769,14 +1769,14 @@ PyDoc_STRVAR(al_GetResourceByName__doc__,
static PyObject *
al_GetResourceByName(PyObject *self, PyObject *args)
{
- int res, start_res, type;
- char *name;
+ int res, start_res, type;
+ char *name;
- if (!PyArg_ParseTuple(args, "isi:GetResourceByName", &start_res, &name, &type))
- return NULL;
- if ((res = alGetResourceByName(start_res, name, type)) == 0)
- return NULL;
- return PyInt_FromLong((long) res);
+ if (!PyArg_ParseTuple(args, "isi:GetResourceByName", &start_res, &name, &type))
+ return NULL;
+ if ((res = alGetResourceByName(start_res, name, type)) == 0)
+ return NULL;
+ return PyInt_FromLong((long) res);
}
PyDoc_STRVAR(al_IsSubtype__doc__,
@@ -1785,11 +1785,11 @@ PyDoc_STRVAR(al_IsSubtype__doc__,
static PyObject *
al_IsSubtype(PyObject *self, PyObject *args)
{
- int type, subtype;
+ int type, subtype;
- if (!PyArg_ParseTuple(args, "ii:IsSubtype", &type, &subtype))
- return NULL;
- return PyInt_FromLong((long) alIsSubtype(type, subtype));
+ if (!PyArg_ParseTuple(args, "ii:IsSubtype", &type, &subtype))
+ return NULL;
+ return PyInt_FromLong((long) alIsSubtype(type, subtype));
}
PyDoc_STRVAR(al_SetErrorHandler__doc__, "");
@@ -1798,10 +1798,10 @@ static PyObject *
al_SetErrorHandler(PyObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":SetErrorHandler"))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ":SetErrorHandler"))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* AL_NO_ELEM */
@@ -1811,144 +1811,144 @@ al_SetErrorHandler(PyObject *self, PyObject *args)
static PyObject *
al_openport(PyObject *self, PyObject *args)
{
- char *name, *dir;
- ALport port;
- alcobject *config = NULL;
+ char *name, *dir;
+ ALport port;
+ alcobject *config = NULL;
- if (!PyArg_ParseTuple(args, "ss|O!:OpenPort", &name, &dir, &Alctype, &config))
- return NULL;
- if ((port = ALopenport(name, dir, config ? config->config : NULL)) == NULL)
- return NULL;
- return newalpobject(port);
+ if (!PyArg_ParseTuple(args, "ss|O!:OpenPort", &name, &dir, &Alctype, &config))
+ return NULL;
+ if ((port = ALopenport(name, dir, config ? config->config : NULL)) == NULL)
+ return NULL;
+ return newalpobject(port);
}
static PyObject *
al_newconfig(PyObject *self, PyObject *args)
{
- ALconfig config;
+ ALconfig config;
- if (!PyArg_ParseTuple(args, ":NewConfig"))
- return NULL;
- if ((config = ALnewconfig ()) == NULL)
- return NULL;
- return newalcobject(config);
+ if (!PyArg_ParseTuple(args, ":NewConfig"))
+ return NULL;
+ if ((config = ALnewconfig ()) == NULL)
+ return NULL;
+ return newalcobject(config);
}
static PyObject *
al_queryparams(PyObject *self, PyObject *args)
{
- long device;
- long length;
- long *PVbuffer;
- long PVdummy[2];
- PyObject *v = NULL;
- int i;
-
- if (!PyArg_ParseTuple(args, "l:queryparams", &device))
- return NULL;
- if ((length = ALqueryparams(device, PVdummy, 2L)) == -1)
- return NULL;
- if ((PVbuffer = PyMem_NEW(long, length)) == NULL)
- return PyErr_NoMemory();
- if (ALqueryparams(device, PVbuffer, length) >= 0 &&
- (v = PyList_New((int)length)) != NULL) {
- for (i = 0; i < length; i++)
- PyList_SetItem(v, i, PyInt_FromLong(PVbuffer[i]));
- }
- PyMem_DEL(PVbuffer);
- return v;
+ long device;
+ long length;
+ long *PVbuffer;
+ long PVdummy[2];
+ PyObject *v = NULL;
+ int i;
+
+ if (!PyArg_ParseTuple(args, "l:queryparams", &device))
+ return NULL;
+ if ((length = ALqueryparams(device, PVdummy, 2L)) == -1)
+ return NULL;
+ if ((PVbuffer = PyMem_NEW(long, length)) == NULL)
+ return PyErr_NoMemory();
+ if (ALqueryparams(device, PVbuffer, length) >= 0 &&
+ (v = PyList_New((int)length)) != NULL) {
+ for (i = 0; i < length; i++)
+ PyList_SetItem(v, i, PyInt_FromLong(PVbuffer[i]));
+ }
+ PyMem_DEL(PVbuffer);
+ return v;
}
static PyObject *
doParams(PyObject *args, int (*func)(long, long *, long), int modified)
{
- long device;
- PyObject *list, *v;
- long *PVbuffer;
- long length;
- int i;
-
- if (!PyArg_ParseTuple(args, "lO!", &device, &PyList_Type, &list))
- return NULL;
- length = PyList_Size(list);
- PVbuffer = PyMem_NEW(long, length);
- if (PVbuffer == NULL)
- return PyErr_NoMemory();
- for (i = 0; i < length; i++) {
- v = PyList_GetItem(list, i);
- if (!PyInt_Check(v)) {
- PyMem_DEL(PVbuffer);
- PyErr_BadArgument();
- return NULL;
- }
- PVbuffer[i] = PyInt_AsLong(v);
- }
-
- if ((*func)(device, PVbuffer, length) == -1) {
- PyMem_DEL(PVbuffer);
- return NULL;
- }
-
- if (modified) {
- for (i = 0; i < length; i++)
- PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
- }
-
- PyMem_DEL(PVbuffer);
-
- Py_INCREF(Py_None);
- return Py_None;
+ long device;
+ PyObject *list, *v;
+ long *PVbuffer;
+ long length;
+ int i;
+
+ if (!PyArg_ParseTuple(args, "lO!", &device, &PyList_Type, &list))
+ return NULL;
+ length = PyList_Size(list);
+ PVbuffer = PyMem_NEW(long, length);
+ if (PVbuffer == NULL)
+ return PyErr_NoMemory();
+ for (i = 0; i < length; i++) {
+ v = PyList_GetItem(list, i);
+ if (!PyInt_Check(v)) {
+ PyMem_DEL(PVbuffer);
+ PyErr_BadArgument();
+ return NULL;
+ }
+ PVbuffer[i] = PyInt_AsLong(v);
+ }
+
+ if ((*func)(device, PVbuffer, length) == -1) {
+ PyMem_DEL(PVbuffer);
+ return NULL;
+ }
+
+ if (modified) {
+ for (i = 0; i < length; i++)
+ PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
+ }
+
+ PyMem_DEL(PVbuffer);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
al_getparams(PyObject *self, PyObject *args)
{
- return doParams(args, ALgetparams, 1);
+ return doParams(args, ALgetparams, 1);
}
static PyObject *
al_setparams(PyObject *self, PyObject *args)
{
- return doParams(args, ALsetparams, 0);
+ return doParams(args, ALsetparams, 0);
}
static PyObject *
al_getname(PyObject *self, PyObject *args)
{
- long device, descriptor;
- char *name;
+ long device, descriptor;
+ char *name;
- if (!PyArg_ParseTuple(args, "ll:getname", &device, &descriptor))
- return NULL;
- if ((name = ALgetname(device, descriptor)) == NULL)
- return NULL;
- return PyString_FromString(name);
+ if (!PyArg_ParseTuple(args, "ll:getname", &device, &descriptor))
+ return NULL;
+ if ((name = ALgetname(device, descriptor)) == NULL)
+ return NULL;
+ return PyString_FromString(name);
}
static PyObject *
al_getdefault(PyObject *self, PyObject *args)
{
- long device, descriptor, value;
+ long device, descriptor, value;
- if (!PyArg_ParseTuple(args, "ll:getdefault", &device, &descriptor))
- return NULL;
- if ((value = ALgetdefault(device, descriptor)) == -1)
- return NULL;
- return PyLong_FromLong(value);
+ if (!PyArg_ParseTuple(args, "ll:getdefault", &device, &descriptor))
+ return NULL;
+ if ((value = ALgetdefault(device, descriptor)) == -1)
+ return NULL;
+ return PyLong_FromLong(value);
}
static PyObject *
al_getminmax(PyObject *self, PyObject *args)
{
- long device, descriptor, min, max;
+ long device, descriptor, min, max;
- if (!PyArg_ParseTuple(args, "ll:getminmax", &device, &descriptor))
- return NULL;
- min = -1;
- max = -1;
- if (ALgetminmax(device, descriptor, &min, &max) == -1)
- return NULL;
- return Py_BuildValue("ll", min, max);
+ if (!PyArg_ParseTuple(args, "ll:getminmax", &device, &descriptor))
+ return NULL;
+ min = -1;
+ max = -1;
+ if (ALgetminmax(device, descriptor, &min, &max) == -1)
+ return NULL;
+ return Py_BuildValue("ll", min, max);
}
#endif /* OLD_INTERFACE */
@@ -1956,34 +1956,34 @@ al_getminmax(PyObject *self, PyObject *args)
/* List of methods defined in the module */
static struct PyMethodDef al_methods[] = {
-#ifdef AL_NO_ELEM /* IRIX 6 */
- {"NewConfig", (PyCFunction)al_NewConfig, METH_VARARGS, al_NewConfig__doc__},
- {"OpenPort", (PyCFunction)al_OpenPort, METH_VARARGS, al_OpenPort__doc__},
- {"Connect", (PyCFunction)al_Connect, METH_VARARGS, al_Connect__doc__},
- {"Disconnect", (PyCFunction)al_Disconnect, METH_VARARGS, al_Disconnect__doc__},
- {"GetParams", (PyCFunction)al_GetParams, METH_VARARGS, al_GetParams__doc__},
- {"SetParams", (PyCFunction)al_SetParams, METH_VARARGS, al_SetParams__doc__},
- {"QueryValues", (PyCFunction)al_QueryValues, METH_VARARGS, al_QueryValues__doc__},
- {"GetParamInfo", (PyCFunction)al_GetParamInfo, METH_VARARGS, al_GetParamInfo__doc__},
- {"GetResourceByName", (PyCFunction)al_GetResourceByName, METH_VARARGS, al_GetResourceByName__doc__},
- {"IsSubtype", (PyCFunction)al_IsSubtype, METH_VARARGS, al_IsSubtype__doc__},
+#ifdef AL_NO_ELEM /* IRIX 6 */
+ {"NewConfig", (PyCFunction)al_NewConfig, METH_VARARGS, al_NewConfig__doc__},
+ {"OpenPort", (PyCFunction)al_OpenPort, METH_VARARGS, al_OpenPort__doc__},
+ {"Connect", (PyCFunction)al_Connect, METH_VARARGS, al_Connect__doc__},
+ {"Disconnect", (PyCFunction)al_Disconnect, METH_VARARGS, al_Disconnect__doc__},
+ {"GetParams", (PyCFunction)al_GetParams, METH_VARARGS, al_GetParams__doc__},
+ {"SetParams", (PyCFunction)al_SetParams, METH_VARARGS, al_SetParams__doc__},
+ {"QueryValues", (PyCFunction)al_QueryValues, METH_VARARGS, al_QueryValues__doc__},
+ {"GetParamInfo", (PyCFunction)al_GetParamInfo, METH_VARARGS, al_GetParamInfo__doc__},
+ {"GetResourceByName", (PyCFunction)al_GetResourceByName, METH_VARARGS, al_GetResourceByName__doc__},
+ {"IsSubtype", (PyCFunction)al_IsSubtype, METH_VARARGS, al_IsSubtype__doc__},
#if 0
- /* this one not supported */
- {"SetErrorHandler", (PyCFunction)al_SetErrorHandler, METH_VARARGS, al_SetErrorHandler__doc__},
+ /* this one not supported */
+ {"SetErrorHandler", (PyCFunction)al_SetErrorHandler, METH_VARARGS, al_SetErrorHandler__doc__},
#endif
#endif /* AL_NO_ELEM */
#ifdef OLD_INTERFACE
- {"openport", (PyCFunction)al_openport, METH_VARARGS},
- {"newconfig", (PyCFunction)al_newconfig, METH_VARARGS},
- {"queryparams", (PyCFunction)al_queryparams, METH_VARARGS},
- {"getparams", (PyCFunction)al_getparams, METH_VARARGS},
- {"setparams", (PyCFunction)al_setparams, METH_VARARGS},
- {"getname", (PyCFunction)al_getname, METH_VARARGS},
- {"getdefault", (PyCFunction)al_getdefault, METH_VARARGS},
- {"getminmax", (PyCFunction)al_getminmax, METH_VARARGS},
+ {"openport", (PyCFunction)al_openport, METH_VARARGS},
+ {"newconfig", (PyCFunction)al_newconfig, METH_VARARGS},
+ {"queryparams", (PyCFunction)al_queryparams, METH_VARARGS},
+ {"getparams", (PyCFunction)al_getparams, METH_VARARGS},
+ {"setparams", (PyCFunction)al_setparams, METH_VARARGS},
+ {"getname", (PyCFunction)al_getname, METH_VARARGS},
+ {"getdefault", (PyCFunction)al_getdefault, METH_VARARGS},
+ {"getminmax", (PyCFunction)al_getminmax, METH_VARARGS},
#endif /* OLD_INTERFACE */
- {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
+ {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
};
@@ -1994,1239 +1994,1239 @@ PyDoc_STRVAR(al_module_documentation, "");
void
inital(void)
{
- PyObject *m, *d, *x;
+ PyObject *m, *d, *x;
- if (PyErr_WarnPy3k("the al module has been removed in "
- "Python 3.0", 2) < 0)
- return;
+ if (PyErr_WarnPy3k("the al module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
- /* Create the module and add the functions */
- m = Py_InitModule4("al", al_methods,
- al_module_documentation,
- (PyObject*)NULL,PYTHON_API_VERSION);
- if (m == NULL)
- return;
+ /* Create the module and add the functions */
+ m = Py_InitModule4("al", al_methods,
+ al_module_documentation,
+ (PyObject*)NULL,PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
- ErrorObject = PyErr_NewException("al.error", NULL, NULL);
- PyDict_SetItemString(d, "error", ErrorObject);
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
+ ErrorObject = PyErr_NewException("al.error", NULL, NULL);
+ PyDict_SetItemString(d, "error", ErrorObject);
- /* XXXX Add constants here */
+ /* XXXX Add constants here */
#ifdef AL_4CHANNEL
- x = PyInt_FromLong((long) AL_4CHANNEL);
- if (x == NULL || PyDict_SetItemString(d, "FOURCHANNEL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_4CHANNEL);
+ if (x == NULL || PyDict_SetItemString(d, "FOURCHANNEL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ADAT_IF_TYPE
- x = PyInt_FromLong((long) AL_ADAT_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "ADAT_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ADAT_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "ADAT_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ADAT_MCLK_TYPE
- x = PyInt_FromLong((long) AL_ADAT_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "ADAT_MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ADAT_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "ADAT_MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_AES_IF_TYPE
- x = PyInt_FromLong((long) AL_AES_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "AES_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_AES_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "AES_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_AES_MCLK_TYPE
- x = PyInt_FromLong((long) AL_AES_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "AES_MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_AES_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "AES_MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ANALOG_IF_TYPE
- x = PyInt_FromLong((long) AL_ANALOG_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "ANALOG_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ANALOG_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "ANALOG_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ASSOCIATE
- x = PyInt_FromLong((long) AL_ASSOCIATE);
- if (x == NULL || PyDict_SetItemString(d, "ASSOCIATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ASSOCIATE);
+ if (x == NULL || PyDict_SetItemString(d, "ASSOCIATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_BUFFER_NULL
- x = PyInt_FromLong((long) AL_BAD_BUFFER_NULL);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_NULL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_BUFFER_NULL);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_NULL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_BUFFERLENGTH
- x = PyInt_FromLong((long) AL_BAD_BUFFERLENGTH);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_BUFFERLENGTH);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_BUFFERLENGTH_NEG
- x = PyInt_FromLong((long) AL_BAD_BUFFERLENGTH_NEG);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_NEG", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_BUFFERLENGTH_NEG);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_NEG", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_BUFFERLENGTH_ODD
- x = PyInt_FromLong((long) AL_BAD_BUFFERLENGTH_ODD);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_ODD", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_BUFFERLENGTH_ODD);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_ODD", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_CHANNELS
- x = PyInt_FromLong((long) AL_BAD_CHANNELS);
- if (x == NULL || PyDict_SetItemString(d, "BAD_CHANNELS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_CHANNELS);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_CHANNELS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_CONFIG
- x = PyInt_FromLong((long) AL_BAD_CONFIG);
- if (x == NULL || PyDict_SetItemString(d, "BAD_CONFIG", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_CONFIG);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_CONFIG", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_COUNT_NEG
- x = PyInt_FromLong((long) AL_BAD_COUNT_NEG);
- if (x == NULL || PyDict_SetItemString(d, "BAD_COUNT_NEG", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_COUNT_NEG);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_COUNT_NEG", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_DEVICE
- x = PyInt_FromLong((long) AL_BAD_DEVICE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_DEVICE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_DEVICE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_DEVICE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_DEVICE_ACCESS
- x = PyInt_FromLong((long) AL_BAD_DEVICE_ACCESS);
- if (x == NULL || PyDict_SetItemString(d, "BAD_DEVICE_ACCESS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_DEVICE_ACCESS);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_DEVICE_ACCESS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_DIRECTION
- x = PyInt_FromLong((long) AL_BAD_DIRECTION);
- if (x == NULL || PyDict_SetItemString(d, "BAD_DIRECTION", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_DIRECTION);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_DIRECTION", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_FILLPOINT
- x = PyInt_FromLong((long) AL_BAD_FILLPOINT);
- if (x == NULL || PyDict_SetItemString(d, "BAD_FILLPOINT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_FILLPOINT);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_FILLPOINT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_FLOATMAX
- x = PyInt_FromLong((long) AL_BAD_FLOATMAX);
- if (x == NULL || PyDict_SetItemString(d, "BAD_FLOATMAX", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_FLOATMAX);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_FLOATMAX", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_ILLEGAL_STATE
- x = PyInt_FromLong((long) AL_BAD_ILLEGAL_STATE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_ILLEGAL_STATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_ILLEGAL_STATE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_ILLEGAL_STATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_NO_PORTS
- x = PyInt_FromLong((long) AL_BAD_NO_PORTS);
- if (x == NULL || PyDict_SetItemString(d, "BAD_NO_PORTS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_NO_PORTS);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_NO_PORTS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_NOT_FOUND
- x = PyInt_FromLong((long) AL_BAD_NOT_FOUND);
- if (x == NULL || PyDict_SetItemString(d, "BAD_NOT_FOUND", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_NOT_FOUND);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_NOT_FOUND", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_NOT_IMPLEMENTED
- x = PyInt_FromLong((long) AL_BAD_NOT_IMPLEMENTED);
- if (x == NULL || PyDict_SetItemString(d, "BAD_NOT_IMPLEMENTED", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_NOT_IMPLEMENTED);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_NOT_IMPLEMENTED", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_OUT_OF_MEM
- x = PyInt_FromLong((long) AL_BAD_OUT_OF_MEM);
- if (x == NULL || PyDict_SetItemString(d, "BAD_OUT_OF_MEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_OUT_OF_MEM);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_OUT_OF_MEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_PARAM
- x = PyInt_FromLong((long) AL_BAD_PARAM);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_PARAM);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_PERMISSIONS
- x = PyInt_FromLong((long) AL_BAD_PERMISSIONS);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PERMISSIONS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_PERMISSIONS);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PERMISSIONS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_PORT
- x = PyInt_FromLong((long) AL_BAD_PORT);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PORT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_PORT);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PORT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_PORTSTYLE
- x = PyInt_FromLong((long) AL_BAD_PORTSTYLE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PORTSTYLE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_PORTSTYLE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PORTSTYLE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_PVBUFFER
- x = PyInt_FromLong((long) AL_BAD_PVBUFFER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PVBUFFER", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_PVBUFFER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PVBUFFER", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_QSIZE
- x = PyInt_FromLong((long) AL_BAD_QSIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_QSIZE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_QSIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_QSIZE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_RATE
- x = PyInt_FromLong((long) AL_BAD_RATE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_RATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_RATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_RESOURCE
- x = PyInt_FromLong((long) AL_BAD_RESOURCE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_RESOURCE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_RESOURCE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_RESOURCE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_SAMPFMT
- x = PyInt_FromLong((long) AL_BAD_SAMPFMT);
- if (x == NULL || PyDict_SetItemString(d, "BAD_SAMPFMT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_SAMPFMT);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_SAMPFMT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_TRANSFER_SIZE
- x = PyInt_FromLong((long) AL_BAD_TRANSFER_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_TRANSFER_SIZE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_TRANSFER_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_TRANSFER_SIZE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_WIDTH
- x = PyInt_FromLong((long) AL_BAD_WIDTH);
- if (x == NULL || PyDict_SetItemString(d, "BAD_WIDTH", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_WIDTH);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_WIDTH", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CHANNEL_MODE
- x = PyInt_FromLong((long) AL_CHANNEL_MODE);
- if (x == NULL || PyDict_SetItemString(d, "CHANNEL_MODE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CHANNEL_MODE);
+ if (x == NULL || PyDict_SetItemString(d, "CHANNEL_MODE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CHANNELS
- x = PyInt_FromLong((long) AL_CHANNELS);
- if (x == NULL || PyDict_SetItemString(d, "CHANNELS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CHANNELS);
+ if (x == NULL || PyDict_SetItemString(d, "CHANNELS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CHAR_ELEM
- x = PyInt_FromLong((long) AL_CHAR_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "CHAR_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CHAR_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "CHAR_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CLOCK_GEN
- x = PyInt_FromLong((long) AL_CLOCK_GEN);
- if (x == NULL || PyDict_SetItemString(d, "CLOCK_GEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CLOCK_GEN);
+ if (x == NULL || PyDict_SetItemString(d, "CLOCK_GEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CLOCKGEN_TYPE
- x = PyInt_FromLong((long) AL_CLOCKGEN_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "CLOCKGEN_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CLOCKGEN_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "CLOCKGEN_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CONNECT
- x = PyInt_FromLong((long) AL_CONNECT);
- if (x == NULL || PyDict_SetItemString(d, "CONNECT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CONNECT);
+ if (x == NULL || PyDict_SetItemString(d, "CONNECT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CONNECTION_TYPE
- x = PyInt_FromLong((long) AL_CONNECTION_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "CONNECTION_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CONNECTION_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "CONNECTION_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CONNECTIONS
- x = PyInt_FromLong((long) AL_CONNECTIONS);
- if (x == NULL || PyDict_SetItemString(d, "CONNECTIONS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CONNECTIONS);
+ if (x == NULL || PyDict_SetItemString(d, "CONNECTIONS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CRYSTAL_MCLK_TYPE
- x = PyInt_FromLong((long) AL_CRYSTAL_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "CRYSTAL_MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CRYSTAL_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "CRYSTAL_MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DEFAULT_DEVICE
- x = PyInt_FromLong((long) AL_DEFAULT_DEVICE);
- if (x == NULL || PyDict_SetItemString(d, "DEFAULT_DEVICE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DEFAULT_DEVICE);
+ if (x == NULL || PyDict_SetItemString(d, "DEFAULT_DEVICE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DEFAULT_INPUT
- x = PyInt_FromLong((long) AL_DEFAULT_INPUT);
- if (x == NULL || PyDict_SetItemString(d, "DEFAULT_INPUT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DEFAULT_INPUT);
+ if (x == NULL || PyDict_SetItemString(d, "DEFAULT_INPUT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DEFAULT_OUTPUT
- x = PyInt_FromLong((long) AL_DEFAULT_OUTPUT);
- if (x == NULL || PyDict_SetItemString(d, "DEFAULT_OUTPUT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DEFAULT_OUTPUT);
+ if (x == NULL || PyDict_SetItemString(d, "DEFAULT_OUTPUT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DEST
- x = PyInt_FromLong((long) AL_DEST);
- if (x == NULL || PyDict_SetItemString(d, "DEST", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DEST);
+ if (x == NULL || PyDict_SetItemString(d, "DEST", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DEVICE_TYPE
- x = PyInt_FromLong((long) AL_DEVICE_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "DEVICE_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DEVICE_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "DEVICE_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DEVICES
- x = PyInt_FromLong((long) AL_DEVICES);
- if (x == NULL || PyDict_SetItemString(d, "DEVICES", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DEVICES);
+ if (x == NULL || PyDict_SetItemString(d, "DEVICES", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DIGITAL_IF_TYPE
- x = PyInt_FromLong((long) AL_DIGITAL_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "DIGITAL_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DIGITAL_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "DIGITAL_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DIGITAL_INPUT_RATE
- x = PyInt_FromLong((long) AL_DIGITAL_INPUT_RATE);
- if (x == NULL || PyDict_SetItemString(d, "DIGITAL_INPUT_RATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DIGITAL_INPUT_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "DIGITAL_INPUT_RATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DISCONNECT
- x = PyInt_FromLong((long) AL_DISCONNECT);
- if (x == NULL || PyDict_SetItemString(d, "DISCONNECT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DISCONNECT);
+ if (x == NULL || PyDict_SetItemString(d, "DISCONNECT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ENUM_ELEM
- x = PyInt_FromLong((long) AL_ENUM_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "ENUM_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ENUM_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "ENUM_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ENUM_VALUE
- x = PyInt_FromLong((long) AL_ENUM_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "ENUM_VALUE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ENUM_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "ENUM_VALUE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_INPUT_OVERFLOW
- x = PyInt_FromLong((long) AL_ERROR_INPUT_OVERFLOW);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_INPUT_OVERFLOW", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_INPUT_OVERFLOW);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_INPUT_OVERFLOW", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_LENGTH
- x = PyInt_FromLong((long) AL_ERROR_LENGTH);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_LENGTH", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_LENGTH);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_LENGTH", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_LOCATION_LSP
- x = PyInt_FromLong((long) AL_ERROR_LOCATION_LSP);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_LOCATION_LSP", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_LOCATION_LSP);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_LOCATION_LSP", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_LOCATION_MSP
- x = PyInt_FromLong((long) AL_ERROR_LOCATION_MSP);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_LOCATION_MSP", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_LOCATION_MSP);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_LOCATION_MSP", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_NUMBER
- x = PyInt_FromLong((long) AL_ERROR_NUMBER);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_NUMBER", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_NUMBER);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_NUMBER", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_OUTPUT_UNDERFLOW
- x = PyInt_FromLong((long) AL_ERROR_OUTPUT_UNDERFLOW);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_OUTPUT_UNDERFLOW", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_OUTPUT_UNDERFLOW);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_OUTPUT_UNDERFLOW", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_TYPE
- x = PyInt_FromLong((long) AL_ERROR_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_FIXED_ELEM
- x = PyInt_FromLong((long) AL_FIXED_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "FIXED_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_FIXED_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "FIXED_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_FIXED_MCLK_TYPE
- x = PyInt_FromLong((long) AL_FIXED_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "FIXED_MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_FIXED_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "FIXED_MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_GAIN
- x = PyInt_FromLong((long) AL_GAIN);
- if (x == NULL || PyDict_SetItemString(d, "GAIN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_GAIN);
+ if (x == NULL || PyDict_SetItemString(d, "GAIN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_GAIN_REF
- x = PyInt_FromLong((long) AL_GAIN_REF);
- if (x == NULL || PyDict_SetItemString(d, "GAIN_REF", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_GAIN_REF);
+ if (x == NULL || PyDict_SetItemString(d, "GAIN_REF", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_HRB_TYPE
- x = PyInt_FromLong((long) AL_HRB_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "HRB_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_HRB_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "HRB_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_COUNT
- x = PyInt_FromLong((long) AL_INPUT_COUNT);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_COUNT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_COUNT);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_COUNT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_DEVICE_TYPE
- x = PyInt_FromLong((long) AL_INPUT_DEVICE_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_DEVICE_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_DEVICE_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_DEVICE_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_DIGITAL
- x = PyInt_FromLong((long) AL_INPUT_DIGITAL);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_DIGITAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_DIGITAL);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_DIGITAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_HRB_TYPE
- x = PyInt_FromLong((long) AL_INPUT_HRB_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_HRB_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_HRB_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_HRB_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_LINE
- x = PyInt_FromLong((long) AL_INPUT_LINE);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_LINE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_LINE);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_LINE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_MIC
- x = PyInt_FromLong((long) AL_INPUT_MIC);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_MIC", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_MIC);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_MIC", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_PORT_TYPE
- x = PyInt_FromLong((long) AL_INPUT_PORT_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_PORT_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_PORT_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_PORT_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_RATE
- x = PyInt_FromLong((long) AL_INPUT_RATE);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_RATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_RATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_SOURCE
- x = PyInt_FromLong((long) AL_INPUT_SOURCE);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_SOURCE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_SOURCE);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_SOURCE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INT32_ELEM
- x = PyInt_FromLong((long) AL_INT32_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "INT32_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INT32_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "INT32_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INT64_ELEM
- x = PyInt_FromLong((long) AL_INT64_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "INT64_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INT64_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "INT64_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INTERFACE
- x = PyInt_FromLong((long) AL_INTERFACE);
- if (x == NULL || PyDict_SetItemString(d, "INTERFACE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INTERFACE);
+ if (x == NULL || PyDict_SetItemString(d, "INTERFACE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INTERFACE_TYPE
- x = PyInt_FromLong((long) AL_INTERFACE_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "INTERFACE_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INTERFACE_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "INTERFACE_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INVALID_PARAM
- x = PyInt_FromLong((long) AL_INVALID_PARAM);
- if (x == NULL || PyDict_SetItemString(d, "INVALID_PARAM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INVALID_PARAM);
+ if (x == NULL || PyDict_SetItemString(d, "INVALID_PARAM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INVALID_VALUE
- x = PyInt_FromLong((long) AL_INVALID_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "INVALID_VALUE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INVALID_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "INVALID_VALUE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_JITTER
- x = PyInt_FromLong((long) AL_JITTER);
- if (x == NULL || PyDict_SetItemString(d, "JITTER", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_JITTER);
+ if (x == NULL || PyDict_SetItemString(d, "JITTER", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LABEL
- x = PyInt_FromLong((long) AL_LABEL);
- if (x == NULL || PyDict_SetItemString(d, "LABEL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LABEL);
+ if (x == NULL || PyDict_SetItemString(d, "LABEL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LEFT_INPUT_ATTEN
- x = PyInt_FromLong((long) AL_LEFT_INPUT_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "LEFT_INPUT_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LEFT_INPUT_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "LEFT_INPUT_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LEFT_MONITOR_ATTEN
- x = PyInt_FromLong((long) AL_LEFT_MONITOR_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "LEFT_MONITOR_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LEFT_MONITOR_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "LEFT_MONITOR_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LEFT_SPEAKER_GAIN
- x = PyInt_FromLong((long) AL_LEFT_SPEAKER_GAIN);
- if (x == NULL || PyDict_SetItemString(d, "LEFT_SPEAKER_GAIN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LEFT_SPEAKER_GAIN);
+ if (x == NULL || PyDict_SetItemString(d, "LEFT_SPEAKER_GAIN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LEFT1_INPUT_ATTEN
- x = PyInt_FromLong((long) AL_LEFT1_INPUT_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "LEFT1_INPUT_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LEFT1_INPUT_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "LEFT1_INPUT_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LEFT2_INPUT_ATTEN
- x = PyInt_FromLong((long) AL_LEFT2_INPUT_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "LEFT2_INPUT_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LEFT2_INPUT_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "LEFT2_INPUT_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LINE_IF_TYPE
- x = PyInt_FromLong((long) AL_LINE_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "LINE_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LINE_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "LINE_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LOCKED
- x = PyInt_FromLong((long) AL_LOCKED);
- if (x == NULL || PyDict_SetItemString(d, "LOCKED", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LOCKED);
+ if (x == NULL || PyDict_SetItemString(d, "LOCKED", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MASTER_CLOCK
- x = PyInt_FromLong((long) AL_MASTER_CLOCK);
- if (x == NULL || PyDict_SetItemString(d, "MASTER_CLOCK", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MASTER_CLOCK);
+ if (x == NULL || PyDict_SetItemString(d, "MASTER_CLOCK", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MATRIX_VAL
- x = PyInt_FromLong((long) AL_MATRIX_VAL);
- if (x == NULL || PyDict_SetItemString(d, "MATRIX_VAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MATRIX_VAL);
+ if (x == NULL || PyDict_SetItemString(d, "MATRIX_VAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_ERROR
- x = PyInt_FromLong((long) AL_MAX_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "MAX_ERROR", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_ERROR", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_EVENT_PARAM
- x = PyInt_FromLong((long) AL_MAX_EVENT_PARAM);
- if (x == NULL || PyDict_SetItemString(d, "MAX_EVENT_PARAM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_EVENT_PARAM);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_EVENT_PARAM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_PBUFSIZE
- x = PyInt_FromLong((long) AL_MAX_PBUFSIZE);
- if (x == NULL || PyDict_SetItemString(d, "MAX_PBUFSIZE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_PBUFSIZE);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_PBUFSIZE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_PORTS
- x = PyInt_FromLong((long) AL_MAX_PORTS);
- if (x == NULL || PyDict_SetItemString(d, "MAX_PORTS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_PORTS);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_PORTS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_RESOURCE_ID
- x = PyInt_FromLong((long) AL_MAX_RESOURCE_ID);
- if (x == NULL || PyDict_SetItemString(d, "MAX_RESOURCE_ID", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_RESOURCE_ID);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_RESOURCE_ID", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_SETSIZE
- x = PyInt_FromLong((long) AL_MAX_SETSIZE);
- if (x == NULL || PyDict_SetItemString(d, "MAX_SETSIZE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_SETSIZE);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_SETSIZE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_STRLEN
- x = PyInt_FromLong((long) AL_MAX_STRLEN);
- if (x == NULL || PyDict_SetItemString(d, "MAX_STRLEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_STRLEN);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_STRLEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MCLK_TYPE
- x = PyInt_FromLong((long) AL_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MIC_IF_TYPE
- x = PyInt_FromLong((long) AL_MIC_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "MIC_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MIC_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "MIC_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MONITOR_CTL
- x = PyInt_FromLong((long) AL_MONITOR_CTL);
- if (x == NULL || PyDict_SetItemString(d, "MONITOR_CTL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MONITOR_CTL);
+ if (x == NULL || PyDict_SetItemString(d, "MONITOR_CTL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MONITOR_OFF
- x = PyInt_FromLong((long) AL_MONITOR_OFF);
- if (x == NULL || PyDict_SetItemString(d, "MONITOR_OFF", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MONITOR_OFF);
+ if (x == NULL || PyDict_SetItemString(d, "MONITOR_OFF", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MONITOR_ON
- x = PyInt_FromLong((long) AL_MONITOR_ON);
- if (x == NULL || PyDict_SetItemString(d, "MONITOR_ON", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MONITOR_ON);
+ if (x == NULL || PyDict_SetItemString(d, "MONITOR_ON", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MONO
- x = PyInt_FromLong((long) AL_MONO);
- if (x == NULL || PyDict_SetItemString(d, "MONO", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MONO);
+ if (x == NULL || PyDict_SetItemString(d, "MONO", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MUTE
- x = PyInt_FromLong((long) AL_MUTE);
- if (x == NULL || PyDict_SetItemString(d, "MUTE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MUTE);
+ if (x == NULL || PyDict_SetItemString(d, "MUTE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NAME
- x = PyInt_FromLong((long) AL_NAME);
- if (x == NULL || PyDict_SetItemString(d, "NAME", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NAME);
+ if (x == NULL || PyDict_SetItemString(d, "NAME", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NEG_INFINITY
- x = PyInt_FromLong((long) AL_NEG_INFINITY);
- if (x == NULL || PyDict_SetItemString(d, "NEG_INFINITY", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NEG_INFINITY);
+ if (x == NULL || PyDict_SetItemString(d, "NEG_INFINITY", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NEG_INFINITY_BIT
- x = PyInt_FromLong((long) AL_NEG_INFINITY_BIT);
- if (x == NULL || PyDict_SetItemString(d, "NEG_INFINITY_BIT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NEG_INFINITY_BIT);
+ if (x == NULL || PyDict_SetItemString(d, "NEG_INFINITY_BIT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NO_CHANGE
- x = PyInt_FromLong((long) AL_NO_CHANGE);
- if (x == NULL || PyDict_SetItemString(d, "NO_CHANGE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NO_CHANGE);
+ if (x == NULL || PyDict_SetItemString(d, "NO_CHANGE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NO_CHANGE_BIT
- x = PyInt_FromLong((long) AL_NO_CHANGE_BIT);
- if (x == NULL || PyDict_SetItemString(d, "NO_CHANGE_BIT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NO_CHANGE_BIT);
+ if (x == NULL || PyDict_SetItemString(d, "NO_CHANGE_BIT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NO_ELEM
- x = PyInt_FromLong((long) AL_NO_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "NO_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NO_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "NO_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NO_ERRORS
- x = PyInt_FromLong((long) AL_NO_ERRORS);
- if (x == NULL || PyDict_SetItemString(d, "NO_ERRORS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NO_ERRORS);
+ if (x == NULL || PyDict_SetItemString(d, "NO_ERRORS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NO_OP
- x = PyInt_FromLong((long) AL_NO_OP);
- if (x == NULL || PyDict_SetItemString(d, "NO_OP", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NO_OP);
+ if (x == NULL || PyDict_SetItemString(d, "NO_OP", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NO_VAL
- x = PyInt_FromLong((long) AL_NO_VAL);
- if (x == NULL || PyDict_SetItemString(d, "NO_VAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NO_VAL);
+ if (x == NULL || PyDict_SetItemString(d, "NO_VAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NULL_INTERFACE
- x = PyInt_FromLong((long) AL_NULL_INTERFACE);
- if (x == NULL || PyDict_SetItemString(d, "NULL_INTERFACE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NULL_INTERFACE);
+ if (x == NULL || PyDict_SetItemString(d, "NULL_INTERFACE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NULL_RESOURCE
- x = PyInt_FromLong((long) AL_NULL_RESOURCE);
- if (x == NULL || PyDict_SetItemString(d, "NULL_RESOURCE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NULL_RESOURCE);
+ if (x == NULL || PyDict_SetItemString(d, "NULL_RESOURCE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_OPTICAL_IF_TYPE
- x = PyInt_FromLong((long) AL_OPTICAL_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "OPTICAL_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_OPTICAL_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "OPTICAL_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_OUTPUT_COUNT
- x = PyInt_FromLong((long) AL_OUTPUT_COUNT);
- if (x == NULL || PyDict_SetItemString(d, "OUTPUT_COUNT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_OUTPUT_COUNT);
+ if (x == NULL || PyDict_SetItemString(d, "OUTPUT_COUNT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_OUTPUT_DEVICE_TYPE
- x = PyInt_FromLong((long) AL_OUTPUT_DEVICE_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "OUTPUT_DEVICE_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_OUTPUT_DEVICE_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "OUTPUT_DEVICE_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_OUTPUT_HRB_TYPE
- x = PyInt_FromLong((long) AL_OUTPUT_HRB_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "OUTPUT_HRB_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_OUTPUT_HRB_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "OUTPUT_HRB_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_OUTPUT_PORT_TYPE
- x = PyInt_FromLong((long) AL_OUTPUT_PORT_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "OUTPUT_PORT_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_OUTPUT_PORT_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "OUTPUT_PORT_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_OUTPUT_RATE
- x = PyInt_FromLong((long) AL_OUTPUT_RATE);
- if (x == NULL || PyDict_SetItemString(d, "OUTPUT_RATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_OUTPUT_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "OUTPUT_RATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PARAM_BIT
- x = PyInt_FromLong((long) AL_PARAM_BIT);
- if (x == NULL || PyDict_SetItemString(d, "PARAM_BIT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PARAM_BIT);
+ if (x == NULL || PyDict_SetItemString(d, "PARAM_BIT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PARAMS
- x = PyInt_FromLong((long) AL_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "PARAMS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "PARAMS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PORT_COUNT
- x = PyInt_FromLong((long) AL_PORT_COUNT);
- if (x == NULL || PyDict_SetItemString(d, "PORT_COUNT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PORT_COUNT);
+ if (x == NULL || PyDict_SetItemString(d, "PORT_COUNT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PORT_TYPE
- x = PyInt_FromLong((long) AL_PORT_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "PORT_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PORT_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "PORT_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PORTS
- x = PyInt_FromLong((long) AL_PORTS);
- if (x == NULL || PyDict_SetItemString(d, "PORTS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PORTS);
+ if (x == NULL || PyDict_SetItemString(d, "PORTS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PORTSTYLE_DIRECT
- x = PyInt_FromLong((long) AL_PORTSTYLE_DIRECT);
- if (x == NULL || PyDict_SetItemString(d, "PORTSTYLE_DIRECT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PORTSTYLE_DIRECT);
+ if (x == NULL || PyDict_SetItemString(d, "PORTSTYLE_DIRECT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PORTSTYLE_SERIAL
- x = PyInt_FromLong((long) AL_PORTSTYLE_SERIAL);
- if (x == NULL || PyDict_SetItemString(d, "PORTSTYLE_SERIAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PORTSTYLE_SERIAL);
+ if (x == NULL || PyDict_SetItemString(d, "PORTSTYLE_SERIAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PRINT_ERRORS
- x = PyInt_FromLong((long) AL_PRINT_ERRORS);
- if (x == NULL || PyDict_SetItemString(d, "PRINT_ERRORS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PRINT_ERRORS);
+ if (x == NULL || PyDict_SetItemString(d, "PRINT_ERRORS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PTR_ELEM
- x = PyInt_FromLong((long) AL_PTR_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "PTR_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PTR_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "PTR_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RANGE_VALUE
- x = PyInt_FromLong((long) AL_RANGE_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "RANGE_VALUE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RANGE_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "RANGE_VALUE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE
- x = PyInt_FromLong((long) AL_RATE);
- if (x == NULL || PyDict_SetItemString(d, "RATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "RATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_11025
- x = PyInt_FromLong((long) AL_RATE_11025);
- if (x == NULL || PyDict_SetItemString(d, "RATE_11025", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_11025);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_11025", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_16000
- x = PyInt_FromLong((long) AL_RATE_16000);
- if (x == NULL || PyDict_SetItemString(d, "RATE_16000", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_16000);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_16000", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_22050
- x = PyInt_FromLong((long) AL_RATE_22050);
- if (x == NULL || PyDict_SetItemString(d, "RATE_22050", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_22050);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_22050", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_32000
- x = PyInt_FromLong((long) AL_RATE_32000);
- if (x == NULL || PyDict_SetItemString(d, "RATE_32000", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_32000);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_32000", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_44100
- x = PyInt_FromLong((long) AL_RATE_44100);
- if (x == NULL || PyDict_SetItemString(d, "RATE_44100", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_44100);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_44100", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_48000
- x = PyInt_FromLong((long) AL_RATE_48000);
- if (x == NULL || PyDict_SetItemString(d, "RATE_48000", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_48000);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_48000", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_8000
- x = PyInt_FromLong((long) AL_RATE_8000);
- if (x == NULL || PyDict_SetItemString(d, "RATE_8000", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_8000);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_8000", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_AES_1
- x = PyInt_FromLong((long) AL_RATE_AES_1);
- if (x == NULL || PyDict_SetItemString(d, "RATE_AES_1", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_AES_1);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_AES_1", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_AES_1s
- x = PyInt_FromLong((long) AL_RATE_AES_1s);
- if (x == NULL || PyDict_SetItemString(d, "RATE_AES_1s", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_AES_1s);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_AES_1s", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_AES_2
- x = PyInt_FromLong((long) AL_RATE_AES_2);
- if (x == NULL || PyDict_SetItemString(d, "RATE_AES_2", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_AES_2);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_AES_2", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_AES_3
- x = PyInt_FromLong((long) AL_RATE_AES_3);
- if (x == NULL || PyDict_SetItemString(d, "RATE_AES_3", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_AES_3);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_AES_3", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_AES_4
- x = PyInt_FromLong((long) AL_RATE_AES_4);
- if (x == NULL || PyDict_SetItemString(d, "RATE_AES_4", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_AES_4);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_AES_4", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_AES_6
- x = PyInt_FromLong((long) AL_RATE_AES_6);
- if (x == NULL || PyDict_SetItemString(d, "RATE_AES_6", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_AES_6);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_AES_6", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_FRACTION_D
- x = PyInt_FromLong((long) AL_RATE_FRACTION_D);
- if (x == NULL || PyDict_SetItemString(d, "RATE_FRACTION_D", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_FRACTION_D);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_FRACTION_D", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_FRACTION_N
- x = PyInt_FromLong((long) AL_RATE_FRACTION_N);
- if (x == NULL || PyDict_SetItemString(d, "RATE_FRACTION_N", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_FRACTION_N);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_FRACTION_N", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_INPUTRATE
- x = PyInt_FromLong((long) AL_RATE_INPUTRATE);
- if (x == NULL || PyDict_SetItemString(d, "RATE_INPUTRATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_INPUTRATE);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_INPUTRATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_NO_DIGITAL_INPUT
- x = PyInt_FromLong((long) AL_RATE_NO_DIGITAL_INPUT);
- if (x == NULL || PyDict_SetItemString(d, "RATE_NO_DIGITAL_INPUT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_NO_DIGITAL_INPUT);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_NO_DIGITAL_INPUT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_UNACQUIRED
- x = PyInt_FromLong((long) AL_RATE_UNACQUIRED);
- if (x == NULL || PyDict_SetItemString(d, "RATE_UNACQUIRED", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_UNACQUIRED);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_UNACQUIRED", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_UNDEFINED
- x = PyInt_FromLong((long) AL_RATE_UNDEFINED);
- if (x == NULL || PyDict_SetItemString(d, "RATE_UNDEFINED", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_UNDEFINED);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_UNDEFINED", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_REF_0DBV
- x = PyInt_FromLong((long) AL_REF_0DBV);
- if (x == NULL || PyDict_SetItemString(d, "REF_0DBV", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_REF_0DBV);
+ if (x == NULL || PyDict_SetItemString(d, "REF_0DBV", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_REF_NONE
- x = PyInt_FromLong((long) AL_REF_NONE);
- if (x == NULL || PyDict_SetItemString(d, "REF_NONE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_REF_NONE);
+ if (x == NULL || PyDict_SetItemString(d, "REF_NONE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESERVED1_TYPE
- x = PyInt_FromLong((long) AL_RESERVED1_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "RESERVED1_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESERVED1_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "RESERVED1_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESERVED2_TYPE
- x = PyInt_FromLong((long) AL_RESERVED2_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "RESERVED2_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESERVED2_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "RESERVED2_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESERVED3_TYPE
- x = PyInt_FromLong((long) AL_RESERVED3_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "RESERVED3_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESERVED3_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "RESERVED3_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESERVED4_TYPE
- x = PyInt_FromLong((long) AL_RESERVED4_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "RESERVED4_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESERVED4_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "RESERVED4_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESOURCE
- x = PyInt_FromLong((long) AL_RESOURCE);
- if (x == NULL || PyDict_SetItemString(d, "RESOURCE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESOURCE);
+ if (x == NULL || PyDict_SetItemString(d, "RESOURCE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESOURCE_ELEM
- x = PyInt_FromLong((long) AL_RESOURCE_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "RESOURCE_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESOURCE_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "RESOURCE_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESOURCE_TYPE
- x = PyInt_FromLong((long) AL_RESOURCE_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "RESOURCE_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESOURCE_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "RESOURCE_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RIGHT_INPUT_ATTEN
- x = PyInt_FromLong((long) AL_RIGHT_INPUT_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "RIGHT_INPUT_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RIGHT_INPUT_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "RIGHT_INPUT_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RIGHT_MONITOR_ATTEN
- x = PyInt_FromLong((long) AL_RIGHT_MONITOR_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "RIGHT_MONITOR_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RIGHT_MONITOR_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "RIGHT_MONITOR_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RIGHT_SPEAKER_GAIN
- x = PyInt_FromLong((long) AL_RIGHT_SPEAKER_GAIN);
- if (x == NULL || PyDict_SetItemString(d, "RIGHT_SPEAKER_GAIN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RIGHT_SPEAKER_GAIN);
+ if (x == NULL || PyDict_SetItemString(d, "RIGHT_SPEAKER_GAIN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RIGHT1_INPUT_ATTEN
- x = PyInt_FromLong((long) AL_RIGHT1_INPUT_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "RIGHT1_INPUT_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RIGHT1_INPUT_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "RIGHT1_INPUT_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RIGHT2_INPUT_ATTEN
- x = PyInt_FromLong((long) AL_RIGHT2_INPUT_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "RIGHT2_INPUT_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RIGHT2_INPUT_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "RIGHT2_INPUT_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SAMPFMT_DOUBLE
- x = PyInt_FromLong((long) AL_SAMPFMT_DOUBLE);
- if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_DOUBLE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SAMPFMT_DOUBLE);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_DOUBLE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SAMPFMT_FLOAT
- x = PyInt_FromLong((long) AL_SAMPFMT_FLOAT);
- if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_FLOAT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SAMPFMT_FLOAT);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_FLOAT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SAMPFMT_TWOSCOMP
- x = PyInt_FromLong((long) AL_SAMPFMT_TWOSCOMP);
- if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_TWOSCOMP", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SAMPFMT_TWOSCOMP);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_TWOSCOMP", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SAMPLE_16
- x = PyInt_FromLong((long) AL_SAMPLE_16);
- if (x == NULL || PyDict_SetItemString(d, "SAMPLE_16", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SAMPLE_16);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPLE_16", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SAMPLE_24
- x = PyInt_FromLong((long) AL_SAMPLE_24);
- if (x == NULL || PyDict_SetItemString(d, "SAMPLE_24", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SAMPLE_24);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPLE_24", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SAMPLE_8
- x = PyInt_FromLong((long) AL_SAMPLE_8);
- if (x == NULL || PyDict_SetItemString(d, "SAMPLE_8", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SAMPLE_8);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPLE_8", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SCALAR_VAL
- x = PyInt_FromLong((long) AL_SCALAR_VAL);
- if (x == NULL || PyDict_SetItemString(d, "SCALAR_VAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SCALAR_VAL);
+ if (x == NULL || PyDict_SetItemString(d, "SCALAR_VAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SET_VAL
- x = PyInt_FromLong((long) AL_SET_VAL);
- if (x == NULL || PyDict_SetItemString(d, "SET_VAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SET_VAL);
+ if (x == NULL || PyDict_SetItemString(d, "SET_VAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SHORT_NAME
- x = PyInt_FromLong((long) AL_SHORT_NAME);
- if (x == NULL || PyDict_SetItemString(d, "SHORT_NAME", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SHORT_NAME);
+ if (x == NULL || PyDict_SetItemString(d, "SHORT_NAME", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SMPTE272M_IF_TYPE
- x = PyInt_FromLong((long) AL_SMPTE272M_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "SMPTE272M_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SMPTE272M_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "SMPTE272M_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SOURCE
- x = PyInt_FromLong((long) AL_SOURCE);
- if (x == NULL || PyDict_SetItemString(d, "SOURCE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SOURCE);
+ if (x == NULL || PyDict_SetItemString(d, "SOURCE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SPEAKER_IF_TYPE
- x = PyInt_FromLong((long) AL_SPEAKER_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "SPEAKER_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SPEAKER_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "SPEAKER_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SPEAKER_MUTE_CTL
- x = PyInt_FromLong((long) AL_SPEAKER_MUTE_CTL);
- if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_CTL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SPEAKER_MUTE_CTL);
+ if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_CTL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SPEAKER_MUTE_OFF
- x = PyInt_FromLong((long) AL_SPEAKER_MUTE_OFF);
- if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_OFF", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SPEAKER_MUTE_OFF);
+ if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_OFF", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SPEAKER_MUTE_ON
- x = PyInt_FromLong((long) AL_SPEAKER_MUTE_ON);
- if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_ON", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SPEAKER_MUTE_ON);
+ if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_ON", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SPEAKER_PLUS_LINE_IF_TYPE
- x = PyInt_FromLong((long) AL_SPEAKER_PLUS_LINE_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "SPEAKER_PLUS_LINE_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SPEAKER_PLUS_LINE_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "SPEAKER_PLUS_LINE_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_STEREO
- x = PyInt_FromLong((long) AL_STEREO);
- if (x == NULL || PyDict_SetItemString(d, "STEREO", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_STEREO);
+ if (x == NULL || PyDict_SetItemString(d, "STEREO", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_STRING_VAL
- x = PyInt_FromLong((long) AL_STRING_VAL);
- if (x == NULL || PyDict_SetItemString(d, "STRING_VAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_STRING_VAL);
+ if (x == NULL || PyDict_SetItemString(d, "STRING_VAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SUBSYSTEM
- x = PyInt_FromLong((long) AL_SUBSYSTEM);
- if (x == NULL || PyDict_SetItemString(d, "SUBSYSTEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SUBSYSTEM);
+ if (x == NULL || PyDict_SetItemString(d, "SUBSYSTEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SUBSYSTEM_TYPE
- x = PyInt_FromLong((long) AL_SUBSYSTEM_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "SUBSYSTEM_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SUBSYSTEM_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "SUBSYSTEM_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SYNC_INPUT_TO_AES
- x = PyInt_FromLong((long) AL_SYNC_INPUT_TO_AES);
- if (x == NULL || PyDict_SetItemString(d, "SYNC_INPUT_TO_AES", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SYNC_INPUT_TO_AES);
+ if (x == NULL || PyDict_SetItemString(d, "SYNC_INPUT_TO_AES", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SYNC_OUTPUT_TO_AES
- x = PyInt_FromLong((long) AL_SYNC_OUTPUT_TO_AES);
- if (x == NULL || PyDict_SetItemString(d, "SYNC_OUTPUT_TO_AES", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SYNC_OUTPUT_TO_AES);
+ if (x == NULL || PyDict_SetItemString(d, "SYNC_OUTPUT_TO_AES", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SYSTEM
- x = PyInt_FromLong((long) AL_SYSTEM);
- if (x == NULL || PyDict_SetItemString(d, "SYSTEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SYSTEM);
+ if (x == NULL || PyDict_SetItemString(d, "SYSTEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SYSTEM_TYPE
- x = PyInt_FromLong((long) AL_SYSTEM_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "SYSTEM_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SYSTEM_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "SYSTEM_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_TEST_IF_TYPE
- x = PyInt_FromLong((long) AL_TEST_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "TEST_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_TEST_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "TEST_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_TYPE
- x = PyInt_FromLong((long) AL_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_TYPE_BIT
- x = PyInt_FromLong((long) AL_TYPE_BIT);
- if (x == NULL || PyDict_SetItemString(d, "TYPE_BIT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_TYPE_BIT);
+ if (x == NULL || PyDict_SetItemString(d, "TYPE_BIT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_UNUSED_COUNT
- x = PyInt_FromLong((long) AL_UNUSED_COUNT);
- if (x == NULL || PyDict_SetItemString(d, "UNUSED_COUNT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_UNUSED_COUNT);
+ if (x == NULL || PyDict_SetItemString(d, "UNUSED_COUNT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_UNUSED_PORTS
- x = PyInt_FromLong((long) AL_UNUSED_PORTS);
- if (x == NULL || PyDict_SetItemString(d, "UNUSED_PORTS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_UNUSED_PORTS);
+ if (x == NULL || PyDict_SetItemString(d, "UNUSED_PORTS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_VARIABLE_MCLK_TYPE
- x = PyInt_FromLong((long) AL_VARIABLE_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "VARIABLE_MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_VARIABLE_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "VARIABLE_MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_VECTOR_VAL
- x = PyInt_FromLong((long) AL_VECTOR_VAL);
- if (x == NULL || PyDict_SetItemString(d, "VECTOR_VAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_VECTOR_VAL);
+ if (x == NULL || PyDict_SetItemString(d, "VECTOR_VAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_VIDEO_MCLK_TYPE
- x = PyInt_FromLong((long) AL_VIDEO_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "VIDEO_MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_VIDEO_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "VIDEO_MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_WORDSIZE
- x = PyInt_FromLong((long) AL_WORDSIZE);
- if (x == NULL || PyDict_SetItemString(d, "WORDSIZE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_WORDSIZE);
+ if (x == NULL || PyDict_SetItemString(d, "WORDSIZE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
-#ifdef AL_NO_ELEM /* IRIX 6 */
- (void) alSetErrorHandler(ErrorHandler);
+#ifdef AL_NO_ELEM /* IRIX 6 */
+ (void) alSetErrorHandler(ErrorHandler);
#endif /* AL_NO_ELEM */
#ifdef OLD_INTERFACE
- (void) ALseterrorhandler(ErrorHandler);
+ (void) ALseterrorhandler(ErrorHandler);
#endif /* OLD_INTERFACE */
-
+
error:
- return;
+ return;
}
diff --git a/Modules/arraymodule.c b/Modules/arraymodule.c
index e11a598..b571fe8 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,18 +22,18 @@ 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 *);
+ int typecode;
+ int itemsize;
+ PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
+ int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
};
typedef struct arrayobject {
- PyObject_VAR_HEAD
- char *ob_item;
- Py_ssize_t allocated;
- struct arraydescr *ob_descr;
- PyObject *weakreflist; /* List of weak references */
+ PyObject_VAR_HEAD
+ char *ob_item;
+ Py_ssize_t allocated;
+ struct arraydescr *ob_descr;
+ PyObject *weakreflist; /* List of weak references */
} arrayobject;
static PyTypeObject Arraytype;
@@ -44,49 +44,49 @@ static PyTypeObject Arraytype;
static int
array_resize(arrayobject *self, Py_ssize_t newsize)
{
- char *items;
- size_t _new_size;
-
- /* 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 list.
- */
-
- if (self->allocated >= newsize &&
- Py_SIZE(self) < newsize + 16 &&
- self->ob_item != NULL) {
- Py_SIZE(self) = newsize;
- 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;
+
+ /* 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 list.
+ */
+
+ if (self->allocated >= newsize &&
+ Py_SIZE(self) < newsize + 16 &&
+ self->ob_item != NULL) {
+ Py_SIZE(self) = newsize;
+ 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;
}
/****************************************************************************
@@ -104,308 +104,308 @@ in bounds; that's the responsibility of the caller.
static PyObject *
c_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyString_FromStringAndSize(&((char *)ap->ob_item)[i], 1);
+ return PyString_FromStringAndSize(&((char *)ap->ob_item)[i], 1);
}
static int
c_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- char x;
- if (!PyArg_Parse(v, "c;array item must be char", &x))
- return -1;
- if (i >= 0)
- ((char *)ap->ob_item)[i] = x;
- return 0;
+ char x;
+ if (!PyArg_Parse(v, "c;array item must be char", &x))
+ return -1;
+ if (i >= 0)
+ ((char *)ap->ob_item)[i] = x;
+ return 0;
}
static PyObject *
b_getitem(arrayobject *ap, Py_ssize_t i)
{
- long x = ((char *)ap->ob_item)[i];
- if (x >= 128)
- x -= 256;
- return PyInt_FromLong(x);
+ long x = ((char *)ap->ob_item)[i];
+ if (x >= 128)
+ x -= 256;
+ return PyInt_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 PyInt_FromLong(x);
+ long x = ((unsigned char *)ap->ob_item)[i];
+ return PyInt_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;
}
#ifdef Py_USING_UNICODE
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;
}
#endif
static PyObject *
h_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyInt_FromLong((long) ((short *)ap->ob_item)[i]);
+ return PyInt_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 PyInt_FromLong((long) ((unsigned short *)ap->ob_item)[i]);
+ return PyInt_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 PyInt_FromLong((long) ((int *)ap->ob_item)[i]);
+ return PyInt_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 PyInt_FromLong(((long *)ap->ob_item)[i]);
+ return PyInt_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;
}
/* Description of types */
static struct arraydescr descriptors[] = {
- {'c', sizeof(char), c_getitem, c_setitem},
- {'b', sizeof(char), b_getitem, b_setitem},
- {'B', sizeof(char), BB_getitem, BB_setitem},
+ {'c', sizeof(char), c_getitem, c_setitem},
+ {'b', sizeof(char), b_getitem, b_setitem},
+ {'B', sizeof(char), BB_getitem, BB_setitem},
#ifdef Py_USING_UNICODE
- {'u', sizeof(Py_UNICODE), u_getitem, u_setitem},
+ {'u', sizeof(Py_UNICODE), u_getitem, u_setitem},
#endif
- {'h', sizeof(short), h_getitem, h_setitem},
- {'H', sizeof(short), HH_getitem, HH_setitem},
- {'i', sizeof(int), i_getitem, i_setitem},
- {'I', sizeof(int), II_getitem, II_setitem},
- {'l', sizeof(long), l_getitem, l_setitem},
- {'L', sizeof(long), LL_getitem, LL_setitem},
- {'f', sizeof(float), f_getitem, f_setitem},
- {'d', sizeof(double), d_getitem, d_setitem},
- {'\0', 0, 0, 0} /* Sentinel */
+ {'h', sizeof(short), h_getitem, h_setitem},
+ {'H', sizeof(short), HH_getitem, HH_setitem},
+ {'i', sizeof(int), i_getitem, i_setitem},
+ {'I', sizeof(int), II_getitem, II_setitem},
+ {'l', sizeof(long), l_getitem, l_setitem},
+ {'L', sizeof(long), LL_getitem, LL_setitem},
+ {'f', sizeof(float), f_getitem, f_setitem},
+ {'d', sizeof(double), d_getitem, d_setitem},
+ {'\0', 0, 0, 0} /* Sentinel */
};
/****************************************************************************
@@ -415,78 +415,78 @@ 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();
- }
- }
- 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();
+ }
+ }
+ 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 */
@@ -494,141 +494,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,
@@ -639,297 +639,297 @@ 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);
- 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);
- Py_SIZE(a) += d;
- PyMem_RESIZE(item, char, Py_SIZE(a)*a->ob_descr->itemsize);
- /* Can't fail */
- a->ob_item = item;
- a->allocated = Py_SIZE(a);
- }
- else if (d > 0) { /* Insert d items */
- PyMem_RESIZE(item, char,
- (Py_SIZE(a) + d)*a->ob_descr->itemsize);
- if (item == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- memmove(item + (ihigh+d)*a->ob_descr->itemsize,
- item + ihigh*a->ob_descr->itemsize,
- (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
- a->ob_item = item;
- Py_SIZE(a) += d;
- a->allocated = Py_SIZE(a);
- }
- 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);
+ 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);
+ Py_SIZE(a) += d;
+ PyMem_RESIZE(item, char, Py_SIZE(a)*a->ob_descr->itemsize);
+ /* Can't fail */
+ a->ob_item = item;
+ a->allocated = Py_SIZE(a);
+ }
+ else if (d > 0) { /* Insert d items */
+ PyMem_RESIZE(item, char,
+ (Py_SIZE(a) + d)*a->ob_descr->itemsize);
+ if (item == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ memmove(item + (ihigh+d)*a->ob_descr->itemsize,
+ item + ihigh*a->ob_descr->itemsize,
+ (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
+ a->ob_item = item;
+ Py_SIZE(a) += d;
+ a->allocated = Py_SIZE(a);
+ }
+ 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;
- char *old_item;
+ Py_ssize_t size;
+ char *old_item;
- if (!array_Check(bb))
- return array_iter_extend(self, bb);
+ 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;
- }
- size = Py_SIZE(self) + Py_SIZE(b);
- old_item = self->ob_item;
- PyMem_RESIZE(self->ob_item, char, size*self->ob_descr->itemsize);
- if (self->ob_item == NULL) {
- self->ob_item = old_item;
- PyErr_NoMemory();
- return -1;
- }
- memcpy(self->ob_item + Py_SIZE(self)*self->ob_descr->itemsize,
- b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
- Py_SIZE(self) = size;
- self->allocated = size;
-
- 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;
+ }
+ size = Py_SIZE(self) + Py_SIZE(b);
+ old_item = self->ob_item;
+ PyMem_RESIZE(self->ob_item, char, size*self->ob_descr->itemsize);
+ if (self->ob_item == NULL) {
+ self->ob_item = old_item;
+ PyErr_NoMemory();
+ return -1;
+ }
+ memcpy(self->ob_item + Py_SIZE(self)*self->ob_descr->itemsize,
+ b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
+ Py_SIZE(self) = size;
+ self->allocated = size;
+
+ 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) {
- PyMem_FREE(items);
- self->ob_item = NULL;
- Py_SIZE(self) = 0;
- self->allocated = 0;
- }
- else {
- if (size > PY_SSIZE_T_MAX / n) {
- return PyErr_NoMemory();
- }
- PyMem_RESIZE(items, char, n * size);
- if (items == NULL)
- return PyErr_NoMemory();
- p = items;
- for (i = 1; i < n; i++) {
- p += size;
- memcpy(p, items, size);
- }
- self->ob_item = items;
- Py_SIZE(self) *= n;
- self->allocated = Py_SIZE(self);
- }
- }
- 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) {
+ PyMem_FREE(items);
+ self->ob_item = NULL;
+ Py_SIZE(self) = 0;
+ self->allocated = 0;
+ }
+ else {
+ if (size > PY_SSIZE_T_MAX / n) {
+ return PyErr_NoMemory();
+ }
+ PyMem_RESIZE(items, char, n * size);
+ if (items == NULL)
+ return PyErr_NoMemory();
+ p = items;
+ for (i = 1; i < n; i++) {
+ p += size;
+ memcpy(p, items, size);
+ }
+ self->ob_item = items;
+ Py_SIZE(self) *= n;
+ self->allocated = Py_SIZE(self);
+ }
+ }
+ 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 PyInt_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 PyInt_FromSsize_t(count);
}
PyDoc_STRVAR(count_doc,
@@ -940,20 +940,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 PyInt_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 PyInt_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,
@@ -964,38 +964,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,
@@ -1006,27 +1006,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,
@@ -1037,10 +1037,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,
@@ -1051,11 +1051,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,
@@ -1067,15 +1067,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, PyInt_FromLong((long)(Py_SIZE(self))));
+ PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item));
+ PyTuple_SET_ITEM(retval, 1, PyInt_FromLong((long)(Py_SIZE(self))));
- return retval;
+ return retval;
}
PyDoc_STRVAR(buffer_info_doc,
@@ -1090,7 +1090,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,
@@ -1102,52 +1102,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,
@@ -1159,33 +1159,33 @@ Byteswap all items of the array. If the items in the array are not 1, 2,\n\
static PyObject *
array_reduce(arrayobject *array)
{
- PyObject *dict, *result;
-
- dict = PyObject_GetAttrString((PyObject *)array, "__dict__");
- if (dict == NULL) {
- PyErr_Clear();
- dict = Py_None;
- Py_INCREF(dict);
- }
- if (Py_SIZE(array) > 0) {
- if (array->ob_descr->itemsize
- > PY_SSIZE_T_MAX / array->ob_size) {
- return PyErr_NoMemory();
- }
- result = Py_BuildValue("O(cs#)O",
- Py_TYPE(array),
- array->ob_descr->typecode,
- array->ob_item,
- Py_SIZE(array) * array->ob_descr->itemsize,
- dict);
- } else {
- result = Py_BuildValue("O(c)O",
- Py_TYPE(array),
- array->ob_descr->typecode,
- dict);
- }
- Py_DECREF(dict);
- return result;
+ PyObject *dict, *result;
+
+ dict = PyObject_GetAttrString((PyObject *)array, "__dict__");
+ if (dict == NULL) {
+ PyErr_Clear();
+ dict = Py_None;
+ Py_INCREF(dict);
+ }
+ if (Py_SIZE(array) > 0) {
+ if (array->ob_descr->itemsize
+ > PY_SSIZE_T_MAX / array->ob_size) {
+ return PyErr_NoMemory();
+ }
+ result = Py_BuildValue("O(cs#)O",
+ Py_TYPE(array),
+ array->ob_descr->typecode,
+ array->ob_item,
+ Py_SIZE(array) * array->ob_descr->itemsize,
+ dict);
+ } else {
+ result = Py_BuildValue("O(c)O",
+ Py_TYPE(array),
+ array->ob_descr->typecode,
+ dict);
+ }
+ Py_DECREF(dict);
+ return result;
}
PyDoc_STRVAR(array_doc, "Return state information for pickling.");
@@ -1193,28 +1193,28 @@ PyDoc_STRVAR(array_doc, "Return state information for pickling.");
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,
@@ -1225,50 +1225,50 @@ Reverse the order of the items in the array.");
static PyObject *
array_fromfile(arrayobject *self, PyObject *args)
{
- PyObject *f;
- Py_ssize_t n;
- FILE *fp;
- if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n))
- return NULL;
- fp = PyFile_AsFile(f);
- if (fp == NULL) {
- PyErr_SetString(PyExc_TypeError, "arg1 must be open file");
- return NULL;
- }
- if (n > 0) {
- char *item = self->ob_item;
- Py_ssize_t itemsize = self->ob_descr->itemsize;
- size_t nread;
- Py_ssize_t newlength;
- size_t newbytes;
- /* Be careful here about overflow */
- if ((newlength = Py_SIZE(self) + n) <= 0 ||
- (newbytes = newlength * itemsize) / itemsize !=
- (size_t)newlength)
- goto nomem;
- PyMem_RESIZE(item, char, newbytes);
- if (item == NULL) {
- nomem:
- PyErr_NoMemory();
- return NULL;
- }
- self->ob_item = item;
- Py_SIZE(self) += n;
- self->allocated = Py_SIZE(self);
- nread = fread(item + (Py_SIZE(self) - n) * itemsize,
- itemsize, n, fp);
- if (nread < (size_t)n) {
- Py_SIZE(self) -= (n - nread);
- PyMem_RESIZE(item, char, Py_SIZE(self)*itemsize);
- self->ob_item = item;
- self->allocated = Py_SIZE(self);
- PyErr_SetString(PyExc_EOFError,
- "not enough items in file");
- return NULL;
- }
- }
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *f;
+ Py_ssize_t n;
+ FILE *fp;
+ if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n))
+ return NULL;
+ fp = PyFile_AsFile(f);
+ if (fp == NULL) {
+ PyErr_SetString(PyExc_TypeError, "arg1 must be open file");
+ return NULL;
+ }
+ if (n > 0) {
+ char *item = self->ob_item;
+ Py_ssize_t itemsize = self->ob_descr->itemsize;
+ size_t nread;
+ Py_ssize_t newlength;
+ size_t newbytes;
+ /* Be careful here about overflow */
+ if ((newlength = Py_SIZE(self) + n) <= 0 ||
+ (newbytes = newlength * itemsize) / itemsize !=
+ (size_t)newlength)
+ goto nomem;
+ PyMem_RESIZE(item, char, newbytes);
+ if (item == NULL) {
+ nomem:
+ PyErr_NoMemory();
+ return NULL;
+ }
+ self->ob_item = item;
+ Py_SIZE(self) += n;
+ self->allocated = Py_SIZE(self);
+ nread = fread(item + (Py_SIZE(self) - n) * itemsize,
+ itemsize, n, fp);
+ if (nread < (size_t)n) {
+ Py_SIZE(self) -= (n - nread);
+ PyMem_RESIZE(item, char, Py_SIZE(self)*itemsize);
+ self->ob_item = item;
+ self->allocated = Py_SIZE(self);
+ PyErr_SetString(PyExc_EOFError,
+ "not enough items in file");
+ return NULL;
+ }
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(fromfile_doc,
@@ -1281,33 +1281,33 @@ array. Also called as read.");
static PyObject *
array_fromfile_as_read(arrayobject *self, PyObject *args)
{
- if (PyErr_WarnPy3k("array.read() not supported in 3.x; "
- "use array.fromfile()", 1) < 0)
- return NULL;
- return array_fromfile(self, args);
+ if (PyErr_WarnPy3k("array.read() not supported in 3.x; "
+ "use array.fromfile()", 1) < 0)
+ return NULL;
+ return array_fromfile(self, args);
}
static PyObject *
array_tofile(arrayobject *self, PyObject *f)
{
- FILE *fp;
-
- fp = PyFile_AsFile(f);
- if (fp == NULL) {
- PyErr_SetString(PyExc_TypeError, "arg must be open file");
- return NULL;
- }
- if (self->ob_size > 0) {
- if (fwrite(self->ob_item, self->ob_descr->itemsize,
- self->ob_size, fp) != (size_t)self->ob_size) {
- PyErr_SetFromErrno(PyExc_IOError);
- clearerr(fp);
- return NULL;
- }
- }
- Py_INCREF(Py_None);
- return Py_None;
+ FILE *fp;
+
+ fp = PyFile_AsFile(f);
+ if (fp == NULL) {
+ PyErr_SetString(PyExc_TypeError, "arg must be open file");
+ return NULL;
+ }
+ if (self->ob_size > 0) {
+ if (fwrite(self->ob_item, self->ob_descr->itemsize,
+ self->ob_size, fp) != (size_t)self->ob_size) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ clearerr(fp);
+ return NULL;
+ }
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(tofile_doc,
@@ -1320,53 +1320,53 @@ write.");
static PyObject *
array_tofile_as_write(arrayobject *self, PyObject *f)
{
- if (PyErr_WarnPy3k("array.write() not supported in 3.x; "
- "use array.tofile()", 1) < 0)
- return NULL;
- return array_tofile(self, f);
+ if (PyErr_WarnPy3k("array.write() not supported in 3.x; "
+ "use array.tofile()", 1) < 0)
+ return NULL;
+ return array_tofile(self, f);
}
static PyObject *
array_fromlist(arrayobject *self, PyObject *list)
{
- Py_ssize_t n;
- Py_ssize_t itemsize = self->ob_descr->itemsize;
-
- if (!PyList_Check(list)) {
- PyErr_SetString(PyExc_TypeError, "arg must be list");
- return NULL;
- }
- n = PyList_Size(list);
- if (n > 0) {
- char *item = self->ob_item;
- Py_ssize_t i;
- PyMem_RESIZE(item, char, (Py_SIZE(self) + n) * itemsize);
- if (item == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- self->ob_item = item;
- Py_SIZE(self) += n;
- self->allocated = Py_SIZE(self);
- 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) {
- Py_SIZE(self) -= n;
- if (itemsize && (self->ob_size > PY_SSIZE_T_MAX / itemsize)) {
- return PyErr_NoMemory();
- }
- PyMem_RESIZE(item, char,
- Py_SIZE(self) * itemsize);
- self->ob_item = item;
- self->allocated = Py_SIZE(self);
- return NULL;
- }
- }
- }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_ssize_t n;
+ Py_ssize_t itemsize = self->ob_descr->itemsize;
+
+ if (!PyList_Check(list)) {
+ PyErr_SetString(PyExc_TypeError, "arg must be list");
+ return NULL;
+ }
+ n = PyList_Size(list);
+ if (n > 0) {
+ char *item = self->ob_item;
+ Py_ssize_t i;
+ PyMem_RESIZE(item, char, (Py_SIZE(self) + n) * itemsize);
+ if (item == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ self->ob_item = item;
+ Py_SIZE(self) += n;
+ self->allocated = Py_SIZE(self);
+ 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) {
+ Py_SIZE(self) -= n;
+ if (itemsize && (self->ob_size > PY_SSIZE_T_MAX / itemsize)) {
+ return PyErr_NoMemory();
+ }
+ PyMem_RESIZE(item, char,
+ Py_SIZE(self) * itemsize);
+ self->ob_item = item;
+ self->allocated = Py_SIZE(self);
+ return NULL;
+ }
+ }
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(fromlist_doc,
@@ -1378,20 +1378,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,
@@ -1403,36 +1403,36 @@ 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) {
- char *item = self->ob_item;
- if ((n > PY_SSIZE_T_MAX - Py_SIZE(self)) ||
- ((Py_SIZE(self) + n) > PY_SSIZE_T_MAX / itemsize)) {
- return PyErr_NoMemory();
- }
- PyMem_RESIZE(item, char, (Py_SIZE(self) + n) * itemsize);
- if (item == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- self->ob_item = item;
- Py_SIZE(self) += n;
- self->allocated = Py_SIZE(self);
- memcpy(item + (Py_SIZE(self) - n) * itemsize,
- str, itemsize*n);
- }
- 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) {
+ char *item = self->ob_item;
+ if ((n > PY_SSIZE_T_MAX - Py_SIZE(self)) ||
+ ((Py_SIZE(self) + n) > PY_SSIZE_T_MAX / itemsize)) {
+ return PyErr_NoMemory();
+ }
+ PyMem_RESIZE(item, char, (Py_SIZE(self) + n) * itemsize);
+ if (item == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ self->ob_item = item;
+ Py_SIZE(self) += n;
+ self->allocated = Py_SIZE(self);
+ memcpy(item + (Py_SIZE(self) - n) * itemsize,
+ str, itemsize*n);
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(fromstring_doc,
@@ -1445,12 +1445,12 @@ values,as if it had been read from a file using the fromfile() method).");
static PyObject *
array_tostring(arrayobject *self, PyObject *unused)
{
- if (self->ob_size <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
- return PyString_FromStringAndSize(self->ob_item,
- Py_SIZE(self) * self->ob_descr->itemsize);
- } else {
- return PyErr_NoMemory();
- }
+ if (self->ob_size <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
+ return PyString_FromStringAndSize(self->ob_item,
+ Py_SIZE(self) * self->ob_descr->itemsize);
+ } else {
+ return PyErr_NoMemory();
+ }
}
PyDoc_STRVAR(tostring_doc,
@@ -1465,36 +1465,36 @@ representation.");
static PyObject *
array_fromunicode(arrayobject *self, PyObject *args)
{
- Py_UNICODE *ustr;
- Py_ssize_t n;
-
- if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n))
- return NULL;
- if (self->ob_descr->typecode != 'u') {
- PyErr_SetString(PyExc_ValueError,
- "fromunicode() may only be called on "
- "type 'u' arrays");
- return NULL;
- }
- if (n > 0) {
- Py_UNICODE *item = (Py_UNICODE *) self->ob_item;
- if (Py_SIZE(self) > PY_SSIZE_T_MAX - n) {
- return PyErr_NoMemory();
- }
- PyMem_RESIZE(item, Py_UNICODE, Py_SIZE(self) + n);
- if (item == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- self->ob_item = (char *) item;
- Py_SIZE(self) += n;
- self->allocated = Py_SIZE(self);
- memcpy(item + Py_SIZE(self) - n,
- ustr, n * sizeof(Py_UNICODE));
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ Py_UNICODE *ustr;
+ Py_ssize_t n;
+
+ if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n))
+ return NULL;
+ if (self->ob_descr->typecode != 'u') {
+ PyErr_SetString(PyExc_ValueError,
+ "fromunicode() may only be called on "
+ "type 'u' arrays");
+ return NULL;
+ }
+ if (n > 0) {
+ Py_UNICODE *item = (Py_UNICODE *) self->ob_item;
+ if (Py_SIZE(self) > PY_SSIZE_T_MAX - n) {
+ return PyErr_NoMemory();
+ }
+ PyMem_RESIZE(item, Py_UNICODE, Py_SIZE(self) + n);
+ if (item == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ self->ob_item = (char *) item;
+ Py_SIZE(self) += n;
+ self->allocated = Py_SIZE(self);
+ memcpy(item + Py_SIZE(self) - n,
+ ustr, n * sizeof(Py_UNICODE));
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(fromunicode_doc,
@@ -1509,12 +1509,12 @@ append Unicode data to an array of some other type.");
static PyObject *
array_tounicode(arrayobject *self, PyObject *unused)
{
- if (self->ob_descr->typecode != 'u') {
- PyErr_SetString(PyExc_ValueError,
- "tounicode() may only be called on type 'u' arrays");
- return NULL;
- }
- return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
+ if (self->ob_descr->typecode != 'u') {
+ PyErr_SetString(PyExc_ValueError,
+ "tounicode() may only be called on type 'u' arrays");
+ return NULL;
+ }
+ return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
}
PyDoc_STRVAR(tounicode_doc,
@@ -1531,321 +1531,321 @@ an array of some other type.");
static PyObject *
array_get_typecode(arrayobject *a, void *closure)
{
- char tc = a->ob_descr->typecode;
- return PyString_FromStringAndSize(&tc, 1);
+ char tc = a->ob_descr->typecode;
+ return PyString_FromStringAndSize(&tc, 1);
}
static PyObject *
array_get_itemsize(arrayobject *a, void *closure)
{
- return PyInt_FromLong((long)a->ob_descr->itemsize);
+ return PyInt_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},
+ {"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},
#ifdef Py_USING_UNICODE
- {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS,
- fromunicode_doc},
+ {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS,
+ fromunicode_doc},
#endif
- {"index", (PyCFunction)array_index, METH_O,
- index_doc},
- {"insert", (PyCFunction)array_insert, METH_VARARGS,
- insert_doc},
- {"pop", (PyCFunction)array_pop, METH_VARARGS,
- pop_doc},
- {"read", (PyCFunction)array_fromfile_as_read, METH_VARARGS,
- fromfile_doc},
- {"__reduce__", (PyCFunction)array_reduce, METH_NOARGS,
- array_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},
+ {"index", (PyCFunction)array_index, METH_O,
+ index_doc},
+ {"insert", (PyCFunction)array_insert, METH_VARARGS,
+ insert_doc},
+ {"pop", (PyCFunction)array_pop, METH_VARARGS,
+ pop_doc},
+ {"read", (PyCFunction)array_fromfile_as_read, METH_VARARGS,
+ fromfile_doc},
+ {"__reduce__", (PyCFunction)array_reduce, METH_NOARGS,
+ array_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},
#ifdef Py_USING_UNICODE
- {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS,
- tounicode_doc},
+ {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS,
+ tounicode_doc},
#endif
- {"write", (PyCFunction)array_tofile_as_write, METH_O,
- tofile_doc},
- {NULL, NULL} /* sentinel */
+ {"write", (PyCFunction)array_tofile_as_write, METH_O,
+ tofile_doc},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
array_repr(arrayobject *a)
{
- char buf[256], typecode;
- PyObject *s, *t, *v = NULL;
- Py_ssize_t len;
-
- len = Py_SIZE(a);
- typecode = a->ob_descr->typecode;
- if (len == 0) {
- PyOS_snprintf(buf, sizeof(buf), "array('%c')", typecode);
- return PyString_FromString(buf);
- }
-
- if (typecode == 'c')
- v = array_tostring(a, NULL);
+ char buf[256], typecode;
+ PyObject *s, *t, *v = NULL;
+ Py_ssize_t len;
+
+ len = Py_SIZE(a);
+ typecode = a->ob_descr->typecode;
+ if (len == 0) {
+ PyOS_snprintf(buf, sizeof(buf), "array('%c')", typecode);
+ return PyString_FromString(buf);
+ }
+
+ if (typecode == 'c')
+ v = array_tostring(a, NULL);
#ifdef Py_USING_UNICODE
- else if (typecode == 'u')
- v = array_tounicode(a, NULL);
+ else if (typecode == 'u')
+ v = array_tounicode(a, NULL);
#endif
- else
- v = array_tolist(a, NULL);
- t = PyObject_Repr(v);
- Py_XDECREF(v);
+ else
+ v = array_tolist(a, NULL);
+ t = PyObject_Repr(v);
+ Py_XDECREF(v);
- PyOS_snprintf(buf, sizeof(buf), "array('%c', ", typecode);
- s = PyString_FromString(buf);
- PyString_ConcatAndDel(&s, t);
- PyString_ConcatAndDel(&s, PyString_FromString(")"));
- return s;
+ PyOS_snprintf(buf, sizeof(buf), "array('%c', ", typecode);
+ s = PyString_FromString(buf);
+ PyString_ConcatAndDel(&s, t);
+ PyString_ConcatAndDel(&s, PyString_FromString(")"));
+ 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;
- 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;
+ 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 = "";
@@ -1853,164 +1853,164 @@ static const void *emptybuf = "";
static Py_ssize_t
array_buffer_getreadbuf(arrayobject *self, Py_ssize_t index, const void **ptr)
{
- if ( index != 0 ) {
- PyErr_SetString(PyExc_SystemError,
- "Accessing non-existent array segment");
- return -1;
- }
- *ptr = (void *)self->ob_item;
- if (*ptr == NULL)
- *ptr = emptybuf;
- return Py_SIZE(self)*self->ob_descr->itemsize;
+ if ( index != 0 ) {
+ PyErr_SetString(PyExc_SystemError,
+ "Accessing non-existent array segment");
+ return -1;
+ }
+ *ptr = (void *)self->ob_item;
+ if (*ptr == NULL)
+ *ptr = emptybuf;
+ return Py_SIZE(self)*self->ob_descr->itemsize;
}
static Py_ssize_t
array_buffer_getwritebuf(arrayobject *self, Py_ssize_t index, const void **ptr)
{
- if ( index != 0 ) {
- PyErr_SetString(PyExc_SystemError,
- "Accessing non-existent array segment");
- return -1;
- }
- *ptr = (void *)self->ob_item;
- if (*ptr == NULL)
- *ptr = emptybuf;
- return Py_SIZE(self)*self->ob_descr->itemsize;
+ if ( index != 0 ) {
+ PyErr_SetString(PyExc_SystemError,
+ "Accessing non-existent array segment");
+ return -1;
+ }
+ *ptr = (void *)self->ob_item;
+ if (*ptr == NULL)
+ *ptr = emptybuf;
+ return Py_SIZE(self)*self->ob_descr->itemsize;
}
static Py_ssize_t
array_buffer_getsegcount(arrayobject *self, Py_ssize_t *lenp)
{
- if ( lenp )
- *lenp = Py_SIZE(self)*self->ob_descr->itemsize;
- return 1;
+ if ( lenp )
+ *lenp = Py_SIZE(self)*self->ob_descr->itemsize;
+ return 1;
}
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*/
- (ssizessizeargfunc)array_slice, /*sq_slice*/
- (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
- (ssizessizeobjargproc)array_ass_slice, /*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*/
+ (ssizessizeargfunc)array_slice, /*sq_slice*/
+ (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
+ (ssizessizeobjargproc)array_ass_slice, /*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 = {
- (readbufferproc)array_buffer_getreadbuf,
- (writebufferproc)array_buffer_getwritebuf,
- (segcountproc)array_buffer_getsegcount,
- NULL,
+ (readbufferproc)array_buffer_getreadbuf,
+ (writebufferproc)array_buffer_getwritebuf,
+ (segcountproc)array_buffer_getsegcount,
+ NULL,
};
static PyObject *
array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- char 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)
- || PyString_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 && PyString_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);
+ char 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)
+ || PyString_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 && PyString_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);
#ifdef Py_USING_UNICODE
- } 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);
- }
+ } 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);
+ }
#endif
- }
- 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 c, b, B, u, h, H, i, I, l, L, f or d)");
- return NULL;
+ }
+ 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 c, b, B, u, h, H, i, I, l, L, f or d)");
+ return NULL;
}
@@ -2081,55 +2081,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_compare */
- (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 | Py_TPFLAGS_HAVE_WEAKREFS, /* 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_compare */
+ (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 | Py_TPFLAGS_HAVE_WEAKREFS, /* 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;
@@ -2139,79 +2139,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_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 */
- 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_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 */
+ 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 */
};
@@ -2226,17 +2226,17 @@ static PyMethodDef a_methods[] = {
PyMODINIT_FUNC
initarray(void)
{
- PyObject *m;
+ PyObject *m;
- Arraytype.ob_type = &PyType_Type;
- PyArrayIter_Type.ob_type = &PyType_Type;
- m = Py_InitModule3("array", a_methods, module_doc);
- if (m == NULL)
- return;
+ Arraytype.ob_type = &PyType_Type;
+ PyArrayIter_Type.ob_type = &PyType_Type;
+ m = Py_InitModule3("array", a_methods, module_doc);
+ if (m == NULL)
+ return;
- Py_INCREF((PyObject *)&Arraytype);
- PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
- Py_INCREF((PyObject *)&Arraytype);
- PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
- /* No need to check the error here, the caller will do that */
+ Py_INCREF((PyObject *)&Arraytype);
+ PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
+ Py_INCREF((PyObject *)&Arraytype);
+ PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
+ /* No need to check the error here, the caller will do that */
}
diff --git a/Modules/audioop.c b/Modules/audioop.c
index 767cae6..e1f8284 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 PyInt_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 PyInt_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 PyInt_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 PyInt_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 PyInt_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 PyInt_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 PyInt_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 PyInt_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 PyStringObject,
- 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 PyStringObject,
+ 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,1096 +560,1096 @@ 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 PyInt_FromLong(best_j);
+ }
+
+ return PyInt_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 PyInt_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 PyInt_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 PyInt_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 PyInt_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 PyInt_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 PyInt_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 = PyString_FromStringAndSize(NULL, len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_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)
{
- 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",
- &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;
- }
-
- rv = PyString_FromStringAndSize(NULL, len/2);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_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;
- }
- return rv;
+ 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",
+ &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;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, len/2);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_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;
+ }
+ 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 = PyString_FromStringAndSize(NULL, new_len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, new_len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, len1);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, len1);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, len);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_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 = PyString_FromStringAndSize(NULL, len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_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 = PyString_FromStringAndSize(NULL, new_len);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_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 = PyString_FromStringAndSize(NULL, new_len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_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 < 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 < 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 = PyString_FromStringAndSize(NULL, nbytes);
+
+ if (str == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ goto exit;
+ }
+ }
+ ncp = PyString_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 = PyString_FromStringAndSize(NULL, nbytes);
-
- if (str == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- goto exit;
- }
- }
- ncp = PyString_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 - PyString_AsString(str));
- if (len == 0) {
- /*don't want to resize to zero length*/
- rv = PyString_FromStringAndSize("", 0);
- Py_DECREF(str);
- str = rv;
- } else if (_PyString_Resize(&str, len) < 0)
- 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 - PyString_AsString(str));
+ if (len == 0) {
+ /*don't want to resize to zero length*/
+ rv = PyString_FromStringAndSize("", 0);
+ Py_DECREF(str);
+ str = rv;
+ } else if (_PyString_Resize(&str, len) < 0)
+ 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 = PyString_FromStringAndSize(NULL, len/size);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_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 = PyString_FromStringAndSize(NULL, len/size);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_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 = PyString_FromStringAndSize(NULL, new_len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, new_len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, len/size);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_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 = PyString_FromStringAndSize(NULL, len/size);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_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 = PyString_FromStringAndSize(NULL, new_len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, new_len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, len/(size*2));
+ if ( str == 0 )
+ return 0;
+ ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, len/(size*2));
- if ( str == 0 )
- return 0;
- ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, new_len);
+ if ( str == 0 )
+ return 0;
+ ncp = (signed char *)PyString_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 = PyString_FromStringAndSize(NULL, new_len);
- if ( str == 0 )
- return 0;
- ncp = (signed char *)PyString_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 }
};
PyMODINIT_FUNC
initaudioop(void)
{
- PyObject *m, *d;
- m = Py_InitModule("audioop", audioop_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- if (d == NULL)
- return;
- AudioopError = PyErr_NewException("audioop.error", NULL, NULL);
- if (AudioopError != NULL)
- PyDict_SetItemString(d,"error",AudioopError);
+ PyObject *m, *d;
+ m = Py_InitModule("audioop", audioop_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ if (d == NULL)
+ return;
+ AudioopError = PyErr_NewException("audioop.error", NULL, NULL);
+ if (AudioopError != NULL)
+ PyDict_SetItemString(d,"error",AudioopError);
}
diff --git a/Modules/binascii.c b/Modules/binascii.c
index 65471a6..d985773 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,77 +188,77 @@ PyDoc_STRVAR(doc_a2b_uu, "(ascii) -> bin. Decode a line of uuencoded data");
static PyObject *
binascii_a2b_uu(PyObject *self, PyObject *args)
{
- 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, "t#:a2b_uu", &ascii_data, &ascii_len) )
- return NULL;
-
- assert(ascii_len >= 0);
-
- /* First byte: binary data length (in bytes) */
- bin_len = (*ascii_data++ - ' ') & 077;
- ascii_len--;
-
- /* Allocate the buffer */
- if ( (rv=PyString_FromStringAndSize(NULL, bin_len)) == NULL )
- return NULL;
- bin_data = (unsigned char *)PyString_AsString(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");
- 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");
- Py_DECREF(rv);
- return NULL;
- }
- }
- return rv;
+ 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, "t#:a2b_uu", &ascii_data, &ascii_len) )
+ return NULL;
+
+ assert(ascii_len >= 0);
+
+ /* First byte: binary data length (in bytes) */
+ bin_len = (*ascii_data++ - ' ') & 077;
+ ascii_len--;
+
+ /* Allocate the buffer */
+ if ( (rv=PyString_FromStringAndSize(NULL, bin_len)) == NULL )
+ return NULL;
+ bin_data = (unsigned char *)PyString_AsString(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");
+ 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");
+ Py_DECREF(rv);
+ return NULL;
+ }
+ }
+ return rv;
}
PyDoc_STRVAR(doc_b2a_uu, "(bin) -> ascii. Uuencode line of data");
@@ -266,75 +266,75 @@ PyDoc_STRVAR(doc_b2a_uu, "(bin) -> ascii. Uuencode line of data");
static PyObject *
binascii_b2a_uu(PyObject *self, PyObject *args)
{
- 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, "s#:b2a_uu", &bin_data, &bin_len) )
- return NULL;
- if ( bin_len > 45 ) {
- /* The 45 is a limit that appears in all uuencode's */
- PyErr_SetString(Error, "At most 45 bytes at once");
- return NULL;
- }
-
- /* We're lazy and allocate to much (fixed up later) */
- if ( (rv=PyString_FromStringAndSize(NULL, 2 + (bin_len+2)/3*4)) == NULL )
- return NULL;
- ascii_data = (unsigned char *)PyString_AsString(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 */
-
- _PyString_Resize(&rv, (ascii_data -
- (unsigned char *)PyString_AsString(rv)));
- return rv;
+ 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, "s#:b2a_uu", &bin_data, &bin_len) )
+ return NULL;
+ if ( bin_len > 45 ) {
+ /* The 45 is a limit that appears in all uuencode's */
+ PyErr_SetString(Error, "At most 45 bytes at once");
+ return NULL;
+ }
+
+ /* We're lazy and allocate to much (fixed up later) */
+ if ( (rv=PyString_FromStringAndSize(NULL, 2 + (bin_len+2)/3*4)) == NULL )
+ return NULL;
+ ascii_data = (unsigned char *)PyString_AsString(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 */
+
+ _PyString_Resize(&rv, (ascii_data -
+ (unsigned char *)PyString_AsString(rv)));
+ 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");
@@ -342,95 +342,95 @@ PyDoc_STRVAR(doc_a2b_base64, "(ascii) -> bin. Decode a line of base64 data");
static PyObject *
binascii_a2b_base64(PyObject *self, PyObject *args)
{
- 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, "t#:a2b_base64", &ascii_data, &ascii_len) )
- return NULL;
-
- assert(ascii_len >= 0);
-
- if (ascii_len > PY_SSIZE_T_MAX - 3)
- return PyErr_NoMemory();
-
- bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */
-
- /* Allocate the buffer */
- if ( (rv=PyString_FromStringAndSize(NULL, bin_len)) == NULL )
- return NULL;
- bin_data = (unsigned char *)PyString_AsString(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) {
- 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; _PyString_Resize() won't do this for us.
- */
- if (bin_len > 0)
- _PyString_Resize(&rv, bin_len);
- else {
- Py_DECREF(rv);
- rv = PyString_FromString("");
- }
- return rv;
+ 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, "t#:a2b_base64", &ascii_data, &ascii_len) )
+ return NULL;
+
+ assert(ascii_len >= 0);
+
+ if (ascii_len > PY_SSIZE_T_MAX - 3)
+ return PyErr_NoMemory();
+
+ bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */
+
+ /* Allocate the buffer */
+ if ( (rv=PyString_FromStringAndSize(NULL, bin_len)) == NULL )
+ return NULL;
+ bin_data = (unsigned char *)PyString_AsString(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) {
+ 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; _PyString_Resize() won't do this for us.
+ */
+ if (bin_len > 0)
+ _PyString_Resize(&rv, bin_len);
+ else {
+ Py_DECREF(rv);
+ rv = PyString_FromString("");
+ }
+ return rv;
}
PyDoc_STRVAR(doc_b2a_base64, "(bin) -> ascii. Base64-code line of data");
@@ -438,55 +438,55 @@ PyDoc_STRVAR(doc_b2a_base64, "(bin) -> ascii. Base64-code line of data");
static PyObject *
binascii_b2a_base64(PyObject *self, PyObject *args)
{
- 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, "s#:b2a_base64", &bin_data, &bin_len) )
- return NULL;
-
- assert(bin_len >= 0);
-
- if ( bin_len > BASE64_MAXBIN ) {
- PyErr_SetString(Error, "Too much data for base64 line");
- 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=PyString_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL )
- return NULL;
- ascii_data = (unsigned char *)PyString_AsString(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 */
-
- _PyString_Resize(&rv, (ascii_data -
- (unsigned char *)PyString_AsString(rv)));
- return rv;
+ 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, "s#:b2a_base64", &bin_data, &bin_len) )
+ return NULL;
+
+ assert(bin_len >= 0);
+
+ if ( bin_len > BASE64_MAXBIN ) {
+ PyErr_SetString(Error, "Too much data for base64 line");
+ 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=PyString_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL )
+ return NULL;
+ ascii_data = (unsigned char *)PyString_AsString(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 */
+
+ _PyString_Resize(&rv, (ascii_data -
+ (unsigned char *)PyString_AsString(rv)));
+ return rv;
}
PyDoc_STRVAR(doc_a2b_hqx, "ascii -> bin, done. Decode .hqx coding");
@@ -494,70 +494,70 @@ PyDoc_STRVAR(doc_a2b_hqx, "ascii -> bin, done. Decode .hqx coding");
static PyObject *
binascii_a2b_hqx(PyObject *self, PyObject *args)
{
- 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, "t#:a2b_hqx", &ascii_data, &len) )
- return NULL;
-
- assert(len >= 0);
-
- if (len > PY_SSIZE_T_MAX - 2)
- 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=PyString_FromStringAndSize(NULL, len+2)) == NULL )
- return NULL;
- bin_data = (unsigned char *)PyString_AsString(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");
- 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");
- Py_DECREF(rv);
- return NULL;
- }
- _PyString_Resize(
- &rv, (bin_data - (unsigned char *)PyString_AsString(rv)));
- if (rv) {
- PyObject *rrv = Py_BuildValue("Oi", rv, done);
- Py_DECREF(rv);
- return rrv;
- }
-
- return NULL;
+ 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, "t#:a2b_hqx", &ascii_data, &len) )
+ return NULL;
+
+ assert(len >= 0);
+
+ if (len > PY_SSIZE_T_MAX - 2)
+ 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=PyString_FromStringAndSize(NULL, len+2)) == NULL )
+ return NULL;
+ bin_data = (unsigned char *)PyString_AsString(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");
+ 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");
+ Py_DECREF(rv);
+ return NULL;
+ }
+ _PyString_Resize(
+ &rv, (bin_data - (unsigned char *)PyString_AsString(rv)));
+ if (rv) {
+ PyObject *rrv = Py_BuildValue("Oi", rv, done);
+ Py_DECREF(rv);
+ return rrv;
+ }
+
+ return NULL;
}
PyDoc_STRVAR(doc_rlecode_hqx, "Binhex RLE-code binary data");
@@ -565,51 +565,51 @@ PyDoc_STRVAR(doc_rlecode_hqx, "Binhex RLE-code binary data");
static PyObject *
binascii_rlecode_hqx(PyObject *self, PyObject *args)
{
- unsigned char *in_data, *out_data;
- PyObject *rv;
- unsigned char ch;
- Py_ssize_t in, inend, len;
-
- if ( !PyArg_ParseTuple(args, "s#:rlecode_hqx", &in_data, &len) )
- return NULL;
-
- assert(len >= 0);
-
- if (len > PY_SSIZE_T_MAX / 2 - 2)
- return PyErr_NoMemory();
-
- /* Worst case: output is twice as big as input (fixed later) */
- if ( (rv=PyString_FromStringAndSize(NULL, len*2+2)) == NULL )
- return NULL;
- out_data = (unsigned char *)PyString_AsString(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;
- }
- }
- }
- _PyString_Resize(&rv, (out_data -
- (unsigned char *)PyString_AsString(rv)));
- return rv;
+ unsigned char *in_data, *out_data;
+ PyObject *rv;
+ unsigned char ch;
+ Py_ssize_t in, inend, len;
+
+ if ( !PyArg_ParseTuple(args, "s#:rlecode_hqx", &in_data, &len) )
+ return NULL;
+
+ assert(len >= 0);
+
+ if (len > PY_SSIZE_T_MAX / 2 - 2)
+ return PyErr_NoMemory();
+
+ /* Worst case: output is twice as big as input (fixed later) */
+ if ( (rv=PyString_FromStringAndSize(NULL, len*2+2)) == NULL )
+ return NULL;
+ out_data = (unsigned char *)PyString_AsString(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;
+ }
+ }
+ }
+ _PyString_Resize(&rv, (out_data -
+ (unsigned char *)PyString_AsString(rv)));
+ return rv;
}
PyDoc_STRVAR(doc_b2a_hqx, "Encode .hqx data");
@@ -617,44 +617,44 @@ PyDoc_STRVAR(doc_b2a_hqx, "Encode .hqx data");
static PyObject *
binascii_b2a_hqx(PyObject *self, PyObject *args)
{
- 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, "s#:b2a_hqx", &bin_data, &len) )
- return NULL;
-
- assert(len >= 0);
-
- if (len > PY_SSIZE_T_MAX / 2 - 2)
- return PyErr_NoMemory();
-
- /* Allocate a buffer that is at least large enough */
- if ( (rv=PyString_FromStringAndSize(NULL, len*2+2)) == NULL )
- return NULL;
- ascii_data = (unsigned char *)PyString_AsString(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];
- }
- _PyString_Resize(&rv, (ascii_data -
- (unsigned char *)PyString_AsString(rv)));
- return rv;
+ 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, "s#:b2a_hqx", &bin_data, &len) )
+ return NULL;
+
+ assert(len >= 0);
+
+ if (len > PY_SSIZE_T_MAX / 2 - 2)
+ return PyErr_NoMemory();
+
+ /* Allocate a buffer that is at least large enough */
+ if ( (rv=PyString_FromStringAndSize(NULL, len*2+2)) == NULL )
+ return NULL;
+ ascii_data = (unsigned char *)PyString_AsString(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];
+ }
+ _PyString_Resize(&rv, (ascii_data -
+ (unsigned char *)PyString_AsString(rv)));
+ return rv;
}
PyDoc_STRVAR(doc_rledecode_hqx, "Decode hexbin RLE-coded string");
@@ -662,100 +662,100 @@ PyDoc_STRVAR(doc_rledecode_hqx, "Decode hexbin RLE-coded string");
static PyObject *
binascii_rledecode_hqx(PyObject *self, PyObject *args)
{
- unsigned char *in_data, *out_data;
- unsigned char in_byte, in_repeat;
- PyObject *rv;
- Py_ssize_t in_len, out_len, out_len_left;
+ 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", &in_data, &in_len) )
- return NULL;
+ if ( !PyArg_ParseTuple(args, "s#:rledecode_hqx", &in_data, &in_len) )
+ return NULL;
- assert(in_len >= 0);
+ assert(in_len >= 0);
- /* Empty string is a special case */
- if ( in_len == 0 )
- return PyString_FromString("");
+ /* Empty string is a special case */
+ if ( in_len == 0 )
+ return PyString_FromString("");
else if (in_len > PY_SSIZE_T_MAX / 2)
- return PyErr_NoMemory();
-
- /* Allocate a buffer of reasonable size. Resized when needed */
- out_len = in_len*2;
- if ( (rv=PyString_FromStringAndSize(NULL, out_len)) == NULL )
- return NULL;
- out_len_left = out_len;
- out_data = (unsigned char *)PyString_AsString(rv);
-
- /*
- ** We need two macros here to get/put bytes and handle
- ** end-of-buffer for input and output strings.
- */
+ return PyErr_NoMemory();
+
+ /* Allocate a buffer of reasonable size. Resized when needed */
+ out_len = in_len*2;
+ if ( (rv=PyString_FromStringAndSize(NULL, out_len)) == NULL )
+ return NULL;
+ out_len_left = out_len;
+ out_data = (unsigned char *)PyString_AsString(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); \
- return NULL; \
- } \
- b = *in_data++; \
- } while(0)
+ do { \
+ if ( --in_len < 0 ) { \
+ PyErr_SetString(Incomplete, ""); \
+ Py_DECREF(rv); \
+ 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(); \
- _PyString_Resize(&rv, 2*out_len); \
- if ( rv == NULL ) return NULL; \
- out_data = (unsigned char *)PyString_AsString(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");
- 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);
- }
- }
- _PyString_Resize(&rv, (out_data -
- (unsigned char *)PyString_AsString(rv)));
- return rv;
+ do { \
+ if ( --out_len_left < 0 ) { \
+ if ( out_len > PY_SSIZE_T_MAX / 2) return PyErr_NoMemory(); \
+ _PyString_Resize(&rv, 2*out_len); \
+ if ( rv == NULL ) return NULL; \
+ out_data = (unsigned char *)PyString_AsString(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");
+ 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);
+ }
+ }
+ _PyString_Resize(&rv, (out_data -
+ (unsigned char *)PyString_AsString(rv)));
+ return rv;
}
PyDoc_STRVAR(doc_crc_hqx,
@@ -764,18 +764,18 @@ PyDoc_STRVAR(doc_crc_hqx,
static PyObject *
binascii_crc_hqx(PyObject *self, PyObject *args)
{
- unsigned char *bin_data;
- unsigned int crc;
- Py_ssize_t len;
+ unsigned char *bin_data;
+ unsigned int crc;
+ Py_ssize_t len;
- if ( !PyArg_ParseTuple(args, "s#i:crc_hqx", &bin_data, &len, &crc) )
- return NULL;
+ if ( !PyArg_ParseTuple(args, "s#i:crc_hqx", &bin_data, &len, &crc) )
+ return NULL;
- while(len-- > 0) {
- crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++];
- }
+ while(len-- > 0) {
+ crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++];
+ }
- return Py_BuildValue("i", crc);
+ return Py_BuildValue("i", crc);
}
PyDoc_STRVAR(doc_crc32,
@@ -792,7 +792,7 @@ binascii_crc32(PyObject *self, PyObject *args)
int signed_val;
if (!PyArg_ParseTuple(args, "s#|I:crc32", &buf, &len, &crc32val))
- return NULL;
+ return NULL;
/* In Python 2.x we return a signed integer regardless of native platform
* long size (the 32bit unsigned long is treated as 32-bit signed and sign
* extended into a 64-bit long inside the integer object). 3.0 does the
@@ -922,21 +922,21 @@ static unsigned int crc_32_tab[256] = {
static PyObject *
binascii_crc32(PyObject *self, PyObject *args)
{ /* By Jim Ahlstrom; All rights transferred to CNRI */
- unsigned char *bin_data;
- unsigned int crc = 0U; /* initial value of CRC */
- Py_ssize_t len;
- int result;
+ unsigned char *bin_data;
+ unsigned int crc = 0U; /* initial value of CRC */
+ Py_ssize_t len;
+ int result;
- if ( !PyArg_ParseTuple(args, "s#|I:crc32", &bin_data, &len, &crc) )
- return NULL;
+ if ( !PyArg_ParseTuple(args, "s#|I:crc32", &bin_data, &len, &crc) )
+ return NULL;
- crc = ~ crc;
- while (len-- > 0)
- crc = crc_32_tab[(crc ^ *bin_data++) & 0xffU] ^ (crc >> 8);
- /* Note: (crc >> 8) MUST zero fill on left */
+ crc = ~ crc;
+ while (len-- > 0)
+ crc = crc_32_tab[(crc ^ *bin_data++) & 0xffU] ^ (crc >> 8);
+ /* Note: (crc >> 8) MUST zero fill on left */
- result = (int)(crc ^ 0xFFFFFFFFU);
- return PyInt_FromLong(result);
+ result = (int)(crc ^ 0xFFFFFFFFU);
+ return PyInt_FromLong(result);
}
#endif /* USE_ZLIB_CRC32 */
@@ -944,41 +944,41 @@ binascii_crc32(PyObject *self, PyObject *args)
static PyObject *
binascii_hexlify(PyObject *self, PyObject *args)
{
- char* argbuf;
- Py_ssize_t arglen;
- PyObject *retval;
- char* retbuf;
- Py_ssize_t i, j;
-
- if (!PyArg_ParseTuple(args, "s#:b2a_hex", &argbuf, &arglen))
- return NULL;
-
- assert(arglen >= 0);
- if (arglen > PY_SSIZE_T_MAX / 2)
- return PyErr_NoMemory();
-
- retval = PyString_FromStringAndSize(NULL, arglen*2);
- if (!retval)
- return NULL;
- retbuf = PyString_AsString(retval);
- if (!retbuf)
- goto finally;
-
- /* 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;
- }
- return retval;
+ char* argbuf;
+ Py_ssize_t arglen;
+ PyObject *retval;
+ char* retbuf;
+ Py_ssize_t i, j;
+
+ if (!PyArg_ParseTuple(args, "s#:b2a_hex", &argbuf, &arglen))
+ return NULL;
+
+ assert(arglen >= 0);
+ if (arglen > PY_SSIZE_T_MAX / 2)
+ return PyErr_NoMemory();
+
+ retval = PyString_FromStringAndSize(NULL, arglen*2);
+ if (!retval)
+ return NULL;
+ retbuf = PyString_AsString(retval);
+ if (!retbuf)
+ goto finally;
+
+ /* 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;
+ }
+ return retval;
finally:
- Py_DECREF(retval);
- return NULL;
+ Py_DECREF(retval);
+ return NULL;
}
PyDoc_STRVAR(doc_hexlify,
@@ -990,63 +990,63 @@ 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)
{
- char* argbuf;
- Py_ssize_t arglen;
- PyObject *retval;
- char* retbuf;
- Py_ssize_t i, j;
-
- if (!PyArg_ParseTuple(args, "s#:a2b_hex", &argbuf, &arglen))
- return NULL;
-
- 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) {
- PyErr_SetString(PyExc_TypeError, "Odd-length string");
- return NULL;
- }
-
- retval = PyString_FromStringAndSize(NULL, (arglen/2));
- if (!retval)
- return NULL;
- retbuf = PyString_AsString(retval);
- if (!retbuf)
- goto finally;
-
- 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(PyExc_TypeError,
- "Non-hexadecimal digit found");
- goto finally;
- }
- retbuf[j++] = (top << 4) + bot;
- }
- return retval;
+ char* argbuf;
+ Py_ssize_t arglen;
+ PyObject *retval;
+ char* retbuf;
+ Py_ssize_t i, j;
+
+ if (!PyArg_ParseTuple(args, "s#:a2b_hex", &argbuf, &arglen))
+ return NULL;
+
+ 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) {
+ PyErr_SetString(PyExc_TypeError, "Odd-length string");
+ return NULL;
+ }
+
+ retval = PyString_FromStringAndSize(NULL, (arglen/2));
+ if (!retval)
+ return NULL;
+ retbuf = PyString_AsString(retval);
+ if (!retbuf)
+ goto finally;
+
+ 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(PyExc_TypeError,
+ "Non-hexadecimal digit found");
+ goto finally;
+ }
+ retbuf[j++] = (top << 4) + bot;
+ }
+ return retval;
finally:
- Py_DECREF(retval);
- return NULL;
+ Py_DECREF(retval);
+ return NULL;
}
PyDoc_STRVAR(doc_unhexlify,
@@ -1075,90 +1075,90 @@ 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;
- 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, &data,
- &datalen, &header))
- return NULL;
-
- /* 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) {
- 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 = PyString_FromStringAndSize((char *)odata, out)) == NULL) {
- PyMem_Free(odata);
- return NULL;
- }
- PyMem_Free(odata);
- return rv;
+ Py_ssize_t in, out;
+ char ch;
+ 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, &data,
+ &datalen, &header))
+ return NULL;
+
+ /* 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) {
+ 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 = PyString_FromStringAndSize((char *)odata, out)) == NULL) {
+ PyMem_Free(odata);
+ return NULL;
+ }
+ 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,
@@ -1175,204 +1175,204 @@ 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;
- 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, "s#|iii", kwlist, &data,
- &datalen, &quotetabs, &istext, &header))
- return NULL;
-
- /* 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) {
- 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 = PyString_FromStringAndSize((char *)odata, out)) == NULL) {
- PyMem_Free(odata);
- return NULL;
- }
- PyMem_Free(odata);
- return rv;
+ Py_ssize_t in, out;
+ 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, "s#|iii", kwlist, &data,
+ &datalen, &quotetabs, &istext, &header))
+ return NULL;
+
+ /* 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) {
+ 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 = PyString_FromStringAndSize((char *)odata, out)) == NULL) {
+ PyMem_Free(odata);
+ return NULL;
+ }
+ 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 */
};
@@ -1382,20 +1382,20 @@ PyDoc_STRVAR(doc_binascii, "Conversion between binary data and ASCII");
PyMODINIT_FUNC
initbinascii(void)
{
- PyObject *m, *d, *x;
-
- /* Create the module and add the functions */
- m = Py_InitModule("binascii", binascii_module_methods);
- if (m == NULL)
- return;
-
- d = PyModule_GetDict(m);
- x = PyString_FromString(doc_binascii);
- PyDict_SetItemString(d, "__doc__", x);
- Py_XDECREF(x);
-
- Error = PyErr_NewException("binascii.Error", NULL, NULL);
- PyDict_SetItemString(d, "Error", Error);
- Incomplete = PyErr_NewException("binascii.Incomplete", NULL, NULL);
- PyDict_SetItemString(d, "Incomplete", Incomplete);
+ PyObject *m, *d, *x;
+
+ /* Create the module and add the functions */
+ m = Py_InitModule("binascii", binascii_module_methods);
+ if (m == NULL)
+ return;
+
+ d = PyModule_GetDict(m);
+ x = PyString_FromString(doc_binascii);
+ PyDict_SetItemString(d, "__doc__", x);
+ Py_XDECREF(x);
+
+ Error = PyErr_NewException("binascii.Error", NULL, NULL);
+ PyDict_SetItemString(d, "Error", Error);
+ Incomplete = PyErr_NewException("binascii.Incomplete", NULL, NULL);
+ PyDict_SetItemString(d, "Incomplete", Incomplete);
}
diff --git a/Modules/bsddbmodule.c b/Modules/bsddbmodule.c
index 0972882..5fd4fb1 100644
--- a/Modules/bsddbmodule.c
+++ b/Modules/bsddbmodule.c
@@ -30,12 +30,12 @@
(it messes up the info required in the Setup file) */
typedef struct {
- PyObject_HEAD
- DB *di_bsddb;
- int di_size; /* -1 means recompute */
- int di_type;
+ PyObject_HEAD
+ DB *di_bsddb;
+ int di_size; /* -1 means recompute */
+ int di_type;
#ifdef WITH_THREAD
- PyThread_type_lock di_lock;
+ PyThread_type_lock di_lock;
#endif
} bsddbobject;
@@ -44,819 +44,819 @@ static PyTypeObject Bsddbtype;
#define is_bsddbobject(v) ((v)->ob_type == &Bsddbtype)
#define check_bsddbobject_open(v, r) if ((v)->di_bsddb == NULL) \
{ PyErr_SetString(BsddbError, \
- "BSDDB object has already been closed"); \
+ "BSDDB object has already been closed"); \
return r; }
static PyObject *BsddbError;
static PyObject *
newdbhashobject(char *file, int flags, int mode,
- int bsize, int ffactor, int nelem, int cachesize,
- int hash, int lorder)
+ int bsize, int ffactor, int nelem, int cachesize,
+ int hash, int lorder)
{
- bsddbobject *dp;
- HASHINFO info;
+ bsddbobject *dp;
+ HASHINFO info;
- if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
- return NULL;
+ if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
+ return NULL;
- info.bsize = bsize;
- info.ffactor = ffactor;
- info.nelem = nelem;
- info.cachesize = cachesize;
- info.hash = NULL; /* XXX should derive from hash argument */
- info.lorder = lorder;
+ info.bsize = bsize;
+ info.ffactor = ffactor;
+ info.nelem = nelem;
+ info.cachesize = cachesize;
+ info.hash = NULL; /* XXX should derive from hash argument */
+ info.lorder = lorder;
#ifdef O_BINARY
- flags |= O_BINARY;
+ flags |= O_BINARY;
#endif
- Py_BEGIN_ALLOW_THREADS
- dp->di_bsddb = dbopen(file, flags, mode, DB_HASH, &info);
- Py_END_ALLOW_THREADS
- if (dp->di_bsddb == NULL) {
- PyErr_SetFromErrno(BsddbError);
+ Py_BEGIN_ALLOW_THREADS
+ dp->di_bsddb = dbopen(file, flags, mode, DB_HASH, &info);
+ Py_END_ALLOW_THREADS
+ if (dp->di_bsddb == NULL) {
+ PyErr_SetFromErrno(BsddbError);
#ifdef WITH_THREAD
- dp->di_lock = NULL;
+ dp->di_lock = NULL;
#endif
- Py_DECREF(dp);
- return NULL;
- }
+ Py_DECREF(dp);
+ return NULL;
+ }
- dp->di_size = -1;
- dp->di_type = DB_HASH;
+ dp->di_size = -1;
+ dp->di_type = DB_HASH;
#ifdef WITH_THREAD
- dp->di_lock = PyThread_allocate_lock();
- if (dp->di_lock == NULL) {
- PyErr_SetString(BsddbError, "can't allocate lock");
- Py_DECREF(dp);
- return NULL;
- }
+ dp->di_lock = PyThread_allocate_lock();
+ if (dp->di_lock == NULL) {
+ PyErr_SetString(BsddbError, "can't allocate lock");
+ Py_DECREF(dp);
+ return NULL;
+ }
#endif
- return (PyObject *)dp;
+ return (PyObject *)dp;
}
static PyObject *
newdbbtobject(char *file, int flags, int mode,
- int btflags, int cachesize, int maxkeypage,
- int minkeypage, int psize, int lorder)
+ int btflags, int cachesize, int maxkeypage,
+ int minkeypage, int psize, int lorder)
{
- bsddbobject *dp;
- BTREEINFO info;
+ bsddbobject *dp;
+ BTREEINFO info;
- if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
- return NULL;
+ if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
+ return NULL;
- info.flags = btflags;
- info.cachesize = cachesize;
- info.maxkeypage = maxkeypage;
- info.minkeypage = minkeypage;
- info.psize = psize;
- info.lorder = lorder;
- info.compare = 0; /* Use default comparison functions, for now..*/
- info.prefix = 0;
+ info.flags = btflags;
+ info.cachesize = cachesize;
+ info.maxkeypage = maxkeypage;
+ info.minkeypage = minkeypage;
+ info.psize = psize;
+ info.lorder = lorder;
+ info.compare = 0; /* Use default comparison functions, for now..*/
+ info.prefix = 0;
#ifdef O_BINARY
- flags |= O_BINARY;
+ flags |= O_BINARY;
#endif
- Py_BEGIN_ALLOW_THREADS
- dp->di_bsddb = dbopen(file, flags, mode, DB_BTREE, &info);
- Py_END_ALLOW_THREADS
- if (dp->di_bsddb == NULL) {
- PyErr_SetFromErrno(BsddbError);
+ Py_BEGIN_ALLOW_THREADS
+ dp->di_bsddb = dbopen(file, flags, mode, DB_BTREE, &info);
+ Py_END_ALLOW_THREADS
+ if (dp->di_bsddb == NULL) {
+ PyErr_SetFromErrno(BsddbError);
#ifdef WITH_THREAD
- dp->di_lock = NULL;
+ dp->di_lock = NULL;
#endif
- Py_DECREF(dp);
- return NULL;
- }
+ Py_DECREF(dp);
+ return NULL;
+ }
- dp->di_size = -1;
- dp->di_type = DB_BTREE;
+ dp->di_size = -1;
+ dp->di_type = DB_BTREE;
#ifdef WITH_THREAD
- dp->di_lock = PyThread_allocate_lock();
- if (dp->di_lock == NULL) {
- PyErr_SetString(BsddbError, "can't allocate lock");
- Py_DECREF(dp);
- return NULL;
- }
+ dp->di_lock = PyThread_allocate_lock();
+ if (dp->di_lock == NULL) {
+ PyErr_SetString(BsddbError, "can't allocate lock");
+ Py_DECREF(dp);
+ return NULL;
+ }
#endif
- return (PyObject *)dp;
+ return (PyObject *)dp;
}
static PyObject *
newdbrnobject(char *file, int flags, int mode,
- int rnflags, int cachesize, int psize, int lorder,
- size_t reclen, u_char bval, char *bfname)
+ int rnflags, int cachesize, int psize, int lorder,
+ size_t reclen, u_char bval, char *bfname)
{
- bsddbobject *dp;
- RECNOINFO info;
- int fd;
+ bsddbobject *dp;
+ RECNOINFO info;
+ int fd;
- if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
- return NULL;
+ if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
+ return NULL;
- info.flags = rnflags;
- info.cachesize = cachesize;
- info.psize = psize;
- info.lorder = lorder;
- info.reclen = reclen;
- info.bval = bval;
- info.bfname = bfname;
+ info.flags = rnflags;
+ info.cachesize = cachesize;
+ info.psize = psize;
+ info.lorder = lorder;
+ info.reclen = reclen;
+ info.bval = bval;
+ info.bfname = bfname;
#ifdef O_BINARY
- flags |= O_BINARY;
+ flags |= O_BINARY;
#endif
- /* This is a hack to avoid a dbopen() bug that happens when
- * it fails. */
- fd = open(file, flags);
- if (fd == -1) {
- dp->di_bsddb = NULL;
- }
- else {
- close(fd);
- Py_BEGIN_ALLOW_THREADS
- dp->di_bsddb = dbopen(file, flags, mode, DB_RECNO, &info);
- Py_END_ALLOW_THREADS
- }
- if (dp->di_bsddb == NULL) {
- PyErr_SetFromErrno(BsddbError);
+ /* This is a hack to avoid a dbopen() bug that happens when
+ * it fails. */
+ fd = open(file, flags);
+ if (fd == -1) {
+ dp->di_bsddb = NULL;
+ }
+ else {
+ close(fd);
+ Py_BEGIN_ALLOW_THREADS
+ dp->di_bsddb = dbopen(file, flags, mode, DB_RECNO, &info);
+ Py_END_ALLOW_THREADS
+ }
+ if (dp->di_bsddb == NULL) {
+ PyErr_SetFromErrno(BsddbError);
#ifdef WITH_THREAD
- dp->di_lock = NULL;
+ dp->di_lock = NULL;
#endif
- Py_DECREF(dp);
- return NULL;
- }
+ Py_DECREF(dp);
+ return NULL;
+ }
- dp->di_size = -1;
- dp->di_type = DB_RECNO;
+ dp->di_size = -1;
+ dp->di_type = DB_RECNO;
#ifdef WITH_THREAD
- dp->di_lock = PyThread_allocate_lock();
- if (dp->di_lock == NULL) {
- PyErr_SetString(BsddbError, "can't allocate lock");
- Py_DECREF(dp);
- return NULL;
- }
+ dp->di_lock = PyThread_allocate_lock();
+ if (dp->di_lock == NULL) {
+ PyErr_SetString(BsddbError, "can't allocate lock");
+ Py_DECREF(dp);
+ return NULL;
+ }
#endif
- return (PyObject *)dp;
+ return (PyObject *)dp;
}
static void
bsddb_dealloc(bsddbobject *dp)
{
#ifdef WITH_THREAD
- if (dp->di_lock) {
- PyThread_acquire_lock(dp->di_lock, 0);
- PyThread_release_lock(dp->di_lock);
- PyThread_free_lock(dp->di_lock);
- dp->di_lock = NULL;
- }
+ if (dp->di_lock) {
+ PyThread_acquire_lock(dp->di_lock, 0);
+ PyThread_release_lock(dp->di_lock);
+ PyThread_free_lock(dp->di_lock);
+ dp->di_lock = NULL;
+ }
#endif
- if (dp->di_bsddb != NULL) {
- int status;
- Py_BEGIN_ALLOW_THREADS
- status = (dp->di_bsddb->close)(dp->di_bsddb);
- Py_END_ALLOW_THREADS
- if (status != 0)
- fprintf(stderr,
- "Python bsddb: close errno %d in dealloc\n",
- errno);
- }
- PyObject_Del(dp);
+ if (dp->di_bsddb != NULL) {
+ int status;
+ Py_BEGIN_ALLOW_THREADS
+ status = (dp->di_bsddb->close)(dp->di_bsddb);
+ Py_END_ALLOW_THREADS
+ if (status != 0)
+ fprintf(stderr,
+ "Python bsddb: close errno %d in dealloc\n",
+ errno);
+ }
+ PyObject_Del(dp);
}
#ifdef WITH_THREAD
#define BSDDB_BGN_SAVE(_dp) \
- Py_BEGIN_ALLOW_THREADS PyThread_acquire_lock(_dp->di_lock,1);
+ Py_BEGIN_ALLOW_THREADS PyThread_acquire_lock(_dp->di_lock,1);
#define BSDDB_END_SAVE(_dp) \
- PyThread_release_lock(_dp->di_lock); Py_END_ALLOW_THREADS
+ PyThread_release_lock(_dp->di_lock); Py_END_ALLOW_THREADS
#else
-#define BSDDB_BGN_SAVE(_dp) Py_BEGIN_ALLOW_THREADS
+#define BSDDB_BGN_SAVE(_dp) Py_BEGIN_ALLOW_THREADS
#define BSDDB_END_SAVE(_dp) Py_END_ALLOW_THREADS
#endif
static Py_ssize_t
bsddb_length(bsddbobject *dp)
{
- check_bsddbobject_open(dp, -1);
- if (dp->di_size < 0) {
- DBT krec, drec;
- int status;
- int size = 0;
- BSDDB_BGN_SAVE(dp)
- for (status = (dp->di_bsddb->seq)(dp->di_bsddb,
- &krec, &drec,R_FIRST);
- status == 0;
- status = (dp->di_bsddb->seq)(dp->di_bsddb,
- &krec, &drec, R_NEXT))
- size++;
- BSDDB_END_SAVE(dp)
- if (status < 0) {
- PyErr_SetFromErrno(BsddbError);
- return -1;
- }
- dp->di_size = size;
- }
- return dp->di_size;
+ check_bsddbobject_open(dp, -1);
+ if (dp->di_size < 0) {
+ DBT krec, drec;
+ int status;
+ int size = 0;
+ BSDDB_BGN_SAVE(dp)
+ for (status = (dp->di_bsddb->seq)(dp->di_bsddb,
+ &krec, &drec,R_FIRST);
+ status == 0;
+ status = (dp->di_bsddb->seq)(dp->di_bsddb,
+ &krec, &drec, R_NEXT))
+ size++;
+ BSDDB_END_SAVE(dp)
+ if (status < 0) {
+ PyErr_SetFromErrno(BsddbError);
+ return -1;
+ }
+ dp->di_size = size;
+ }
+ return dp->di_size;
}
static PyObject *
bsddb_subscript(bsddbobject *dp, PyObject *key)
{
- int status;
- DBT krec, drec;
- char *data,buf[4096];
- int size;
- PyObject *result;
- recno_t recno;
-
- if (dp->di_type == DB_RECNO) {
- if (!PyArg_Parse(key, "i", &recno)) {
- PyErr_SetString(PyExc_TypeError,
- "key type must be integer");
- return NULL;
- }
- krec.data = &recno;
- krec.size = sizeof(recno);
- }
- else {
- if (!PyArg_Parse(key, "s#", &data, &size)) {
- PyErr_SetString(PyExc_TypeError,
- "key type must be string");
- return NULL;
- }
- krec.data = data;
- krec.size = size;
- }
- check_bsddbobject_open(dp, NULL);
-
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->get)(dp->di_bsddb, &krec, &drec, 0);
- if (status == 0) {
- if (drec.size > sizeof(buf)) data = malloc(drec.size);
- else data = buf;
- if (data!=NULL) memcpy(data,drec.data,drec.size);
- }
- BSDDB_END_SAVE(dp)
- if (data==NULL) return PyErr_NoMemory();
- if (status != 0) {
- if (status < 0)
- PyErr_SetFromErrno(BsddbError);
- else
- PyErr_SetObject(PyExc_KeyError, key);
- return NULL;
- }
-
- result = PyString_FromStringAndSize(data, (int)drec.size);
- if (data != buf) free(data);
- return result;
+ int status;
+ DBT krec, drec;
+ char *data,buf[4096];
+ int size;
+ PyObject *result;
+ recno_t recno;
+
+ if (dp->di_type == DB_RECNO) {
+ if (!PyArg_Parse(key, "i", &recno)) {
+ PyErr_SetString(PyExc_TypeError,
+ "key type must be integer");
+ return NULL;
+ }
+ krec.data = &recno;
+ krec.size = sizeof(recno);
+ }
+ else {
+ if (!PyArg_Parse(key, "s#", &data, &size)) {
+ PyErr_SetString(PyExc_TypeError,
+ "key type must be string");
+ return NULL;
+ }
+ krec.data = data;
+ krec.size = size;
+ }
+ check_bsddbobject_open(dp, NULL);
+
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->get)(dp->di_bsddb, &krec, &drec, 0);
+ if (status == 0) {
+ if (drec.size > sizeof(buf)) data = malloc(drec.size);
+ else data = buf;
+ if (data!=NULL) memcpy(data,drec.data,drec.size);
+ }
+ BSDDB_END_SAVE(dp)
+ if (data==NULL) return PyErr_NoMemory();
+ if (status != 0) {
+ if (status < 0)
+ PyErr_SetFromErrno(BsddbError);
+ else
+ PyErr_SetObject(PyExc_KeyError, key);
+ return NULL;
+ }
+
+ result = PyString_FromStringAndSize(data, (int)drec.size);
+ if (data != buf) free(data);
+ return result;
}
static int
bsddb_ass_sub(bsddbobject *dp, PyObject *key, PyObject *value)
{
- int status;
- DBT krec, drec;
- char *data;
- int size;
- recno_t recno;
-
- if (dp->di_type == DB_RECNO) {
- if (!PyArg_Parse(key, "i", &recno)) {
- PyErr_SetString(PyExc_TypeError,
- "bsddb key type must be integer");
- return -1;
- }
- krec.data = &recno;
- krec.size = sizeof(recno);
- }
- else {
- if (!PyArg_Parse(key, "s#", &data, &size)) {
- PyErr_SetString(PyExc_TypeError,
- "bsddb key type must be string");
- return -1;
- }
- krec.data = data;
- krec.size = size;
- }
- check_bsddbobject_open(dp, -1);
- dp->di_size = -1;
- if (value == NULL) {
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->del)(dp->di_bsddb, &krec, 0);
- BSDDB_END_SAVE(dp)
- }
- else {
- if (!PyArg_Parse(value, "s#", &data, &size)) {
- PyErr_SetString(PyExc_TypeError,
- "bsddb value type must be string");
- return -1;
- }
- drec.data = data;
- drec.size = size;
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->put)(dp->di_bsddb, &krec, &drec, 0);
- BSDDB_END_SAVE(dp)
- }
- if (status != 0) {
- if (status < 0)
- PyErr_SetFromErrno(BsddbError);
- else
- PyErr_SetObject(PyExc_KeyError, key);
- return -1;
- }
- return 0;
+ int status;
+ DBT krec, drec;
+ char *data;
+ int size;
+ recno_t recno;
+
+ if (dp->di_type == DB_RECNO) {
+ if (!PyArg_Parse(key, "i", &recno)) {
+ PyErr_SetString(PyExc_TypeError,
+ "bsddb key type must be integer");
+ return -1;
+ }
+ krec.data = &recno;
+ krec.size = sizeof(recno);
+ }
+ else {
+ if (!PyArg_Parse(key, "s#", &data, &size)) {
+ PyErr_SetString(PyExc_TypeError,
+ "bsddb key type must be string");
+ return -1;
+ }
+ krec.data = data;
+ krec.size = size;
+ }
+ check_bsddbobject_open(dp, -1);
+ dp->di_size = -1;
+ if (value == NULL) {
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->del)(dp->di_bsddb, &krec, 0);
+ BSDDB_END_SAVE(dp)
+ }
+ else {
+ if (!PyArg_Parse(value, "s#", &data, &size)) {
+ PyErr_SetString(PyExc_TypeError,
+ "bsddb value type must be string");
+ return -1;
+ }
+ drec.data = data;
+ drec.size = size;
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->put)(dp->di_bsddb, &krec, &drec, 0);
+ BSDDB_END_SAVE(dp)
+ }
+ if (status != 0) {
+ if (status < 0)
+ PyErr_SetFromErrno(BsddbError);
+ else
+ PyErr_SetObject(PyExc_KeyError, key);
+ return -1;
+ }
+ return 0;
}
static PyMappingMethods bsddb_as_mapping = {
- (lenfunc)bsddb_length, /*mp_length*/
- (binaryfunc)bsddb_subscript, /*mp_subscript*/
- (objobjargproc)bsddb_ass_sub, /*mp_ass_subscript*/
+ (lenfunc)bsddb_length, /*mp_length*/
+ (binaryfunc)bsddb_subscript, /*mp_subscript*/
+ (objobjargproc)bsddb_ass_sub, /*mp_ass_subscript*/
};
static PyObject *
bsddb_close(bsddbobject *dp)
{
- if (dp->di_bsddb != NULL) {
- int status;
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->close)(dp->di_bsddb);
- BSDDB_END_SAVE(dp)
- if (status != 0) {
- dp->di_bsddb = NULL;
- PyErr_SetFromErrno(BsddbError);
- return NULL;
- }
- }
- dp->di_bsddb = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (dp->di_bsddb != NULL) {
+ int status;
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->close)(dp->di_bsddb);
+ BSDDB_END_SAVE(dp)
+ if (status != 0) {
+ dp->di_bsddb = NULL;
+ PyErr_SetFromErrno(BsddbError);
+ return NULL;
+ }
+ }
+ dp->di_bsddb = NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
bsddb_keys(bsddbobject *dp)
{
- PyObject *list, *item=NULL;
- DBT krec, drec;
- char *data=NULL,buf[4096];
- int status;
- int err;
-
- check_bsddbobject_open(dp, NULL);
- list = PyList_New(0);
- if (list == NULL)
- return NULL;
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_FIRST);
- if (status == 0) {
- if (krec.size > sizeof(buf)) data = malloc(krec.size);
- else data = buf;
- if (data != NULL) memcpy(data,krec.data,krec.size);
- }
- BSDDB_END_SAVE(dp)
- if (status == 0 && data==NULL) return PyErr_NoMemory();
- while (status == 0) {
- if (dp->di_type == DB_RECNO)
- item = PyInt_FromLong(*((int*)data));
- else
- item = PyString_FromStringAndSize(data,
- (int)krec.size);
- if (data != buf) free(data);
- if (item == NULL) {
- Py_DECREF(list);
- return NULL;
- }
- err = PyList_Append(list, item);
- Py_DECREF(item);
- if (err != 0) {
- Py_DECREF(list);
- return NULL;
- }
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->seq)
- (dp->di_bsddb, &krec, &drec, R_NEXT);
- if (status == 0) {
- if (krec.size > sizeof(buf))
- data = malloc(krec.size);
- else data = buf;
- if (data != NULL)
- memcpy(data,krec.data,krec.size);
- }
- BSDDB_END_SAVE(dp)
- if (data == NULL) return PyErr_NoMemory();
- }
- if (status < 0) {
- PyErr_SetFromErrno(BsddbError);
- Py_DECREF(list);
- return NULL;
- }
- if (dp->di_size < 0)
- dp->di_size = PyList_Size(list); /* We just did the work */
- return list;
+ PyObject *list, *item=NULL;
+ DBT krec, drec;
+ char *data=NULL,buf[4096];
+ int status;
+ int err;
+
+ check_bsddbobject_open(dp, NULL);
+ list = PyList_New(0);
+ if (list == NULL)
+ return NULL;
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_FIRST);
+ if (status == 0) {
+ if (krec.size > sizeof(buf)) data = malloc(krec.size);
+ else data = buf;
+ if (data != NULL) memcpy(data,krec.data,krec.size);
+ }
+ BSDDB_END_SAVE(dp)
+ if (status == 0 && data==NULL) return PyErr_NoMemory();
+ while (status == 0) {
+ if (dp->di_type == DB_RECNO)
+ item = PyInt_FromLong(*((int*)data));
+ else
+ item = PyString_FromStringAndSize(data,
+ (int)krec.size);
+ if (data != buf) free(data);
+ if (item == NULL) {
+ Py_DECREF(list);
+ return NULL;
+ }
+ err = PyList_Append(list, item);
+ Py_DECREF(item);
+ if (err != 0) {
+ Py_DECREF(list);
+ return NULL;
+ }
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->seq)
+ (dp->di_bsddb, &krec, &drec, R_NEXT);
+ if (status == 0) {
+ if (krec.size > sizeof(buf))
+ data = malloc(krec.size);
+ else data = buf;
+ if (data != NULL)
+ memcpy(data,krec.data,krec.size);
+ }
+ BSDDB_END_SAVE(dp)
+ if (data == NULL) return PyErr_NoMemory();
+ }
+ if (status < 0) {
+ PyErr_SetFromErrno(BsddbError);
+ Py_DECREF(list);
+ return NULL;
+ }
+ if (dp->di_size < 0)
+ dp->di_size = PyList_Size(list); /* We just did the work */
+ return list;
}
static PyObject *
bsddb_has_key(bsddbobject *dp, PyObject *args)
{
- DBT krec, drec;
- int status;
- char *data;
- int size;
- recno_t recno;
-
- if (dp->di_type == DB_RECNO) {
- if (!PyArg_ParseTuple(args, "i;key type must be integer",
- &recno)) {
- return NULL;
- }
- krec.data = &recno;
- krec.size = sizeof(recno);
- }
- else {
- if (!PyArg_ParseTuple(args, "s#;key type must be string",
- &data, &size)) {
- return NULL;
- }
- krec.data = data;
- krec.size = size;
- }
- check_bsddbobject_open(dp, NULL);
-
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->get)(dp->di_bsddb, &krec, &drec, 0);
- BSDDB_END_SAVE(dp)
- if (status < 0) {
- PyErr_SetFromErrno(BsddbError);
- return NULL;
- }
-
- return PyInt_FromLong(status == 0);
+ DBT krec, drec;
+ int status;
+ char *data;
+ int size;
+ recno_t recno;
+
+ if (dp->di_type == DB_RECNO) {
+ if (!PyArg_ParseTuple(args, "i;key type must be integer",
+ &recno)) {
+ return NULL;
+ }
+ krec.data = &recno;
+ krec.size = sizeof(recno);
+ }
+ else {
+ if (!PyArg_ParseTuple(args, "s#;key type must be string",
+ &data, &size)) {
+ return NULL;
+ }
+ krec.data = data;
+ krec.size = size;
+ }
+ check_bsddbobject_open(dp, NULL);
+
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->get)(dp->di_bsddb, &krec, &drec, 0);
+ BSDDB_END_SAVE(dp)
+ if (status < 0) {
+ PyErr_SetFromErrno(BsddbError);
+ return NULL;
+ }
+
+ return PyInt_FromLong(status == 0);
}
static PyObject *
bsddb_set_location(bsddbobject *dp, PyObject *key)
{
- int status;
- DBT krec, drec;
- char *data,buf[4096];
- int size;
- PyObject *result;
- recno_t recno;
-
- if (dp->di_type == DB_RECNO) {
- if (!PyArg_ParseTuple(key, "i;key type must be integer",
- &recno)) {
- return NULL;
- }
- krec.data = &recno;
- krec.size = sizeof(recno);
- }
- else {
- if (!PyArg_ParseTuple(key, "s#;key type must be string",
- &data, &size)) {
- return NULL;
- }
- krec.data = data;
- krec.size = size;
- }
- check_bsddbobject_open(dp, NULL);
-
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_CURSOR);
- if (status == 0) {
- if (drec.size > sizeof(buf)) data = malloc(drec.size);
- else data = buf;
- if (data!=NULL) memcpy(data,drec.data,drec.size);
- }
- BSDDB_END_SAVE(dp)
- if (data==NULL) return PyErr_NoMemory();
- if (status != 0) {
- if (status < 0)
- PyErr_SetFromErrno(BsddbError);
- else
- PyErr_SetObject(PyExc_KeyError, key);
- return NULL;
- }
-
- if (dp->di_type == DB_RECNO)
- result = Py_BuildValue("is#", *((int*)krec.data),
- data, drec.size);
- else
- result = Py_BuildValue("s#s#", krec.data, krec.size,
- data, drec.size);
- if (data != buf) free(data);
- return result;
+ int status;
+ DBT krec, drec;
+ char *data,buf[4096];
+ int size;
+ PyObject *result;
+ recno_t recno;
+
+ if (dp->di_type == DB_RECNO) {
+ if (!PyArg_ParseTuple(key, "i;key type must be integer",
+ &recno)) {
+ return NULL;
+ }
+ krec.data = &recno;
+ krec.size = sizeof(recno);
+ }
+ else {
+ if (!PyArg_ParseTuple(key, "s#;key type must be string",
+ &data, &size)) {
+ return NULL;
+ }
+ krec.data = data;
+ krec.size = size;
+ }
+ check_bsddbobject_open(dp, NULL);
+
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_CURSOR);
+ if (status == 0) {
+ if (drec.size > sizeof(buf)) data = malloc(drec.size);
+ else data = buf;
+ if (data!=NULL) memcpy(data,drec.data,drec.size);
+ }
+ BSDDB_END_SAVE(dp)
+ if (data==NULL) return PyErr_NoMemory();
+ if (status != 0) {
+ if (status < 0)
+ PyErr_SetFromErrno(BsddbError);
+ else
+ PyErr_SetObject(PyExc_KeyError, key);
+ return NULL;
+ }
+
+ if (dp->di_type == DB_RECNO)
+ result = Py_BuildValue("is#", *((int*)krec.data),
+ data, drec.size);
+ else
+ result = Py_BuildValue("s#s#", krec.data, krec.size,
+ data, drec.size);
+ if (data != buf) free(data);
+ return result;
}
static PyObject *
bsddb_seq(bsddbobject *dp, int sequence_request)
{
- int status;
- DBT krec, drec;
- char *kdata=NULL,kbuf[4096];
- char *ddata=NULL,dbuf[4096];
- PyObject *result;
-
- check_bsddbobject_open(dp, NULL);
- krec.data = 0;
- krec.size = 0;
-
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec,
- &drec, sequence_request);
- if (status == 0) {
- if (krec.size > sizeof(kbuf)) kdata = malloc(krec.size);
- else kdata = kbuf;
- if (kdata != NULL) memcpy(kdata,krec.data,krec.size);
- if (drec.size > sizeof(dbuf)) ddata = malloc(drec.size);
- else ddata = dbuf;
- if (ddata != NULL) memcpy(ddata,drec.data,drec.size);
- }
- BSDDB_END_SAVE(dp)
- if (status == 0) {
- if ((kdata == NULL) || (ddata == NULL))
- return PyErr_NoMemory();
- }
- else {
- /* (status != 0) */
- if (status < 0)
- PyErr_SetFromErrno(BsddbError);
- else
- PyErr_SetString(PyExc_KeyError, "no key/data pairs");
- return NULL;
- }
-
- if (dp->di_type == DB_RECNO)
- result = Py_BuildValue("is#", *((int*)kdata),
- ddata, drec.size);
- else
- result = Py_BuildValue("s#s#", kdata, krec.size,
- ddata, drec.size);
- if (kdata != kbuf) free(kdata);
- if (ddata != dbuf) free(ddata);
- return result;
+ int status;
+ DBT krec, drec;
+ char *kdata=NULL,kbuf[4096];
+ char *ddata=NULL,dbuf[4096];
+ PyObject *result;
+
+ check_bsddbobject_open(dp, NULL);
+ krec.data = 0;
+ krec.size = 0;
+
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec,
+ &drec, sequence_request);
+ if (status == 0) {
+ if (krec.size > sizeof(kbuf)) kdata = malloc(krec.size);
+ else kdata = kbuf;
+ if (kdata != NULL) memcpy(kdata,krec.data,krec.size);
+ if (drec.size > sizeof(dbuf)) ddata = malloc(drec.size);
+ else ddata = dbuf;
+ if (ddata != NULL) memcpy(ddata,drec.data,drec.size);
+ }
+ BSDDB_END_SAVE(dp)
+ if (status == 0) {
+ if ((kdata == NULL) || (ddata == NULL))
+ return PyErr_NoMemory();
+ }
+ else {
+ /* (status != 0) */
+ if (status < 0)
+ PyErr_SetFromErrno(BsddbError);
+ else
+ PyErr_SetString(PyExc_KeyError, "no key/data pairs");
+ return NULL;
+ }
+
+ if (dp->di_type == DB_RECNO)
+ result = Py_BuildValue("is#", *((int*)kdata),
+ ddata, drec.size);
+ else
+ result = Py_BuildValue("s#s#", kdata, krec.size,
+ ddata, drec.size);
+ if (kdata != kbuf) free(kdata);
+ if (ddata != dbuf) free(ddata);
+ return result;
}
static PyObject *
bsddb_next(bsddbobject *dp)
{
- return bsddb_seq(dp, R_NEXT);
+ return bsddb_seq(dp, R_NEXT);
}
static PyObject *
bsddb_previous(bsddbobject *dp)
{
- return bsddb_seq(dp, R_PREV);
+ return bsddb_seq(dp, R_PREV);
}
static PyObject *
bsddb_first(bsddbobject *dp)
{
- return bsddb_seq(dp, R_FIRST);
+ return bsddb_seq(dp, R_FIRST);
}
static PyObject *
bsddb_last(bsddbobject *dp)
{
- return bsddb_seq(dp, R_LAST);
+ return bsddb_seq(dp, R_LAST);
}
static PyObject *
bsddb_sync(bsddbobject *dp)
{
- int status;
-
- check_bsddbobject_open(dp, NULL);
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->sync)(dp->di_bsddb, 0);
- BSDDB_END_SAVE(dp)
- if (status != 0) {
- PyErr_SetFromErrno(BsddbError);
- return NULL;
- }
- return PyInt_FromLong(status = 0);
+ int status;
+
+ check_bsddbobject_open(dp, NULL);
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->sync)(dp->di_bsddb, 0);
+ BSDDB_END_SAVE(dp)
+ if (status != 0) {
+ PyErr_SetFromErrno(BsddbError);
+ return NULL;
+ }
+ return PyInt_FromLong(status = 0);
}
static PyMethodDef bsddb_methods[] = {
- {"close", (PyCFunction)bsddb_close, METH_NOARGS},
- {"keys", (PyCFunction)bsddb_keys, METH_NOARGS},
- {"has_key", (PyCFunction)bsddb_has_key, METH_VARARGS},
- {"set_location", (PyCFunction)bsddb_set_location, METH_VARARGS},
- {"next", (PyCFunction)bsddb_next, METH_NOARGS},
- {"previous", (PyCFunction)bsddb_previous, METH_NOARGS},
- {"first", (PyCFunction)bsddb_first, METH_NOARGS},
- {"last", (PyCFunction)bsddb_last, METH_NOARGS},
- {"sync", (PyCFunction)bsddb_sync, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {"close", (PyCFunction)bsddb_close, METH_NOARGS},
+ {"keys", (PyCFunction)bsddb_keys, METH_NOARGS},
+ {"has_key", (PyCFunction)bsddb_has_key, METH_VARARGS},
+ {"set_location", (PyCFunction)bsddb_set_location, METH_VARARGS},
+ {"next", (PyCFunction)bsddb_next, METH_NOARGS},
+ {"previous", (PyCFunction)bsddb_previous, METH_NOARGS},
+ {"first", (PyCFunction)bsddb_first, METH_NOARGS},
+ {"last", (PyCFunction)bsddb_last, METH_NOARGS},
+ {"sync", (PyCFunction)bsddb_sync, METH_NOARGS},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
bsddb_getattr(PyObject *dp, char *name)
{
- return Py_FindMethod(bsddb_methods, dp, name);
+ return Py_FindMethod(bsddb_methods, dp, name);
}
static PyTypeObject Bsddbtype = {
- PyObject_HEAD_INIT(NULL)
- 0,
- "bsddb.bsddb",
- sizeof(bsddbobject),
- 0,
- (destructor)bsddb_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)bsddb_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- &bsddb_as_mapping, /*tp_as_mapping*/
+ PyObject_HEAD_INIT(NULL)
+ 0,
+ "bsddb.bsddb",
+ sizeof(bsddbobject),
+ 0,
+ (destructor)bsddb_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)bsddb_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ &bsddb_as_mapping, /*tp_as_mapping*/
};
static PyObject *
bsdhashopen(PyObject *self, PyObject *args)
{
- char *file;
- char *flag = NULL;
- int flags = O_RDONLY;
- int mode = 0666;
- int bsize = 0;
- int ffactor = 0;
- int nelem = 0;
- int cachesize = 0;
- int hash = 0; /* XXX currently ignored */
- int lorder = 0;
-
- if (!PyArg_ParseTuple(args, "z|siiiiiii:hashopen",
- &file, &flag, &mode,
- &bsize, &ffactor, &nelem, &cachesize,
- &hash, &lorder))
- return NULL;
- if (flag != NULL) {
- /* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
- if (flag[0] == 'r')
- flags = O_RDONLY;
- else if (flag[0] == 'w')
- flags = O_RDWR;
- else if (flag[0] == 'c')
- flags = O_RDWR|O_CREAT;
- else if (flag[0] == 'n')
- flags = O_RDWR|O_CREAT|O_TRUNC;
- else {
- PyErr_SetString(BsddbError,
- "Flag should begin with 'r', 'w', 'c' or 'n'");
- return NULL;
- }
- if (flag[1] == 'l') {
+ char *file;
+ char *flag = NULL;
+ int flags = O_RDONLY;
+ int mode = 0666;
+ int bsize = 0;
+ int ffactor = 0;
+ int nelem = 0;
+ int cachesize = 0;
+ int hash = 0; /* XXX currently ignored */
+ int lorder = 0;
+
+ if (!PyArg_ParseTuple(args, "z|siiiiiii:hashopen",
+ &file, &flag, &mode,
+ &bsize, &ffactor, &nelem, &cachesize,
+ &hash, &lorder))
+ return NULL;
+ if (flag != NULL) {
+ /* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
+ if (flag[0] == 'r')
+ flags = O_RDONLY;
+ else if (flag[0] == 'w')
+ flags = O_RDWR;
+ else if (flag[0] == 'c')
+ flags = O_RDWR|O_CREAT;
+ else if (flag[0] == 'n')
+ flags = O_RDWR|O_CREAT|O_TRUNC;
+ else {
+ PyErr_SetString(BsddbError,
+ "Flag should begin with 'r', 'w', 'c' or 'n'");
+ return NULL;
+ }
+ if (flag[1] == 'l') {
#if defined(O_EXLOCK) && defined(O_SHLOCK)
- if (flag[0] == 'r')
- flags |= O_SHLOCK;
- else
- flags |= O_EXLOCK;
+ if (flag[0] == 'r')
+ flags |= O_SHLOCK;
+ else
+ flags |= O_EXLOCK;
#else
- PyErr_SetString(BsddbError,
- "locking not supported on this platform");
- return NULL;
+ PyErr_SetString(BsddbError,
+ "locking not supported on this platform");
+ return NULL;
#endif
- }
- }
- return newdbhashobject(file, flags, mode,
- bsize, ffactor, nelem, cachesize, hash, lorder);
+ }
+ }
+ return newdbhashobject(file, flags, mode,
+ bsize, ffactor, nelem, cachesize, hash, lorder);
}
static PyObject *
bsdbtopen(PyObject *self, PyObject *args)
{
- char *file;
- char *flag = NULL;
- int flags = O_RDONLY;
- int mode = 0666;
- int cachesize = 0;
- int maxkeypage = 0;
- int minkeypage = 0;
- int btflags = 0;
- unsigned int psize = 0;
- int lorder = 0;
-
- if (!PyArg_ParseTuple(args, "z|siiiiiii:btopen",
- &file, &flag, &mode,
- &btflags, &cachesize, &maxkeypage, &minkeypage,
- &psize, &lorder))
- return NULL;
- if (flag != NULL) {
- /* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
- if (flag[0] == 'r')
- flags = O_RDONLY;
- else if (flag[0] == 'w')
- flags = O_RDWR;
- else if (flag[0] == 'c')
- flags = O_RDWR|O_CREAT;
- else if (flag[0] == 'n')
- flags = O_RDWR|O_CREAT|O_TRUNC;
- else {
- PyErr_SetString(BsddbError,
- "Flag should begin with 'r', 'w', 'c' or 'n'");
- return NULL;
- }
- if (flag[1] == 'l') {
+ char *file;
+ char *flag = NULL;
+ int flags = O_RDONLY;
+ int mode = 0666;
+ int cachesize = 0;
+ int maxkeypage = 0;
+ int minkeypage = 0;
+ int btflags = 0;
+ unsigned int psize = 0;
+ int lorder = 0;
+
+ if (!PyArg_ParseTuple(args, "z|siiiiiii:btopen",
+ &file, &flag, &mode,
+ &btflags, &cachesize, &maxkeypage, &minkeypage,
+ &psize, &lorder))
+ return NULL;
+ if (flag != NULL) {
+ /* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
+ if (flag[0] == 'r')
+ flags = O_RDONLY;
+ else if (flag[0] == 'w')
+ flags = O_RDWR;
+ else if (flag[0] == 'c')
+ flags = O_RDWR|O_CREAT;
+ else if (flag[0] == 'n')
+ flags = O_RDWR|O_CREAT|O_TRUNC;
+ else {
+ PyErr_SetString(BsddbError,
+ "Flag should begin with 'r', 'w', 'c' or 'n'");
+ return NULL;
+ }
+ if (flag[1] == 'l') {
#if defined(O_EXLOCK) && defined(O_SHLOCK)
- if (flag[0] == 'r')
- flags |= O_SHLOCK;
- else
- flags |= O_EXLOCK;
+ if (flag[0] == 'r')
+ flags |= O_SHLOCK;
+ else
+ flags |= O_EXLOCK;
#else
- PyErr_SetString(BsddbError,
- "locking not supported on this platform");
- return NULL;
+ PyErr_SetString(BsddbError,
+ "locking not supported on this platform");
+ return NULL;
#endif
- }
- }
- return newdbbtobject(file, flags, mode,
- btflags, cachesize, maxkeypage, minkeypage,
- psize, lorder);
+ }
+ }
+ return newdbbtobject(file, flags, mode,
+ btflags, cachesize, maxkeypage, minkeypage,
+ psize, lorder);
}
static PyObject *
bsdrnopen(PyObject *self, PyObject *args)
{
- char *file;
- char *flag = NULL;
- int flags = O_RDONLY;
- int mode = 0666;
- int cachesize = 0;
- int rnflags = 0;
- unsigned int psize = 0;
- int lorder = 0;
- size_t reclen = 0;
- char *bval = "";
- char *bfname = NULL;
-
- if (!PyArg_ParseTuple(args, "z|siiiiiiss:rnopen",
- &file, &flag, &mode,
- &rnflags, &cachesize, &psize, &lorder,
- &reclen, &bval, &bfname))
- return NULL;
-
- if (flag != NULL) {
- /* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
- if (flag[0] == 'r')
- flags = O_RDONLY;
- else if (flag[0] == 'w')
- flags = O_RDWR;
- else if (flag[0] == 'c')
- flags = O_RDWR|O_CREAT;
- else if (flag[0] == 'n')
- flags = O_RDWR|O_CREAT|O_TRUNC;
- else {
- PyErr_SetString(BsddbError,
- "Flag should begin with 'r', 'w', 'c' or 'n'");
- return NULL;
- }
- if (flag[1] == 'l') {
+ char *file;
+ char *flag = NULL;
+ int flags = O_RDONLY;
+ int mode = 0666;
+ int cachesize = 0;
+ int rnflags = 0;
+ unsigned int psize = 0;
+ int lorder = 0;
+ size_t reclen = 0;
+ char *bval = "";
+ char *bfname = NULL;
+
+ if (!PyArg_ParseTuple(args, "z|siiiiiiss:rnopen",
+ &file, &flag, &mode,
+ &rnflags, &cachesize, &psize, &lorder,
+ &reclen, &bval, &bfname))
+ return NULL;
+
+ if (flag != NULL) {
+ /* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
+ if (flag[0] == 'r')
+ flags = O_RDONLY;
+ else if (flag[0] == 'w')
+ flags = O_RDWR;
+ else if (flag[0] == 'c')
+ flags = O_RDWR|O_CREAT;
+ else if (flag[0] == 'n')
+ flags = O_RDWR|O_CREAT|O_TRUNC;
+ else {
+ PyErr_SetString(BsddbError,
+ "Flag should begin with 'r', 'w', 'c' or 'n'");
+ return NULL;
+ }
+ if (flag[1] == 'l') {
#if defined(O_EXLOCK) && defined(O_SHLOCK)
- if (flag[0] == 'r')
- flags |= O_SHLOCK;
- else
- flags |= O_EXLOCK;
+ if (flag[0] == 'r')
+ flags |= O_SHLOCK;
+ else
+ flags |= O_EXLOCK;
#else
- PyErr_SetString(BsddbError,
- "locking not supported on this platform");
- return NULL;
+ PyErr_SetString(BsddbError,
+ "locking not supported on this platform");
+ return NULL;
#endif
- }
- else if (flag[1] != '\0') {
- PyErr_SetString(BsddbError,
- "Flag char 2 should be 'l' or absent");
- return NULL;
- }
- }
- return newdbrnobject(file, flags, mode, rnflags, cachesize,
- psize, lorder, reclen, bval[0], bfname);
+ }
+ else if (flag[1] != '\0') {
+ PyErr_SetString(BsddbError,
+ "Flag char 2 should be 'l' or absent");
+ return NULL;
+ }
+ }
+ return newdbrnobject(file, flags, mode, rnflags, cachesize,
+ psize, lorder, reclen, bval[0], bfname);
}
static PyMethodDef bsddbmodule_methods[] = {
- {"hashopen", (PyCFunction)bsdhashopen, METH_VARARGS},
- {"btopen", (PyCFunction)bsdbtopen, METH_VARARGS},
- {"rnopen", (PyCFunction)bsdrnopen, METH_VARARGS},
- /* strictly for use by dbhhash!!! */
- {"open", (PyCFunction)bsdhashopen, METH_VARARGS},
- {0, 0},
+ {"hashopen", (PyCFunction)bsdhashopen, METH_VARARGS},
+ {"btopen", (PyCFunction)bsdbtopen, METH_VARARGS},
+ {"rnopen", (PyCFunction)bsdrnopen, METH_VARARGS},
+ /* strictly for use by dbhhash!!! */
+ {"open", (PyCFunction)bsdhashopen, METH_VARARGS},
+ {0, 0},
};
PyMODINIT_FUNC
initbsddb185(void) {
- PyObject *m, *d;
+ PyObject *m, *d;
if (PyErr_WarnPy3k("the bsddb185 module has been removed in "
"Python 3.0", 2) < 0)
- return;
-
- Bsddbtype.ob_type = &PyType_Type;
- m = Py_InitModule("bsddb185", bsddbmodule_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- BsddbError = PyErr_NewException("bsddb.error", NULL, NULL);
- if (BsddbError != NULL)
- PyDict_SetItemString(d, "error", BsddbError);
+ return;
+
+ Bsddbtype.ob_type = &PyType_Type;
+ m = Py_InitModule("bsddb185", bsddbmodule_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ BsddbError = PyErr_NewException("bsddb.error", NULL, NULL);
+ if (BsddbError != NULL)
+ PyDict_SetItemString(d, "error", BsddbError);
}
diff --git a/Modules/bz2module.c b/Modules/bz2module.c
index a53d1a5..dcb5dc6 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,53 +91,53 @@ 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
- PyObject *file;
+ PyObject_HEAD
+ PyObject *file;
- 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 */
- int f_softspace; /* Flag used by 'print' command */
+ int f_softspace; /* Flag used by 'print' command */
- int f_univ_newline; /* Handle any newline convention */
- int f_newlinetypes; /* Types of newlines seen */
- int f_skipnextlf; /* Skip next \n */
+ int f_univ_newline; /* Handle any newline convention */
+ int f_newlinetypes; /* Types of newlines seen */
+ int f_skipnextlf; /* Skip next \n */
- 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;
@@ -147,59 +147,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
@@ -218,228 +218,228 @@ 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;
- int newlinetypes = f->f_newlinetypes;
- int skipnextlf = f->f_skipnextlf;
- int univ_newline = f->f_univ_newline;
-
- total_v_size = n > 0 ? n : 100;
- v = PyString_FromStringAndSize((char *)NULL, total_v_size);
- if (v == NULL)
- return NULL;
-
- buf = BUF(v);
- end = buf + total_v_size;
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- while (buf != end) {
- bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1);
- f->pos++;
- if (bytes_read == 0) break;
- if (univ_newline) {
- if (skipnextlf) {
- skipnextlf = 0;
- if (c == '\n') {
- /* Seeing a \n here with skipnextlf true means we
- * saw a \r before.
- */
- newlinetypes |= NEWLINE_CRLF;
- if (bzerror != BZ_OK) break;
- bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1);
- f->pos++;
- if (bytes_read == 0) break;
- } else {
- newlinetypes |= NEWLINE_CR;
- }
- }
- if (c == '\r') {
- skipnextlf = 1;
- c = '\n';
- } else if (c == '\n')
- newlinetypes |= NEWLINE_LF;
- }
- *buf++ = c;
- if (bzerror != BZ_OK || c == '\n') break;
- }
- if (univ_newline && bzerror == BZ_STREAM_END && skipnextlf)
- newlinetypes |= NEWLINE_CR;
- Py_END_ALLOW_THREADS
- f->f_newlinetypes = newlinetypes;
- f->f_skipnextlf = skipnextlf;
- 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 (_PyString_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)
- _PyString_Resize(&v, used_v_size);
- 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;
+ int newlinetypes = f->f_newlinetypes;
+ int skipnextlf = f->f_skipnextlf;
+ int univ_newline = f->f_univ_newline;
+
+ total_v_size = n > 0 ? n : 100;
+ v = PyString_FromStringAndSize((char *)NULL, total_v_size);
+ if (v == NULL)
+ return NULL;
+
+ buf = BUF(v);
+ end = buf + total_v_size;
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ while (buf != end) {
+ bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1);
+ f->pos++;
+ if (bytes_read == 0) break;
+ if (univ_newline) {
+ if (skipnextlf) {
+ skipnextlf = 0;
+ if (c == '\n') {
+ /* Seeing a \n here with skipnextlf true means we
+ * saw a \r before.
+ */
+ newlinetypes |= NEWLINE_CRLF;
+ if (bzerror != BZ_OK) break;
+ bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1);
+ f->pos++;
+ if (bytes_read == 0) break;
+ } else {
+ newlinetypes |= NEWLINE_CR;
+ }
+ }
+ if (c == '\r') {
+ skipnextlf = 1;
+ c = '\n';
+ } else if (c == '\n')
+ newlinetypes |= NEWLINE_LF;
+ }
+ *buf++ = c;
+ if (bzerror != BZ_OK || c == '\n') break;
+ }
+ if (univ_newline && bzerror == BZ_STREAM_END && skipnextlf)
+ newlinetypes |= NEWLINE_CR;
+ Py_END_ALLOW_THREADS
+ f->f_newlinetypes = newlinetypes;
+ f->f_skipnextlf = skipnextlf;
+ 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 (_PyString_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)
+ _PyString_Resize(&v, used_v_size);
+ return v;
}
/* This is a hacked version of Python's
* fileobject.c:Py_UniversalNewlineFread(). */
size_t
Util_UnivNewlineRead(int *bzerror, BZFILE *stream,
- char* buf, size_t n, BZ2FileObject *f)
+ char* buf, size_t n, BZ2FileObject *f)
{
- char *dst = buf;
- int newlinetypes, skipnextlf;
-
- assert(buf != NULL);
- assert(stream != NULL);
-
- if (!f->f_univ_newline)
- return BZ2_bzRead(bzerror, stream, buf, n);
-
- newlinetypes = f->f_newlinetypes;
- skipnextlf = f->f_skipnextlf;
-
- /* Invariant: n is the number of bytes remaining to be filled
- * in the buffer.
- */
- while (n) {
- size_t nread;
- int shortread;
- char *src = dst;
-
- nread = BZ2_bzRead(bzerror, stream, dst, n);
- assert(nread <= n);
- n -= nread; /* assuming 1 byte out for each in; will adjust */
- shortread = n != 0; /* true iff EOF or error */
- while (nread--) {
- char c = *src++;
- if (c == '\r') {
- /* Save as LF and set flag to skip next LF. */
- *dst++ = '\n';
- skipnextlf = 1;
- }
- else if (skipnextlf && c == '\n') {
- /* Skip LF, and remember we saw CR LF. */
- skipnextlf = 0;
- newlinetypes |= NEWLINE_CRLF;
- ++n;
- }
- else {
- /* Normal char to be stored in buffer. Also
- * update the newlinetypes flag if either this
- * is an LF or the previous char was a CR.
- */
- if (c == '\n')
- newlinetypes |= NEWLINE_LF;
- else if (skipnextlf)
- newlinetypes |= NEWLINE_CR;
- *dst++ = c;
- skipnextlf = 0;
- }
- }
- if (shortread) {
- /* If this is EOF, update type flags. */
- if (skipnextlf && *bzerror == BZ_STREAM_END)
- newlinetypes |= NEWLINE_CR;
- break;
- }
- }
- f->f_newlinetypes = newlinetypes;
- f->f_skipnextlf = skipnextlf;
- return dst - buf;
+ char *dst = buf;
+ int newlinetypes, skipnextlf;
+
+ assert(buf != NULL);
+ assert(stream != NULL);
+
+ if (!f->f_univ_newline)
+ return BZ2_bzRead(bzerror, stream, buf, n);
+
+ newlinetypes = f->f_newlinetypes;
+ skipnextlf = f->f_skipnextlf;
+
+ /* Invariant: n is the number of bytes remaining to be filled
+ * in the buffer.
+ */
+ while (n) {
+ size_t nread;
+ int shortread;
+ char *src = dst;
+
+ nread = BZ2_bzRead(bzerror, stream, dst, n);
+ assert(nread <= n);
+ n -= nread; /* assuming 1 byte out for each in; will adjust */
+ shortread = n != 0; /* true iff EOF or error */
+ while (nread--) {
+ char c = *src++;
+ if (c == '\r') {
+ /* Save as LF and set flag to skip next LF. */
+ *dst++ = '\n';
+ skipnextlf = 1;
+ }
+ else if (skipnextlf && c == '\n') {
+ /* Skip LF, and remember we saw CR LF. */
+ skipnextlf = 0;
+ newlinetypes |= NEWLINE_CRLF;
+ ++n;
+ }
+ else {
+ /* Normal char to be stored in buffer. Also
+ * update the newlinetypes flag if either this
+ * is an LF or the previous char was a CR.
+ */
+ if (c == '\n')
+ newlinetypes |= NEWLINE_LF;
+ else if (skipnextlf)
+ newlinetypes |= NEWLINE_CR;
+ *dst++ = c;
+ skipnextlf = 0;
+ }
+ }
+ if (shortread) {
+ /* If this is EOF, update type flags. */
+ if (skipnextlf && *bzerror == BZ_STREAM_END)
+ newlinetypes |= NEWLINE_CR;
+ break;
+ }
+ }
+ f->f_newlinetypes = newlinetypes;
+ f->f_skipnextlf = skipnextlf;
+ return dst - buf;
}
/* 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 = Util_UnivNewlineRead(&bzerror, f->fp, f->f_buf,
- bufsize, f);
- 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 = Util_UnivNewlineRead(&bzerror, f->fp, f->f_buf,
+ bufsize, f);
+ 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
@@ -447,45 +447,45 @@ Util_ReadAhead(BZ2FileObject *f, int bufsize)
static PyStringObject *
Util_ReadAheadGetLineSkip(BZ2FileObject *f, int skip, int bufsize)
{
- PyStringObject* 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 (PyStringObject *)
- PyString_FromStringAndSize(NULL, skip);
- bufptr = memchr(f->f_bufptr, '\n', len);
- if (bufptr != NULL) {
- bufptr++; /* Count the '\n' */
- len = bufptr - f->f_bufptr;
- s = (PyStringObject *)
- PyString_FromStringAndSize(NULL, skip+len);
- if (s == NULL)
- return NULL;
- memcpy(PyString_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(PyString_AS_STRING(s)+skip, bufptr, len);
- PyMem_Free(buf);
- }
- return s;
+ PyStringObject* 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 (PyStringObject *)
+ PyString_FromStringAndSize(NULL, skip);
+ bufptr = memchr(f->f_bufptr, '\n', len);
+ if (bufptr != NULL) {
+ bufptr++; /* Count the '\n' */
+ len = bufptr - f->f_bufptr;
+ s = (PyStringObject *)
+ PyString_FromStringAndSize(NULL, skip+len);
+ if (s == NULL)
+ return NULL;
+ memcpy(PyString_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(PyString_AS_STRING(s)+skip, bufptr, len);
+ PyMem_Free(buf);
+ }
+ return s;
}
/* ===================================================================== */
@@ -502,79 +502,79 @@ 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 = PyString_FromString("");
- 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 = PyString_FromStringAndSize((char *)NULL, buffersize);
- if (ret == NULL)
- goto cleanup;
- bytesread = 0;
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- chunksize = Util_UnivNewlineRead(&bzerror, self->fp,
- BUF(ret)+bytesread,
- buffersize-bytesread,
- self);
- 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 (_PyString_Resize(&ret, buffersize) < 0)
- goto cleanup;
- } else {
- break;
- }
- }
- if (bytesread != buffersize)
- _PyString_Resize(&ret, bytesread);
+ 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 = PyString_FromString("");
+ 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 = PyString_FromStringAndSize((char *)NULL, buffersize);
+ if (ret == NULL)
+ goto cleanup;
+ bytesread = 0;
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ chunksize = Util_UnivNewlineRead(&bzerror, self->fp,
+ BUF(ret)+bytesread,
+ buffersize-bytesread,
+ self);
+ 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 (_PyString_Resize(&ret, buffersize) < 0)
+ goto cleanup;
+ } else {
+ break;
+ }
+ }
+ if (bytesread != buffersize)
+ _PyString_Resize(&ret, bytesread);
cleanup:
- RELEASE_LOCK(self);
- return ret;
+ RELEASE_LOCK(self);
+ return ret;
}
PyDoc_STRVAR(BZ2File_readline__doc__,
@@ -589,37 +589,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 = PyString_FromString("");
- 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 = PyString_FromString("");
- 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 = PyString_FromString("");
+ 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 = PyString_FromString("");
+ 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__,
@@ -634,148 +634,148 @@ 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 = Util_UnivNewlineRead(&bzerror, self->fp,
- buffer+nfilled,
- buffersize-nfilled, self);
- 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 = PyString_FromStringAndSize(
- NULL, buffersize);
- if (big_buffer == NULL)
- goto error;
- buffer = PyString_AS_STRING(big_buffer);
- memcpy(buffer, small_buffer, nfilled);
- }
- else {
- /* Grow the big buffer */
- _PyString_Resize(&big_buffer, buffersize);
- buffer = PyString_AS_STRING(big_buffer);
- }
- continue;
- }
- end = buffer+nfilled+nread;
- q = buffer;
- while (p != NULL) {
- /* Process complete lines */
- p++;
- line = PyString_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 = PyString_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;
- }
- PyString_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 = Util_UnivNewlineRead(&bzerror, self->fp,
+ buffer+nfilled,
+ buffersize-nfilled, self);
+ 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 = PyString_FromStringAndSize(
+ NULL, buffersize);
+ if (big_buffer == NULL)
+ goto error;
+ buffer = PyString_AS_STRING(big_buffer);
+ memcpy(buffer, small_buffer, nfilled);
+ }
+ else {
+ /* Grow the big buffer */
+ _PyString_Resize(&big_buffer, buffersize);
+ buffer = PyString_AS_STRING(big_buffer);
+ }
+ continue;
+ }
+ end = buffer+nfilled+nread;
+ q = buffer;
+ while (p != NULL) {
+ /* Process complete lines */
+ p++;
+ line = PyString_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 = PyString_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;
+ }
+ PyString_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_xreadlines__doc__,
@@ -796,52 +796,52 @@ 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, "s*: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;
- }
-
- self->f_softspace = 0;
-
- 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, "s*: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;
+ }
+
+ self->f_softspace = 0;
+
+ 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__,
@@ -857,124 +857,124 @@ 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 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 (!PyString_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 "
- "strings");
- goto error;
- }
- line = PyString_FromStringAndSize(buffer,
- len);
- if (line == NULL)
- goto error;
- Py_DECREF(v);
- PyList_SET_ITEM(list, i, line);
- }
- }
-
- self->f_softspace = 0;
-
- /* 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 = PyString_GET_SIZE(line);
- BZ2_bzWrite (&bzerror, self->fp,
- PyString_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 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 (!PyString_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 "
+ "strings");
+ goto error;
+ }
+ line = PyString_FromStringAndSize(buffer,
+ len);
+ if (line == NULL)
+ goto error;
+ Py_DECREF(v);
+ PyList_SET_ITEM(list, i, line);
+ }
+ }
+
+ self->f_softspace = 0;
+
+ /* 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 = PyString_GET_SIZE(line);
+ BZ2_bzWrite (&bzerror, self->fp,
+ PyString_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
}
@@ -994,148 +994,148 @@ 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 = PyInt_AsLong(offobj);
+ offset = PyInt_AsLong(offobj);
#else
- offset = PyLong_Check(offobj) ?
- PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
+ offset = PyLong_Check(offobj) ?
+ PyLong_AsLongLong(offobj) : PyInt_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 = Util_UnivNewlineRead(
- &bzerror, self->fp,
- buffer, buffersize,
- self);
- 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 (self->fp) {
- PyFile_DecUseCount((PyFileObject *)self->file);
- self->fp = NULL;
- }
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto cleanup;
- }
- ret = PyObject_CallMethod(self->file, "seek", "(i)", 0);
- if (!ret)
- goto cleanup;
- Py_DECREF(ret);
- ret = NULL;
- self->pos = 0;
- self->fp = BZ2_bzReadOpen(&bzerror, PyFile_AsFile(self->file),
- 0, 0, NULL, 0);
- if (self->fp)
- PyFile_IncUseCount((PyFileObject *)self->file);
- 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 = Util_UnivNewlineRead(&bzerror, self->fp,
- buffer, readsize, self);
- 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 = Util_UnivNewlineRead(
+ &bzerror, self->fp,
+ buffer, buffersize,
+ self);
+ 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 (self->fp) {
+ PyFile_DecUseCount((PyFileObject *)self->file);
+ self->fp = NULL;
+ }
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto cleanup;
+ }
+ ret = PyObject_CallMethod(self->file, "seek", "(i)", 0);
+ if (!ret)
+ goto cleanup;
+ Py_DECREF(ret);
+ ret = NULL;
+ self->pos = 0;
+ self->fp = BZ2_bzReadOpen(&bzerror, PyFile_AsFile(self->file),
+ 0, 0, NULL, 0);
+ if (self->fp)
+ PyFile_IncUseCount((PyFileObject *)self->file);
+ 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 = Util_UnivNewlineRead(&bzerror, self->fp,
+ buffer, readsize, self);
+ 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__,
@@ -1147,22 +1147,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 = PyInt_FromLong(self->pos);
+ ret = PyInt_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__,
@@ -1176,49 +1176,49 @@ than once without error.\n\
static PyObject *
BZ2File_close(BZ2FileObject *self)
{
- PyObject *ret = NULL;
- int bzerror = BZ_OK;
-
- 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;
- }
- if (self->fp) {
- PyFile_DecUseCount((PyFileObject *)self->file);
- self->fp = NULL;
- }
- self->mode = MODE_CLOSED;
- ret = PyObject_CallMethod(self->file, "close", NULL);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- Py_XDECREF(ret);
- ret = NULL;
- }
-
- RELEASE_LOCK(self);
- return ret;
+ PyObject *ret = NULL;
+ int bzerror = BZ_OK;
+
+ 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;
+ }
+ if (self->fp) {
+ PyFile_DecUseCount((PyFileObject *)self->file);
+ self->fp = NULL;
+ }
+ self->mode = MODE_CLOSED;
+ ret = PyObject_CallMethod(self->file, "close", NULL);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ Py_XDECREF(ret);
+ ret = NULL;
+ }
+
+ RELEASE_LOCK(self);
+ return ret;
}
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__},
- {"xreadlines", (PyCFunction)BZ2File_getiter, METH_VARARGS, BZ2File_xreadlines__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__},
- {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__},
+ {"xreadlines", (PyCFunction)BZ2File_getiter, METH_VARARGS, BZ2File_xreadlines__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__},
+ {NULL, NULL} /* sentinel */
};
@@ -1229,60 +1229,60 @@ static PyMethodDef BZ2File_methods[] = {
static PyObject *
BZ2File_get_newlines(BZ2FileObject *self, void *closure)
{
- switch (self->f_newlinetypes) {
- case NEWLINE_UNKNOWN:
- Py_INCREF(Py_None);
- return Py_None;
- case NEWLINE_CR:
- return PyString_FromString("\r");
- case NEWLINE_LF:
- return PyString_FromString("\n");
- case NEWLINE_CR|NEWLINE_LF:
- return Py_BuildValue("(ss)", "\r", "\n");
- case NEWLINE_CRLF:
- return PyString_FromString("\r\n");
- case NEWLINE_CR|NEWLINE_CRLF:
- return Py_BuildValue("(ss)", "\r", "\r\n");
- case NEWLINE_LF|NEWLINE_CRLF:
- return Py_BuildValue("(ss)", "\n", "\r\n");
- case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
- return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
- default:
- PyErr_Format(PyExc_SystemError,
- "Unknown newlines value 0x%x\n",
- self->f_newlinetypes);
- return NULL;
- }
+ switch (self->f_newlinetypes) {
+ case NEWLINE_UNKNOWN:
+ Py_INCREF(Py_None);
+ return Py_None;
+ case NEWLINE_CR:
+ return PyString_FromString("\r");
+ case NEWLINE_LF:
+ return PyString_FromString("\n");
+ case NEWLINE_CR|NEWLINE_LF:
+ return Py_BuildValue("(ss)", "\r", "\n");
+ case NEWLINE_CRLF:
+ return PyString_FromString("\r\n");
+ case NEWLINE_CR|NEWLINE_CRLF:
+ return Py_BuildValue("(ss)", "\r", "\r\n");
+ case NEWLINE_LF|NEWLINE_CRLF:
+ return Py_BuildValue("(ss)", "\n", "\r\n");
+ case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
+ return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
+ default:
+ PyErr_Format(PyExc_SystemError,
+ "Unknown newlines value 0x%x\n",
+ self->f_newlinetypes);
+ return NULL;
+ }
}
static PyObject *
BZ2File_get_closed(BZ2FileObject *self, void *closure)
{
- return PyInt_FromLong(self->mode == MODE_CLOSED);
+ return PyInt_FromLong(self->mode == MODE_CLOSED);
}
static PyObject *
BZ2File_get_mode(BZ2FileObject *self, void *closure)
{
- return PyObject_GetAttrString(self->file, "mode");
+ return PyObject_GetAttrString(self->file, "mode");
}
static PyObject *
BZ2File_get_name(BZ2FileObject *self, void *closure)
{
- return PyObject_GetAttrString(self->file, "name");
+ return PyObject_GetAttrString(self->file, "name");
}
static PyGetSetDef BZ2File_getset[] = {
- {"closed", (getter)BZ2File_get_closed, NULL,
- "True if the file is closed"},
- {"newlines", (getter)BZ2File_get_newlines, NULL,
- "end-of-line convention used in this file"},
- {"mode", (getter)BZ2File_get_mode, NULL,
- "file mode ('r', 'w', or 'U')"},
- {"name", (getter)BZ2File_get_name, NULL,
- "file name"},
- {NULL} /* Sentinel */
+ {"closed", (getter)BZ2File_get_closed, NULL,
+ "True if the file is closed"},
+ {"newlines", (getter)BZ2File_get_newlines, NULL,
+ "end-of-line convention used in this file"},
+ {"mode", (getter)BZ2File_get_mode, NULL,
+ "file mode ('r', 'w', or 'U')"},
+ {"name", (getter)BZ2File_get_name, NULL,
+ "file name"},
+ {NULL} /* Sentinel */
};
@@ -1293,9 +1293,9 @@ static PyGetSetDef BZ2File_getset[] = {
#define OFF(x) offsetof(BZ2FileObject, x)
static PyMemberDef BZ2File_members[] = {
- {"softspace", T_INT, OFF(f_softspace), 0,
- "flag indicating that a space needs to be printed; used by print"},
- {NULL} /* Sentinel */
+ {"softspace", T_INT, OFF(f_softspace), 0,
+ "flag indicating that a space needs to be printed; used by print"},
+ {NULL} /* Sentinel */
};
/* ===================================================================== */
@@ -1304,153 +1304,153 @@ static PyMemberDef BZ2File_members[] = {
static int
BZ2File_init(BZ2FileObject *self, PyObject *args, PyObject *kwargs)
{
- static char *kwlist[] = {"filename", "mode", "buffering",
- "compresslevel", 0};
- PyObject *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, &name, &mode, &buffering,
- &compresslevel))
- return -1;
-
- if (compresslevel < 1 || compresslevel > 9) {
- PyErr_SetString(PyExc_ValueError,
- "compresslevel must be between 1 and 9");
- return -1;
- }
-
- for (;;) {
- int error = 0;
- switch (*mode) {
- case 'r':
- case 'w':
- if (mode_char)
- error = 1;
- mode_char = *mode;
- break;
-
- case 'b':
- break;
-
- case 'U':
+ static char *kwlist[] = {"filename", "mode", "buffering",
+ "compresslevel", 0};
+ PyObject *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, &name, &mode, &buffering,
+ &compresslevel))
+ return -1;
+
+ if (compresslevel < 1 || compresslevel > 9) {
+ PyErr_SetString(PyExc_ValueError,
+ "compresslevel must be between 1 and 9");
+ return -1;
+ }
+
+ for (;;) {
+ int error = 0;
+ switch (*mode) {
+ case 'r':
+ case 'w':
+ if (mode_char)
+ error = 1;
+ mode_char = *mode;
+ break;
+
+ case 'b':
+ break;
+
+ case 'U':
#ifdef __VMS
- self->f_univ_newline = 0;
+ self->f_univ_newline = 0;
#else
- self->f_univ_newline = 1;
+ self->f_univ_newline = 1;
#endif
- break;
-
- default:
- error = 1;
- break;
- }
- if (error) {
- PyErr_Format(PyExc_ValueError,
- "invalid mode char %c", *mode);
- return -1;
- }
- mode++;
- if (*mode == '\0')
- break;
- }
-
- if (mode_char == 0) {
- mode_char = 'r';
- }
-
- mode = (mode_char == 'r') ? "rb" : "wb";
-
- self->file = PyObject_CallFunction((PyObject*)&PyFile_Type, "(Osi)",
- name, mode, buffering);
- if (self->file == NULL)
- return -1;
-
- /* From now on, we have stuff to dealloc, so jump to error label
- * instead of returning */
+ break;
+
+ default:
+ error = 1;
+ break;
+ }
+ if (error) {
+ PyErr_Format(PyExc_ValueError,
+ "invalid mode char %c", *mode);
+ return -1;
+ }
+ mode++;
+ if (*mode == '\0')
+ break;
+ }
+
+ if (mode_char == 0) {
+ mode_char = 'r';
+ }
+
+ mode = (mode_char == 'r') ? "rb" : "wb";
+
+ self->file = PyObject_CallFunction((PyObject*)&PyFile_Type, "(Osi)",
+ name, mode, buffering);
+ if (self->file == NULL)
+ return -1;
+
+ /* 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,
- PyFile_AsFile(self->file),
- 0, 0, NULL, 0);
- else
- self->fp = BZ2_bzWriteOpen(&bzerror,
- PyFile_AsFile(self->file),
- compresslevel, 0, 0);
+ if (mode_char == 'r')
+ self->fp = BZ2_bzReadOpen(&bzerror,
+ PyFile_AsFile(self->file),
+ 0, 0, NULL, 0);
+ else
+ self->fp = BZ2_bzWriteOpen(&bzerror,
+ PyFile_AsFile(self->file),
+ compresslevel, 0, 0);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
- PyFile_IncUseCount((PyFileObject *)self->file);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
+ PyFile_IncUseCount((PyFileObject *)self->file);
- self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE;
+ self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE;
- return 0;
+ return 0;
error:
- Py_CLEAR(self->file);
+ Py_CLEAR(self->file);
#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;
- }
- if (self->fp) {
- PyFile_DecUseCount((PyFileObject *)self->file);
- self->fp = NULL;
- }
- Util_DropReadAhead(self);
- Py_XDECREF(self->file);
- 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;
+ }
+ if (self->fp) {
+ PyFile_DecUseCount((PyFileObject *)self->file);
+ self->fp = NULL;
+ }
+ Util_DropReadAhead(self);
+ Py_XDECREF(self->file);
+ 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(). */
@@ -1458,21 +1458,21 @@ BZ2File_getiter(BZ2FileObject *self)
static PyObject *
BZ2File_iternext(BZ2FileObject *self)
{
- PyStringObject* 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 || PyString_GET_SIZE(ret) == 0) {
- Py_XDECREF(ret);
- return NULL;
- }
- return (PyObject *)ret;
+ PyStringObject* 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 || PyString_GET_SIZE(ret) == 0) {
+ Py_XDECREF(ret);
+ return NULL;
+ }
+ return (PyObject *)ret;
}
/* ===================================================================== */
@@ -1500,46 +1500,46 @@ newlines are available only when reading.\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_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*/
- 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*/
- BZ2File_members, /*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_Del, /*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_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*/
+ 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*/
+ BZ2File_members, /*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_Del, /*tp_free*/
+ 0, /*tp_is_gc*/
};
@@ -1558,76 +1558,76 @@ 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, "s*:compress", &pdata))
- return NULL;
- data = pdata.buf;
- datasize = pdata.len;
-
- if (datasize == 0) {
- PyBuffer_Release(&pdata);
- return PyString_FromString("");
- }
-
- ACQUIRE_LOCK(self);
- if (!self->running) {
- PyErr_SetString(PyExc_ValueError,
- "this object was already flushed");
- goto error;
- }
-
- ret = PyString_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 (_PyString_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));
- }
- }
-
- _PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
-
- 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, "s*:compress", &pdata))
+ return NULL;
+ data = pdata.buf;
+ datasize = pdata.len;
+
+ if (datasize == 0) {
+ PyBuffer_Release(&pdata);
+ return PyString_FromString("");
+ }
+
+ ACQUIRE_LOCK(self);
+ if (!self->running) {
+ PyErr_SetString(PyExc_ValueError,
+ "this object was already flushed");
+ goto error;
+ }
+
+ ret = PyString_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 (_PyString_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));
+ }
+ }
+
+ _PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
+
+ 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__,
@@ -1640,68 +1640,68 @@ 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 = PyString_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 (_PyString_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)
- _PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
-
- 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 = PyString_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 (_PyString_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)
+ _PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
+
+ 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 */
};
@@ -1711,57 +1711,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);
}
@@ -1778,46 +1778,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_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*/
- 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_Del, /*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_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*/
+ 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_Del, /*tp_free*/
+ 0, /*tp_is_gc*/
};
@@ -1828,8 +1828,8 @@ static PyTypeObject BZ2Comp_Type = {
#define OFF(x) offsetof(BZ2DecompObject, x)
static PyMemberDef BZ2Decomp_members[] = {
- {"unused_data", T_OBJECT, OFF(unused_data), RO},
- {NULL} /* Sentinel */
+ {"unused_data", T_OBJECT, OFF(unused_data), RO},
+ {NULL} /* Sentinel */
};
@@ -1849,88 +1849,88 @@ 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, "s*: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 = PyString_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 =
- PyString_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 (_PyString_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)
- _PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
-
- 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, "s*: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 = PyString_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 =
+ PyString_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 (_PyString_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)
+ _PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
+
+ 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 */
};
@@ -1940,55 +1940,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 = PyString_FromString("");
- if (!self->unused_data)
- goto error;
+ self->unused_data = PyString_FromString("");
+ 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);
}
@@ -2004,46 +2004,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_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*/
- 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_Del, /*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_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*/
+ 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_Del, /*tp_free*/
+ 0, /*tp_is_gc*/
};
@@ -2061,88 +2061,88 @@ 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, "s*|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 = PyString_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 (_PyString_Resize(&ret, bufsize) < 0) {
- BZ2_bzCompressEnd(bzs);
- PyBuffer_Release(&pdata);
- Py_DECREF(ret);
- 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)
- _PyString_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs));
- 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, "s*|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 = PyString_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 (_PyString_Resize(&ret, bufsize) < 0) {
+ BZ2_bzCompressEnd(bzs);
+ PyBuffer_Release(&pdata);
+ Py_DECREF(ret);
+ 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)
+ _PyString_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs));
+ BZ2_bzCompressEnd(bzs);
+
+ PyBuffer_Release(&pdata);
+ return ret;
}
PyDoc_STRVAR(bz2_decompress__doc__,
@@ -2155,94 +2155,94 @@ 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, "s*:decompress", &pdata))
- return NULL;
- data = pdata.buf;
- datasize = pdata.len;
-
- if (datasize == 0) {
- PyBuffer_Release(&pdata);
- return PyString_FromString("");
- }
-
- ret = PyString_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 (_PyString_Resize(&ret, bufsize) < 0) {
- BZ2_bzDecompressEnd(bzs);
- PyBuffer_Release(&pdata);
- Py_DECREF(ret);
- 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)
- _PyString_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs));
- 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, "s*:decompress", &pdata))
+ return NULL;
+ data = pdata.buf;
+ datasize = pdata.len;
+
+ if (datasize == 0) {
+ PyBuffer_Release(&pdata);
+ return PyString_FromString("");
+ }
+
+ ret = PyString_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 (_PyString_Resize(&ret, bufsize) < 0) {
+ BZ2_bzDecompressEnd(bzs);
+ PyBuffer_Release(&pdata);
+ Py_DECREF(ret);
+ 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)
+ _PyString_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs));
+ 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 */
};
/* ===================================================================== */
@@ -2258,24 +2258,24 @@ sequential (de)compression.\n\
PyMODINIT_FUNC
initbz2(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 = Py_InitModule3("bz2", bz2_methods, bz2__doc__);
- if (m == NULL)
- return;
+ m = Py_InitModule3("bz2", bz2_methods, bz2__doc__);
+ if (m == NULL)
+ return;
- PyModule_AddObject(m, "__author__", PyString_FromString(__author__));
+ PyModule_AddObject(m, "__author__", PyString_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);
+ Py_INCREF(&BZ2Decomp_Type);
+ PyModule_AddObject(m, "BZ2Decompressor", (PyObject *)&BZ2Decomp_Type);
}
diff --git a/Modules/cPickle.c b/Modules/cPickle.c
index 937329b..d9bfceb 100644
--- a/Modules/cPickle.c
+++ b/Modules/cPickle.c
@@ -72,7 +72,7 @@ PyDoc_STRVAR(cPickle_module_documentation,
#define SETITEMS 'u'
/* Protocol 2. */
-#define PROTO '\x80' /* identify pickle protocol */
+#define PROTO '\x80' /* identify pickle protocol */
#define NEWOBJ '\x81' /* build object by applying cls.__new__ to argtuple */
#define EXT1 '\x82' /* push object from extension registry; 1-byte index */
#define EXT2 '\x83' /* ditto, but 2-byte index */
@@ -131,37 +131,37 @@ static PyObject *__class___str, *__getinitargs___str, *__dict___str,
*__getstate___str, *__setstate___str, *__name___str, *__reduce___str,
*__reduce_ex___str,
*write_str, *append_str,
- *read_str, *readline_str, *__main___str,
+ *read_str, *readline_str, *__main___str,
*dispatch_table_str;
/*************************************************************************
Internal Data type for pickle data. */
typedef struct {
- PyObject_HEAD
- int length; /* number of initial slots in data currently used */
- int size; /* number of slots in data allocated */
- PyObject **data;
+ PyObject_HEAD
+ int length; /* number of initial slots in data currently used */
+ int size; /* number of slots in data allocated */
+ PyObject **data;
} Pdata;
static void
Pdata_dealloc(Pdata *self)
{
- int i;
- PyObject **p;
+ int i;
+ PyObject **p;
- for (i = self->length, p = self->data; --i >= 0; p++) {
- Py_DECREF(*p);
- }
- if (self->data)
- free(self->data);
- PyObject_Del(self);
+ for (i = self->length, p = self->data; --i >= 0; p++) {
+ Py_DECREF(*p);
+ }
+ if (self->data)
+ free(self->data);
+ PyObject_Del(self);
}
static PyTypeObject PdataType = {
- PyVarObject_HEAD_INIT(NULL, 0) "cPickle.Pdata", sizeof(Pdata), 0,
- (destructor)Pdata_dealloc,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0L,0L,0L,0L, ""
+ PyVarObject_HEAD_INIT(NULL, 0) "cPickle.Pdata", sizeof(Pdata), 0,
+ (destructor)Pdata_dealloc,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0L,0L,0L,0L, ""
};
#define Pdata_Check(O) (Py_TYPE(O) == &PdataType)
@@ -169,24 +169,24 @@ static PyTypeObject PdataType = {
static PyObject *
Pdata_New(void)
{
- Pdata *self;
+ Pdata *self;
- if (!(self = PyObject_New(Pdata, &PdataType)))
- return NULL;
- self->size = 8;
- self->length = 0;
- self->data = malloc(self->size * sizeof(PyObject*));
- if (self->data)
- return (PyObject*)self;
- Py_DECREF(self);
- return PyErr_NoMemory();
+ if (!(self = PyObject_New(Pdata, &PdataType)))
+ return NULL;
+ self->size = 8;
+ self->length = 0;
+ self->data = malloc(self->size * sizeof(PyObject*));
+ if (self->data)
+ return (PyObject*)self;
+ Py_DECREF(self);
+ return PyErr_NoMemory();
}
static int
stackUnderflow(void)
{
- PyErr_SetString(UnpicklingError, "unpickling stack underflow");
- return -1;
+ PyErr_SetString(UnpicklingError, "unpickling stack underflow");
+ return -1;
}
/* Retain only the initial clearto items. If clearto >= the current
@@ -195,60 +195,60 @@ stackUnderflow(void)
static int
Pdata_clear(Pdata *self, int clearto)
{
- int i;
- PyObject **p;
+ int i;
+ PyObject **p;
- if (clearto < 0) return stackUnderflow();
- if (clearto >= self->length) return 0;
+ if (clearto < 0) return stackUnderflow();
+ if (clearto >= self->length) return 0;
- for (i = self->length, p = self->data + clearto;
- --i >= clearto;
- p++) {
- Py_CLEAR(*p);
- }
- self->length = clearto;
+ for (i = self->length, p = self->data + clearto;
+ --i >= clearto;
+ p++) {
+ Py_CLEAR(*p);
+ }
+ self->length = clearto;
- return 0;
+ return 0;
}
static int
Pdata_grow(Pdata *self)
{
- int bigger;
- size_t nbytes;
- PyObject **tmp;
-
- bigger = self->size << 1;
- if (bigger <= 0) /* was 0, or new value overflows */
- goto nomemory;
- if ((int)(size_t)bigger != bigger)
- goto nomemory;
- nbytes = (size_t)bigger * sizeof(PyObject *);
- if (nbytes / sizeof(PyObject *) != (size_t)bigger)
- goto nomemory;
- tmp = realloc(self->data, nbytes);
- if (tmp == NULL)
- goto nomemory;
- self->data = tmp;
- self->size = bigger;
- return 0;
+ int bigger;
+ size_t nbytes;
+ PyObject **tmp;
+
+ bigger = self->size << 1;
+ if (bigger <= 0) /* was 0, or new value overflows */
+ goto nomemory;
+ if ((int)(size_t)bigger != bigger)
+ goto nomemory;
+ nbytes = (size_t)bigger * sizeof(PyObject *);
+ if (nbytes / sizeof(PyObject *) != (size_t)bigger)
+ goto nomemory;
+ tmp = realloc(self->data, nbytes);
+ if (tmp == NULL)
+ goto nomemory;
+ self->data = tmp;
+ self->size = bigger;
+ return 0;
nomemory:
- PyErr_NoMemory();
- return -1;
+ PyErr_NoMemory();
+ return -1;
}
/* D is a Pdata*. Pop the topmost element and store it into V, which
* must be an lvalue holding PyObject*. On stack underflow, UnpicklingError
* is raised and V is set to NULL. D and V may be evaluated several times.
*/
-#define PDATA_POP(D, V) { \
- if ((D)->length) \
- (V) = (D)->data[--((D)->length)]; \
- else { \
- PyErr_SetString(UnpicklingError, "bad pickle data"); \
- (V) = NULL; \
- } \
+#define PDATA_POP(D, V) { \
+ if ((D)->length) \
+ (V) = (D)->data[--((D)->length)]; \
+ else { \
+ PyErr_SetString(UnpicklingError, "bad pickle data"); \
+ (V) = NULL; \
+ } \
}
/* PDATA_PUSH and PDATA_APPEND both push rvalue PyObject* O on to Pdata*
@@ -260,55 +260,55 @@ Pdata_grow(Pdata *self)
*/
/* Push O on stack D, giving ownership of O to the stack. */
-#define PDATA_PUSH(D, O, ER) { \
- if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
- Pdata_grow((Pdata*)(D)) < 0) { \
- Py_DECREF(O); \
- return ER; \
- } \
- ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \
+#define PDATA_PUSH(D, O, ER) { \
+ if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
+ Pdata_grow((Pdata*)(D)) < 0) { \
+ Py_DECREF(O); \
+ return ER; \
+ } \
+ ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \
}
/* Push O on stack D, pushing a new reference. */
-#define PDATA_APPEND(D, O, ER) { \
- if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
- Pdata_grow((Pdata*)(D)) < 0) \
- return ER; \
- Py_INCREF(O); \
- ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \
+#define PDATA_APPEND(D, O, ER) { \
+ if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
+ Pdata_grow((Pdata*)(D)) < 0) \
+ return ER; \
+ Py_INCREF(O); \
+ ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \
}
static PyObject *
Pdata_popTuple(Pdata *self, int start)
{
- PyObject *r;
- int i, j, l;
+ PyObject *r;
+ int i, j, l;
- l = self->length-start;
- r = PyTuple_New(l);
- if (r == NULL)
- return NULL;
- for (i = start, j = 0 ; j < l; i++, j++)
- PyTuple_SET_ITEM(r, j, self->data[i]);
+ l = self->length-start;
+ r = PyTuple_New(l);
+ if (r == NULL)
+ return NULL;
+ for (i = start, j = 0 ; j < l; i++, j++)
+ PyTuple_SET_ITEM(r, j, self->data[i]);
- self->length = start;
- return r;
+ self->length = start;
+ return r;
}
static PyObject *
Pdata_popList(Pdata *self, int start)
{
- PyObject *r;
- int i, j, l;
+ PyObject *r;
+ int i, j, l;
- l=self->length-start;
- if (!( r=PyList_New(l))) return NULL;
- for (i=start, j=0 ; j < l; i++, j++)
- PyList_SET_ITEM(r, j, self->data[i]);
+ l=self->length-start;
+ if (!( r=PyList_New(l))) return NULL;
+ for (i=start, j=0 ; j < l; i++, j++)
+ PyList_SET_ITEM(r, j, self->data[i]);
- self->length=start;
- return r;
+ self->length=start;
+ return r;
}
/*************************************************************************/
@@ -331,28 +331,28 @@ Pdata_popList(Pdata *self, int start)
}
typedef struct Picklerobject {
- PyObject_HEAD
- FILE *fp;
- PyObject *write;
- PyObject *file;
- PyObject *memo;
- PyObject *arg;
- PyObject *pers_func;
- PyObject *inst_pers_func;
-
- /* pickle protocol number, >= 0 */
- int proto;
-
- /* bool, true if proto > 0 */
- int bin;
-
- int fast; /* Fast mode doesn't save in memo, don't use if circ ref */
- int (*write_func)(struct Picklerobject *, const char *, Py_ssize_t);
- char *write_buf;
- int buf_size;
- PyObject *dispatch_table;
- int fast_container; /* count nested container dumps */
- PyObject *fast_memo;
+ PyObject_HEAD
+ FILE *fp;
+ PyObject *write;
+ PyObject *file;
+ PyObject *memo;
+ PyObject *arg;
+ PyObject *pers_func;
+ PyObject *inst_pers_func;
+
+ /* pickle protocol number, >= 0 */
+ int proto;
+
+ /* bool, true if proto > 0 */
+ int bin;
+
+ int fast; /* Fast mode doesn't save in memo, don't use if circ ref */
+ int (*write_func)(struct Picklerobject *, const char *, Py_ssize_t);
+ char *write_buf;
+ int buf_size;
+ PyObject *dispatch_table;
+ int fast_container; /* count nested container dumps */
+ PyObject *fast_memo;
} Picklerobject;
#ifndef PY_CPICKLE_FAST_LIMIT
@@ -362,25 +362,25 @@ typedef struct Picklerobject {
static PyTypeObject Picklertype;
typedef struct Unpicklerobject {
- PyObject_HEAD
- FILE *fp;
- PyObject *file;
- PyObject *readline;
- PyObject *read;
- PyObject *memo;
- PyObject *arg;
- Pdata *stack;
- PyObject *mark;
- PyObject *pers_func;
- PyObject *last_string;
- int *marks;
- int num_marks;
- int marks_size;
- Py_ssize_t (*read_func)(struct Unpicklerobject *, char **, Py_ssize_t);
- Py_ssize_t (*readline_func)(struct Unpicklerobject *, char **);
- int buf_size;
- char *buf;
- PyObject *find_class;
+ PyObject_HEAD
+ FILE *fp;
+ PyObject *file;
+ PyObject *readline;
+ PyObject *read;
+ PyObject *memo;
+ PyObject *arg;
+ Pdata *stack;
+ PyObject *mark;
+ PyObject *pers_func;
+ PyObject *last_string;
+ int *marks;
+ int num_marks;
+ int marks_size;
+ Py_ssize_t (*read_func)(struct Unpicklerobject *, char **, Py_ssize_t);
+ Py_ssize_t (*readline_func)(struct Unpicklerobject *, char **);
+ int buf_size;
+ char *buf;
+ PyObject *find_class;
} Unpicklerobject;
static PyTypeObject Unpicklertype;
@@ -393,306 +393,306 @@ static
PyObject *
cPickle_ErrFormat(PyObject *ErrType, char *stringformat, char *format, ...)
{
- va_list va;
- PyObject *args=0, *retval=0;
- va_start(va, format);
-
- if (format) args = Py_VaBuildValue(format, va);
- va_end(va);
- if (format && ! args) return NULL;
- if (stringformat && !(retval=PyString_FromString(stringformat)))
- return NULL;
-
- if (retval) {
- if (args) {
- PyObject *v;
- v=PyString_Format(retval, args);
- Py_DECREF(retval);
- Py_DECREF(args);
- if (! v) return NULL;
- retval=v;
- }
- }
- else
- if (args) retval=args;
- else {
- PyErr_SetObject(ErrType,Py_None);
- return NULL;
- }
- PyErr_SetObject(ErrType,retval);
- Py_DECREF(retval);
- return NULL;
+ va_list va;
+ PyObject *args=0, *retval=0;
+ va_start(va, format);
+
+ if (format) args = Py_VaBuildValue(format, va);
+ va_end(va);
+ if (format && ! args) return NULL;
+ if (stringformat && !(retval=PyString_FromString(stringformat)))
+ return NULL;
+
+ if (retval) {
+ if (args) {
+ PyObject *v;
+ v=PyString_Format(retval, args);
+ Py_DECREF(retval);
+ Py_DECREF(args);
+ if (! v) return NULL;
+ retval=v;
+ }
+ }
+ else
+ if (args) retval=args;
+ else {
+ PyErr_SetObject(ErrType,Py_None);
+ return NULL;
+ }
+ PyErr_SetObject(ErrType,retval);
+ Py_DECREF(retval);
+ return NULL;
}
static int
write_file(Picklerobject *self, const char *s, Py_ssize_t n)
{
- size_t nbyteswritten;
+ size_t nbyteswritten;
- if (s == NULL) {
- return 0;
- }
+ if (s == NULL) {
+ return 0;
+ }
- if (n > INT_MAX) {
- /* String too large */
- return -1;
- }
+ if (n > INT_MAX) {
+ /* String too large */
+ return -1;
+ }
- PyFile_IncUseCount((PyFileObject *)self->file);
- Py_BEGIN_ALLOW_THREADS
- nbyteswritten = fwrite(s, sizeof(char), n, self->fp);
- Py_END_ALLOW_THREADS
- PyFile_DecUseCount((PyFileObject *)self->file);
- if (nbyteswritten != (size_t)n) {
- PyErr_SetFromErrno(PyExc_IOError);
- return -1;
- }
+ PyFile_IncUseCount((PyFileObject *)self->file);
+ Py_BEGIN_ALLOW_THREADS
+ nbyteswritten = fwrite(s, sizeof(char), n, self->fp);
+ Py_END_ALLOW_THREADS
+ PyFile_DecUseCount((PyFileObject *)self->file);
+ if (nbyteswritten != (size_t)n) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
- return (int)n;
+ return (int)n;
}
static int
write_cStringIO(Picklerobject *self, const char *s, Py_ssize_t n)
{
- if (s == NULL) {
- return 0;
- }
+ if (s == NULL) {
+ return 0;
+ }
- if (PycStringIO->cwrite((PyObject *)self->file, s, n) != n) {
- return -1;
- }
+ if (PycStringIO->cwrite((PyObject *)self->file, s, n) != n) {
+ return -1;
+ }
- return (int)n;
+ return (int)n;
}
static int
write_none(Picklerobject *self, const char *s, Py_ssize_t n)
{
- if (s == NULL) return 0;
- if (n > INT_MAX) return -1;
- return (int)n;
+ if (s == NULL) return 0;
+ if (n > INT_MAX) return -1;
+ return (int)n;
}
static int
write_other(Picklerobject *self, const char *s, Py_ssize_t _n)
{
- PyObject *py_str = 0, *junk = 0;
- int n;
-
- if (_n > INT_MAX)
- return -1;
- n = (int)_n;
- if (s == NULL) {
- if (!( self->buf_size )) return 0;
- py_str = PyString_FromStringAndSize(self->write_buf,
- self->buf_size);
- if (!py_str)
- return -1;
- }
- else {
- if (self->buf_size && (n + self->buf_size) > WRITE_BUF_SIZE) {
- if (write_other(self, NULL, 0) < 0)
- return -1;
- }
-
- if (n > WRITE_BUF_SIZE) {
- if (!( py_str =
- PyString_FromStringAndSize(s, n)))
- return -1;
- }
- else {
- memcpy(self->write_buf + self->buf_size, s, n);
- self->buf_size += n;
- return n;
- }
- }
-
- if (self->write) {
- /* object with write method */
- ARG_TUP(self, py_str);
- if (self->arg) {
- junk = PyObject_Call(self->write, self->arg, NULL);
- FREE_ARG_TUP(self);
- }
- if (junk) Py_DECREF(junk);
- else return -1;
- }
- else
- PDATA_PUSH(self->file, py_str, -1);
-
- self->buf_size = 0;
- return n;
+ PyObject *py_str = 0, *junk = 0;
+ int n;
+
+ if (_n > INT_MAX)
+ return -1;
+ n = (int)_n;
+ if (s == NULL) {
+ if (!( self->buf_size )) return 0;
+ py_str = PyString_FromStringAndSize(self->write_buf,
+ self->buf_size);
+ if (!py_str)
+ return -1;
+ }
+ else {
+ if (self->buf_size && (n + self->buf_size) > WRITE_BUF_SIZE) {
+ if (write_other(self, NULL, 0) < 0)
+ return -1;
+ }
+
+ if (n > WRITE_BUF_SIZE) {
+ if (!( py_str =
+ PyString_FromStringAndSize(s, n)))
+ return -1;
+ }
+ else {
+ memcpy(self->write_buf + self->buf_size, s, n);
+ self->buf_size += n;
+ return n;
+ }
+ }
+
+ if (self->write) {
+ /* object with write method */
+ ARG_TUP(self, py_str);
+ if (self->arg) {
+ junk = PyObject_Call(self->write, self->arg, NULL);
+ FREE_ARG_TUP(self);
+ }
+ if (junk) Py_DECREF(junk);
+ else return -1;
+ }
+ else
+ PDATA_PUSH(self->file, py_str, -1);
+
+ self->buf_size = 0;
+ return n;
}
static Py_ssize_t
read_file(Unpicklerobject *self, char **s, Py_ssize_t n)
{
- size_t nbytesread;
+ size_t nbytesread;
- if (self->buf_size == 0) {
- int size;
+ if (self->buf_size == 0) {
+ int size;
- size = ((n < 32) ? 32 : n);
- if (!( self->buf = (char *)malloc(size))) {
- PyErr_NoMemory();
- return -1;
- }
+ size = ((n < 32) ? 32 : n);
+ if (!( self->buf = (char *)malloc(size))) {
+ PyErr_NoMemory();
+ return -1;
+ }
- self->buf_size = size;
- }
- else if (n > self->buf_size) {
- char *newbuf = (char *)realloc(self->buf, n);
- if (!newbuf) {
- PyErr_NoMemory();
- return -1;
- }
- self->buf = newbuf;
- self->buf_size = n;
- }
+ self->buf_size = size;
+ }
+ else if (n > self->buf_size) {
+ char *newbuf = (char *)realloc(self->buf, n);
+ if (!newbuf) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ self->buf = newbuf;
+ self->buf_size = n;
+ }
- PyFile_IncUseCount((PyFileObject *)self->file);
- Py_BEGIN_ALLOW_THREADS
- nbytesread = fread(self->buf, sizeof(char), n, self->fp);
- Py_END_ALLOW_THREADS
- PyFile_DecUseCount((PyFileObject *)self->file);
- if (nbytesread != (size_t)n) {
- if (feof(self->fp)) {
- PyErr_SetNone(PyExc_EOFError);
- return -1;
- }
+ PyFile_IncUseCount((PyFileObject *)self->file);
+ Py_BEGIN_ALLOW_THREADS
+ nbytesread = fread(self->buf, sizeof(char), n, self->fp);
+ Py_END_ALLOW_THREADS
+ PyFile_DecUseCount((PyFileObject *)self->file);
+ if (nbytesread != (size_t)n) {
+ if (feof(self->fp)) {
+ PyErr_SetNone(PyExc_EOFError);
+ return -1;
+ }
- PyErr_SetFromErrno(PyExc_IOError);
- return -1;
- }
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
- *s = self->buf;
+ *s = self->buf;
- return n;
+ return n;
}
static Py_ssize_t
readline_file(Unpicklerobject *self, char **s)
{
- int i;
-
- if (self->buf_size == 0) {
- if (!( self->buf = (char *)malloc(40))) {
- PyErr_NoMemory();
- return -1;
- }
- self->buf_size = 40;
- }
-
- i = 0;
- while (1) {
- int bigger;
- char *newbuf;
- for (; i < (self->buf_size - 1); i++) {
- if (feof(self->fp) ||
- (self->buf[i] = getc(self->fp)) == '\n') {
- self->buf[i + 1] = '\0';
- *s = self->buf;
- return i + 1;
- }
- }
- bigger = self->buf_size << 1;
- if (bigger <= 0) { /* overflow */
- PyErr_NoMemory();
- return -1;
- }
- newbuf = (char *)realloc(self->buf, bigger);
- if (!newbuf) {
- PyErr_NoMemory();
- return -1;
- }
- self->buf = newbuf;
- self->buf_size = bigger;
- }
+ int i;
+
+ if (self->buf_size == 0) {
+ if (!( self->buf = (char *)malloc(40))) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ self->buf_size = 40;
+ }
+
+ i = 0;
+ while (1) {
+ int bigger;
+ char *newbuf;
+ for (; i < (self->buf_size - 1); i++) {
+ if (feof(self->fp) ||
+ (self->buf[i] = getc(self->fp)) == '\n') {
+ self->buf[i + 1] = '\0';
+ *s = self->buf;
+ return i + 1;
+ }
+ }
+ bigger = self->buf_size << 1;
+ if (bigger <= 0) { /* overflow */
+ PyErr_NoMemory();
+ return -1;
+ }
+ newbuf = (char *)realloc(self->buf, bigger);
+ if (!newbuf) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ self->buf = newbuf;
+ self->buf_size = bigger;
+ }
}
static Py_ssize_t
read_cStringIO(Unpicklerobject *self, char **s, Py_ssize_t n)
{
- char *ptr;
+ char *ptr;
- if (PycStringIO->cread((PyObject *)self->file, &ptr, n) != n) {
- PyErr_SetNone(PyExc_EOFError);
- return -1;
- }
+ if (PycStringIO->cread((PyObject *)self->file, &ptr, n) != n) {
+ PyErr_SetNone(PyExc_EOFError);
+ return -1;
+ }
- *s = ptr;
+ *s = ptr;
- return n;
+ return n;
}
static Py_ssize_t
readline_cStringIO(Unpicklerobject *self, char **s)
{
- Py_ssize_t n;
- char *ptr;
+ Py_ssize_t n;
+ char *ptr;
- if ((n = PycStringIO->creadline((PyObject *)self->file, &ptr)) < 0) {
- return -1;
- }
+ if ((n = PycStringIO->creadline((PyObject *)self->file, &ptr)) < 0) {
+ return -1;
+ }
- *s = ptr;
+ *s = ptr;
- return n;
+ return n;
}
static Py_ssize_t
read_other(Unpicklerobject *self, char **s, Py_ssize_t n)
{
- PyObject *bytes, *str=0;
+ PyObject *bytes, *str=0;
- if (!( bytes = PyInt_FromSsize_t(n))) return -1;
+ if (!( bytes = PyInt_FromSsize_t(n))) return -1;
- ARG_TUP(self, bytes);
- if (self->arg) {
- str = PyObject_Call(self->read, self->arg, NULL);
- FREE_ARG_TUP(self);
- }
- if (! str) return -1;
+ ARG_TUP(self, bytes);
+ if (self->arg) {
+ str = PyObject_Call(self->read, self->arg, NULL);
+ FREE_ARG_TUP(self);
+ }
+ if (! str) return -1;
- Py_XDECREF(self->last_string);
- self->last_string = str;
+ Py_XDECREF(self->last_string);
+ self->last_string = str;
- if (! (*s = PyString_AsString(str))) return -1;
+ if (! (*s = PyString_AsString(str))) return -1;
- if (PyString_GET_SIZE(str) != n) {
- PyErr_SetNone(PyExc_EOFError);
- return -1;
- }
+ if (PyString_GET_SIZE(str) != n) {
+ PyErr_SetNone(PyExc_EOFError);
+ return -1;
+ }
- return n;
+ return n;
}
static Py_ssize_t
readline_other(Unpicklerobject *self, char **s)
{
- PyObject *str;
- Py_ssize_t str_size;
+ PyObject *str;
+ Py_ssize_t str_size;
- if (!( str = PyObject_CallObject(self->readline, empty_tuple))) {
- return -1;
- }
+ if (!( str = PyObject_CallObject(self->readline, empty_tuple))) {
+ return -1;
+ }
- if ((str_size = PyString_Size(str)) < 0)
- return -1;
+ if ((str_size = PyString_Size(str)) < 0)
+ return -1;
- Py_XDECREF(self->last_string);
- self->last_string = str;
+ Py_XDECREF(self->last_string);
+ self->last_string = str;
- if (! (*s = PyString_AsString(str)))
- return -1;
+ if (! (*s = PyString_AsString(str)))
+ return -1;
- return str_size;
+ return str_size;
}
/* Copy the first n bytes from s into newly malloc'ed memory, plus a
@@ -702,566 +702,566 @@ readline_other(Unpicklerobject *self, char **s)
static char *
pystrndup(const char *s, int n)
{
- char *r = (char *)malloc(n+1);
- if (r == NULL)
- return (char*)PyErr_NoMemory();
- memcpy(r, s, n);
- r[n] = 0;
- return r;
+ char *r = (char *)malloc(n+1);
+ if (r == NULL)
+ return (char*)PyErr_NoMemory();
+ memcpy(r, s, n);
+ r[n] = 0;
+ return r;
}
static int
get(Picklerobject *self, PyObject *id)
{
- PyObject *value, *mv;
- long c_value;
- char s[30];
- size_t len;
-
- if (!( mv = PyDict_GetItem(self->memo, id))) {
- PyErr_SetObject(PyExc_KeyError, id);
- return -1;
- }
-
- if (!( value = PyTuple_GetItem(mv, 0)))
- return -1;
-
- if (!( PyInt_Check(value))) {
- PyErr_SetString(PicklingError, "no int where int expected in memo");
- return -1;
- }
- c_value = PyInt_AS_LONG((PyIntObject*)value);
-
- if (!self->bin) {
- s[0] = GET;
- PyOS_snprintf(s + 1, sizeof(s) - 1, "%ld\n", c_value);
- len = strlen(s);
- }
- else if (Pdata_Check(self->file)) {
- if (write_other(self, NULL, 0) < 0) return -1;
- PDATA_APPEND(self->file, mv, -1);
- return 0;
- }
- else {
- if (c_value < 256) {
- s[0] = BINGET;
- s[1] = (int)(c_value & 0xff);
- len = 2;
- }
- else {
- s[0] = LONG_BINGET;
- s[1] = (int)(c_value & 0xff);
- s[2] = (int)((c_value >> 8) & 0xff);
- s[3] = (int)((c_value >> 16) & 0xff);
- s[4] = (int)((c_value >> 24) & 0xff);
- len = 5;
- }
- }
-
- if (self->write_func(self, s, len) < 0)
- return -1;
-
- return 0;
+ PyObject *value, *mv;
+ long c_value;
+ char s[30];
+ size_t len;
+
+ if (!( mv = PyDict_GetItem(self->memo, id))) {
+ PyErr_SetObject(PyExc_KeyError, id);
+ return -1;
+ }
+
+ if (!( value = PyTuple_GetItem(mv, 0)))
+ return -1;
+
+ if (!( PyInt_Check(value))) {
+ PyErr_SetString(PicklingError, "no int where int expected in memo");
+ return -1;
+ }
+ c_value = PyInt_AS_LONG((PyIntObject*)value);
+
+ if (!self->bin) {
+ s[0] = GET;
+ PyOS_snprintf(s + 1, sizeof(s) - 1, "%ld\n", c_value);
+ len = strlen(s);
+ }
+ else if (Pdata_Check(self->file)) {
+ if (write_other(self, NULL, 0) < 0) return -1;
+ PDATA_APPEND(self->file, mv, -1);
+ return 0;
+ }
+ else {
+ if (c_value < 256) {
+ s[0] = BINGET;
+ s[1] = (int)(c_value & 0xff);
+ len = 2;
+ }
+ else {
+ s[0] = LONG_BINGET;
+ s[1] = (int)(c_value & 0xff);
+ s[2] = (int)((c_value >> 8) & 0xff);
+ s[3] = (int)((c_value >> 16) & 0xff);
+ s[4] = (int)((c_value >> 24) & 0xff);
+ len = 5;
+ }
+ }
+
+ if (self->write_func(self, s, len) < 0)
+ return -1;
+
+ return 0;
}
static int
put(Picklerobject *self, PyObject *ob)
{
- if (Py_REFCNT(ob) < 2 || self->fast)
- return 0;
+ if (Py_REFCNT(ob) < 2 || self->fast)
+ return 0;
- return put2(self, ob);
+ return put2(self, ob);
}
static int
put2(Picklerobject *self, PyObject *ob)
{
- char c_str[30];
- int p;
- size_t len;
- int res = -1;
- PyObject *py_ob_id = 0, *memo_len = 0, *t = 0;
-
- if (self->fast)
- return 0;
-
- if ((p = PyDict_Size(self->memo)) < 0)
- goto finally;
-
- /* Make sure memo keys are positive! */
- /* XXX Why?
- * XXX And does "positive" really mean non-negative?
- * XXX pickle.py starts with PUT index 0, not 1. This makes for
- * XXX gratuitous differences between the pickling modules.
- */
- p++;
-
- if (!( py_ob_id = PyLong_FromVoidPtr(ob)))
- goto finally;
-
- if (!( memo_len = PyInt_FromLong(p)))
- goto finally;
-
- if (!( t = PyTuple_New(2)))
- goto finally;
-
- PyTuple_SET_ITEM(t, 0, memo_len);
- Py_INCREF(memo_len);
- PyTuple_SET_ITEM(t, 1, ob);
- Py_INCREF(ob);
-
- if (PyDict_SetItem(self->memo, py_ob_id, t) < 0)
- goto finally;
-
- if (!self->bin) {
- c_str[0] = PUT;
- PyOS_snprintf(c_str + 1, sizeof(c_str) - 1, "%d\n", p);
- len = strlen(c_str);
- }
- else if (Pdata_Check(self->file)) {
- if (write_other(self, NULL, 0) < 0) return -1;
- PDATA_APPEND(self->file, memo_len, -1);
- res=0; /* Job well done ;) */
- goto finally;
- }
- else {
- if (p >= 256) {
- c_str[0] = LONG_BINPUT;
- c_str[1] = (int)(p & 0xff);
- c_str[2] = (int)((p >> 8) & 0xff);
- c_str[3] = (int)((p >> 16) & 0xff);
- c_str[4] = (int)((p >> 24) & 0xff);
- len = 5;
- }
- else {
- c_str[0] = BINPUT;
- c_str[1] = p;
- len = 2;
- }
- }
-
- if (self->write_func(self, c_str, len) < 0)
- goto finally;
-
- res = 0;
+ char c_str[30];
+ int p;
+ size_t len;
+ int res = -1;
+ PyObject *py_ob_id = 0, *memo_len = 0, *t = 0;
+
+ if (self->fast)
+ return 0;
+
+ if ((p = PyDict_Size(self->memo)) < 0)
+ goto finally;
+
+ /* Make sure memo keys are positive! */
+ /* XXX Why?
+ * XXX And does "positive" really mean non-negative?
+ * XXX pickle.py starts with PUT index 0, not 1. This makes for
+ * XXX gratuitous differences between the pickling modules.
+ */
+ p++;
+
+ if (!( py_ob_id = PyLong_FromVoidPtr(ob)))
+ goto finally;
+
+ if (!( memo_len = PyInt_FromLong(p)))
+ goto finally;
+
+ if (!( t = PyTuple_New(2)))
+ goto finally;
+
+ PyTuple_SET_ITEM(t, 0, memo_len);
+ Py_INCREF(memo_len);
+ PyTuple_SET_ITEM(t, 1, ob);
+ Py_INCREF(ob);
+
+ if (PyDict_SetItem(self->memo, py_ob_id, t) < 0)
+ goto finally;
+
+ if (!self->bin) {
+ c_str[0] = PUT;
+ PyOS_snprintf(c_str + 1, sizeof(c_str) - 1, "%d\n", p);
+ len = strlen(c_str);
+ }
+ else if (Pdata_Check(self->file)) {
+ if (write_other(self, NULL, 0) < 0) return -1;
+ PDATA_APPEND(self->file, memo_len, -1);
+ res=0; /* Job well done ;) */
+ goto finally;
+ }
+ else {
+ if (p >= 256) {
+ c_str[0] = LONG_BINPUT;
+ c_str[1] = (int)(p & 0xff);
+ c_str[2] = (int)((p >> 8) & 0xff);
+ c_str[3] = (int)((p >> 16) & 0xff);
+ c_str[4] = (int)((p >> 24) & 0xff);
+ len = 5;
+ }
+ else {
+ c_str[0] = BINPUT;
+ c_str[1] = p;
+ len = 2;
+ }
+ }
+
+ if (self->write_func(self, c_str, len) < 0)
+ goto finally;
+
+ res = 0;
finally:
- Py_XDECREF(py_ob_id);
- Py_XDECREF(memo_len);
- Py_XDECREF(t);
+ Py_XDECREF(py_ob_id);
+ Py_XDECREF(memo_len);
+ Py_XDECREF(t);
- return res;
+ return res;
}
static PyObject *
whichmodule(PyObject *global, PyObject *global_name)
{
- Py_ssize_t i, j;
- PyObject *module = 0, *modules_dict = 0,
- *global_name_attr = 0, *name = 0;
+ Py_ssize_t i, j;
+ PyObject *module = 0, *modules_dict = 0,
+ *global_name_attr = 0, *name = 0;
- module = PyObject_GetAttrString(global, "__module__");
- if (module)
- return module;
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- return NULL;
+ module = PyObject_GetAttrString(global, "__module__");
+ if (module)
+ return module;
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ return NULL;
- if (!( modules_dict = PySys_GetObject("modules")))
- return NULL;
+ if (!( modules_dict = PySys_GetObject("modules")))
+ return NULL;
- i = 0;
- while ((j = PyDict_Next(modules_dict, &i, &name, &module))) {
+ i = 0;
+ while ((j = PyDict_Next(modules_dict, &i, &name, &module))) {
- if (PyObject_Compare(name, __main___str)==0) continue;
+ if (PyObject_Compare(name, __main___str)==0) continue;
- global_name_attr = PyObject_GetAttr(module, global_name);
- if (!global_name_attr) {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- return NULL;
- continue;
- }
+ global_name_attr = PyObject_GetAttr(module, global_name);
+ if (!global_name_attr) {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ return NULL;
+ continue;
+ }
- if (global_name_attr != global) {
- Py_DECREF(global_name_attr);
- continue;
- }
+ if (global_name_attr != global) {
+ Py_DECREF(global_name_attr);
+ continue;
+ }
- Py_DECREF(global_name_attr);
+ Py_DECREF(global_name_attr);
- break;
- }
+ break;
+ }
- /* The following implements the rule in pickle.py added in 1.5
- that used __main__ if no module is found. I don't actually
- like this rule. jlf
- */
- if (!j) {
- j=1;
- name=__main___str;
- }
+ /* The following implements the rule in pickle.py added in 1.5
+ that used __main__ if no module is found. I don't actually
+ like this rule. jlf
+ */
+ if (!j) {
+ j=1;
+ name=__main___str;
+ }
- Py_INCREF(name);
- return name;
+ Py_INCREF(name);
+ return name;
}
static int
fast_save_enter(Picklerobject *self, PyObject *obj)
{
- /* if fast_container < 0, we're doing an error exit. */
- if (++self->fast_container >= PY_CPICKLE_FAST_LIMIT) {
- PyObject *key = NULL;
- if (self->fast_memo == NULL) {
- self->fast_memo = PyDict_New();
- if (self->fast_memo == NULL) {
- self->fast_container = -1;
- return 0;
- }
- }
- key = PyLong_FromVoidPtr(obj);
- if (key == NULL)
- return 0;
- if (PyDict_GetItem(self->fast_memo, key)) {
- Py_DECREF(key);
- PyErr_Format(PyExc_ValueError,
- "fast mode: can't pickle cyclic objects "
- "including object type %s at %p",
- Py_TYPE(obj)->tp_name, obj);
- self->fast_container = -1;
- return 0;
- }
- if (PyDict_SetItem(self->fast_memo, key, Py_None) < 0) {
- Py_DECREF(key);
- self->fast_container = -1;
- return 0;
- }
- Py_DECREF(key);
- }
- return 1;
+ /* if fast_container < 0, we're doing an error exit. */
+ if (++self->fast_container >= PY_CPICKLE_FAST_LIMIT) {
+ PyObject *key = NULL;
+ if (self->fast_memo == NULL) {
+ self->fast_memo = PyDict_New();
+ if (self->fast_memo == NULL) {
+ self->fast_container = -1;
+ return 0;
+ }
+ }
+ key = PyLong_FromVoidPtr(obj);
+ if (key == NULL)
+ return 0;
+ if (PyDict_GetItem(self->fast_memo, key)) {
+ Py_DECREF(key);
+ PyErr_Format(PyExc_ValueError,
+ "fast mode: can't pickle cyclic objects "
+ "including object type %s at %p",
+ Py_TYPE(obj)->tp_name, obj);
+ self->fast_container = -1;
+ return 0;
+ }
+ if (PyDict_SetItem(self->fast_memo, key, Py_None) < 0) {
+ Py_DECREF(key);
+ self->fast_container = -1;
+ return 0;
+ }
+ Py_DECREF(key);
+ }
+ return 1;
}
int
fast_save_leave(Picklerobject *self, PyObject *obj)
{
- if (self->fast_container-- >= PY_CPICKLE_FAST_LIMIT) {
- PyObject *key = PyLong_FromVoidPtr(obj);
- if (key == NULL)
- return 0;
- if (PyDict_DelItem(self->fast_memo, key) < 0) {
- Py_DECREF(key);
- return 0;
- }
- Py_DECREF(key);
- }
- return 1;
+ if (self->fast_container-- >= PY_CPICKLE_FAST_LIMIT) {
+ PyObject *key = PyLong_FromVoidPtr(obj);
+ if (key == NULL)
+ return 0;
+ if (PyDict_DelItem(self->fast_memo, key) < 0) {
+ Py_DECREF(key);
+ return 0;
+ }
+ Py_DECREF(key);
+ }
+ return 1;
}
static int
save_none(Picklerobject *self, PyObject *args)
{
- static char none = NONE;
- if (self->write_func(self, &none, 1) < 0)
- return -1;
+ static char none = NONE;
+ if (self->write_func(self, &none, 1) < 0)
+ return -1;
- return 0;
+ return 0;
}
static int
save_bool(Picklerobject *self, PyObject *args)
{
- static const char *buf[2] = {FALSE, TRUE};
- static char len[2] = {sizeof(FALSE)-1, sizeof(TRUE)-1};
- long l = PyInt_AS_LONG((PyIntObject *)args);
+ static const char *buf[2] = {FALSE, TRUE};
+ static char len[2] = {sizeof(FALSE)-1, sizeof(TRUE)-1};
+ long l = PyInt_AS_LONG((PyIntObject *)args);
- if (self->proto >= 2) {
- char opcode = l ? NEWTRUE : NEWFALSE;
- if (self->write_func(self, &opcode, 1) < 0)
- return -1;
- }
- else if (self->write_func(self, buf[l], len[l]) < 0)
- return -1;
- return 0;
+ if (self->proto >= 2) {
+ char opcode = l ? NEWTRUE : NEWFALSE;
+ if (self->write_func(self, &opcode, 1) < 0)
+ return -1;
+ }
+ else if (self->write_func(self, buf[l], len[l]) < 0)
+ return -1;
+ return 0;
}
static int
save_int(Picklerobject *self, PyObject *args)
{
- char c_str[32];
- long l = PyInt_AS_LONG((PyIntObject *)args);
- int len = 0;
+ char c_str[32];
+ long l = PyInt_AS_LONG((PyIntObject *)args);
+ int len = 0;
- if (!self->bin
+ if (!self->bin
#if SIZEOF_LONG > 4
- || l > 0x7fffffffL
- || l < -0x80000000L
+ || l > 0x7fffffffL
+ || l < -0x80000000L
#endif
- ) {
- /* Text-mode pickle, or long too big to fit in the 4-byte
- * signed BININT format: store as a string.
- */
- c_str[0] = INT;
- PyOS_snprintf(c_str + 1, sizeof(c_str) - 1, "%ld\n", l);
- if (self->write_func(self, c_str, strlen(c_str)) < 0)
- return -1;
- }
- else {
- /* Binary pickle and l fits in a signed 4-byte int. */
- c_str[1] = (int)( l & 0xff);
- c_str[2] = (int)((l >> 8) & 0xff);
- c_str[3] = (int)((l >> 16) & 0xff);
- c_str[4] = (int)((l >> 24) & 0xff);
-
- if ((c_str[4] == 0) && (c_str[3] == 0)) {
- if (c_str[2] == 0) {
- c_str[0] = BININT1;
- len = 2;
- }
- else {
- c_str[0] = BININT2;
- len = 3;
- }
- }
- else {
- c_str[0] = BININT;
- len = 5;
- }
-
- if (self->write_func(self, c_str, len) < 0)
- return -1;
- }
-
- return 0;
+ ) {
+ /* Text-mode pickle, or long too big to fit in the 4-byte
+ * signed BININT format: store as a string.
+ */
+ c_str[0] = INT;
+ PyOS_snprintf(c_str + 1, sizeof(c_str) - 1, "%ld\n", l);
+ if (self->write_func(self, c_str, strlen(c_str)) < 0)
+ return -1;
+ }
+ else {
+ /* Binary pickle and l fits in a signed 4-byte int. */
+ c_str[1] = (int)( l & 0xff);
+ c_str[2] = (int)((l >> 8) & 0xff);
+ c_str[3] = (int)((l >> 16) & 0xff);
+ c_str[4] = (int)((l >> 24) & 0xff);
+
+ if ((c_str[4] == 0) && (c_str[3] == 0)) {
+ if (c_str[2] == 0) {
+ c_str[0] = BININT1;
+ len = 2;
+ }
+ else {
+ c_str[0] = BININT2;
+ len = 3;
+ }
+ }
+ else {
+ c_str[0] = BININT;
+ len = 5;
+ }
+
+ if (self->write_func(self, c_str, len) < 0)
+ return -1;
+ }
+
+ return 0;
}
static int
save_long(Picklerobject *self, PyObject *args)
{
- Py_ssize_t size;
- int res = -1;
- PyObject *repr = NULL;
-
- static char l = LONG;
-
- if (self->proto >= 2) {
- /* Linear-time pickling. */
- size_t nbits;
- size_t nbytes;
- unsigned char *pdata;
- char c_str[5];
- int i;
- int sign = _PyLong_Sign(args);
-
- if (sign == 0) {
- /* It's 0 -- an empty bytestring. */
- c_str[0] = LONG1;
- c_str[1] = 0;
- i = self->write_func(self, c_str, 2);
- if (i < 0) goto finally;
- res = 0;
- goto finally;
- }
- nbits = _PyLong_NumBits(args);
- if (nbits == (size_t)-1 && PyErr_Occurred())
- goto finally;
- /* How many bytes do we need? There are nbits >> 3 full
- * bytes of data, and nbits & 7 leftover bits. If there
- * are any leftover bits, then we clearly need another
- * byte. Wnat's not so obvious is that we *probably*
- * need another byte even if there aren't any leftovers:
- * the most-significant bit of the most-significant byte
- * acts like a sign bit, and it's usually got a sense
- * opposite of the one we need. The exception is longs
- * of the form -(2**(8*j-1)) for j > 0. Such a long is
- * its own 256's-complement, so has the right sign bit
- * even without the extra byte. That's a pain to check
- * for in advance, though, so we always grab an extra
- * byte at the start, and cut it back later if possible.
- */
- nbytes = (nbits >> 3) + 1;
- if (nbytes > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError, "long too large "
- "to pickle");
- goto finally;
- }
- repr = PyString_FromStringAndSize(NULL, (int)nbytes);
- if (repr == NULL) goto finally;
- pdata = (unsigned char *)PyString_AS_STRING(repr);
- i = _PyLong_AsByteArray((PyLongObject *)args,
- pdata, nbytes,
- 1 /* little endian */, 1 /* signed */);
- if (i < 0) goto finally;
- /* If the long is negative, this may be a byte more than
- * needed. This is so iff the MSB is all redundant sign
- * bits.
- */
- if (sign < 0 && nbytes > 1 && pdata[nbytes - 1] == 0xff &&
- (pdata[nbytes - 2] & 0x80) != 0)
- --nbytes;
-
- if (nbytes < 256) {
- c_str[0] = LONG1;
- c_str[1] = (char)nbytes;
- size = 2;
- }
- else {
- c_str[0] = LONG4;
- size = (int)nbytes;
- for (i = 1; i < 5; i++) {
- c_str[i] = (char)(size & 0xff);
- size >>= 8;
- }
- size = 5;
- }
- i = self->write_func(self, c_str, size);
- if (i < 0) goto finally;
- i = self->write_func(self, (char *)pdata, (int)nbytes);
- if (i < 0) goto finally;
- res = 0;
- goto finally;
- }
-
- /* proto < 2: write the repr and newline. This is quadratic-time
- * (in the number of digits), in both directions.
- */
- if (!( repr = PyObject_Repr(args)))
- goto finally;
-
- if ((size = PyString_Size(repr)) < 0)
- goto finally;
-
- if (self->write_func(self, &l, 1) < 0)
- goto finally;
-
- if (self->write_func(self,
- PyString_AS_STRING((PyStringObject *)repr),
- size) < 0)
- goto finally;
-
- if (self->write_func(self, "\n", 1) < 0)
- goto finally;
-
- res = 0;
+ Py_ssize_t size;
+ int res = -1;
+ PyObject *repr = NULL;
+
+ static char l = LONG;
+
+ if (self->proto >= 2) {
+ /* Linear-time pickling. */
+ size_t nbits;
+ size_t nbytes;
+ unsigned char *pdata;
+ char c_str[5];
+ int i;
+ int sign = _PyLong_Sign(args);
+
+ if (sign == 0) {
+ /* It's 0 -- an empty bytestring. */
+ c_str[0] = LONG1;
+ c_str[1] = 0;
+ i = self->write_func(self, c_str, 2);
+ if (i < 0) goto finally;
+ res = 0;
+ goto finally;
+ }
+ nbits = _PyLong_NumBits(args);
+ if (nbits == (size_t)-1 && PyErr_Occurred())
+ goto finally;
+ /* How many bytes do we need? There are nbits >> 3 full
+ * bytes of data, and nbits & 7 leftover bits. If there
+ * are any leftover bits, then we clearly need another
+ * byte. Wnat's not so obvious is that we *probably*
+ * need another byte even if there aren't any leftovers:
+ * the most-significant bit of the most-significant byte
+ * acts like a sign bit, and it's usually got a sense
+ * opposite of the one we need. The exception is longs
+ * of the form -(2**(8*j-1)) for j > 0. Such a long is
+ * its own 256's-complement, so has the right sign bit
+ * even without the extra byte. That's a pain to check
+ * for in advance, though, so we always grab an extra
+ * byte at the start, and cut it back later if possible.
+ */
+ nbytes = (nbits >> 3) + 1;
+ if (nbytes > INT_MAX) {
+ PyErr_SetString(PyExc_OverflowError, "long too large "
+ "to pickle");
+ goto finally;
+ }
+ repr = PyString_FromStringAndSize(NULL, (int)nbytes);
+ if (repr == NULL) goto finally;
+ pdata = (unsigned char *)PyString_AS_STRING(repr);
+ i = _PyLong_AsByteArray((PyLongObject *)args,
+ pdata, nbytes,
+ 1 /* little endian */, 1 /* signed */);
+ if (i < 0) goto finally;
+ /* If the long is negative, this may be a byte more than
+ * needed. This is so iff the MSB is all redundant sign
+ * bits.
+ */
+ if (sign < 0 && nbytes > 1 && pdata[nbytes - 1] == 0xff &&
+ (pdata[nbytes - 2] & 0x80) != 0)
+ --nbytes;
+
+ if (nbytes < 256) {
+ c_str[0] = LONG1;
+ c_str[1] = (char)nbytes;
+ size = 2;
+ }
+ else {
+ c_str[0] = LONG4;
+ size = (int)nbytes;
+ for (i = 1; i < 5; i++) {
+ c_str[i] = (char)(size & 0xff);
+ size >>= 8;
+ }
+ size = 5;
+ }
+ i = self->write_func(self, c_str, size);
+ if (i < 0) goto finally;
+ i = self->write_func(self, (char *)pdata, (int)nbytes);
+ if (i < 0) goto finally;
+ res = 0;
+ goto finally;
+ }
+
+ /* proto < 2: write the repr and newline. This is quadratic-time
+ * (in the number of digits), in both directions.
+ */
+ if (!( repr = PyObject_Repr(args)))
+ goto finally;
+
+ if ((size = PyString_Size(repr)) < 0)
+ goto finally;
+
+ if (self->write_func(self, &l, 1) < 0)
+ goto finally;
+
+ if (self->write_func(self,
+ PyString_AS_STRING((PyStringObject *)repr),
+ size) < 0)
+ goto finally;
+
+ if (self->write_func(self, "\n", 1) < 0)
+ goto finally;
+
+ res = 0;
finally:
- Py_XDECREF(repr);
- return res;
+ Py_XDECREF(repr);
+ return res;
}
static int
save_float(Picklerobject *self, PyObject *args)
{
- double x = PyFloat_AS_DOUBLE((PyFloatObject *)args);
+ double x = PyFloat_AS_DOUBLE((PyFloatObject *)args);
- if (self->bin) {
- char str[9];
- str[0] = BINFLOAT;
- if (_PyFloat_Pack8(x, (unsigned char *)&str[1], 0) < 0)
- return -1;
- if (self->write_func(self, str, 9) < 0)
- return -1;
- }
- else {
- char c_str[250];
- c_str[0] = FLOAT;
- PyOS_ascii_formatd(c_str + 1, sizeof(c_str) - 2, "%.17g", x);
- /* Extend the formatted string with a newline character */
- strcat(c_str, "\n");
-
- if (self->write_func(self, c_str, strlen(c_str)) < 0)
- return -1;
- }
+ if (self->bin) {
+ char str[9];
+ str[0] = BINFLOAT;
+ if (_PyFloat_Pack8(x, (unsigned char *)&str[1], 0) < 0)
+ return -1;
+ if (self->write_func(self, str, 9) < 0)
+ return -1;
+ }
+ else {
+ char c_str[250];
+ c_str[0] = FLOAT;
+ PyOS_ascii_formatd(c_str + 1, sizeof(c_str) - 2, "%.17g", x);
+ /* Extend the formatted string with a newline character */
+ strcat(c_str, "\n");
+
+ if (self->write_func(self, c_str, strlen(c_str)) < 0)
+ return -1;
+ }
- return 0;
+ return 0;
}
static int
save_string(Picklerobject *self, PyObject *args, int doput)
{
- int size, len;
- PyObject *repr=0;
-
- if ((size = PyString_Size(args)) < 0)
- return -1;
-
- if (!self->bin) {
- char *repr_str;
-
- static char string = STRING;
-
- if (!( repr = PyObject_Repr(args)))
- return -1;
-
- if ((len = PyString_Size(repr)) < 0)
- goto err;
- repr_str = PyString_AS_STRING((PyStringObject *)repr);
-
- if (self->write_func(self, &string, 1) < 0)
- goto err;
-
- if (self->write_func(self, repr_str, len) < 0)
- goto err;
-
- if (self->write_func(self, "\n", 1) < 0)
- goto err;
-
- Py_XDECREF(repr);
- }
- else {
- int i;
- char c_str[5];
-
- if ((size = PyString_Size(args)) < 0)
- return -1;
-
- if (size < 256) {
- c_str[0] = SHORT_BINSTRING;
- c_str[1] = size;
- len = 2;
- }
- else if (size <= INT_MAX) {
- c_str[0] = BINSTRING;
- for (i = 1; i < 5; i++)
- c_str[i] = (int)(size >> ((i - 1) * 8));
- len = 5;
- }
- else
- return -1; /* string too large */
-
- if (self->write_func(self, c_str, len) < 0)
- return -1;
-
- if (size > 128 && Pdata_Check(self->file)) {
- if (write_other(self, NULL, 0) < 0) return -1;
- PDATA_APPEND(self->file, args, -1);
- }
- else {
- if (self->write_func(self,
- PyString_AS_STRING(
- (PyStringObject *)args),
- size) < 0)
- return -1;
- }
- }
-
- if (doput)
- if (put(self, args) < 0)
- return -1;
-
- return 0;
+ int size, len;
+ PyObject *repr=0;
+
+ if ((size = PyString_Size(args)) < 0)
+ return -1;
+
+ if (!self->bin) {
+ char *repr_str;
+
+ static char string = STRING;
+
+ if (!( repr = PyObject_Repr(args)))
+ return -1;
+
+ if ((len = PyString_Size(repr)) < 0)
+ goto err;
+ repr_str = PyString_AS_STRING((PyStringObject *)repr);
+
+ if (self->write_func(self, &string, 1) < 0)
+ goto err;
+
+ if (self->write_func(self, repr_str, len) < 0)
+ goto err;
+
+ if (self->write_func(self, "\n", 1) < 0)
+ goto err;
+
+ Py_XDECREF(repr);
+ }
+ else {
+ int i;
+ char c_str[5];
+
+ if ((size = PyString_Size(args)) < 0)
+ return -1;
+
+ if (size < 256) {
+ c_str[0] = SHORT_BINSTRING;
+ c_str[1] = size;
+ len = 2;
+ }
+ else if (size <= INT_MAX) {
+ c_str[0] = BINSTRING;
+ for (i = 1; i < 5; i++)
+ c_str[i] = (int)(size >> ((i - 1) * 8));
+ len = 5;
+ }
+ else
+ return -1; /* string too large */
+
+ if (self->write_func(self, c_str, len) < 0)
+ return -1;
+
+ if (size > 128 && Pdata_Check(self->file)) {
+ if (write_other(self, NULL, 0) < 0) return -1;
+ PDATA_APPEND(self->file, args, -1);
+ }
+ else {
+ if (self->write_func(self,
+ PyString_AS_STRING(
+ (PyStringObject *)args),
+ size) < 0)
+ return -1;
+ }
+ }
+
+ if (doput)
+ if (put(self, args) < 0)
+ return -1;
+
+ return 0;
err:
- Py_XDECREF(repr);
- return -1;
+ Py_XDECREF(repr);
+ return -1;
}
@@ -1283,71 +1283,71 @@ modified_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)
#endif
if (size > PY_SSIZE_T_MAX / expandsize)
- return PyErr_NoMemory();
+ return PyErr_NoMemory();
repr = PyString_FromStringAndSize(NULL, expandsize * size);
if (repr == NULL)
- return NULL;
+ return NULL;
if (size == 0)
- return repr;
+ return repr;
p = q = PyString_AS_STRING(repr);
while (size-- > 0) {
- Py_UNICODE ch = *s++;
+ Py_UNICODE ch = *s++;
#ifdef Py_UNICODE_WIDE
- /* Map 32-bit characters to '\Uxxxxxxxx' */
- if (ch >= 0x10000) {
- *p++ = '\\';
- *p++ = 'U';
- *p++ = hexdigit[(ch >> 28) & 0xf];
- *p++ = hexdigit[(ch >> 24) & 0xf];
- *p++ = hexdigit[(ch >> 20) & 0xf];
- *p++ = hexdigit[(ch >> 16) & 0xf];
- *p++ = hexdigit[(ch >> 12) & 0xf];
- *p++ = hexdigit[(ch >> 8) & 0xf];
- *p++ = hexdigit[(ch >> 4) & 0xf];
- *p++ = hexdigit[ch & 15];
- }
- else
+ /* Map 32-bit characters to '\Uxxxxxxxx' */
+ if (ch >= 0x10000) {
+ *p++ = '\\';
+ *p++ = 'U';
+ *p++ = hexdigit[(ch >> 28) & 0xf];
+ *p++ = hexdigit[(ch >> 24) & 0xf];
+ *p++ = hexdigit[(ch >> 20) & 0xf];
+ *p++ = hexdigit[(ch >> 16) & 0xf];
+ *p++ = hexdigit[(ch >> 12) & 0xf];
+ *p++ = hexdigit[(ch >> 8) & 0xf];
+ *p++ = hexdigit[(ch >> 4) & 0xf];
+ *p++ = hexdigit[ch & 15];
+ }
+ else
#else
- /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
- if (ch >= 0xD800 && ch < 0xDC00) {
- Py_UNICODE ch2;
- Py_UCS4 ucs;
-
- ch2 = *s++;
- size--;
- if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
- ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
- *p++ = '\\';
- *p++ = 'U';
- *p++ = hexdigit[(ucs >> 28) & 0xf];
- *p++ = hexdigit[(ucs >> 24) & 0xf];
- *p++ = hexdigit[(ucs >> 20) & 0xf];
- *p++ = hexdigit[(ucs >> 16) & 0xf];
- *p++ = hexdigit[(ucs >> 12) & 0xf];
- *p++ = hexdigit[(ucs >> 8) & 0xf];
- *p++ = hexdigit[(ucs >> 4) & 0xf];
- *p++ = hexdigit[ucs & 0xf];
- continue;
- }
- /* Fall through: isolated surrogates are copied as-is */
- s--;
- size++;
- }
+ /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
+ if (ch >= 0xD800 && ch < 0xDC00) {
+ Py_UNICODE ch2;
+ Py_UCS4 ucs;
+
+ ch2 = *s++;
+ size--;
+ if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
+ ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
+ *p++ = '\\';
+ *p++ = 'U';
+ *p++ = hexdigit[(ucs >> 28) & 0xf];
+ *p++ = hexdigit[(ucs >> 24) & 0xf];
+ *p++ = hexdigit[(ucs >> 20) & 0xf];
+ *p++ = hexdigit[(ucs >> 16) & 0xf];
+ *p++ = hexdigit[(ucs >> 12) & 0xf];
+ *p++ = hexdigit[(ucs >> 8) & 0xf];
+ *p++ = hexdigit[(ucs >> 4) & 0xf];
+ *p++ = hexdigit[ucs & 0xf];
+ continue;
+ }
+ /* Fall through: isolated surrogates are copied as-is */
+ s--;
+ size++;
+ }
#endif
- /* Map 16-bit characters to '\uxxxx' */
- if (ch >= 256 || ch == '\\' || ch == '\n') {
- *p++ = '\\';
- *p++ = 'u';
- *p++ = hexdigit[(ch >> 12) & 0xf];
- *p++ = hexdigit[(ch >> 8) & 0xf];
- *p++ = hexdigit[(ch >> 4) & 0xf];
- *p++ = hexdigit[ch & 15];
- }
- /* Copy everything else as-is */
- else
- *p++ = (char) ch;
+ /* Map 16-bit characters to '\uxxxx' */
+ if (ch >= 256 || ch == '\\' || ch == '\n') {
+ *p++ = '\\';
+ *p++ = 'u';
+ *p++ = hexdigit[(ch >> 12) & 0xf];
+ *p++ = hexdigit[(ch >> 8) & 0xf];
+ *p++ = hexdigit[(ch >> 4) & 0xf];
+ *p++ = hexdigit[ch & 15];
+ }
+ /* Copy everything else as-is */
+ else
+ *p++ = (char) ch;
}
*p = '\0';
_PyString_Resize(&repr, p - q);
@@ -1357,79 +1357,79 @@ modified_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)
static int
save_unicode(Picklerobject *self, PyObject *args, int doput)
{
- Py_ssize_t size, len;
- PyObject *repr=0;
-
- if (!PyUnicode_Check(args))
- return -1;
-
- if (!self->bin) {
- char *repr_str;
- static char string = UNICODE;
-
- repr = modified_EncodeRawUnicodeEscape(
- PyUnicode_AS_UNICODE(args), PyUnicode_GET_SIZE(args));
- if (!repr)
- return -1;
+ Py_ssize_t size, len;
+ PyObject *repr=0;
- if ((len = PyString_Size(repr)) < 0)
- goto err;
- repr_str = PyString_AS_STRING((PyStringObject *)repr);
+ if (!PyUnicode_Check(args))
+ return -1;
- if (self->write_func(self, &string, 1) < 0)
- goto err;
+ if (!self->bin) {
+ char *repr_str;
+ static char string = UNICODE;
- if (self->write_func(self, repr_str, len) < 0)
- goto err;
+ repr = modified_EncodeRawUnicodeEscape(
+ PyUnicode_AS_UNICODE(args), PyUnicode_GET_SIZE(args));
+ if (!repr)
+ return -1;
- if (self->write_func(self, "\n", 1) < 0)
- goto err;
+ if ((len = PyString_Size(repr)) < 0)
+ goto err;
+ repr_str = PyString_AS_STRING((PyStringObject *)repr);
- Py_XDECREF(repr);
- }
- else {
- int i;
- char c_str[5];
+ if (self->write_func(self, &string, 1) < 0)
+ goto err;
- if (!( repr = PyUnicode_AsUTF8String(args)))
- return -1;
+ if (self->write_func(self, repr_str, len) < 0)
+ goto err;
- if ((size = PyString_Size(repr)) < 0)
- goto err;
- if (size > INT_MAX)
- return -1; /* string too large */
+ if (self->write_func(self, "\n", 1) < 0)
+ goto err;
- c_str[0] = BINUNICODE;
- for (i = 1; i < 5; i++)
- c_str[i] = (int)(size >> ((i - 1) * 8));
- len = 5;
-
- if (self->write_func(self, c_str, len) < 0)
- goto err;
-
- if (size > 128 && Pdata_Check(self->file)) {
- if (write_other(self, NULL, 0) < 0)
- goto err;
- PDATA_APPEND(self->file, repr, -1);
- }
- else {
- if (self->write_func(self, PyString_AS_STRING(repr),
- size) < 0)
- goto err;
- }
+ Py_XDECREF(repr);
+ }
+ else {
+ int i;
+ char c_str[5];
+
+ if (!( repr = PyUnicode_AsUTF8String(args)))
+ return -1;
+
+ if ((size = PyString_Size(repr)) < 0)
+ goto err;
+ if (size > INT_MAX)
+ return -1; /* string too large */
+
+ c_str[0] = BINUNICODE;
+ for (i = 1; i < 5; i++)
+ c_str[i] = (int)(size >> ((i - 1) * 8));
+ len = 5;
+
+ if (self->write_func(self, c_str, len) < 0)
+ goto err;
+
+ if (size > 128 && Pdata_Check(self->file)) {
+ if (write_other(self, NULL, 0) < 0)
+ goto err;
+ PDATA_APPEND(self->file, repr, -1);
+ }
+ else {
+ if (self->write_func(self, PyString_AS_STRING(repr),
+ size) < 0)
+ goto err;
+ }
- Py_DECREF(repr);
- }
+ Py_DECREF(repr);
+ }
- if (doput)
- if (put(self, args) < 0)
- return -1;
+ if (doput)
+ if (put(self, args) < 0)
+ return -1;
- return 0;
+ return 0;
err:
- Py_XDECREF(repr);
- return -1;
+ Py_XDECREF(repr);
+ return -1;
}
#endif
@@ -1437,23 +1437,23 @@ save_unicode(Picklerobject *self, PyObject *args, int doput)
static int
store_tuple_elements(Picklerobject *self, PyObject *t, int len)
{
- int i;
- int res = -1; /* guilty until proved innocent */
+ int i;
+ int res = -1; /* guilty until proved innocent */
- assert(PyTuple_Size(t) == len);
+ assert(PyTuple_Size(t) == len);
- for (i = 0; i < len; i++) {
- PyObject *element = PyTuple_GET_ITEM(t, i);
+ for (i = 0; i < len; i++) {
+ PyObject *element = PyTuple_GET_ITEM(t, i);
- if (element == NULL)
- goto finally;
- if (save(self, element, 0) < 0)
- goto finally;
- }
- res = 0;
+ if (element == NULL)
+ goto finally;
+ if (save(self, element, 0) < 0)
+ goto finally;
+ }
+ res = 0;
finally:
- return res;
+ return res;
}
/* Tuples are ubiquitous in the pickle protocols, so many techniques are
@@ -1465,108 +1465,108 @@ store_tuple_elements(Picklerobject *self, PyObject *t, int len)
static int
save_tuple(Picklerobject *self, PyObject *args)
{
- PyObject *py_tuple_id = NULL;
- int len, i;
- int res = -1;
-
- static char tuple = TUPLE;
- static char pop = POP;
- static char pop_mark = POP_MARK;
- static char len2opcode[] = {EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3};
-
- if ((len = PyTuple_Size(args)) < 0)
- goto finally;
-
- if (len == 0) {
- char c_str[2];
-
- if (self->proto) {
- c_str[0] = EMPTY_TUPLE;
- len = 1;
- }
- else {
- c_str[0] = MARK;
- c_str[1] = TUPLE;
- len = 2;
- }
- if (self->write_func(self, c_str, len) >= 0)
- res = 0;
- /* Don't memoize an empty tuple. */
- goto finally;
- }
-
- /* A non-empty tuple. */
-
- /* id(tuple) isn't in the memo now. If it shows up there after
- * saving the tuple elements, the tuple must be recursive, in
- * which case we'll pop everything we put on the stack, and fetch
- * its value from the memo.
- */
- py_tuple_id = PyLong_FromVoidPtr(args);
- if (py_tuple_id == NULL)
- goto finally;
-
- if (len <= 3 && self->proto >= 2) {
- /* Use TUPLE{1,2,3} opcodes. */
- if (store_tuple_elements(self, args, len) < 0)
- goto finally;
- if (PyDict_GetItem(self->memo, py_tuple_id)) {
- /* pop the len elements */
- for (i = 0; i < len; ++i)
- if (self->write_func(self, &pop, 1) < 0)
- goto finally;
- /* fetch from memo */
- if (get(self, py_tuple_id) < 0)
- goto finally;
- res = 0;
- goto finally;
- }
- /* Not recursive. */
- if (self->write_func(self, len2opcode + len, 1) < 0)
- goto finally;
- goto memoize;
- }
-
- /* proto < 2 and len > 0, or proto >= 2 and len > 3.
- * Generate MARK elt1 elt2 ... TUPLE
- */
- if (self->write_func(self, &MARKv, 1) < 0)
- goto finally;
-
- if (store_tuple_elements(self, args, len) < 0)
- goto finally;
-
- if (PyDict_GetItem(self->memo, py_tuple_id)) {
- /* pop the stack stuff we pushed */
- if (self->bin) {
- if (self->write_func(self, &pop_mark, 1) < 0)
- goto finally;
- }
- else {
- /* Note that we pop one more than len, to remove
- * the MARK too.
- */
- for (i = 0; i <= len; i++)
- if (self->write_func(self, &pop, 1) < 0)
- goto finally;
- }
- /* fetch from memo */
- if (get(self, py_tuple_id) >= 0)
- res = 0;
- goto finally;
- }
-
- /* Not recursive. */
- if (self->write_func(self, &tuple, 1) < 0)
- goto finally;
+ PyObject *py_tuple_id = NULL;
+ int len, i;
+ int res = -1;
+
+ static char tuple = TUPLE;
+ static char pop = POP;
+ static char pop_mark = POP_MARK;
+ static char len2opcode[] = {EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3};
+
+ if ((len = PyTuple_Size(args)) < 0)
+ goto finally;
+
+ if (len == 0) {
+ char c_str[2];
+
+ if (self->proto) {
+ c_str[0] = EMPTY_TUPLE;
+ len = 1;
+ }
+ else {
+ c_str[0] = MARK;
+ c_str[1] = TUPLE;
+ len = 2;
+ }
+ if (self->write_func(self, c_str, len) >= 0)
+ res = 0;
+ /* Don't memoize an empty tuple. */
+ goto finally;
+ }
+
+ /* A non-empty tuple. */
+
+ /* id(tuple) isn't in the memo now. If it shows up there after
+ * saving the tuple elements, the tuple must be recursive, in
+ * which case we'll pop everything we put on the stack, and fetch
+ * its value from the memo.
+ */
+ py_tuple_id = PyLong_FromVoidPtr(args);
+ if (py_tuple_id == NULL)
+ goto finally;
+
+ if (len <= 3 && self->proto >= 2) {
+ /* Use TUPLE{1,2,3} opcodes. */
+ if (store_tuple_elements(self, args, len) < 0)
+ goto finally;
+ if (PyDict_GetItem(self->memo, py_tuple_id)) {
+ /* pop the len elements */
+ for (i = 0; i < len; ++i)
+ if (self->write_func(self, &pop, 1) < 0)
+ goto finally;
+ /* fetch from memo */
+ if (get(self, py_tuple_id) < 0)
+ goto finally;
+ res = 0;
+ goto finally;
+ }
+ /* Not recursive. */
+ if (self->write_func(self, len2opcode + len, 1) < 0)
+ goto finally;
+ goto memoize;
+ }
+
+ /* proto < 2 and len > 0, or proto >= 2 and len > 3.
+ * Generate MARK elt1 elt2 ... TUPLE
+ */
+ if (self->write_func(self, &MARKv, 1) < 0)
+ goto finally;
+
+ if (store_tuple_elements(self, args, len) < 0)
+ goto finally;
+
+ if (PyDict_GetItem(self->memo, py_tuple_id)) {
+ /* pop the stack stuff we pushed */
+ if (self->bin) {
+ if (self->write_func(self, &pop_mark, 1) < 0)
+ goto finally;
+ }
+ else {
+ /* Note that we pop one more than len, to remove
+ * the MARK too.
+ */
+ for (i = 0; i <= len; i++)
+ if (self->write_func(self, &pop, 1) < 0)
+ goto finally;
+ }
+ /* fetch from memo */
+ if (get(self, py_tuple_id) >= 0)
+ res = 0;
+ goto finally;
+ }
+
+ /* Not recursive. */
+ if (self->write_func(self, &tuple, 1) < 0)
+ goto finally;
memoize:
- if (put(self, args) >= 0)
- res = 0;
+ if (put(self, args) >= 0)
+ res = 0;
finally:
- Py_XDECREF(py_tuple_id);
- return res;
+ Py_XDECREF(py_tuple_id);
+ return res;
}
/* iter is an iterator giving items, and we batch up chunks of
@@ -1578,157 +1578,157 @@ save_tuple(Picklerobject *self, PyObject *args)
static int
batch_list(Picklerobject *self, PyObject *iter)
{
- PyObject *obj = NULL;
- PyObject *firstitem = NULL;
- int i, n;
-
- static char append = APPEND;
- static char appends = APPENDS;
-
- assert(iter != NULL);
-
- if (self->proto == 0) {
- /* APPENDS isn't available; do one at a time. */
- for (;;) {
- obj = PyIter_Next(iter);
- if (obj == NULL) {
- if (PyErr_Occurred())
- return -1;
- break;
- }
- i = save(self, obj, 0);
- Py_DECREF(obj);
- if (i < 0)
- return -1;
- if (self->write_func(self, &append, 1) < 0)
- return -1;
- }
- return 0;
- }
-
- /* proto > 0: write in batches of BATCHSIZE. */
- do {
- /* Get first item */
- firstitem = PyIter_Next(iter);
- if (firstitem == NULL) {
- if (PyErr_Occurred())
- goto BatchFailed;
-
- /* nothing more to add */
- break;
- }
-
- /* Try to get a second item */
- obj = PyIter_Next(iter);
- if (obj == NULL) {
- if (PyErr_Occurred())
- goto BatchFailed;
-
- /* Only one item to write */
- if (save(self, firstitem, 0) < 0)
- goto BatchFailed;
- if (self->write_func(self, &append, 1) < 0)
- goto BatchFailed;
- Py_CLEAR(firstitem);
- break;
- }
-
- /* More than one item to write */
-
- /* Pump out MARK, items, APPENDS. */
- if (self->write_func(self, &MARKv, 1) < 0)
- goto BatchFailed;
-
- if (save(self, firstitem, 0) < 0)
- goto BatchFailed;
- Py_CLEAR(firstitem);
- n = 1;
-
- /* Fetch and save up to BATCHSIZE items */
- while (obj) {
- if (save(self, obj, 0) < 0)
- goto BatchFailed;
- Py_CLEAR(obj);
- n += 1;
-
- if (n == BATCHSIZE)
- break;
-
- obj = PyIter_Next(iter);
- if (obj == NULL) {
- if (PyErr_Occurred())
- goto BatchFailed;
- break;
- }
- }
-
- if (self->write_func(self, &appends, 1) < 0)
- goto BatchFailed;
-
- } while (n == BATCHSIZE);
- return 0;
+ PyObject *obj = NULL;
+ PyObject *firstitem = NULL;
+ int i, n;
+
+ static char append = APPEND;
+ static char appends = APPENDS;
+
+ assert(iter != NULL);
+
+ if (self->proto == 0) {
+ /* APPENDS isn't available; do one at a time. */
+ for (;;) {
+ obj = PyIter_Next(iter);
+ if (obj == NULL) {
+ if (PyErr_Occurred())
+ return -1;
+ break;
+ }
+ i = save(self, obj, 0);
+ Py_DECREF(obj);
+ if (i < 0)
+ return -1;
+ if (self->write_func(self, &append, 1) < 0)
+ return -1;
+ }
+ return 0;
+ }
+
+ /* proto > 0: write in batches of BATCHSIZE. */
+ do {
+ /* Get first item */
+ firstitem = PyIter_Next(iter);
+ if (firstitem == NULL) {
+ if (PyErr_Occurred())
+ goto BatchFailed;
+
+ /* nothing more to add */
+ break;
+ }
+
+ /* Try to get a second item */
+ obj = PyIter_Next(iter);
+ if (obj == NULL) {
+ if (PyErr_Occurred())
+ goto BatchFailed;
+
+ /* Only one item to write */
+ if (save(self, firstitem, 0) < 0)
+ goto BatchFailed;
+ if (self->write_func(self, &append, 1) < 0)
+ goto BatchFailed;
+ Py_CLEAR(firstitem);
+ break;
+ }
+
+ /* More than one item to write */
+
+ /* Pump out MARK, items, APPENDS. */
+ if (self->write_func(self, &MARKv, 1) < 0)
+ goto BatchFailed;
+
+ if (save(self, firstitem, 0) < 0)
+ goto BatchFailed;
+ Py_CLEAR(firstitem);
+ n = 1;
+
+ /* Fetch and save up to BATCHSIZE items */
+ while (obj) {
+ if (save(self, obj, 0) < 0)
+ goto BatchFailed;
+ Py_CLEAR(obj);
+ n += 1;
+
+ if (n == BATCHSIZE)
+ break;
+
+ obj = PyIter_Next(iter);
+ if (obj == NULL) {
+ if (PyErr_Occurred())
+ goto BatchFailed;
+ break;
+ }
+ }
+
+ if (self->write_func(self, &appends, 1) < 0)
+ goto BatchFailed;
+
+ } while (n == BATCHSIZE);
+ return 0;
BatchFailed:
- Py_XDECREF(firstitem);
- Py_XDECREF(obj);
- return -1;
+ Py_XDECREF(firstitem);
+ Py_XDECREF(obj);
+ return -1;
}
static int
save_list(Picklerobject *self, PyObject *args)
{
- int res = -1;
- char s[3];
- int len;
- PyObject *iter;
-
- if (self->fast && !fast_save_enter(self, args))
- goto finally;
-
- /* Create an empty list. */
- if (self->bin) {
- s[0] = EMPTY_LIST;
- len = 1;
- }
- else {
- s[0] = MARK;
- s[1] = LIST;
- len = 2;
- }
-
- if (self->write_func(self, s, len) < 0)
- goto finally;
-
- /* Get list length, and bow out early if empty. */
- if ((len = PyList_Size(args)) < 0)
- goto finally;
-
- /* Memoize. */
- if (len == 0) {
- if (put(self, args) >= 0)
- res = 0;
- goto finally;
- }
- if (put2(self, args) < 0)
- goto finally;
-
- /* Materialize the list elements. */
- iter = PyObject_GetIter(args);
- if (iter == NULL)
- goto finally;
-
- if (Py_EnterRecursiveCall(" while pickling an object") == 0)
- {
- res = batch_list(self, iter);
- Py_LeaveRecursiveCall();
- }
- Py_DECREF(iter);
+ int res = -1;
+ char s[3];
+ int len;
+ PyObject *iter;
+
+ if (self->fast && !fast_save_enter(self, args))
+ goto finally;
+
+ /* Create an empty list. */
+ if (self->bin) {
+ s[0] = EMPTY_LIST;
+ len = 1;
+ }
+ else {
+ s[0] = MARK;
+ s[1] = LIST;
+ len = 2;
+ }
+
+ if (self->write_func(self, s, len) < 0)
+ goto finally;
+
+ /* Get list length, and bow out early if empty. */
+ if ((len = PyList_Size(args)) < 0)
+ goto finally;
+
+ /* Memoize. */
+ if (len == 0) {
+ if (put(self, args) >= 0)
+ res = 0;
+ goto finally;
+ }
+ if (put2(self, args) < 0)
+ goto finally;
+
+ /* Materialize the list elements. */
+ iter = PyObject_GetIter(args);
+ if (iter == NULL)
+ goto finally;
+
+ if (Py_EnterRecursiveCall(" while pickling an object") == 0)
+ {
+ res = batch_list(self, iter);
+ Py_LeaveRecursiveCall();
+ }
+ Py_DECREF(iter);
finally:
- if (self->fast && !fast_save_leave(self, args))
- res = -1;
+ if (self->fast && !fast_save_leave(self, args))
+ res = -1;
- return res;
+ return res;
}
@@ -1746,523 +1746,523 @@ save_list(Picklerobject *self, PyObject *args)
static int
batch_dict(Picklerobject *self, PyObject *iter)
{
- PyObject *p = NULL;
- PyObject *firstitem = NULL;
- int i, n;
-
- static char setitem = SETITEM;
- static char setitems = SETITEMS;
-
- assert(iter != NULL);
-
- if (self->proto == 0) {
- /* SETITEMS isn't available; do one at a time. */
- for (;;) {
- p = PyIter_Next(iter);
- if (p == NULL) {
- if (PyErr_Occurred())
- return -1;
- break;
- }
- if (!PyTuple_Check(p) || PyTuple_Size(p) != 2) {
- PyErr_SetString(PyExc_TypeError, "dict items "
- "iterator must return 2-tuples");
- return -1;
- }
- i = save(self, PyTuple_GET_ITEM(p, 0), 0);
- if (i >= 0)
- i = save(self, PyTuple_GET_ITEM(p, 1), 0);
- Py_DECREF(p);
- if (i < 0)
- return -1;
- if (self->write_func(self, &setitem, 1) < 0)
- return -1;
- }
- return 0;
- }
-
- /* proto > 0: write in batches of BATCHSIZE. */
- do {
- /* Get first item */
- firstitem = PyIter_Next(iter);
- if (firstitem == NULL) {
- if (PyErr_Occurred())
- goto BatchFailed;
-
- /* nothing more to add */
- break;
- }
- if (!PyTuple_Check(firstitem) || PyTuple_Size(firstitem) != 2) {
- PyErr_SetString(PyExc_TypeError, "dict items "
- "iterator must return 2-tuples");
- goto BatchFailed;
- }
-
- /* Try to get a second item */
- p = PyIter_Next(iter);
- if (p == NULL) {
- if (PyErr_Occurred())
- goto BatchFailed;
-
- /* Only one item to write */
- if (save(self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0)
- goto BatchFailed;
- if (save(self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0)
- goto BatchFailed;
- if (self->write_func(self, &setitem, 1) < 0)
- goto BatchFailed;
- Py_CLEAR(firstitem);
- break;
- }
-
- /* More than one item to write */
-
- /* Pump out MARK, items, SETITEMS. */
- if (self->write_func(self, &MARKv, 1) < 0)
- goto BatchFailed;
-
- if (save(self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0)
- goto BatchFailed;
- if (save(self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0)
- goto BatchFailed;
- Py_CLEAR(firstitem);
- n = 1;
-
- /* Fetch and save up to BATCHSIZE items */
- while (p) {
- if (!PyTuple_Check(p) || PyTuple_Size(p) != 2) {
- PyErr_SetString(PyExc_TypeError, "dict items "
- "iterator must return 2-tuples");
- goto BatchFailed;
- }
- if (save(self, PyTuple_GET_ITEM(p, 0), 0) < 0)
- goto BatchFailed;
- if (save(self, PyTuple_GET_ITEM(p, 1), 0) < 0)
- goto BatchFailed;
- Py_CLEAR(p);
- n += 1;
-
- if (n == BATCHSIZE)
- break;
-
- p = PyIter_Next(iter);
- if (p == NULL) {
- if (PyErr_Occurred())
- goto BatchFailed;
- break;
- }
- }
-
- if (self->write_func(self, &setitems, 1) < 0)
- goto BatchFailed;
-
- } while (n == BATCHSIZE);
- return 0;
+ PyObject *p = NULL;
+ PyObject *firstitem = NULL;
+ int i, n;
+
+ static char setitem = SETITEM;
+ static char setitems = SETITEMS;
+
+ assert(iter != NULL);
+
+ if (self->proto == 0) {
+ /* SETITEMS isn't available; do one at a time. */
+ for (;;) {
+ p = PyIter_Next(iter);
+ if (p == NULL) {
+ if (PyErr_Occurred())
+ return -1;
+ break;
+ }
+ if (!PyTuple_Check(p) || PyTuple_Size(p) != 2) {
+ PyErr_SetString(PyExc_TypeError, "dict items "
+ "iterator must return 2-tuples");
+ return -1;
+ }
+ i = save(self, PyTuple_GET_ITEM(p, 0), 0);
+ if (i >= 0)
+ i = save(self, PyTuple_GET_ITEM(p, 1), 0);
+ Py_DECREF(p);
+ if (i < 0)
+ return -1;
+ if (self->write_func(self, &setitem, 1) < 0)
+ return -1;
+ }
+ return 0;
+ }
+
+ /* proto > 0: write in batches of BATCHSIZE. */
+ do {
+ /* Get first item */
+ firstitem = PyIter_Next(iter);
+ if (firstitem == NULL) {
+ if (PyErr_Occurred())
+ goto BatchFailed;
+
+ /* nothing more to add */
+ break;
+ }
+ if (!PyTuple_Check(firstitem) || PyTuple_Size(firstitem) != 2) {
+ PyErr_SetString(PyExc_TypeError, "dict items "
+ "iterator must return 2-tuples");
+ goto BatchFailed;
+ }
+
+ /* Try to get a second item */
+ p = PyIter_Next(iter);
+ if (p == NULL) {
+ if (PyErr_Occurred())
+ goto BatchFailed;
+
+ /* Only one item to write */
+ if (save(self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0)
+ goto BatchFailed;
+ if (save(self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0)
+ goto BatchFailed;
+ if (self->write_func(self, &setitem, 1) < 0)
+ goto BatchFailed;
+ Py_CLEAR(firstitem);
+ break;
+ }
+
+ /* More than one item to write */
+
+ /* Pump out MARK, items, SETITEMS. */
+ if (self->write_func(self, &MARKv, 1) < 0)
+ goto BatchFailed;
+
+ if (save(self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0)
+ goto BatchFailed;
+ if (save(self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0)
+ goto BatchFailed;
+ Py_CLEAR(firstitem);
+ n = 1;
+
+ /* Fetch and save up to BATCHSIZE items */
+ while (p) {
+ if (!PyTuple_Check(p) || PyTuple_Size(p) != 2) {
+ PyErr_SetString(PyExc_TypeError, "dict items "
+ "iterator must return 2-tuples");
+ goto BatchFailed;
+ }
+ if (save(self, PyTuple_GET_ITEM(p, 0), 0) < 0)
+ goto BatchFailed;
+ if (save(self, PyTuple_GET_ITEM(p, 1), 0) < 0)
+ goto BatchFailed;
+ Py_CLEAR(p);
+ n += 1;
+
+ if (n == BATCHSIZE)
+ break;
+
+ p = PyIter_Next(iter);
+ if (p == NULL) {
+ if (PyErr_Occurred())
+ goto BatchFailed;
+ break;
+ }
+ }
+
+ if (self->write_func(self, &setitems, 1) < 0)
+ goto BatchFailed;
+
+ } while (n == BATCHSIZE);
+ return 0;
BatchFailed:
- Py_XDECREF(firstitem);
- Py_XDECREF(p);
- return -1;
+ Py_XDECREF(firstitem);
+ Py_XDECREF(p);
+ return -1;
}
static int
save_dict(Picklerobject *self, PyObject *args)
{
- int res = -1;
- char s[3];
- int len;
- PyObject *iter;
-
- if (self->fast && !fast_save_enter(self, args))
- goto finally;
-
- /* Create an empty dict. */
- if (self->bin) {
- s[0] = EMPTY_DICT;
- len = 1;
- }
- else {
- s[0] = MARK;
- s[1] = DICT;
- len = 2;
- }
-
- if (self->write_func(self, s, len) < 0)
- goto finally;
-
- /* Get dict size, and bow out early if empty. */
- if ((len = PyDict_Size(args)) < 0)
- goto finally;
-
- if (len == 0) {
- if (put(self, args) >= 0)
- res = 0;
- goto finally;
- }
- if (put2(self, args) < 0)
- goto finally;
-
- /* Materialize the dict items. */
- iter = PyObject_CallMethod(args, "iteritems", "()");
- if (iter == NULL)
- goto finally;
- if (Py_EnterRecursiveCall(" while pickling an object") == 0)
- {
- res = batch_dict(self, iter);
- Py_LeaveRecursiveCall();
- }
- Py_DECREF(iter);
+ int res = -1;
+ char s[3];
+ int len;
+ PyObject *iter;
+
+ if (self->fast && !fast_save_enter(self, args))
+ goto finally;
+
+ /* Create an empty dict. */
+ if (self->bin) {
+ s[0] = EMPTY_DICT;
+ len = 1;
+ }
+ else {
+ s[0] = MARK;
+ s[1] = DICT;
+ len = 2;
+ }
+
+ if (self->write_func(self, s, len) < 0)
+ goto finally;
+
+ /* Get dict size, and bow out early if empty. */
+ if ((len = PyDict_Size(args)) < 0)
+ goto finally;
+
+ if (len == 0) {
+ if (put(self, args) >= 0)
+ res = 0;
+ goto finally;
+ }
+ if (put2(self, args) < 0)
+ goto finally;
+
+ /* Materialize the dict items. */
+ iter = PyObject_CallMethod(args, "iteritems", "()");
+ if (iter == NULL)
+ goto finally;
+ if (Py_EnterRecursiveCall(" while pickling an object") == 0)
+ {
+ res = batch_dict(self, iter);
+ Py_LeaveRecursiveCall();
+ }
+ Py_DECREF(iter);
finally:
- if (self->fast && !fast_save_leave(self, args))
- res = -1;
+ if (self->fast && !fast_save_leave(self, args))
+ res = -1;
- return res;
+ return res;
}
static int
save_inst(Picklerobject *self, PyObject *args)
{
- PyObject *class = 0, *module = 0, *name = 0, *state = 0,
- *getinitargs_func = 0, *getstate_func = 0, *class_args = 0;
- char *module_str, *name_str;
- int module_size, name_size, res = -1;
-
- static char inst = INST, obj = OBJ, build = BUILD;
-
- if (self->fast && !fast_save_enter(self, args))
- goto finally;
-
- if (self->write_func(self, &MARKv, 1) < 0)
- goto finally;
-
- if (!( class = PyObject_GetAttr(args, __class___str)))
- goto finally;
-
- if (self->bin) {
- if (save(self, class, 0) < 0)
- goto finally;
- }
-
- if ((getinitargs_func = PyObject_GetAttr(args, __getinitargs___str))) {
- PyObject *element = 0;
- int i, len;
-
- if (!( class_args =
- PyObject_Call(getinitargs_func, empty_tuple, NULL)))
- goto finally;
-
- if ((len = PyObject_Size(class_args)) < 0)
- goto finally;
-
- for (i = 0; i < len; i++) {
- if (!( element = PySequence_GetItem(class_args, i)))
- goto finally;
-
- if (save(self, element, 0) < 0) {
- Py_DECREF(element);
- goto finally;
- }
-
- Py_DECREF(element);
- }
- }
- else {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- goto finally;
- }
-
- if (!self->bin) {
- if (!( name = ((PyClassObject *)class)->cl_name )) {
- PyErr_SetString(PicklingError, "class has no name");
- goto finally;
- }
-
- if (!( module = whichmodule(class, name)))
- goto finally;
-
-
- if ((module_size = PyString_Size(module)) < 0 ||
- (name_size = PyString_Size(name)) < 0)
- goto finally;
-
- module_str = PyString_AS_STRING((PyStringObject *)module);
- name_str = PyString_AS_STRING((PyStringObject *)name);
-
- if (self->write_func(self, &inst, 1) < 0)
- goto finally;
-
- if (self->write_func(self, module_str, module_size) < 0)
- goto finally;
-
- if (self->write_func(self, "\n", 1) < 0)
- goto finally;
-
- if (self->write_func(self, name_str, name_size) < 0)
- goto finally;
-
- if (self->write_func(self, "\n", 1) < 0)
- goto finally;
- }
- else if (self->write_func(self, &obj, 1) < 0) {
- goto finally;
- }
-
- if ((getstate_func = PyObject_GetAttr(args, __getstate___str))) {
- state = PyObject_Call(getstate_func, empty_tuple, NULL);
- if (!state)
- goto finally;
- }
- else {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- goto finally;
-
- if (!( state = PyObject_GetAttr(args, __dict___str))) {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- goto finally;
- res = 0;
- goto finally;
- }
- }
-
- if (!PyDict_Check(state)) {
- if (put2(self, args) < 0)
- goto finally;
- }
- else {
- if (put(self, args) < 0)
- goto finally;
- }
-
- if (save(self, state, 0) < 0)
- goto finally;
-
- if (self->write_func(self, &build, 1) < 0)
- goto finally;
-
- res = 0;
+ PyObject *class = 0, *module = 0, *name = 0, *state = 0,
+ *getinitargs_func = 0, *getstate_func = 0, *class_args = 0;
+ char *module_str, *name_str;
+ int module_size, name_size, res = -1;
+
+ static char inst = INST, obj = OBJ, build = BUILD;
+
+ if (self->fast && !fast_save_enter(self, args))
+ goto finally;
+
+ if (self->write_func(self, &MARKv, 1) < 0)
+ goto finally;
+
+ if (!( class = PyObject_GetAttr(args, __class___str)))
+ goto finally;
+
+ if (self->bin) {
+ if (save(self, class, 0) < 0)
+ goto finally;
+ }
+
+ if ((getinitargs_func = PyObject_GetAttr(args, __getinitargs___str))) {
+ PyObject *element = 0;
+ int i, len;
+
+ if (!( class_args =
+ PyObject_Call(getinitargs_func, empty_tuple, NULL)))
+ goto finally;
+
+ if ((len = PyObject_Size(class_args)) < 0)
+ goto finally;
+
+ for (i = 0; i < len; i++) {
+ if (!( element = PySequence_GetItem(class_args, i)))
+ goto finally;
+
+ if (save(self, element, 0) < 0) {
+ Py_DECREF(element);
+ goto finally;
+ }
+
+ Py_DECREF(element);
+ }
+ }
+ else {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ goto finally;
+ }
+
+ if (!self->bin) {
+ if (!( name = ((PyClassObject *)class)->cl_name )) {
+ PyErr_SetString(PicklingError, "class has no name");
+ goto finally;
+ }
+
+ if (!( module = whichmodule(class, name)))
+ goto finally;
+
+
+ if ((module_size = PyString_Size(module)) < 0 ||
+ (name_size = PyString_Size(name)) < 0)
+ goto finally;
+
+ module_str = PyString_AS_STRING((PyStringObject *)module);
+ name_str = PyString_AS_STRING((PyStringObject *)name);
+
+ if (self->write_func(self, &inst, 1) < 0)
+ goto finally;
+
+ if (self->write_func(self, module_str, module_size) < 0)
+ goto finally;
+
+ if (self->write_func(self, "\n", 1) < 0)
+ goto finally;
+
+ if (self->write_func(self, name_str, name_size) < 0)
+ goto finally;
+
+ if (self->write_func(self, "\n", 1) < 0)
+ goto finally;
+ }
+ else if (self->write_func(self, &obj, 1) < 0) {
+ goto finally;
+ }
+
+ if ((getstate_func = PyObject_GetAttr(args, __getstate___str))) {
+ state = PyObject_Call(getstate_func, empty_tuple, NULL);
+ if (!state)
+ goto finally;
+ }
+ else {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ goto finally;
+
+ if (!( state = PyObject_GetAttr(args, __dict___str))) {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ goto finally;
+ res = 0;
+ goto finally;
+ }
+ }
+
+ if (!PyDict_Check(state)) {
+ if (put2(self, args) < 0)
+ goto finally;
+ }
+ else {
+ if (put(self, args) < 0)
+ goto finally;
+ }
+
+ if (save(self, state, 0) < 0)
+ goto finally;
+
+ if (self->write_func(self, &build, 1) < 0)
+ goto finally;
+
+ res = 0;
finally:
- if (self->fast && !fast_save_leave(self, args))
- res = -1;
+ if (self->fast && !fast_save_leave(self, args))
+ res = -1;
- Py_XDECREF(module);
- Py_XDECREF(class);
- Py_XDECREF(state);
- Py_XDECREF(getinitargs_func);
- Py_XDECREF(getstate_func);
- Py_XDECREF(class_args);
+ Py_XDECREF(module);
+ Py_XDECREF(class);
+ Py_XDECREF(state);
+ Py_XDECREF(getinitargs_func);
+ Py_XDECREF(getstate_func);
+ Py_XDECREF(class_args);
- return res;
+ return res;
}
static int
save_global(Picklerobject *self, PyObject *args, PyObject *name)
{
- PyObject *global_name = 0, *module = 0, *mod = 0, *klass = 0;
- char *name_str, *module_str;
- int module_size, name_size, res = -1;
-
- static char global = GLOBAL;
-
- if (name) {
- global_name = name;
- Py_INCREF(global_name);
- }
- else {
- if (!( global_name = PyObject_GetAttr(args, __name___str)))
- goto finally;
- }
-
- if (!( module = whichmodule(args, global_name)))
- goto finally;
-
- if ((module_size = PyString_Size(module)) < 0 ||
- (name_size = PyString_Size(global_name)) < 0)
- goto finally;
-
- module_str = PyString_AS_STRING((PyStringObject *)module);
- name_str = PyString_AS_STRING((PyStringObject *)global_name);
-
- /* XXX This can be doing a relative import. Clearly it shouldn't,
- but I don't know how to stop it. :-( */
- mod = PyImport_ImportModule(module_str);
- if (mod == NULL) {
- cPickle_ErrFormat(PicklingError,
- "Can't pickle %s: import of module %s "
- "failed",
- "OS", args, module);
- goto finally;
- }
- klass = PyObject_GetAttrString(mod, name_str);
- if (klass == NULL) {
- cPickle_ErrFormat(PicklingError,
- "Can't pickle %s: attribute lookup %s.%s "
- "failed",
- "OSS", args, module, global_name);
- goto finally;
- }
- if (klass != args) {
- Py_DECREF(klass);
- cPickle_ErrFormat(PicklingError,
- "Can't pickle %s: it's not the same object "
- "as %s.%s",
- "OSS", args, module, global_name);
- goto finally;
- }
- Py_DECREF(klass);
-
- if (self->proto >= 2) {
- /* See whether this is in the extension registry, and if
- * so generate an EXT opcode.
- */
- PyObject *py_code; /* extension code as Python object */
- long code; /* extension code as C value */
- char c_str[5];
- int n;
-
- PyTuple_SET_ITEM(two_tuple, 0, module);
- PyTuple_SET_ITEM(two_tuple, 1, global_name);
- py_code = PyDict_GetItem(extension_registry, two_tuple);
- if (py_code == NULL)
- goto gen_global; /* not registered */
-
- /* Verify py_code has the right type and value. */
- if (!PyInt_Check(py_code)) {
- cPickle_ErrFormat(PicklingError, "Can't pickle %s: "
- "extension code %s isn't an integer",
- "OO", args, py_code);
- goto finally;
- }
- code = PyInt_AS_LONG(py_code);
- if (code <= 0 || code > 0x7fffffffL) {
- cPickle_ErrFormat(PicklingError, "Can't pickle %s: "
- "extension code %ld is out of range",
- "Ol", args, code);
- goto finally;
- }
-
- /* Generate an EXT opcode. */
- if (code <= 0xff) {
- c_str[0] = EXT1;
- c_str[1] = (char)code;
- n = 2;
- }
- else if (code <= 0xffff) {
- c_str[0] = EXT2;
- c_str[1] = (char)(code & 0xff);
- c_str[2] = (char)((code >> 8) & 0xff);
- n = 3;
- }
- else {
- c_str[0] = EXT4;
- c_str[1] = (char)(code & 0xff);
- c_str[2] = (char)((code >> 8) & 0xff);
- c_str[3] = (char)((code >> 16) & 0xff);
- c_str[4] = (char)((code >> 24) & 0xff);
- n = 5;
- }
-
- if (self->write_func(self, c_str, n) >= 0)
- res = 0;
- goto finally; /* and don't memoize */
- }
+ PyObject *global_name = 0, *module = 0, *mod = 0, *klass = 0;
+ char *name_str, *module_str;
+ int module_size, name_size, res = -1;
+
+ static char global = GLOBAL;
+
+ if (name) {
+ global_name = name;
+ Py_INCREF(global_name);
+ }
+ else {
+ if (!( global_name = PyObject_GetAttr(args, __name___str)))
+ goto finally;
+ }
+
+ if (!( module = whichmodule(args, global_name)))
+ goto finally;
+
+ if ((module_size = PyString_Size(module)) < 0 ||
+ (name_size = PyString_Size(global_name)) < 0)
+ goto finally;
+
+ module_str = PyString_AS_STRING((PyStringObject *)module);
+ name_str = PyString_AS_STRING((PyStringObject *)global_name);
+
+ /* XXX This can be doing a relative import. Clearly it shouldn't,
+ but I don't know how to stop it. :-( */
+ mod = PyImport_ImportModule(module_str);
+ if (mod == NULL) {
+ cPickle_ErrFormat(PicklingError,
+ "Can't pickle %s: import of module %s "
+ "failed",
+ "OS", args, module);
+ goto finally;
+ }
+ klass = PyObject_GetAttrString(mod, name_str);
+ if (klass == NULL) {
+ cPickle_ErrFormat(PicklingError,
+ "Can't pickle %s: attribute lookup %s.%s "
+ "failed",
+ "OSS", args, module, global_name);
+ goto finally;
+ }
+ if (klass != args) {
+ Py_DECREF(klass);
+ cPickle_ErrFormat(PicklingError,
+ "Can't pickle %s: it's not the same object "
+ "as %s.%s",
+ "OSS", args, module, global_name);
+ goto finally;
+ }
+ Py_DECREF(klass);
+
+ if (self->proto >= 2) {
+ /* See whether this is in the extension registry, and if
+ * so generate an EXT opcode.
+ */
+ PyObject *py_code; /* extension code as Python object */
+ long code; /* extension code as C value */
+ char c_str[5];
+ int n;
+
+ PyTuple_SET_ITEM(two_tuple, 0, module);
+ PyTuple_SET_ITEM(two_tuple, 1, global_name);
+ py_code = PyDict_GetItem(extension_registry, two_tuple);
+ if (py_code == NULL)
+ goto gen_global; /* not registered */
+
+ /* Verify py_code has the right type and value. */
+ if (!PyInt_Check(py_code)) {
+ cPickle_ErrFormat(PicklingError, "Can't pickle %s: "
+ "extension code %s isn't an integer",
+ "OO", args, py_code);
+ goto finally;
+ }
+ code = PyInt_AS_LONG(py_code);
+ if (code <= 0 || code > 0x7fffffffL) {
+ cPickle_ErrFormat(PicklingError, "Can't pickle %s: "
+ "extension code %ld is out of range",
+ "Ol", args, code);
+ goto finally;
+ }
+
+ /* Generate an EXT opcode. */
+ if (code <= 0xff) {
+ c_str[0] = EXT1;
+ c_str[1] = (char)code;
+ n = 2;
+ }
+ else if (code <= 0xffff) {
+ c_str[0] = EXT2;
+ c_str[1] = (char)(code & 0xff);
+ c_str[2] = (char)((code >> 8) & 0xff);
+ n = 3;
+ }
+ else {
+ c_str[0] = EXT4;
+ c_str[1] = (char)(code & 0xff);
+ c_str[2] = (char)((code >> 8) & 0xff);
+ c_str[3] = (char)((code >> 16) & 0xff);
+ c_str[4] = (char)((code >> 24) & 0xff);
+ n = 5;
+ }
+
+ if (self->write_func(self, c_str, n) >= 0)
+ res = 0;
+ goto finally; /* and don't memoize */
+ }
gen_global:
- if (self->write_func(self, &global, 1) < 0)
- goto finally;
+ if (self->write_func(self, &global, 1) < 0)
+ goto finally;
- if (self->write_func(self, module_str, module_size) < 0)
- goto finally;
+ if (self->write_func(self, module_str, module_size) < 0)
+ goto finally;
- if (self->write_func(self, "\n", 1) < 0)
- goto finally;
+ if (self->write_func(self, "\n", 1) < 0)
+ goto finally;
- if (self->write_func(self, name_str, name_size) < 0)
- goto finally;
+ if (self->write_func(self, name_str, name_size) < 0)
+ goto finally;
- if (self->write_func(self, "\n", 1) < 0)
- goto finally;
+ if (self->write_func(self, "\n", 1) < 0)
+ goto finally;
- if (put(self, args) < 0)
- goto finally;
+ if (put(self, args) < 0)
+ goto finally;
- res = 0;
+ res = 0;
finally:
- Py_XDECREF(module);
- Py_XDECREF(global_name);
- Py_XDECREF(mod);
+ Py_XDECREF(module);
+ Py_XDECREF(global_name);
+ Py_XDECREF(mod);
- return res;
+ return res;
}
static int
save_pers(Picklerobject *self, PyObject *args, PyObject *f)
{
- PyObject *pid = 0;
- int size, res = -1;
-
- static char persid = PERSID, binpersid = BINPERSID;
-
- Py_INCREF(args);
- ARG_TUP(self, args);
- if (self->arg) {
- pid = PyObject_Call(f, self->arg, NULL);
- FREE_ARG_TUP(self);
- }
- if (! pid) return -1;
-
- if (pid != Py_None) {
- if (!self->bin) {
- if (!PyString_Check(pid)) {
- PyErr_SetString(PicklingError,
- "persistent id must be string");
- goto finally;
- }
-
- if (self->write_func(self, &persid, 1) < 0)
- goto finally;
-
- if ((size = PyString_Size(pid)) < 0)
- goto finally;
-
- if (self->write_func(self,
- PyString_AS_STRING(
- (PyStringObject *)pid),
- size) < 0)
- goto finally;
-
- if (self->write_func(self, "\n", 1) < 0)
- goto finally;
-
- res = 1;
- goto finally;
- }
- else if (save(self, pid, 1) >= 0) {
- if (self->write_func(self, &binpersid, 1) < 0)
- res = -1;
- else
- res = 1;
- }
-
- goto finally;
- }
-
- res = 0;
+ PyObject *pid = 0;
+ int size, res = -1;
+
+ static char persid = PERSID, binpersid = BINPERSID;
+
+ Py_INCREF(args);
+ ARG_TUP(self, args);
+ if (self->arg) {
+ pid = PyObject_Call(f, self->arg, NULL);
+ FREE_ARG_TUP(self);
+ }
+ if (! pid) return -1;
+
+ if (pid != Py_None) {
+ if (!self->bin) {
+ if (!PyString_Check(pid)) {
+ PyErr_SetString(PicklingError,
+ "persistent id must be string");
+ goto finally;
+ }
+
+ if (self->write_func(self, &persid, 1) < 0)
+ goto finally;
+
+ if ((size = PyString_Size(pid)) < 0)
+ goto finally;
+
+ if (self->write_func(self,
+ PyString_AS_STRING(
+ (PyStringObject *)pid),
+ size) < 0)
+ goto finally;
+
+ if (self->write_func(self, "\n", 1) < 0)
+ goto finally;
+
+ res = 1;
+ goto finally;
+ }
+ else if (save(self, pid, 1) >= 0) {
+ if (self->write_func(self, &binpersid, 1) < 0)
+ res = -1;
+ else
+ res = 1;
+ }
+
+ goto finally;
+ }
+
+ res = 0;
finally:
- Py_XDECREF(pid);
+ Py_XDECREF(pid);
- return res;
+ return res;
}
/* We're saving ob, and args is the 2-thru-5 tuple returned by the
@@ -2271,621 +2271,621 @@ save_pers(Picklerobject *self, PyObject *args, PyObject *f)
static int
save_reduce(Picklerobject *self, PyObject *args, PyObject *fn, PyObject *ob)
{
- PyObject *callable;
- PyObject *argtup;
- PyObject *state = NULL;
- PyObject *listitems = Py_None;
- PyObject *dictitems = Py_None;
- Py_ssize_t size;
-
- int use_newobj = self->proto >= 2;
-
- static char reduce = REDUCE;
- static char build = BUILD;
- static char newobj = NEWOBJ;
-
- size = PyTuple_Size(args);
- if (size < 2 || size > 5) {
- cPickle_ErrFormat(PicklingError, "tuple returned by "
- "%s must contain 2 through 5 elements",
- "O", fn);
- return -1;
- }
-
- if (! PyArg_UnpackTuple(args, "save_reduce", 2, 5,
- &callable,
- &argtup,
- &state,
- &listitems,
- &dictitems))
- return -1;
-
- if (!PyTuple_Check(argtup)) {
- cPickle_ErrFormat(PicklingError, "Second element of "
- "tuple returned by %s must be a tuple",
- "O", fn);
- return -1;
- }
-
- if (state == Py_None)
- state = NULL;
-
- if (listitems == Py_None)
- listitems = NULL;
- else if (!PyIter_Check(listitems)) {
- cPickle_ErrFormat(PicklingError, "Fourth element of "
- "tuple returned by %s must be an iterator, not %s",
- "Os", fn, Py_TYPE(listitems)->tp_name);
- return -1;
- }
-
- if (dictitems == Py_None)
- dictitems = NULL;
- else if (!PyIter_Check(dictitems)) {
- cPickle_ErrFormat(PicklingError, "Fifth element of "
- "tuple returned by %s must be an iterator, not %s",
- "Os", fn, Py_TYPE(dictitems)->tp_name);
- return -1;
- }
-
- /* Protocol 2 special case: if callable's name is __newobj__, use
- * NEWOBJ. This consumes a lot of code.
- */
- if (use_newobj) {
- PyObject *temp = PyObject_GetAttr(callable, __name___str);
-
- if (temp == NULL) {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- return -1;
- use_newobj = 0;
- }
- else {
- use_newobj = PyString_Check(temp) &&
- strcmp(PyString_AS_STRING(temp),
- "__newobj__") == 0;
- Py_DECREF(temp);
- }
- }
- if (use_newobj) {
- PyObject *cls;
- PyObject *newargtup;
- int n, i;
-
- /* Sanity checks. */
- n = PyTuple_Size(argtup);
- if (n < 1) {
- PyErr_SetString(PicklingError, "__newobj__ arglist "
- "is empty");
- return -1;
- }
-
- cls = PyTuple_GET_ITEM(argtup, 0);
- if (! PyObject_HasAttrString(cls, "__new__")) {
- PyErr_SetString(PicklingError, "args[0] from "
- "__newobj__ args has no __new__");
- return -1;
- }
-
- /* XXX How could ob be NULL? */
- if (ob != NULL) {
- PyObject *ob_dot_class;
-
- ob_dot_class = PyObject_GetAttr(ob, __class___str);
- if (ob_dot_class == NULL) {
- if (PyErr_ExceptionMatches(
- PyExc_AttributeError))
- PyErr_Clear();
- else
- return -1;
- }
- i = ob_dot_class != cls; /* true iff a problem */
- Py_XDECREF(ob_dot_class);
- if (i) {
- PyErr_SetString(PicklingError, "args[0] from "
- "__newobj__ args has the wrong class");
- return -1;
- }
- }
-
- /* Save the class and its __new__ arguments. */
- if (save(self, cls, 0) < 0)
- return -1;
-
- newargtup = PyTuple_New(n-1); /* argtup[1:] */
- if (newargtup == NULL)
- return -1;
- for (i = 1; i < n; ++i) {
- PyObject *temp = PyTuple_GET_ITEM(argtup, i);
- Py_INCREF(temp);
- PyTuple_SET_ITEM(newargtup, i-1, temp);
- }
- i = save(self, newargtup, 0);
- Py_DECREF(newargtup);
- if (i < 0)
- return -1;
-
- /* Add NEWOBJ opcode. */
- if (self->write_func(self, &newobj, 1) < 0)
- return -1;
- }
- else {
- /* Not using NEWOBJ. */
- if (save(self, callable, 0) < 0 ||
- save(self, argtup, 0) < 0 ||
- self->write_func(self, &reduce, 1) < 0)
- return -1;
- }
-
- /* Memoize. */
- /* XXX How can ob be NULL? */
- if (ob != NULL) {
- if (state && !PyDict_Check(state)) {
- if (put2(self, ob) < 0)
- return -1;
- }
- else if (put(self, ob) < 0)
- return -1;
- }
-
-
- if (listitems && batch_list(self, listitems) < 0)
- return -1;
-
- if (dictitems && batch_dict(self, dictitems) < 0)
- return -1;
-
- if (state) {
- if (save(self, state, 0) < 0 ||
- self->write_func(self, &build, 1) < 0)
- return -1;
- }
-
- return 0;
+ PyObject *callable;
+ PyObject *argtup;
+ PyObject *state = NULL;
+ PyObject *listitems = Py_None;
+ PyObject *dictitems = Py_None;
+ Py_ssize_t size;
+
+ int use_newobj = self->proto >= 2;
+
+ static char reduce = REDUCE;
+ static char build = BUILD;
+ static char newobj = NEWOBJ;
+
+ size = PyTuple_Size(args);
+ if (size < 2 || size > 5) {
+ cPickle_ErrFormat(PicklingError, "tuple returned by "
+ "%s must contain 2 through 5 elements",
+ "O", fn);
+ return -1;
+ }
+
+ if (! PyArg_UnpackTuple(args, "save_reduce", 2, 5,
+ &callable,
+ &argtup,
+ &state,
+ &listitems,
+ &dictitems))
+ return -1;
+
+ if (!PyTuple_Check(argtup)) {
+ cPickle_ErrFormat(PicklingError, "Second element of "
+ "tuple returned by %s must be a tuple",
+ "O", fn);
+ return -1;
+ }
+
+ if (state == Py_None)
+ state = NULL;
+
+ if (listitems == Py_None)
+ listitems = NULL;
+ else if (!PyIter_Check(listitems)) {
+ cPickle_ErrFormat(PicklingError, "Fourth element of "
+ "tuple returned by %s must be an iterator, not %s",
+ "Os", fn, Py_TYPE(listitems)->tp_name);
+ return -1;
+ }
+
+ if (dictitems == Py_None)
+ dictitems = NULL;
+ else if (!PyIter_Check(dictitems)) {
+ cPickle_ErrFormat(PicklingError, "Fifth element of "
+ "tuple returned by %s must be an iterator, not %s",
+ "Os", fn, Py_TYPE(dictitems)->tp_name);
+ return -1;
+ }
+
+ /* Protocol 2 special case: if callable's name is __newobj__, use
+ * NEWOBJ. This consumes a lot of code.
+ */
+ if (use_newobj) {
+ PyObject *temp = PyObject_GetAttr(callable, __name___str);
+
+ if (temp == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ return -1;
+ use_newobj = 0;
+ }
+ else {
+ use_newobj = PyString_Check(temp) &&
+ strcmp(PyString_AS_STRING(temp),
+ "__newobj__") == 0;
+ Py_DECREF(temp);
+ }
+ }
+ if (use_newobj) {
+ PyObject *cls;
+ PyObject *newargtup;
+ int n, i;
+
+ /* Sanity checks. */
+ n = PyTuple_Size(argtup);
+ if (n < 1) {
+ PyErr_SetString(PicklingError, "__newobj__ arglist "
+ "is empty");
+ return -1;
+ }
+
+ cls = PyTuple_GET_ITEM(argtup, 0);
+ if (! PyObject_HasAttrString(cls, "__new__")) {
+ PyErr_SetString(PicklingError, "args[0] from "
+ "__newobj__ args has no __new__");
+ return -1;
+ }
+
+ /* XXX How could ob be NULL? */
+ if (ob != NULL) {
+ PyObject *ob_dot_class;
+
+ ob_dot_class = PyObject_GetAttr(ob, __class___str);
+ if (ob_dot_class == NULL) {
+ if (PyErr_ExceptionMatches(
+ PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ return -1;
+ }
+ i = ob_dot_class != cls; /* true iff a problem */
+ Py_XDECREF(ob_dot_class);
+ if (i) {
+ PyErr_SetString(PicklingError, "args[0] from "
+ "__newobj__ args has the wrong class");
+ return -1;
+ }
+ }
+
+ /* Save the class and its __new__ arguments. */
+ if (save(self, cls, 0) < 0)
+ return -1;
+
+ newargtup = PyTuple_New(n-1); /* argtup[1:] */
+ if (newargtup == NULL)
+ return -1;
+ for (i = 1; i < n; ++i) {
+ PyObject *temp = PyTuple_GET_ITEM(argtup, i);
+ Py_INCREF(temp);
+ PyTuple_SET_ITEM(newargtup, i-1, temp);
+ }
+ i = save(self, newargtup, 0);
+ Py_DECREF(newargtup);
+ if (i < 0)
+ return -1;
+
+ /* Add NEWOBJ opcode. */
+ if (self->write_func(self, &newobj, 1) < 0)
+ return -1;
+ }
+ else {
+ /* Not using NEWOBJ. */
+ if (save(self, callable, 0) < 0 ||
+ save(self, argtup, 0) < 0 ||
+ self->write_func(self, &reduce, 1) < 0)
+ return -1;
+ }
+
+ /* Memoize. */
+ /* XXX How can ob be NULL? */
+ if (ob != NULL) {
+ if (state && !PyDict_Check(state)) {
+ if (put2(self, ob) < 0)
+ return -1;
+ }
+ else if (put(self, ob) < 0)
+ return -1;
+ }
+
+
+ if (listitems && batch_list(self, listitems) < 0)
+ return -1;
+
+ if (dictitems && batch_dict(self, dictitems) < 0)
+ return -1;
+
+ if (state) {
+ if (save(self, state, 0) < 0 ||
+ self->write_func(self, &build, 1) < 0)
+ return -1;
+ }
+
+ return 0;
}
static int
save(Picklerobject *self, PyObject *args, int pers_save)
{
- PyTypeObject *type;
- PyObject *py_ob_id = 0, *__reduce__ = 0, *t = 0;
- int res = -1;
- int tmp;
-
- if (Py_EnterRecursiveCall(" while pickling an object"))
- return -1;
-
- if (!pers_save && self->pers_func) {
- if ((tmp = save_pers(self, args, self->pers_func)) != 0) {
- res = tmp;
- goto finally;
- }
- }
-
- if (args == Py_None) {
- res = save_none(self, args);
- goto finally;
- }
-
- type = Py_TYPE(args);
-
- switch (type->tp_name[0]) {
- case 'b':
- if (args == Py_False || args == Py_True) {
- res = save_bool(self, args);
- goto finally;
- }
- break;
- case 'i':
- if (type == &PyInt_Type) {
- res = save_int(self, args);
- goto finally;
- }
- break;
-
- case 'l':
- if (type == &PyLong_Type) {
- res = save_long(self, args);
- goto finally;
- }
- break;
-
- case 'f':
- if (type == &PyFloat_Type) {
- res = save_float(self, args);
- goto finally;
- }
- break;
-
- case 't':
- if (type == &PyTuple_Type && PyTuple_Size(args) == 0) {
- res = save_tuple(self, args);
- goto finally;
- }
- break;
-
- case 's':
- if ((type == &PyString_Type) && (PyString_GET_SIZE(args) < 2)) {
- res = save_string(self, args, 0);
- goto finally;
- }
- break;
+ PyTypeObject *type;
+ PyObject *py_ob_id = 0, *__reduce__ = 0, *t = 0;
+ int res = -1;
+ int tmp;
+
+ if (Py_EnterRecursiveCall(" while pickling an object"))
+ return -1;
+
+ if (!pers_save && self->pers_func) {
+ if ((tmp = save_pers(self, args, self->pers_func)) != 0) {
+ res = tmp;
+ goto finally;
+ }
+ }
+
+ if (args == Py_None) {
+ res = save_none(self, args);
+ goto finally;
+ }
+
+ type = Py_TYPE(args);
+
+ switch (type->tp_name[0]) {
+ case 'b':
+ if (args == Py_False || args == Py_True) {
+ res = save_bool(self, args);
+ goto finally;
+ }
+ break;
+ case 'i':
+ if (type == &PyInt_Type) {
+ res = save_int(self, args);
+ goto finally;
+ }
+ break;
+
+ case 'l':
+ if (type == &PyLong_Type) {
+ res = save_long(self, args);
+ goto finally;
+ }
+ break;
+
+ case 'f':
+ if (type == &PyFloat_Type) {
+ res = save_float(self, args);
+ goto finally;
+ }
+ break;
+
+ case 't':
+ if (type == &PyTuple_Type && PyTuple_Size(args) == 0) {
+ res = save_tuple(self, args);
+ goto finally;
+ }
+ break;
+
+ case 's':
+ if ((type == &PyString_Type) && (PyString_GET_SIZE(args) < 2)) {
+ res = save_string(self, args, 0);
+ goto finally;
+ }
+ break;
#ifdef Py_USING_UNICODE
- case 'u':
- if ((type == &PyUnicode_Type) && (PyString_GET_SIZE(args) < 2)) {
- res = save_unicode(self, args, 0);
- goto finally;
- }
- break;
+ case 'u':
+ if ((type == &PyUnicode_Type) && (PyString_GET_SIZE(args) < 2)) {
+ res = save_unicode(self, args, 0);
+ goto finally;
+ }
+ break;
#endif
- }
+ }
- if (Py_REFCNT(args) > 1) {
- if (!( py_ob_id = PyLong_FromVoidPtr(args)))
- goto finally;
+ if (Py_REFCNT(args) > 1) {
+ if (!( py_ob_id = PyLong_FromVoidPtr(args)))
+ goto finally;
- if (PyDict_GetItem(self->memo, py_ob_id)) {
- if (get(self, py_ob_id) < 0)
- goto finally;
+ if (PyDict_GetItem(self->memo, py_ob_id)) {
+ if (get(self, py_ob_id) < 0)
+ goto finally;
- res = 0;
- goto finally;
- }
- }
+ res = 0;
+ goto finally;
+ }
+ }
- switch (type->tp_name[0]) {
- case 's':
- if (type == &PyString_Type) {
- res = save_string(self, args, 1);
- goto finally;
- }
- break;
+ switch (type->tp_name[0]) {
+ case 's':
+ if (type == &PyString_Type) {
+ res = save_string(self, args, 1);
+ goto finally;
+ }
+ break;
#ifdef Py_USING_UNICODE
- case 'u':
- if (type == &PyUnicode_Type) {
- res = save_unicode(self, args, 1);
- goto finally;
- }
- break;
+ case 'u':
+ if (type == &PyUnicode_Type) {
+ res = save_unicode(self, args, 1);
+ goto finally;
+ }
+ break;
#endif
- case 't':
- if (type == &PyTuple_Type) {
- res = save_tuple(self, args);
- goto finally;
- }
- if (type == &PyType_Type) {
- res = save_global(self, args, NULL);
- goto finally;
- }
- break;
-
- case 'l':
- if (type == &PyList_Type) {
- res = save_list(self, args);
- goto finally;
- }
- break;
-
- case 'd':
- if (type == &PyDict_Type) {
- res = save_dict(self, args);
- goto finally;
- }
- break;
-
- case 'i':
- if (type == &PyInstance_Type) {
- res = save_inst(self, args);
- goto finally;
- }
- break;
-
- case 'c':
- if (type == &PyClass_Type) {
- res = save_global(self, args, NULL);
- goto finally;
- }
- break;
-
- case 'f':
- if (type == &PyFunction_Type) {
- res = save_global(self, args, NULL);
- if (res && PyErr_ExceptionMatches(PickleError)) {
- /* fall back to reduce */
- PyErr_Clear();
- break;
- }
- goto finally;
- }
- break;
-
- case 'b':
- if (type == &PyCFunction_Type) {
- res = save_global(self, args, NULL);
- goto finally;
- }
- }
-
- if (!pers_save && self->inst_pers_func) {
- if ((tmp = save_pers(self, args, self->inst_pers_func)) != 0) {
- res = tmp;
- goto finally;
- }
- }
-
- if (PyType_IsSubtype(type, &PyType_Type)) {
- res = save_global(self, args, NULL);
- goto finally;
- }
-
- /* Get a reduction callable, and call it. This may come from
- * copy_reg.dispatch_table, the object's __reduce_ex__ method,
- * or the object's __reduce__ method.
- */
- __reduce__ = PyDict_GetItem(dispatch_table, (PyObject *)type);
- if (__reduce__ != NULL) {
- Py_INCREF(__reduce__);
- Py_INCREF(args);
- ARG_TUP(self, args);
- if (self->arg) {
- t = PyObject_Call(__reduce__, self->arg, NULL);
- FREE_ARG_TUP(self);
- }
- }
- else {
- /* Check for a __reduce_ex__ method. */
- __reduce__ = PyObject_GetAttr(args, __reduce_ex___str);
- if (__reduce__ != NULL) {
- t = PyInt_FromLong(self->proto);
- if (t != NULL) {
- ARG_TUP(self, t);
- t = NULL;
- if (self->arg) {
- t = PyObject_Call(__reduce__,
- self->arg, NULL);
- FREE_ARG_TUP(self);
- }
- }
- }
- else {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- goto finally;
- /* Check for a __reduce__ method. */
- __reduce__ = PyObject_GetAttr(args, __reduce___str);
- if (__reduce__ != NULL) {
- t = PyObject_Call(__reduce__,
- empty_tuple, NULL);
- }
- else {
- PyErr_SetObject(UnpickleableError, args);
- goto finally;
- }
- }
- }
-
- if (t == NULL)
- goto finally;
-
- if (PyString_Check(t)) {
- res = save_global(self, args, t);
- goto finally;
- }
-
- if (!PyTuple_Check(t)) {
- cPickle_ErrFormat(PicklingError, "Value returned by "
- "%s must be string or tuple",
- "O", __reduce__);
- goto finally;
- }
-
- res = save_reduce(self, t, __reduce__, args);
+ case 't':
+ if (type == &PyTuple_Type) {
+ res = save_tuple(self, args);
+ goto finally;
+ }
+ if (type == &PyType_Type) {
+ res = save_global(self, args, NULL);
+ goto finally;
+ }
+ break;
+
+ case 'l':
+ if (type == &PyList_Type) {
+ res = save_list(self, args);
+ goto finally;
+ }
+ break;
+
+ case 'd':
+ if (type == &PyDict_Type) {
+ res = save_dict(self, args);
+ goto finally;
+ }
+ break;
+
+ case 'i':
+ if (type == &PyInstance_Type) {
+ res = save_inst(self, args);
+ goto finally;
+ }
+ break;
+
+ case 'c':
+ if (type == &PyClass_Type) {
+ res = save_global(self, args, NULL);
+ goto finally;
+ }
+ break;
+
+ case 'f':
+ if (type == &PyFunction_Type) {
+ res = save_global(self, args, NULL);
+ if (res && PyErr_ExceptionMatches(PickleError)) {
+ /* fall back to reduce */
+ PyErr_Clear();
+ break;
+ }
+ goto finally;
+ }
+ break;
+
+ case 'b':
+ if (type == &PyCFunction_Type) {
+ res = save_global(self, args, NULL);
+ goto finally;
+ }
+ }
+
+ if (!pers_save && self->inst_pers_func) {
+ if ((tmp = save_pers(self, args, self->inst_pers_func)) != 0) {
+ res = tmp;
+ goto finally;
+ }
+ }
+
+ if (PyType_IsSubtype(type, &PyType_Type)) {
+ res = save_global(self, args, NULL);
+ goto finally;
+ }
+
+ /* Get a reduction callable, and call it. This may come from
+ * copy_reg.dispatch_table, the object's __reduce_ex__ method,
+ * or the object's __reduce__ method.
+ */
+ __reduce__ = PyDict_GetItem(dispatch_table, (PyObject *)type);
+ if (__reduce__ != NULL) {
+ Py_INCREF(__reduce__);
+ Py_INCREF(args);
+ ARG_TUP(self, args);
+ if (self->arg) {
+ t = PyObject_Call(__reduce__, self->arg, NULL);
+ FREE_ARG_TUP(self);
+ }
+ }
+ else {
+ /* Check for a __reduce_ex__ method. */
+ __reduce__ = PyObject_GetAttr(args, __reduce_ex___str);
+ if (__reduce__ != NULL) {
+ t = PyInt_FromLong(self->proto);
+ if (t != NULL) {
+ ARG_TUP(self, t);
+ t = NULL;
+ if (self->arg) {
+ t = PyObject_Call(__reduce__,
+ self->arg, NULL);
+ FREE_ARG_TUP(self);
+ }
+ }
+ }
+ else {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ goto finally;
+ /* Check for a __reduce__ method. */
+ __reduce__ = PyObject_GetAttr(args, __reduce___str);
+ if (__reduce__ != NULL) {
+ t = PyObject_Call(__reduce__,
+ empty_tuple, NULL);
+ }
+ else {
+ PyErr_SetObject(UnpickleableError, args);
+ goto finally;
+ }
+ }
+ }
+
+ if (t == NULL)
+ goto finally;
+
+ if (PyString_Check(t)) {
+ res = save_global(self, args, t);
+ goto finally;
+ }
+
+ if (!PyTuple_Check(t)) {
+ cPickle_ErrFormat(PicklingError, "Value returned by "
+ "%s must be string or tuple",
+ "O", __reduce__);
+ goto finally;
+ }
+
+ res = save_reduce(self, t, __reduce__, args);
finally:
- Py_LeaveRecursiveCall();
- Py_XDECREF(py_ob_id);
- Py_XDECREF(__reduce__);
- Py_XDECREF(t);
+ Py_LeaveRecursiveCall();
+ Py_XDECREF(py_ob_id);
+ Py_XDECREF(__reduce__);
+ Py_XDECREF(t);
- return res;
+ return res;
}
static int
dump(Picklerobject *self, PyObject *args)
{
- static char stop = STOP;
+ static char stop = STOP;
- if (self->proto >= 2) {
- char bytes[2];
+ if (self->proto >= 2) {
+ char bytes[2];
- bytes[0] = PROTO;
- assert(self->proto >= 0 && self->proto < 256);
- bytes[1] = (char)self->proto;
- if (self->write_func(self, bytes, 2) < 0)
- return -1;
- }
+ bytes[0] = PROTO;
+ assert(self->proto >= 0 && self->proto < 256);
+ bytes[1] = (char)self->proto;
+ if (self->write_func(self, bytes, 2) < 0)
+ return -1;
+ }
- if (save(self, args, 0) < 0)
- return -1;
+ if (save(self, args, 0) < 0)
+ return -1;
- if (self->write_func(self, &stop, 1) < 0)
- return -1;
+ if (self->write_func(self, &stop, 1) < 0)
+ return -1;
- if (self->write_func(self, NULL, 0) < 0)
- return -1;
+ if (self->write_func(self, NULL, 0) < 0)
+ return -1;
- return 0;
+ return 0;
}
static PyObject *
Pickle_clear_memo(Picklerobject *self, PyObject *args)
{
- if (self->memo)
- PyDict_Clear(self->memo);
- Py_INCREF(Py_None);
- return Py_None;
+ if (self->memo)
+ PyDict_Clear(self->memo);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
Pickle_getvalue(Picklerobject *self, PyObject *args)
{
- int l, i, rsize, ssize, clear=1, lm;
- long ik;
- PyObject *k, *r;
- char *s, *p, *have_get;
- Pdata *data;
-
- /* Can be called by Python code or C code */
- if (args && !PyArg_ParseTuple(args, "|i:getvalue", &clear))
- return NULL;
-
- /* Check to make sure we are based on a list */
- if (! Pdata_Check(self->file)) {
- PyErr_SetString(PicklingError,
- "Attempt to getvalue() a non-list-based pickler");
- return NULL;
- }
-
- /* flush write buffer */
- if (write_other(self, NULL, 0) < 0) return NULL;
-
- data=(Pdata*)self->file;
- l=data->length;
-
- /* set up an array to hold get/put status */
- lm = PyDict_Size(self->memo);
- if (lm < 0) return NULL;
- lm++;
- have_get = malloc(lm);
- if (have_get == NULL) return PyErr_NoMemory();
- memset(have_get, 0, lm);
-
- /* Scan for gets. */
- for (rsize = 0, i = l; --i >= 0; ) {
- k = data->data[i];
-
- if (PyString_Check(k))
- rsize += PyString_GET_SIZE(k);
-
- else if (PyInt_Check(k)) { /* put */
- ik = PyInt_AS_LONG((PyIntObject*)k);
- if (ik >= lm || ik == 0) {
- PyErr_SetString(PicklingError,
- "Invalid get data");
- goto err;
- }
- if (have_get[ik]) /* with matching get */
- rsize += ik < 256 ? 2 : 5;
- }
-
- else if (! (PyTuple_Check(k) &&
- PyTuple_GET_SIZE(k) == 2 &&
- PyInt_Check((k = PyTuple_GET_ITEM(k, 0))))
- ) {
- PyErr_SetString(PicklingError,
- "Unexpected data in internal list");
- goto err;
- }
-
- else { /* put */
- ik = PyInt_AS_LONG((PyIntObject *)k);
- if (ik >= lm || ik == 0) {
- PyErr_SetString(PicklingError,
- "Invalid get data");
- return NULL;
- }
- have_get[ik] = 1;
- rsize += ik < 256 ? 2 : 5;
- }
- }
-
- /* Now generate the result */
- r = PyString_FromStringAndSize(NULL, rsize);
- if (r == NULL) goto err;
- s = PyString_AS_STRING((PyStringObject *)r);
-
- for (i = 0; i < l; i++) {
- k = data->data[i];
-
- if (PyString_Check(k)) {
- ssize = PyString_GET_SIZE(k);
- if (ssize) {
- p=PyString_AS_STRING((PyStringObject *)k);
- while (--ssize >= 0)
- *s++ = *p++;
- }
- }
-
- else if (PyTuple_Check(k)) { /* get */
- ik = PyInt_AS_LONG((PyIntObject *)
- PyTuple_GET_ITEM(k, 0));
- if (ik < 256) {
- *s++ = BINGET;
- *s++ = (int)(ik & 0xff);
- }
- else {
- *s++ = LONG_BINGET;
- *s++ = (int)(ik & 0xff);
- *s++ = (int)((ik >> 8) & 0xff);
- *s++ = (int)((ik >> 16) & 0xff);
- *s++ = (int)((ik >> 24) & 0xff);
- }
- }
-
- else { /* put */
- ik = PyInt_AS_LONG((PyIntObject*)k);
-
- if (have_get[ik]) { /* with matching get */
- if (ik < 256) {
- *s++ = BINPUT;
- *s++ = (int)(ik & 0xff);
- }
- else {
- *s++ = LONG_BINPUT;
- *s++ = (int)(ik & 0xff);
- *s++ = (int)((ik >> 8) & 0xff);
- *s++ = (int)((ik >> 16) & 0xff);
- *s++ = (int)((ik >> 24) & 0xff);
- }
- }
- }
- }
-
- if (clear) {
- PyDict_Clear(self->memo);
- Pdata_clear(data, 0);
- }
-
- free(have_get);
- return r;
+ int l, i, rsize, ssize, clear=1, lm;
+ long ik;
+ PyObject *k, *r;
+ char *s, *p, *have_get;
+ Pdata *data;
+
+ /* Can be called by Python code or C code */
+ if (args && !PyArg_ParseTuple(args, "|i:getvalue", &clear))
+ return NULL;
+
+ /* Check to make sure we are based on a list */
+ if (! Pdata_Check(self->file)) {
+ PyErr_SetString(PicklingError,
+ "Attempt to getvalue() a non-list-based pickler");
+ return NULL;
+ }
+
+ /* flush write buffer */
+ if (write_other(self, NULL, 0) < 0) return NULL;
+
+ data=(Pdata*)self->file;
+ l=data->length;
+
+ /* set up an array to hold get/put status */
+ lm = PyDict_Size(self->memo);
+ if (lm < 0) return NULL;
+ lm++;
+ have_get = malloc(lm);
+ if (have_get == NULL) return PyErr_NoMemory();
+ memset(have_get, 0, lm);
+
+ /* Scan for gets. */
+ for (rsize = 0, i = l; --i >= 0; ) {
+ k = data->data[i];
+
+ if (PyString_Check(k))
+ rsize += PyString_GET_SIZE(k);
+
+ else if (PyInt_Check(k)) { /* put */
+ ik = PyInt_AS_LONG((PyIntObject*)k);
+ if (ik >= lm || ik == 0) {
+ PyErr_SetString(PicklingError,
+ "Invalid get data");
+ goto err;
+ }
+ if (have_get[ik]) /* with matching get */
+ rsize += ik < 256 ? 2 : 5;
+ }
+
+ else if (! (PyTuple_Check(k) &&
+ PyTuple_GET_SIZE(k) == 2 &&
+ PyInt_Check((k = PyTuple_GET_ITEM(k, 0))))
+ ) {
+ PyErr_SetString(PicklingError,
+ "Unexpected data in internal list");
+ goto err;
+ }
+
+ else { /* put */
+ ik = PyInt_AS_LONG((PyIntObject *)k);
+ if (ik >= lm || ik == 0) {
+ PyErr_SetString(PicklingError,
+ "Invalid get data");
+ return NULL;
+ }
+ have_get[ik] = 1;
+ rsize += ik < 256 ? 2 : 5;
+ }
+ }
+
+ /* Now generate the result */
+ r = PyString_FromStringAndSize(NULL, rsize);
+ if (r == NULL) goto err;
+ s = PyString_AS_STRING((PyStringObject *)r);
+
+ for (i = 0; i < l; i++) {
+ k = data->data[i];
+
+ if (PyString_Check(k)) {
+ ssize = PyString_GET_SIZE(k);
+ if (ssize) {
+ p=PyString_AS_STRING((PyStringObject *)k);
+ while (--ssize >= 0)
+ *s++ = *p++;
+ }
+ }
+
+ else if (PyTuple_Check(k)) { /* get */
+ ik = PyInt_AS_LONG((PyIntObject *)
+ PyTuple_GET_ITEM(k, 0));
+ if (ik < 256) {
+ *s++ = BINGET;
+ *s++ = (int)(ik & 0xff);
+ }
+ else {
+ *s++ = LONG_BINGET;
+ *s++ = (int)(ik & 0xff);
+ *s++ = (int)((ik >> 8) & 0xff);
+ *s++ = (int)((ik >> 16) & 0xff);
+ *s++ = (int)((ik >> 24) & 0xff);
+ }
+ }
+
+ else { /* put */
+ ik = PyInt_AS_LONG((PyIntObject*)k);
+
+ if (have_get[ik]) { /* with matching get */
+ if (ik < 256) {
+ *s++ = BINPUT;
+ *s++ = (int)(ik & 0xff);
+ }
+ else {
+ *s++ = LONG_BINPUT;
+ *s++ = (int)(ik & 0xff);
+ *s++ = (int)((ik >> 8) & 0xff);
+ *s++ = (int)((ik >> 16) & 0xff);
+ *s++ = (int)((ik >> 24) & 0xff);
+ }
+ }
+ }
+ }
+
+ if (clear) {
+ PyDict_Clear(self->memo);
+ Pdata_clear(data, 0);
+ }
+
+ free(have_get);
+ return r;
err:
- free(have_get);
- return NULL;
+ free(have_get);
+ return NULL;
}
static PyObject *
Pickler_dump(Picklerobject *self, PyObject *args)
{
- PyObject *ob;
- int get=0;
+ PyObject *ob;
+ int get=0;
- if (!( PyArg_ParseTuple(args, "O|i:dump", &ob, &get)))
- return NULL;
+ if (!( PyArg_ParseTuple(args, "O|i:dump", &ob, &get)))
+ return NULL;
- if (dump(self, ob) < 0)
- return NULL;
+ if (dump(self, ob) < 0)
+ return NULL;
- if (get) return Pickle_getvalue(self, NULL);
+ if (get) return Pickle_getvalue(self, NULL);
- /* XXX Why does dump() return self? */
- Py_INCREF(self);
- return (PyObject*)self;
+ /* XXX Why does dump() return self? */
+ Py_INCREF(self);
+ return (PyObject*)self;
}
@@ -2905,250 +2905,250 @@ static struct PyMethodDef Pickler_methods[] =
static Picklerobject *
newPicklerobject(PyObject *file, int proto)
{
- Picklerobject *self;
-
- if (proto < 0)
- proto = HIGHEST_PROTOCOL;
- if (proto > HIGHEST_PROTOCOL) {
- PyErr_Format(PyExc_ValueError, "pickle protocol %d asked for; "
- "the highest available protocol is %d",
- proto, HIGHEST_PROTOCOL);
- return NULL;
- }
-
- self = PyObject_GC_New(Picklerobject, &Picklertype);
- if (self == NULL)
- return NULL;
- self->proto = proto;
- self->bin = proto > 0;
- self->fp = NULL;
- self->write = NULL;
- self->memo = NULL;
- self->arg = NULL;
- self->pers_func = NULL;
- self->inst_pers_func = NULL;
- self->write_buf = NULL;
- self->fast = 0;
- self->fast_container = 0;
- self->fast_memo = NULL;
- self->buf_size = 0;
- self->dispatch_table = NULL;
-
- self->file = NULL;
- if (file)
- Py_INCREF(file);
- else {
- file = Pdata_New();
- if (file == NULL)
- goto err;
- }
- self->file = file;
-
- if (!( self->memo = PyDict_New()))
- goto err;
-
- if (PyFile_Check(file)) {
- self->fp = PyFile_AsFile(file);
- if (self->fp == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto err;
- }
- self->write_func = write_file;
- }
- else if (PycStringIO_OutputCheck(file)) {
- self->write_func = write_cStringIO;
- }
- else if (file == Py_None) {
- self->write_func = write_none;
- }
- else {
- self->write_func = write_other;
-
- if (! Pdata_Check(file)) {
- self->write = PyObject_GetAttr(file, write_str);
- if (!self->write) {
- PyErr_Clear();
- PyErr_SetString(PyExc_TypeError,
- "argument must have 'write' "
- "attribute");
- goto err;
- }
- }
-
- self->write_buf = (char *)PyMem_Malloc(WRITE_BUF_SIZE);
- if (self->write_buf == NULL) {
- PyErr_NoMemory();
- goto err;
- }
- }
-
- if (PyEval_GetRestricted()) {
- /* Restricted execution, get private tables */
- PyObject *m = PyImport_ImportModule("copy_reg");
-
- if (m == NULL)
- goto err;
- self->dispatch_table = PyObject_GetAttr(m, dispatch_table_str);
- Py_DECREF(m);
- if (self->dispatch_table == NULL)
- goto err;
- }
- else {
- self->dispatch_table = dispatch_table;
- Py_INCREF(dispatch_table);
- }
- PyObject_GC_Track(self);
-
- return self;
+ Picklerobject *self;
+
+ if (proto < 0)
+ proto = HIGHEST_PROTOCOL;
+ if (proto > HIGHEST_PROTOCOL) {
+ PyErr_Format(PyExc_ValueError, "pickle protocol %d asked for; "
+ "the highest available protocol is %d",
+ proto, HIGHEST_PROTOCOL);
+ return NULL;
+ }
+
+ self = PyObject_GC_New(Picklerobject, &Picklertype);
+ if (self == NULL)
+ return NULL;
+ self->proto = proto;
+ self->bin = proto > 0;
+ self->fp = NULL;
+ self->write = NULL;
+ self->memo = NULL;
+ self->arg = NULL;
+ self->pers_func = NULL;
+ self->inst_pers_func = NULL;
+ self->write_buf = NULL;
+ self->fast = 0;
+ self->fast_container = 0;
+ self->fast_memo = NULL;
+ self->buf_size = 0;
+ self->dispatch_table = NULL;
+
+ self->file = NULL;
+ if (file)
+ Py_INCREF(file);
+ else {
+ file = Pdata_New();
+ if (file == NULL)
+ goto err;
+ }
+ self->file = file;
+
+ if (!( self->memo = PyDict_New()))
+ goto err;
+
+ if (PyFile_Check(file)) {
+ self->fp = PyFile_AsFile(file);
+ if (self->fp == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto err;
+ }
+ self->write_func = write_file;
+ }
+ else if (PycStringIO_OutputCheck(file)) {
+ self->write_func = write_cStringIO;
+ }
+ else if (file == Py_None) {
+ self->write_func = write_none;
+ }
+ else {
+ self->write_func = write_other;
+
+ if (! Pdata_Check(file)) {
+ self->write = PyObject_GetAttr(file, write_str);
+ if (!self->write) {
+ PyErr_Clear();
+ PyErr_SetString(PyExc_TypeError,
+ "argument must have 'write' "
+ "attribute");
+ goto err;
+ }
+ }
+
+ self->write_buf = (char *)PyMem_Malloc(WRITE_BUF_SIZE);
+ if (self->write_buf == NULL) {
+ PyErr_NoMemory();
+ goto err;
+ }
+ }
+
+ if (PyEval_GetRestricted()) {
+ /* Restricted execution, get private tables */
+ PyObject *m = PyImport_ImportModule("copy_reg");
+
+ if (m == NULL)
+ goto err;
+ self->dispatch_table = PyObject_GetAttr(m, dispatch_table_str);
+ Py_DECREF(m);
+ if (self->dispatch_table == NULL)
+ goto err;
+ }
+ else {
+ self->dispatch_table = dispatch_table;
+ Py_INCREF(dispatch_table);
+ }
+ PyObject_GC_Track(self);
+
+ return self;
err:
- Py_DECREF(self);
- return NULL;
+ Py_DECREF(self);
+ return NULL;
}
static PyObject *
get_Pickler(PyObject *self, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"file", "protocol", NULL};
- PyObject *file = NULL;
- int proto = 0;
-
- /* XXX
- * The documented signature is Pickler(file, protocol=0), but this
- * accepts Pickler() and Pickler(integer) too. The meaning then
- * is clear as mud, undocumented, and not supported by pickle.py.
- * I'm told Zope uses this, but I haven't traced into this code
- * far enough to figure out what it means.
- */
- if (!PyArg_ParseTuple(args, "|i:Pickler", &proto)) {
- PyErr_Clear();
- proto = 0;
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i:Pickler",
- kwlist, &file, &proto))
- return NULL;
- }
- return (PyObject *)newPicklerobject(file, proto);
+ static char *kwlist[] = {"file", "protocol", NULL};
+ PyObject *file = NULL;
+ int proto = 0;
+
+ /* XXX
+ * The documented signature is Pickler(file, protocol=0), but this
+ * accepts Pickler() and Pickler(integer) too. The meaning then
+ * is clear as mud, undocumented, and not supported by pickle.py.
+ * I'm told Zope uses this, but I haven't traced into this code
+ * far enough to figure out what it means.
+ */
+ if (!PyArg_ParseTuple(args, "|i:Pickler", &proto)) {
+ PyErr_Clear();
+ proto = 0;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i:Pickler",
+ kwlist, &file, &proto))
+ return NULL;
+ }
+ return (PyObject *)newPicklerobject(file, proto);
}
static void
Pickler_dealloc(Picklerobject *self)
{
- PyObject_GC_UnTrack(self);
- Py_XDECREF(self->write);
- Py_XDECREF(self->memo);
- Py_XDECREF(self->fast_memo);
- Py_XDECREF(self->arg);
- Py_XDECREF(self->file);
- Py_XDECREF(self->pers_func);
- Py_XDECREF(self->inst_pers_func);
- Py_XDECREF(self->dispatch_table);
- PyMem_Free(self->write_buf);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ PyObject_GC_UnTrack(self);
+ Py_XDECREF(self->write);
+ Py_XDECREF(self->memo);
+ Py_XDECREF(self->fast_memo);
+ Py_XDECREF(self->arg);
+ Py_XDECREF(self->file);
+ Py_XDECREF(self->pers_func);
+ Py_XDECREF(self->inst_pers_func);
+ Py_XDECREF(self->dispatch_table);
+ PyMem_Free(self->write_buf);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static int
Pickler_traverse(Picklerobject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->write);
- Py_VISIT(self->memo);
- Py_VISIT(self->fast_memo);
- Py_VISIT(self->arg);
- Py_VISIT(self->file);
- Py_VISIT(self->pers_func);
- Py_VISIT(self->inst_pers_func);
- Py_VISIT(self->dispatch_table);
- return 0;
+ Py_VISIT(self->write);
+ Py_VISIT(self->memo);
+ Py_VISIT(self->fast_memo);
+ Py_VISIT(self->arg);
+ Py_VISIT(self->file);
+ Py_VISIT(self->pers_func);
+ Py_VISIT(self->inst_pers_func);
+ Py_VISIT(self->dispatch_table);
+ return 0;
}
static int
Pickler_clear(Picklerobject *self)
{
- Py_CLEAR(self->write);
- Py_CLEAR(self->memo);
- Py_CLEAR(self->fast_memo);
- Py_CLEAR(self->arg);
- Py_CLEAR(self->file);
- Py_CLEAR(self->pers_func);
- Py_CLEAR(self->inst_pers_func);
- Py_CLEAR(self->dispatch_table);
- return 0;
+ Py_CLEAR(self->write);
+ Py_CLEAR(self->memo);
+ Py_CLEAR(self->fast_memo);
+ Py_CLEAR(self->arg);
+ Py_CLEAR(self->file);
+ Py_CLEAR(self->pers_func);
+ Py_CLEAR(self->inst_pers_func);
+ Py_CLEAR(self->dispatch_table);
+ return 0;
}
static PyObject *
Pickler_get_pers_func(Picklerobject *p)
{
- if (p->pers_func == NULL)
- PyErr_SetString(PyExc_AttributeError, "persistent_id");
- else
- Py_INCREF(p->pers_func);
- return p->pers_func;
+ if (p->pers_func == NULL)
+ PyErr_SetString(PyExc_AttributeError, "persistent_id");
+ else
+ Py_INCREF(p->pers_func);
+ return p->pers_func;
}
static int
Pickler_set_pers_func(Picklerobject *p, PyObject *v)
{
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "attribute deletion is not supported");
- return -1;
- }
- Py_XDECREF(p->pers_func);
- Py_INCREF(v);
- p->pers_func = v;
- return 0;
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "attribute deletion is not supported");
+ return -1;
+ }
+ Py_XDECREF(p->pers_func);
+ Py_INCREF(v);
+ p->pers_func = v;
+ return 0;
}
static int
Pickler_set_inst_pers_func(Picklerobject *p, PyObject *v)
{
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "attribute deletion is not supported");
- return -1;
- }
- Py_XDECREF(p->inst_pers_func);
- Py_INCREF(v);
- p->inst_pers_func = v;
- return 0;
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "attribute deletion is not supported");
+ return -1;
+ }
+ Py_XDECREF(p->inst_pers_func);
+ Py_INCREF(v);
+ p->inst_pers_func = v;
+ return 0;
}
static PyObject *
Pickler_get_memo(Picklerobject *p)
{
- if (p->memo == NULL)
- PyErr_SetString(PyExc_AttributeError, "memo");
- else
- Py_INCREF(p->memo);
- return p->memo;
+ if (p->memo == NULL)
+ PyErr_SetString(PyExc_AttributeError, "memo");
+ else
+ Py_INCREF(p->memo);
+ return p->memo;
}
static int
Pickler_set_memo(Picklerobject *p, PyObject *v)
{
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "attribute deletion is not supported");
- return -1;
- }
- if (!PyDict_Check(v)) {
- PyErr_SetString(PyExc_TypeError, "memo must be a dictionary");
- return -1;
- }
- Py_XDECREF(p->memo);
- Py_INCREF(v);
- p->memo = v;
- return 0;
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "attribute deletion is not supported");
+ return -1;
+ }
+ if (!PyDict_Check(v)) {
+ PyErr_SetString(PyExc_TypeError, "memo must be a dictionary");
+ return -1;
+ }
+ Py_XDECREF(p->memo);
+ Py_INCREF(v);
+ p->memo = v;
+ return 0;
}
static PyObject *
Pickler_get_error(Picklerobject *p)
{
- /* why is this an attribute on the Pickler? */
- Py_INCREF(PicklingError);
- return PicklingError;
+ /* why is this an attribute on the Pickler? */
+ Py_INCREF(PicklingError);
+ return PicklingError;
}
static PyMemberDef Pickler_members[] = {
@@ -3174,143 +3174,143 @@ static PyTypeObject Picklertype = {
"cPickle.Pickler", /*tp_name*/
sizeof(Picklerobject), /*tp_basicsize*/
0,
- (destructor)Pickler_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
+ (destructor)Pickler_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
- Picklertype__doc__, /* tp_doc */
- (traverseproc)Pickler_traverse, /* tp_traverse */
- (inquiry)Pickler_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- Pickler_methods, /* tp_methods */
- Pickler_members, /* tp_members */
- Pickler_getsets, /* tp_getset */
+ Picklertype__doc__, /* tp_doc */
+ (traverseproc)Pickler_traverse, /* tp_traverse */
+ (inquiry)Pickler_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ Pickler_methods, /* tp_methods */
+ Pickler_members, /* tp_members */
+ Pickler_getsets, /* tp_getset */
};
static PyObject *
find_class(PyObject *py_module_name, PyObject *py_global_name, PyObject *fc)
{
- PyObject *global = 0, *module;
-
- if (fc) {
- if (fc==Py_None) {
- PyErr_SetString(UnpicklingError, "Global and instance "
- "pickles are not supported.");
- return NULL;
- }
- return PyObject_CallFunctionObjArgs(fc, py_module_name,
- py_global_name, NULL);
- }
-
- module = PySys_GetObject("modules");
- if (module == NULL)
- return NULL;
-
- module = PyDict_GetItem(module, py_module_name);
- if (module == NULL) {
- module = PyImport_Import(py_module_name);
- if (!module)
- return NULL;
- global = PyObject_GetAttr(module, py_global_name);
- Py_DECREF(module);
- }
- else
- global = PyObject_GetAttr(module, py_global_name);
- return global;
+ PyObject *global = 0, *module;
+
+ if (fc) {
+ if (fc==Py_None) {
+ PyErr_SetString(UnpicklingError, "Global and instance "
+ "pickles are not supported.");
+ return NULL;
+ }
+ return PyObject_CallFunctionObjArgs(fc, py_module_name,
+ py_global_name, NULL);
+ }
+
+ module = PySys_GetObject("modules");
+ if (module == NULL)
+ return NULL;
+
+ module = PyDict_GetItem(module, py_module_name);
+ if (module == NULL) {
+ module = PyImport_Import(py_module_name);
+ if (!module)
+ return NULL;
+ global = PyObject_GetAttr(module, py_global_name);
+ Py_DECREF(module);
+ }
+ else
+ global = PyObject_GetAttr(module, py_global_name);
+ return global;
}
static int
marker(Unpicklerobject *self)
{
- if (self->num_marks < 1) {
- PyErr_SetString(UnpicklingError, "could not find MARK");
- return -1;
- }
+ if (self->num_marks < 1) {
+ PyErr_SetString(UnpicklingError, "could not find MARK");
+ return -1;
+ }
- return self->marks[--self->num_marks];
+ return self->marks[--self->num_marks];
}
static int
load_none(Unpicklerobject *self)
{
- PDATA_APPEND(self->stack, Py_None, -1);
- return 0;
+ PDATA_APPEND(self->stack, Py_None, -1);
+ return 0;
}
static int
bad_readline(void)
{
- PyErr_SetString(UnpicklingError, "pickle data was truncated");
- return -1;
+ PyErr_SetString(UnpicklingError, "pickle data was truncated");
+ return -1;
}
static int
load_int(Unpicklerobject *self)
{
- PyObject *py_int = 0;
- char *endptr, *s;
- int len, res = -1;
- long l;
-
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
- if (!( s=pystrndup(s,len))) return -1;
-
- errno = 0;
- l = strtol(s, &endptr, 0);
-
- if (errno || (*endptr != '\n') || (endptr[1] != '\0')) {
- /* Hm, maybe we've got something long. Let's try reading
- it as a Python long object. */
- errno = 0;
- py_int = PyLong_FromString(s, NULL, 0);
- if (py_int == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "could not convert string to int");
- goto finally;
- }
- }
- else {
- if (len == 3 && (l == 0 || l == 1)) {
- if (!( py_int = PyBool_FromLong(l))) goto finally;
- }
- else {
- if (!( py_int = PyInt_FromLong(l))) goto finally;
- }
- }
-
- free(s);
- PDATA_PUSH(self->stack, py_int, -1);
- return 0;
+ PyObject *py_int = 0;
+ char *endptr, *s;
+ int len, res = -1;
+ long l;
+
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+ if (!( s=pystrndup(s,len))) return -1;
+
+ errno = 0;
+ l = strtol(s, &endptr, 0);
+
+ if (errno || (*endptr != '\n') || (endptr[1] != '\0')) {
+ /* Hm, maybe we've got something long. Let's try reading
+ it as a Python long object. */
+ errno = 0;
+ py_int = PyLong_FromString(s, NULL, 0);
+ if (py_int == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "could not convert string to int");
+ goto finally;
+ }
+ }
+ else {
+ if (len == 3 && (l == 0 || l == 1)) {
+ if (!( py_int = PyBool_FromLong(l))) goto finally;
+ }
+ else {
+ if (!( py_int = PyInt_FromLong(l))) goto finally;
+ }
+ }
+
+ free(s);
+ PDATA_PUSH(self->stack, py_int, -1);
+ return 0;
finally:
- free(s);
+ free(s);
- return res;
+ return res;
}
static int
load_bool(Unpicklerobject *self, PyObject *boolean)
{
- assert(boolean == Py_True || boolean == Py_False);
- PDATA_APPEND(self->stack, boolean, -1);
- return 0;
+ assert(boolean == Py_True || boolean == Py_False);
+ PDATA_APPEND(self->stack, boolean, -1);
+ return 0;
}
/* s contains x bytes of a little-endian integer. Return its value as a
@@ -3321,99 +3321,99 @@ load_bool(Unpicklerobject *self, PyObject *boolean)
static long
calc_binint(char *s, int x)
{
- unsigned char c;
- int i;
- long l;
+ unsigned char c;
+ int i;
+ long l;
- for (i = 0, l = 0L; i < x; i++) {
- c = (unsigned char)s[i];
- l |= (long)c << (i * 8);
- }
+ for (i = 0, l = 0L; i < x; i++) {
+ c = (unsigned char)s[i];
+ l |= (long)c << (i * 8);
+ }
#if SIZEOF_LONG > 4
- /* Unlike BININT1 and BININT2, BININT (more accurately BININT4)
- * is signed, so on a box with longs bigger than 4 bytes we need
- * to extend a BININT's sign bit to the full width.
- */
- if (x == 4 && l & (1L << 31))
- l |= (~0L) << 32;
+ /* Unlike BININT1 and BININT2, BININT (more accurately BININT4)
+ * is signed, so on a box with longs bigger than 4 bytes we need
+ * to extend a BININT's sign bit to the full width.
+ */
+ if (x == 4 && l & (1L << 31))
+ l |= (~0L) << 32;
#endif
- return l;
+ return l;
}
static int
load_binintx(Unpicklerobject *self, char *s, int x)
{
- PyObject *py_int = 0;
- long l;
+ PyObject *py_int = 0;
+ long l;
- l = calc_binint(s, x);
+ l = calc_binint(s, x);
- if (!( py_int = PyInt_FromLong(l)))
- return -1;
+ if (!( py_int = PyInt_FromLong(l)))
+ return -1;
- PDATA_PUSH(self->stack, py_int, -1);
- return 0;
+ PDATA_PUSH(self->stack, py_int, -1);
+ return 0;
}
static int
load_binint(Unpicklerobject *self)
{
- char *s;
+ char *s;
- if (self->read_func(self, &s, 4) < 0)
- return -1;
+ if (self->read_func(self, &s, 4) < 0)
+ return -1;
- return load_binintx(self, s, 4);
+ return load_binintx(self, s, 4);
}
static int
load_binint1(Unpicklerobject *self)
{
- char *s;
+ char *s;
- if (self->read_func(self, &s, 1) < 0)
- return -1;
+ if (self->read_func(self, &s, 1) < 0)
+ return -1;
- return load_binintx(self, s, 1);
+ return load_binintx(self, s, 1);
}
static int
load_binint2(Unpicklerobject *self)
{
- char *s;
+ char *s;
- if (self->read_func(self, &s, 2) < 0)
- return -1;
+ if (self->read_func(self, &s, 2) < 0)
+ return -1;
- return load_binintx(self, s, 2);
+ return load_binintx(self, s, 2);
}
static int
load_long(Unpicklerobject *self)
{
- PyObject *l = 0;
- char *end, *s;
- int len, res = -1;
+ PyObject *l = 0;
+ char *end, *s;
+ int len, res = -1;
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
- if (!( s=pystrndup(s,len))) return -1;
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+ if (!( s=pystrndup(s,len))) return -1;
- if (!( l = PyLong_FromString(s, &end, 0)))
- goto finally;
+ if (!( l = PyLong_FromString(s, &end, 0)))
+ goto finally;
- free(s);
- PDATA_PUSH(self->stack, l, -1);
- return 0;
+ free(s);
+ PDATA_PUSH(self->stack, l, -1);
+ return 0;
finally:
- free(s);
+ free(s);
- return res;
+ return res;
}
/* 'size' bytes contain the # of bytes of little-endian 256's-complement
@@ -3422,187 +3422,187 @@ load_long(Unpicklerobject *self)
static int
load_counted_long(Unpicklerobject *self, int size)
{
- Py_ssize_t i;
- char *nbytes;
- unsigned char *pdata;
- PyObject *along;
-
- assert(size == 1 || size == 4);
- i = self->read_func(self, &nbytes, size);
- if (i < 0) return -1;
-
- size = calc_binint(nbytes, size);
- if (size < 0) {
- /* Corrupt or hostile pickle -- we never write one like
- * this.
- */
- PyErr_SetString(UnpicklingError, "LONG pickle has negative "
- "byte count");
- return -1;
- }
-
- if (size == 0)
- along = PyLong_FromLong(0L);
- else {
- /* Read the raw little-endian bytes & convert. */
- i = self->read_func(self, (char **)&pdata, size);
- if (i < 0) return -1;
- along = _PyLong_FromByteArray(pdata, (size_t)size,
- 1 /* little endian */, 1 /* signed */);
- }
- if (along == NULL)
- return -1;
- PDATA_PUSH(self->stack, along, -1);
- return 0;
+ Py_ssize_t i;
+ char *nbytes;
+ unsigned char *pdata;
+ PyObject *along;
+
+ assert(size == 1 || size == 4);
+ i = self->read_func(self, &nbytes, size);
+ if (i < 0) return -1;
+
+ size = calc_binint(nbytes, size);
+ if (size < 0) {
+ /* Corrupt or hostile pickle -- we never write one like
+ * this.
+ */
+ PyErr_SetString(UnpicklingError, "LONG pickle has negative "
+ "byte count");
+ return -1;
+ }
+
+ if (size == 0)
+ along = PyLong_FromLong(0L);
+ else {
+ /* Read the raw little-endian bytes & convert. */
+ i = self->read_func(self, (char **)&pdata, size);
+ if (i < 0) return -1;
+ along = _PyLong_FromByteArray(pdata, (size_t)size,
+ 1 /* little endian */, 1 /* signed */);
+ }
+ if (along == NULL)
+ return -1;
+ PDATA_PUSH(self->stack, along, -1);
+ return 0;
}
static int
load_float(Unpicklerobject *self)
{
- PyObject *py_float = 0;
- char *endptr, *s;
- int len, res = -1;
- double d;
+ PyObject *py_float = 0;
+ char *endptr, *s;
+ int len, res = -1;
+ double d;
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
- if (!( s=pystrndup(s,len))) return -1;
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+ if (!( s=pystrndup(s,len))) return -1;
- errno = 0;
- d = PyOS_ascii_strtod(s, &endptr);
+ errno = 0;
+ d = PyOS_ascii_strtod(s, &endptr);
- if ((errno == ERANGE && !(fabs(d) <= 1.0)) ||
- (endptr[0] != '\n') || (endptr[1] != '\0')) {
- PyErr_SetString(PyExc_ValueError,
- "could not convert string to float");
- goto finally;
- }
+ if ((errno == ERANGE && !(fabs(d) <= 1.0)) ||
+ (endptr[0] != '\n') || (endptr[1] != '\0')) {
+ PyErr_SetString(PyExc_ValueError,
+ "could not convert string to float");
+ goto finally;
+ }
- if (!( py_float = PyFloat_FromDouble(d)))
- goto finally;
+ if (!( py_float = PyFloat_FromDouble(d)))
+ goto finally;
- free(s);
- PDATA_PUSH(self->stack, py_float, -1);
- return 0;
+ free(s);
+ PDATA_PUSH(self->stack, py_float, -1);
+ return 0;
finally:
- free(s);
+ free(s);
- return res;
+ return res;
}
static int
load_binfloat(Unpicklerobject *self)
{
- PyObject *py_float;
- double x;
- char *p;
+ PyObject *py_float;
+ double x;
+ char *p;
- if (self->read_func(self, &p, 8) < 0)
- return -1;
+ if (self->read_func(self, &p, 8) < 0)
+ return -1;
- x = _PyFloat_Unpack8((unsigned char *)p, 0);
- if (x == -1.0 && PyErr_Occurred())
- return -1;
+ x = _PyFloat_Unpack8((unsigned char *)p, 0);
+ if (x == -1.0 && PyErr_Occurred())
+ return -1;
- py_float = PyFloat_FromDouble(x);
- if (py_float == NULL)
- return -1;
+ py_float = PyFloat_FromDouble(x);
+ if (py_float == NULL)
+ return -1;
- PDATA_PUSH(self->stack, py_float, -1);
- return 0;
+ PDATA_PUSH(self->stack, py_float, -1);
+ return 0;
}
static int
load_string(Unpicklerobject *self)
{
- PyObject *str = 0;
- int len, res = -1;
- char *s, *p;
-
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
- if (!( s=pystrndup(s,len))) return -1;
-
-
- /* Strip outermost quotes */
- while (s[len-1] <= ' ')
- len--;
- if(s[0]=='"' && s[len-1]=='"'){
- s[len-1] = '\0';
- p = s + 1 ;
- len -= 2;
- } else if(s[0]=='\'' && s[len-1]=='\''){
- s[len-1] = '\0';
- p = s + 1 ;
- len -= 2;
- } else
- goto insecure;
- /********************************************/
-
- str = PyString_DecodeEscape(p, len, NULL, 0, NULL);
- free(s);
- if (str) {
- PDATA_PUSH(self->stack, str, -1);
- res = 0;
- }
- return res;
+ PyObject *str = 0;
+ int len, res = -1;
+ char *s, *p;
+
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+ if (!( s=pystrndup(s,len))) return -1;
+
+
+ /* Strip outermost quotes */
+ while (s[len-1] <= ' ')
+ len--;
+ if(s[0]=='"' && s[len-1]=='"'){
+ s[len-1] = '\0';
+ p = s + 1 ;
+ len -= 2;
+ } else if(s[0]=='\'' && s[len-1]=='\''){
+ s[len-1] = '\0';
+ p = s + 1 ;
+ len -= 2;
+ } else
+ goto insecure;
+ /********************************************/
+
+ str = PyString_DecodeEscape(p, len, NULL, 0, NULL);
+ free(s);
+ if (str) {
+ PDATA_PUSH(self->stack, str, -1);
+ res = 0;
+ }
+ return res;
insecure:
- free(s);
- PyErr_SetString(PyExc_ValueError,"insecure string pickle");
- return -1;
+ free(s);
+ PyErr_SetString(PyExc_ValueError,"insecure string pickle");
+ return -1;
}
static int
load_binstring(Unpicklerobject *self)
{
- PyObject *py_string = 0;
- long l;
- char *s;
+ PyObject *py_string = 0;
+ long l;
+ char *s;
- if (self->read_func(self, &s, 4) < 0) return -1;
+ if (self->read_func(self, &s, 4) < 0) return -1;
- l = calc_binint(s, 4);
- if (l < 0) {
- /* Corrupt or hostile pickle -- we never write one like
- * this.
- */
- PyErr_SetString(UnpicklingError,
- "BINSTRING pickle has negative byte count");
- return -1;
- }
+ l = calc_binint(s, 4);
+ if (l < 0) {
+ /* Corrupt or hostile pickle -- we never write one like
+ * this.
+ */
+ PyErr_SetString(UnpicklingError,
+ "BINSTRING pickle has negative byte count");
+ return -1;
+ }
- if (self->read_func(self, &s, l) < 0)
- return -1;
+ if (self->read_func(self, &s, l) < 0)
+ return -1;
- if (!( py_string = PyString_FromStringAndSize(s, l)))
- return -1;
+ if (!( py_string = PyString_FromStringAndSize(s, l)))
+ return -1;
- PDATA_PUSH(self->stack, py_string, -1);
- return 0;
+ PDATA_PUSH(self->stack, py_string, -1);
+ return 0;
}
static int
load_short_binstring(Unpicklerobject *self)
{
- PyObject *py_string = 0;
- unsigned char l;
- char *s;
+ PyObject *py_string = 0;
+ unsigned char l;
+ char *s;
- if (self->read_func(self, &s, 1) < 0)
- return -1;
+ if (self->read_func(self, &s, 1) < 0)
+ return -1;
- l = (unsigned char)s[0];
+ l = (unsigned char)s[0];
- if (self->read_func(self, &s, l) < 0) return -1;
+ if (self->read_func(self, &s, l) < 0) return -1;
- if (!( py_string = PyString_FromStringAndSize(s, l))) return -1;
+ if (!( py_string = PyString_FromStringAndSize(s, l))) return -1;
- PDATA_PUSH(self->stack, py_string, -1);
- return 0;
+ PDATA_PUSH(self->stack, py_string, -1);
+ return 0;
}
@@ -3610,21 +3610,21 @@ load_short_binstring(Unpicklerobject *self)
static int
load_unicode(Unpicklerobject *self)
{
- PyObject *str = 0;
- int len, res = -1;
- char *s;
+ PyObject *str = 0;
+ int len, res = -1;
+ char *s;
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 1) return bad_readline();
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 1) return bad_readline();
- if (!( str = PyUnicode_DecodeRawUnicodeEscape(s, len - 1, NULL)))
- goto finally;
+ if (!( str = PyUnicode_DecodeRawUnicodeEscape(s, len - 1, NULL)))
+ goto finally;
- PDATA_PUSH(self->stack, str, -1);
- return 0;
+ PDATA_PUSH(self->stack, str, -1);
+ return 0;
finally:
- return res;
+ return res;
}
#endif
@@ -3633,30 +3633,30 @@ load_unicode(Unpicklerobject *self)
static int
load_binunicode(Unpicklerobject *self)
{
- PyObject *unicode;
- long l;
- char *s;
+ PyObject *unicode;
+ long l;
+ char *s;
- if (self->read_func(self, &s, 4) < 0) return -1;
+ if (self->read_func(self, &s, 4) < 0) return -1;
- l = calc_binint(s, 4);
- if (l < 0) {
- /* Corrupt or hostile pickle -- we never write one like
- * this.
- */
- PyErr_SetString(UnpicklingError,
- "BINUNICODE pickle has negative byte count");
- return -1;
- }
+ l = calc_binint(s, 4);
+ if (l < 0) {
+ /* Corrupt or hostile pickle -- we never write one like
+ * this.
+ */
+ PyErr_SetString(UnpicklingError,
+ "BINUNICODE pickle has negative byte count");
+ return -1;
+ }
- if (self->read_func(self, &s, l) < 0)
- return -1;
+ if (self->read_func(self, &s, l) < 0)
+ return -1;
- if (!( unicode = PyUnicode_DecodeUTF8(s, l, NULL)))
- return -1;
+ if (!( unicode = PyUnicode_DecodeUTF8(s, l, NULL)))
+ return -1;
- PDATA_PUSH(self->stack, unicode, -1);
- return 0;
+ PDATA_PUSH(self->stack, unicode, -1);
+ return 0;
}
#endif
@@ -3664,504 +3664,504 @@ load_binunicode(Unpicklerobject *self)
static int
load_tuple(Unpicklerobject *self)
{
- PyObject *tup;
- int i;
+ PyObject *tup;
+ int i;
- if ((i = marker(self)) < 0) return -1;
- if (!( tup=Pdata_popTuple(self->stack, i))) return -1;
- PDATA_PUSH(self->stack, tup, -1);
- return 0;
+ if ((i = marker(self)) < 0) return -1;
+ if (!( tup=Pdata_popTuple(self->stack, i))) return -1;
+ PDATA_PUSH(self->stack, tup, -1);
+ return 0;
}
static int
load_counted_tuple(Unpicklerobject *self, int len)
{
- PyObject *tup = PyTuple_New(len);
+ PyObject *tup = PyTuple_New(len);
- if (tup == NULL)
- return -1;
+ if (tup == NULL)
+ return -1;
- while (--len >= 0) {
- PyObject *element;
+ while (--len >= 0) {
+ PyObject *element;
- PDATA_POP(self->stack, element);
- if (element == NULL)
- return -1;
- PyTuple_SET_ITEM(tup, len, element);
- }
- PDATA_PUSH(self->stack, tup, -1);
- return 0;
+ PDATA_POP(self->stack, element);
+ if (element == NULL)
+ return -1;
+ PyTuple_SET_ITEM(tup, len, element);
+ }
+ PDATA_PUSH(self->stack, tup, -1);
+ return 0;
}
static int
load_empty_list(Unpicklerobject *self)
{
- PyObject *list;
+ PyObject *list;
- if (!( list=PyList_New(0))) return -1;
- PDATA_PUSH(self->stack, list, -1);
- return 0;
+ if (!( list=PyList_New(0))) return -1;
+ PDATA_PUSH(self->stack, list, -1);
+ return 0;
}
static int
load_empty_dict(Unpicklerobject *self)
{
- PyObject *dict;
+ PyObject *dict;
- if (!( dict=PyDict_New())) return -1;
- PDATA_PUSH(self->stack, dict, -1);
- return 0;
+ if (!( dict=PyDict_New())) return -1;
+ PDATA_PUSH(self->stack, dict, -1);
+ return 0;
}
static int
load_list(Unpicklerobject *self)
{
- PyObject *list = 0;
- int i;
+ PyObject *list = 0;
+ int i;
- if ((i = marker(self)) < 0) return -1;
- if (!( list=Pdata_popList(self->stack, i))) return -1;
- PDATA_PUSH(self->stack, list, -1);
- return 0;
+ if ((i = marker(self)) < 0) return -1;
+ if (!( list=Pdata_popList(self->stack, i))) return -1;
+ PDATA_PUSH(self->stack, list, -1);
+ return 0;
}
static int
load_dict(Unpicklerobject *self)
{
- PyObject *dict, *key, *value;
- int i, j, k;
+ PyObject *dict, *key, *value;
+ int i, j, k;
- if ((i = marker(self)) < 0) return -1;
- j=self->stack->length;
+ if ((i = marker(self)) < 0) return -1;
+ j=self->stack->length;
- if (!( dict = PyDict_New())) return -1;
+ if (!( dict = PyDict_New())) return -1;
- for (k = i+1; k < j; k += 2) {
- key =self->stack->data[k-1];
- value=self->stack->data[k ];
- if (PyDict_SetItem(dict, key, value) < 0) {
- Py_DECREF(dict);
- return -1;
- }
- }
- Pdata_clear(self->stack, i);
- PDATA_PUSH(self->stack, dict, -1);
- return 0;
+ for (k = i+1; k < j; k += 2) {
+ key =self->stack->data[k-1];
+ value=self->stack->data[k ];
+ if (PyDict_SetItem(dict, key, value) < 0) {
+ Py_DECREF(dict);
+ return -1;
+ }
+ }
+ Pdata_clear(self->stack, i);
+ PDATA_PUSH(self->stack, dict, -1);
+ return 0;
}
static PyObject *
Instance_New(PyObject *cls, PyObject *args)
{
- PyObject *r = 0;
+ PyObject *r = 0;
- if (PyClass_Check(cls)) {
- int l;
+ if (PyClass_Check(cls)) {
+ int l;
- if ((l=PyObject_Size(args)) < 0) goto err;
- if (!( l )) {
- PyObject *__getinitargs__;
+ if ((l=PyObject_Size(args)) < 0) goto err;
+ if (!( l )) {
+ PyObject *__getinitargs__;
- __getinitargs__ = PyObject_GetAttr(cls,
- __getinitargs___str);
- if (!__getinitargs__) {
- /* We have a class with no __getinitargs__,
- so bypass usual construction */
- PyObject *inst;
+ __getinitargs__ = PyObject_GetAttr(cls,
+ __getinitargs___str);
+ if (!__getinitargs__) {
+ /* We have a class with no __getinitargs__,
+ so bypass usual construction */
+ PyObject *inst;
- PyErr_Clear();
- if (!( inst=PyInstance_NewRaw(cls, NULL)))
- goto err;
- return inst;
- }
- Py_DECREF(__getinitargs__);
- }
+ PyErr_Clear();
+ if (!( inst=PyInstance_NewRaw(cls, NULL)))
+ goto err;
+ return inst;
+ }
+ Py_DECREF(__getinitargs__);
+ }
- if ((r=PyInstance_New(cls, args, NULL))) return r;
- else goto err;
- }
+ if ((r=PyInstance_New(cls, args, NULL))) return r;
+ else goto err;
+ }
- if ((r=PyObject_CallObject(cls, args))) return r;
+ if ((r=PyObject_CallObject(cls, args))) return r;
err:
- {
- PyObject *tp, *v, *tb, *tmp_value;
-
- PyErr_Fetch(&tp, &v, &tb);
- tmp_value = v;
- /* NULL occurs when there was a KeyboardInterrupt */
- if (tmp_value == NULL)
- tmp_value = Py_None;
- if ((r = PyTuple_Pack(3, tmp_value, cls, args))) {
- Py_XDECREF(v);
- v=r;
- }
- PyErr_Restore(tp,v,tb);
- }
- return NULL;
+ {
+ PyObject *tp, *v, *tb, *tmp_value;
+
+ PyErr_Fetch(&tp, &v, &tb);
+ tmp_value = v;
+ /* NULL occurs when there was a KeyboardInterrupt */
+ if (tmp_value == NULL)
+ tmp_value = Py_None;
+ if ((r = PyTuple_Pack(3, tmp_value, cls, args))) {
+ Py_XDECREF(v);
+ v=r;
+ }
+ PyErr_Restore(tp,v,tb);
+ }
+ return NULL;
}
static int
load_obj(Unpicklerobject *self)
{
- PyObject *class, *tup, *obj=0;
- int i;
+ PyObject *class, *tup, *obj=0;
+ int i;
- if ((i = marker(self)) < 0) return -1;
- if (!( tup=Pdata_popTuple(self->stack, i+1))) return -1;
- PDATA_POP(self->stack, class);
- if (class) {
- obj = Instance_New(class, tup);
- Py_DECREF(class);
- }
- Py_DECREF(tup);
+ if ((i = marker(self)) < 0) return -1;
+ if (!( tup=Pdata_popTuple(self->stack, i+1))) return -1;
+ PDATA_POP(self->stack, class);
+ if (class) {
+ obj = Instance_New(class, tup);
+ Py_DECREF(class);
+ }
+ Py_DECREF(tup);
- if (! obj) return -1;
- PDATA_PUSH(self->stack, obj, -1);
- return 0;
+ if (! obj) return -1;
+ PDATA_PUSH(self->stack, obj, -1);
+ return 0;
}
static int
load_inst(Unpicklerobject *self)
{
- PyObject *tup, *class=0, *obj=0, *module_name, *class_name;
- int i, len;
- char *s;
+ PyObject *tup, *class=0, *obj=0, *module_name, *class_name;
+ int i, len;
+ char *s;
- if ((i = marker(self)) < 0) return -1;
+ if ((i = marker(self)) < 0) return -1;
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
- module_name = PyString_FromStringAndSize(s, len - 1);
- if (!module_name) return -1;
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+ module_name = PyString_FromStringAndSize(s, len - 1);
+ if (!module_name) return -1;
- if ((len = self->readline_func(self, &s)) >= 0) {
- if (len < 2) return bad_readline();
- if ((class_name = PyString_FromStringAndSize(s, len - 1))) {
- class = find_class(module_name, class_name,
- self->find_class);
- Py_DECREF(class_name);
- }
- }
- Py_DECREF(module_name);
+ if ((len = self->readline_func(self, &s)) >= 0) {
+ if (len < 2) return bad_readline();
+ if ((class_name = PyString_FromStringAndSize(s, len - 1))) {
+ class = find_class(module_name, class_name,
+ self->find_class);
+ Py_DECREF(class_name);
+ }
+ }
+ Py_DECREF(module_name);
- if (! class) return -1;
+ if (! class) return -1;
- if ((tup=Pdata_popTuple(self->stack, i))) {
- obj = Instance_New(class, tup);
- Py_DECREF(tup);
- }
- Py_DECREF(class);
+ if ((tup=Pdata_popTuple(self->stack, i))) {
+ obj = Instance_New(class, tup);
+ Py_DECREF(tup);
+ }
+ Py_DECREF(class);
- if (! obj) return -1;
+ if (! obj) return -1;
- PDATA_PUSH(self->stack, obj, -1);
- return 0;
+ PDATA_PUSH(self->stack, obj, -1);
+ return 0;
}
static int
load_newobj(Unpicklerobject *self)
{
- PyObject *args = NULL;
- PyObject *clsraw = NULL;
- PyTypeObject *cls; /* clsraw cast to its true type */
- PyObject *obj;
-
- /* Stack is ... cls argtuple, and we want to call
- * cls.__new__(cls, *argtuple).
- */
- PDATA_POP(self->stack, args);
- if (args == NULL) goto Fail;
- if (! PyTuple_Check(args)) {
- PyErr_SetString(UnpicklingError, "NEWOBJ expected an arg "
- "tuple.");
- goto Fail;
- }
-
- PDATA_POP(self->stack, clsraw);
- cls = (PyTypeObject *)clsraw;
- if (cls == NULL) goto Fail;
- if (! PyType_Check(cls)) {
- PyErr_SetString(UnpicklingError, "NEWOBJ class argument "
- "isn't a type object");
- goto Fail;
- }
- if (cls->tp_new == NULL) {
- PyErr_SetString(UnpicklingError, "NEWOBJ class argument "
- "has NULL tp_new");
- goto Fail;
- }
-
- /* Call __new__. */
- obj = cls->tp_new(cls, args, NULL);
- if (obj == NULL) goto Fail;
-
- Py_DECREF(args);
- Py_DECREF(clsraw);
- PDATA_PUSH(self->stack, obj, -1);
- return 0;
+ PyObject *args = NULL;
+ PyObject *clsraw = NULL;
+ PyTypeObject *cls; /* clsraw cast to its true type */
+ PyObject *obj;
+
+ /* Stack is ... cls argtuple, and we want to call
+ * cls.__new__(cls, *argtuple).
+ */
+ PDATA_POP(self->stack, args);
+ if (args == NULL) goto Fail;
+ if (! PyTuple_Check(args)) {
+ PyErr_SetString(UnpicklingError, "NEWOBJ expected an arg "
+ "tuple.");
+ goto Fail;
+ }
+
+ PDATA_POP(self->stack, clsraw);
+ cls = (PyTypeObject *)clsraw;
+ if (cls == NULL) goto Fail;
+ if (! PyType_Check(cls)) {
+ PyErr_SetString(UnpicklingError, "NEWOBJ class argument "
+ "isn't a type object");
+ goto Fail;
+ }
+ if (cls->tp_new == NULL) {
+ PyErr_SetString(UnpicklingError, "NEWOBJ class argument "
+ "has NULL tp_new");
+ goto Fail;
+ }
+
+ /* Call __new__. */
+ obj = cls->tp_new(cls, args, NULL);
+ if (obj == NULL) goto Fail;
+
+ Py_DECREF(args);
+ Py_DECREF(clsraw);
+ PDATA_PUSH(self->stack, obj, -1);
+ return 0;
Fail:
- Py_XDECREF(args);
- Py_XDECREF(clsraw);
- return -1;
+ Py_XDECREF(args);
+ Py_XDECREF(clsraw);
+ return -1;
}
static int
load_global(Unpicklerobject *self)
{
- PyObject *class = 0, *module_name = 0, *class_name = 0;
- int len;
- char *s;
+ PyObject *class = 0, *module_name = 0, *class_name = 0;
+ int len;
+ char *s;
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
- module_name = PyString_FromStringAndSize(s, len - 1);
- if (!module_name) return -1;
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+ module_name = PyString_FromStringAndSize(s, len - 1);
+ if (!module_name) return -1;
- if ((len = self->readline_func(self, &s)) >= 0) {
- if (len < 2) {
- Py_DECREF(module_name);
- return bad_readline();
- }
- if ((class_name = PyString_FromStringAndSize(s, len - 1))) {
- class = find_class(module_name, class_name,
- self->find_class);
- Py_DECREF(class_name);
- }
- }
- Py_DECREF(module_name);
+ if ((len = self->readline_func(self, &s)) >= 0) {
+ if (len < 2) {
+ Py_DECREF(module_name);
+ return bad_readline();
+ }
+ if ((class_name = PyString_FromStringAndSize(s, len - 1))) {
+ class = find_class(module_name, class_name,
+ self->find_class);
+ Py_DECREF(class_name);
+ }
+ }
+ Py_DECREF(module_name);
- if (! class) return -1;
- PDATA_PUSH(self->stack, class, -1);
- return 0;
+ if (! class) return -1;
+ PDATA_PUSH(self->stack, class, -1);
+ return 0;
}
static int
load_persid(Unpicklerobject *self)
{
- PyObject *pid = 0;
- int len;
- char *s;
-
- if (self->pers_func) {
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
-
- pid = PyString_FromStringAndSize(s, len - 1);
- if (!pid) return -1;
-
- if (PyList_Check(self->pers_func)) {
- if (PyList_Append(self->pers_func, pid) < 0) {
- Py_DECREF(pid);
- return -1;
- }
- }
- else {
- ARG_TUP(self, pid);
- if (self->arg) {
- pid = PyObject_Call(self->pers_func, self->arg,
- NULL);
- FREE_ARG_TUP(self);
- }
- }
-
- if (! pid) return -1;
-
- PDATA_PUSH(self->stack, pid, -1);
- return 0;
- }
- else {
- PyErr_SetString(UnpicklingError,
- "A load persistent id instruction was encountered,\n"
- "but no persistent_load function was specified.");
- return -1;
- }
+ PyObject *pid = 0;
+ int len;
+ char *s;
+
+ if (self->pers_func) {
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+
+ pid = PyString_FromStringAndSize(s, len - 1);
+ if (!pid) return -1;
+
+ if (PyList_Check(self->pers_func)) {
+ if (PyList_Append(self->pers_func, pid) < 0) {
+ Py_DECREF(pid);
+ return -1;
+ }
+ }
+ else {
+ ARG_TUP(self, pid);
+ if (self->arg) {
+ pid = PyObject_Call(self->pers_func, self->arg,
+ NULL);
+ FREE_ARG_TUP(self);
+ }
+ }
+
+ if (! pid) return -1;
+
+ PDATA_PUSH(self->stack, pid, -1);
+ return 0;
+ }
+ else {
+ PyErr_SetString(UnpicklingError,
+ "A load persistent id instruction was encountered,\n"
+ "but no persistent_load function was specified.");
+ return -1;
+ }
}
static int
load_binpersid(Unpicklerobject *self)
{
- PyObject *pid = 0;
-
- if (self->pers_func) {
- PDATA_POP(self->stack, pid);
- if (! pid) return -1;
-
- if (PyList_Check(self->pers_func)) {
- if (PyList_Append(self->pers_func, pid) < 0) {
- Py_DECREF(pid);
- return -1;
- }
- }
- else {
- ARG_TUP(self, pid);
- if (self->arg) {
- pid = PyObject_Call(self->pers_func, self->arg,
- NULL);
- FREE_ARG_TUP(self);
- }
- if (! pid) return -1;
- }
-
- PDATA_PUSH(self->stack, pid, -1);
- return 0;
- }
- else {
- PyErr_SetString(UnpicklingError,
- "A load persistent id instruction was encountered,\n"
- "but no persistent_load function was specified.");
- return -1;
- }
+ PyObject *pid = 0;
+
+ if (self->pers_func) {
+ PDATA_POP(self->stack, pid);
+ if (! pid) return -1;
+
+ if (PyList_Check(self->pers_func)) {
+ if (PyList_Append(self->pers_func, pid) < 0) {
+ Py_DECREF(pid);
+ return -1;
+ }
+ }
+ else {
+ ARG_TUP(self, pid);
+ if (self->arg) {
+ pid = PyObject_Call(self->pers_func, self->arg,
+ NULL);
+ FREE_ARG_TUP(self);
+ }
+ if (! pid) return -1;
+ }
+
+ PDATA_PUSH(self->stack, pid, -1);
+ return 0;
+ }
+ else {
+ PyErr_SetString(UnpicklingError,
+ "A load persistent id instruction was encountered,\n"
+ "but no persistent_load function was specified.");
+ return -1;
+ }
}
static int
load_pop(Unpicklerobject *self)
{
- int len = self->stack->length;
-
- /* Note that we split the (pickle.py) stack into two stacks,
- an object stack and a mark stack. We have to be clever and
- pop the right one. We do this by looking at the top of the
- mark stack first, and only signalling a stack underflow if
- the object stack is empty and the mark stack doesn't match
- our expectations.
- */
- if (self->num_marks > 0 && self->marks[self->num_marks - 1] == len) {
- self->num_marks--;
- } else if (len > 0) {
- len--;
- Py_DECREF(self->stack->data[len]);
- self->stack->length = len;
- } else {
- return stackUnderflow();
- }
- return 0;
+ int len = self->stack->length;
+
+ /* Note that we split the (pickle.py) stack into two stacks,
+ an object stack and a mark stack. We have to be clever and
+ pop the right one. We do this by looking at the top of the
+ mark stack first, and only signalling a stack underflow if
+ the object stack is empty and the mark stack doesn't match
+ our expectations.
+ */
+ if (self->num_marks > 0 && self->marks[self->num_marks - 1] == len) {
+ self->num_marks--;
+ } else if (len > 0) {
+ len--;
+ Py_DECREF(self->stack->data[len]);
+ self->stack->length = len;
+ } else {
+ return stackUnderflow();
+ }
+ return 0;
}
static int
load_pop_mark(Unpicklerobject *self)
{
- int i;
+ int i;
- if ((i = marker(self)) < 0)
- return -1;
+ if ((i = marker(self)) < 0)
+ return -1;
- Pdata_clear(self->stack, i);
+ Pdata_clear(self->stack, i);
- return 0;
+ return 0;
}
static int
load_dup(Unpicklerobject *self)
{
- PyObject *last;
- int len;
+ PyObject *last;
+ int len;
- if ((len = self->stack->length) <= 0) return stackUnderflow();
- last=self->stack->data[len-1];
- Py_INCREF(last);
- PDATA_PUSH(self->stack, last, -1);
- return 0;
+ if ((len = self->stack->length) <= 0) return stackUnderflow();
+ last=self->stack->data[len-1];
+ Py_INCREF(last);
+ PDATA_PUSH(self->stack, last, -1);
+ return 0;
}
static int
load_get(Unpicklerobject *self)
{
- PyObject *py_str = 0, *value = 0;
- int len;
- char *s;
- int rc;
+ PyObject *py_str = 0, *value = 0;
+ int len;
+ char *s;
+ int rc;
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
- if (!( py_str = PyString_FromStringAndSize(s, len - 1))) return -1;
+ if (!( py_str = PyString_FromStringAndSize(s, len - 1))) return -1;
- value = PyDict_GetItem(self->memo, py_str);
- if (! value) {
- PyErr_SetObject(BadPickleGet, py_str);
- rc = -1;
- }
- else {
- PDATA_APPEND(self->stack, value, -1);
- rc = 0;
- }
+ value = PyDict_GetItem(self->memo, py_str);
+ if (! value) {
+ PyErr_SetObject(BadPickleGet, py_str);
+ rc = -1;
+ }
+ else {
+ PDATA_APPEND(self->stack, value, -1);
+ rc = 0;
+ }
- Py_DECREF(py_str);
- return rc;
+ Py_DECREF(py_str);
+ return rc;
}
static int
load_binget(Unpicklerobject *self)
{
- PyObject *py_key = 0, *value = 0;
- unsigned char key;
- char *s;
- int rc;
+ PyObject *py_key = 0, *value = 0;
+ unsigned char key;
+ char *s;
+ int rc;
- if (self->read_func(self, &s, 1) < 0) return -1;
+ if (self->read_func(self, &s, 1) < 0) return -1;
- key = (unsigned char)s[0];
- if (!( py_key = PyInt_FromLong((long)key))) return -1;
+ key = (unsigned char)s[0];
+ if (!( py_key = PyInt_FromLong((long)key))) return -1;
- value = PyDict_GetItem(self->memo, py_key);
- if (! value) {
- PyErr_SetObject(BadPickleGet, py_key);
- rc = -1;
- }
- else {
- PDATA_APPEND(self->stack, value, -1);
- rc = 0;
- }
+ value = PyDict_GetItem(self->memo, py_key);
+ if (! value) {
+ PyErr_SetObject(BadPickleGet, py_key);
+ rc = -1;
+ }
+ else {
+ PDATA_APPEND(self->stack, value, -1);
+ rc = 0;
+ }
- Py_DECREF(py_key);
- return rc;
+ Py_DECREF(py_key);
+ return rc;
}
static int
load_long_binget(Unpicklerobject *self)
{
- PyObject *py_key = 0, *value = 0;
- unsigned char c;
- char *s;
- long key;
- int rc;
-
- if (self->read_func(self, &s, 4) < 0) return -1;
-
- c = (unsigned char)s[0];
- key = (long)c;
- c = (unsigned char)s[1];
- key |= (long)c << 8;
- c = (unsigned char)s[2];
- key |= (long)c << 16;
- c = (unsigned char)s[3];
- key |= (long)c << 24;
-
- if (!( py_key = PyInt_FromLong((long)key))) return -1;
-
- value = PyDict_GetItem(self->memo, py_key);
- if (! value) {
- PyErr_SetObject(BadPickleGet, py_key);
- rc = -1;
- }
- else {
- PDATA_APPEND(self->stack, value, -1);
- rc = 0;
- }
+ PyObject *py_key = 0, *value = 0;
+ unsigned char c;
+ char *s;
+ long key;
+ int rc;
+
+ if (self->read_func(self, &s, 4) < 0) return -1;
+
+ c = (unsigned char)s[0];
+ key = (long)c;
+ c = (unsigned char)s[1];
+ key |= (long)c << 8;
+ c = (unsigned char)s[2];
+ key |= (long)c << 16;
+ c = (unsigned char)s[3];
+ key |= (long)c << 24;
+
+ if (!( py_key = PyInt_FromLong((long)key))) return -1;
+
+ value = PyDict_GetItem(self->memo, py_key);
+ if (! value) {
+ PyErr_SetObject(BadPickleGet, py_key);
+ rc = -1;
+ }
+ else {
+ PDATA_APPEND(self->stack, value, -1);
+ rc = 0;
+ }
- Py_DECREF(py_key);
- return rc;
+ Py_DECREF(py_key);
+ return rc;
}
/* Push an object from the extension registry (EXT[124]). nbytes is
@@ -4170,391 +4170,391 @@ load_long_binget(Unpicklerobject *self)
static int
load_extension(Unpicklerobject *self, int nbytes)
{
- char *codebytes; /* the nbytes bytes after the opcode */
- long code; /* calc_binint returns long */
- PyObject *py_code; /* code as a Python int */
- PyObject *obj; /* the object to push */
- PyObject *pair; /* (module_name, class_name) */
- PyObject *module_name, *class_name;
-
- assert(nbytes == 1 || nbytes == 2 || nbytes == 4);
- if (self->read_func(self, &codebytes, nbytes) < 0) return -1;
- code = calc_binint(codebytes, nbytes);
- if (code <= 0) { /* note that 0 is forbidden */
- /* Corrupt or hostile pickle. */
- PyErr_SetString(UnpicklingError, "EXT specifies code <= 0");
- return -1;
- }
-
- /* Look for the code in the cache. */
- py_code = PyInt_FromLong(code);
- if (py_code == NULL) return -1;
- obj = PyDict_GetItem(extension_cache, py_code);
- if (obj != NULL) {
- /* Bingo. */
- Py_DECREF(py_code);
- PDATA_APPEND(self->stack, obj, -1);
- return 0;
- }
-
- /* Look up the (module_name, class_name) pair. */
- pair = PyDict_GetItem(inverted_registry, py_code);
- if (pair == NULL) {
- Py_DECREF(py_code);
- PyErr_Format(PyExc_ValueError, "unregistered extension "
- "code %ld", code);
- return -1;
- }
- /* Since the extension registry is manipulable via Python code,
- * confirm that pair is really a 2-tuple of strings.
- */
- if (!PyTuple_Check(pair) || PyTuple_Size(pair) != 2 ||
- !PyString_Check(module_name = PyTuple_GET_ITEM(pair, 0)) ||
- !PyString_Check(class_name = PyTuple_GET_ITEM(pair, 1))) {
- Py_DECREF(py_code);
- PyErr_Format(PyExc_ValueError, "_inverted_registry[%ld] "
- "isn't a 2-tuple of strings", code);
- return -1;
- }
- /* Load the object. */
- obj = find_class(module_name, class_name, self->find_class);
- if (obj == NULL) {
- Py_DECREF(py_code);
- return -1;
- }
- /* Cache code -> obj. */
- code = PyDict_SetItem(extension_cache, py_code, obj);
- Py_DECREF(py_code);
- if (code < 0) {
- Py_DECREF(obj);
- return -1;
- }
- PDATA_PUSH(self->stack, obj, -1);
- return 0;
+ char *codebytes; /* the nbytes bytes after the opcode */
+ long code; /* calc_binint returns long */
+ PyObject *py_code; /* code as a Python int */
+ PyObject *obj; /* the object to push */
+ PyObject *pair; /* (module_name, class_name) */
+ PyObject *module_name, *class_name;
+
+ assert(nbytes == 1 || nbytes == 2 || nbytes == 4);
+ if (self->read_func(self, &codebytes, nbytes) < 0) return -1;
+ code = calc_binint(codebytes, nbytes);
+ if (code <= 0) { /* note that 0 is forbidden */
+ /* Corrupt or hostile pickle. */
+ PyErr_SetString(UnpicklingError, "EXT specifies code <= 0");
+ return -1;
+ }
+
+ /* Look for the code in the cache. */
+ py_code = PyInt_FromLong(code);
+ if (py_code == NULL) return -1;
+ obj = PyDict_GetItem(extension_cache, py_code);
+ if (obj != NULL) {
+ /* Bingo. */
+ Py_DECREF(py_code);
+ PDATA_APPEND(self->stack, obj, -1);
+ return 0;
+ }
+
+ /* Look up the (module_name, class_name) pair. */
+ pair = PyDict_GetItem(inverted_registry, py_code);
+ if (pair == NULL) {
+ Py_DECREF(py_code);
+ PyErr_Format(PyExc_ValueError, "unregistered extension "
+ "code %ld", code);
+ return -1;
+ }
+ /* Since the extension registry is manipulable via Python code,
+ * confirm that pair is really a 2-tuple of strings.
+ */
+ if (!PyTuple_Check(pair) || PyTuple_Size(pair) != 2 ||
+ !PyString_Check(module_name = PyTuple_GET_ITEM(pair, 0)) ||
+ !PyString_Check(class_name = PyTuple_GET_ITEM(pair, 1))) {
+ Py_DECREF(py_code);
+ PyErr_Format(PyExc_ValueError, "_inverted_registry[%ld] "
+ "isn't a 2-tuple of strings", code);
+ return -1;
+ }
+ /* Load the object. */
+ obj = find_class(module_name, class_name, self->find_class);
+ if (obj == NULL) {
+ Py_DECREF(py_code);
+ return -1;
+ }
+ /* Cache code -> obj. */
+ code = PyDict_SetItem(extension_cache, py_code, obj);
+ Py_DECREF(py_code);
+ if (code < 0) {
+ Py_DECREF(obj);
+ return -1;
+ }
+ PDATA_PUSH(self->stack, obj, -1);
+ return 0;
}
static int
load_put(Unpicklerobject *self)
{
- PyObject *py_str = 0, *value = 0;
- int len, l;
- char *s;
+ PyObject *py_str = 0, *value = 0;
+ int len, l;
+ char *s;
- if ((l = self->readline_func(self, &s)) < 0) return -1;
- if (l < 2) return bad_readline();
- if (!( len=self->stack->length )) return stackUnderflow();
- if (!( py_str = PyString_FromStringAndSize(s, l - 1))) return -1;
- value=self->stack->data[len-1];
- l=PyDict_SetItem(self->memo, py_str, value);
- Py_DECREF(py_str);
- return l;
+ if ((l = self->readline_func(self, &s)) < 0) return -1;
+ if (l < 2) return bad_readline();
+ if (!( len=self->stack->length )) return stackUnderflow();
+ if (!( py_str = PyString_FromStringAndSize(s, l - 1))) return -1;
+ value=self->stack->data[len-1];
+ l=PyDict_SetItem(self->memo, py_str, value);
+ Py_DECREF(py_str);
+ return l;
}
static int
load_binput(Unpicklerobject *self)
{
- PyObject *py_key = 0, *value = 0;
- unsigned char key;
- char *s;
- int len;
+ PyObject *py_key = 0, *value = 0;
+ unsigned char key;
+ char *s;
+ int len;
- if (self->read_func(self, &s, 1) < 0) return -1;
- if (!( (len=self->stack->length) > 0 )) return stackUnderflow();
+ if (self->read_func(self, &s, 1) < 0) return -1;
+ if (!( (len=self->stack->length) > 0 )) return stackUnderflow();
- key = (unsigned char)s[0];
+ key = (unsigned char)s[0];
- if (!( py_key = PyInt_FromLong((long)key))) return -1;
- value=self->stack->data[len-1];
- len=PyDict_SetItem(self->memo, py_key, value);
- Py_DECREF(py_key);
- return len;
+ if (!( py_key = PyInt_FromLong((long)key))) return -1;
+ value=self->stack->data[len-1];
+ len=PyDict_SetItem(self->memo, py_key, value);
+ Py_DECREF(py_key);
+ return len;
}
static int
load_long_binput(Unpicklerobject *self)
{
- PyObject *py_key = 0, *value = 0;
- long key;
- unsigned char c;
- char *s;
- int len;
+ PyObject *py_key = 0, *value = 0;
+ long key;
+ unsigned char c;
+ char *s;
+ int len;
- if (self->read_func(self, &s, 4) < 0) return -1;
- if (!( len=self->stack->length )) return stackUnderflow();
+ if (self->read_func(self, &s, 4) < 0) return -1;
+ if (!( len=self->stack->length )) return stackUnderflow();
- c = (unsigned char)s[0];
- key = (long)c;
- c = (unsigned char)s[1];
- key |= (long)c << 8;
- c = (unsigned char)s[2];
- key |= (long)c << 16;
- c = (unsigned char)s[3];
- key |= (long)c << 24;
+ c = (unsigned char)s[0];
+ key = (long)c;
+ c = (unsigned char)s[1];
+ key |= (long)c << 8;
+ c = (unsigned char)s[2];
+ key |= (long)c << 16;
+ c = (unsigned char)s[3];
+ key |= (long)c << 24;
- if (!( py_key = PyInt_FromLong(key))) return -1;
- value=self->stack->data[len-1];
- len=PyDict_SetItem(self->memo, py_key, value);
- Py_DECREF(py_key);
- return len;
+ if (!( py_key = PyInt_FromLong(key))) return -1;
+ value=self->stack->data[len-1];
+ len=PyDict_SetItem(self->memo, py_key, value);
+ Py_DECREF(py_key);
+ return len;
}
static int
do_append(Unpicklerobject *self, int x)
{
- PyObject *value = 0, *list = 0, *append_method = 0;
- int len, i;
-
- len=self->stack->length;
- if (!( len >= x && x > 0 )) return stackUnderflow();
- /* nothing to do */
- if (len==x) return 0;
-
- list=self->stack->data[x-1];
-
- if (PyList_Check(list)) {
- PyObject *slice;
- int list_len;
-
- slice=Pdata_popList(self->stack, x);
- if (! slice) return -1;
- list_len = PyList_GET_SIZE(list);
- i=PyList_SetSlice(list, list_len, list_len, slice);
- Py_DECREF(slice);
- return i;
- }
- else {
-
- if (!( append_method = PyObject_GetAttr(list, append_str)))
- return -1;
-
- for (i = x; i < len; i++) {
- PyObject *junk;
-
- value=self->stack->data[i];
- junk=0;
- ARG_TUP(self, value);
- if (self->arg) {
- junk = PyObject_Call(append_method, self->arg,
- NULL);
- FREE_ARG_TUP(self);
- }
- if (! junk) {
- Pdata_clear(self->stack, i+1);
- self->stack->length=x;
- Py_DECREF(append_method);
- return -1;
- }
- Py_DECREF(junk);
- }
- self->stack->length=x;
- Py_DECREF(append_method);
- }
-
- return 0;
+ PyObject *value = 0, *list = 0, *append_method = 0;
+ int len, i;
+
+ len=self->stack->length;
+ if (!( len >= x && x > 0 )) return stackUnderflow();
+ /* nothing to do */
+ if (len==x) return 0;
+
+ list=self->stack->data[x-1];
+
+ if (PyList_Check(list)) {
+ PyObject *slice;
+ int list_len;
+
+ slice=Pdata_popList(self->stack, x);
+ if (! slice) return -1;
+ list_len = PyList_GET_SIZE(list);
+ i=PyList_SetSlice(list, list_len, list_len, slice);
+ Py_DECREF(slice);
+ return i;
+ }
+ else {
+
+ if (!( append_method = PyObject_GetAttr(list, append_str)))
+ return -1;
+
+ for (i = x; i < len; i++) {
+ PyObject *junk;
+
+ value=self->stack->data[i];
+ junk=0;
+ ARG_TUP(self, value);
+ if (self->arg) {
+ junk = PyObject_Call(append_method, self->arg,
+ NULL);
+ FREE_ARG_TUP(self);
+ }
+ if (! junk) {
+ Pdata_clear(self->stack, i+1);
+ self->stack->length=x;
+ Py_DECREF(append_method);
+ return -1;
+ }
+ Py_DECREF(junk);
+ }
+ self->stack->length=x;
+ Py_DECREF(append_method);
+ }
+
+ return 0;
}
static int
load_append(Unpicklerobject *self)
{
- return do_append(self, self->stack->length - 1);
+ return do_append(self, self->stack->length - 1);
}
static int
load_appends(Unpicklerobject *self)
{
- return do_append(self, marker(self));
+ return do_append(self, marker(self));
}
static int
do_setitems(Unpicklerobject *self, int x)
{
- PyObject *value = 0, *key = 0, *dict = 0;
- int len, i, r=0;
+ PyObject *value = 0, *key = 0, *dict = 0;
+ int len, i, r=0;
- if (!( (len=self->stack->length) >= x
- && x > 0 )) return stackUnderflow();
+ if (!( (len=self->stack->length) >= x
+ && x > 0 )) return stackUnderflow();
- dict=self->stack->data[x-1];
+ dict=self->stack->data[x-1];
- for (i = x+1; i < len; i += 2) {
- key =self->stack->data[i-1];
- value=self->stack->data[i ];
- if (PyObject_SetItem(dict, key, value) < 0) {
- r=-1;
- break;
- }
- }
+ for (i = x+1; i < len; i += 2) {
+ key =self->stack->data[i-1];
+ value=self->stack->data[i ];
+ if (PyObject_SetItem(dict, key, value) < 0) {
+ r=-1;
+ break;
+ }
+ }
- Pdata_clear(self->stack, x);
+ Pdata_clear(self->stack, x);
- return r;
+ return r;
}
static int
load_setitem(Unpicklerobject *self)
{
- return do_setitems(self, self->stack->length - 2);
+ return do_setitems(self, self->stack->length - 2);
}
static int
load_setitems(Unpicklerobject *self)
{
- return do_setitems(self, marker(self));
+ return do_setitems(self, marker(self));
}
static int
load_build(Unpicklerobject *self)
{
- PyObject *state, *inst, *slotstate;
- PyObject *__setstate__;
- PyObject *d_key, *d_value;
- Py_ssize_t i;
- int res = -1;
-
- /* Stack is ... instance, state. We want to leave instance at
- * the stack top, possibly mutated via instance.__setstate__(state).
- */
- if (self->stack->length < 2)
- return stackUnderflow();
- PDATA_POP(self->stack, state);
- if (state == NULL)
- return -1;
- inst = self->stack->data[self->stack->length - 1];
-
- __setstate__ = PyObject_GetAttr(inst, __setstate___str);
- if (__setstate__ != NULL) {
- PyObject *junk = NULL;
-
- /* The explicit __setstate__ is responsible for everything. */
- ARG_TUP(self, state);
- if (self->arg) {
- junk = PyObject_Call(__setstate__, self->arg, NULL);
- FREE_ARG_TUP(self);
- }
- Py_DECREF(__setstate__);
- if (junk == NULL)
- return -1;
- Py_DECREF(junk);
- return 0;
- }
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return -1;
- PyErr_Clear();
-
- /* A default __setstate__. First see whether state embeds a
- * slot state dict too (a proto 2 addition).
- */
- if (PyTuple_Check(state) && PyTuple_Size(state) == 2) {
- PyObject *temp = state;
- state = PyTuple_GET_ITEM(temp, 0);
- slotstate = PyTuple_GET_ITEM(temp, 1);
- Py_INCREF(state);
- Py_INCREF(slotstate);
- Py_DECREF(temp);
- }
- else
- slotstate = NULL;
-
- /* Set inst.__dict__ from the state dict (if any). */
- if (state != Py_None) {
- PyObject *dict;
- if (! PyDict_Check(state)) {
- PyErr_SetString(UnpicklingError, "state is not a "
- "dictionary");
- goto finally;
- }
- dict = PyObject_GetAttr(inst, __dict___str);
- if (dict == NULL)
- goto finally;
-
- i = 0;
- while (PyDict_Next(state, &i, &d_key, &d_value)) {
- if (PyObject_SetItem(dict, d_key, d_value) < 0)
- goto finally;
- }
- Py_DECREF(dict);
- }
-
- /* Also set instance attributes from the slotstate dict (if any). */
- if (slotstate != NULL) {
- if (! PyDict_Check(slotstate)) {
- PyErr_SetString(UnpicklingError, "slot state is not "
- "a dictionary");
- goto finally;
- }
- i = 0;
- while (PyDict_Next(slotstate, &i, &d_key, &d_value)) {
- if (PyObject_SetAttr(inst, d_key, d_value) < 0)
- goto finally;
- }
- }
- res = 0;
+ PyObject *state, *inst, *slotstate;
+ PyObject *__setstate__;
+ PyObject *d_key, *d_value;
+ Py_ssize_t i;
+ int res = -1;
+
+ /* Stack is ... instance, state. We want to leave instance at
+ * the stack top, possibly mutated via instance.__setstate__(state).
+ */
+ if (self->stack->length < 2)
+ return stackUnderflow();
+ PDATA_POP(self->stack, state);
+ if (state == NULL)
+ return -1;
+ inst = self->stack->data[self->stack->length - 1];
+
+ __setstate__ = PyObject_GetAttr(inst, __setstate___str);
+ if (__setstate__ != NULL) {
+ PyObject *junk = NULL;
+
+ /* The explicit __setstate__ is responsible for everything. */
+ ARG_TUP(self, state);
+ if (self->arg) {
+ junk = PyObject_Call(__setstate__, self->arg, NULL);
+ FREE_ARG_TUP(self);
+ }
+ Py_DECREF(__setstate__);
+ if (junk == NULL)
+ return -1;
+ Py_DECREF(junk);
+ return 0;
+ }
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -1;
+ PyErr_Clear();
+
+ /* A default __setstate__. First see whether state embeds a
+ * slot state dict too (a proto 2 addition).
+ */
+ if (PyTuple_Check(state) && PyTuple_Size(state) == 2) {
+ PyObject *temp = state;
+ state = PyTuple_GET_ITEM(temp, 0);
+ slotstate = PyTuple_GET_ITEM(temp, 1);
+ Py_INCREF(state);
+ Py_INCREF(slotstate);
+ Py_DECREF(temp);
+ }
+ else
+ slotstate = NULL;
+
+ /* Set inst.__dict__ from the state dict (if any). */
+ if (state != Py_None) {
+ PyObject *dict;
+ if (! PyDict_Check(state)) {
+ PyErr_SetString(UnpicklingError, "state is not a "
+ "dictionary");
+ goto finally;
+ }
+ dict = PyObject_GetAttr(inst, __dict___str);
+ if (dict == NULL)
+ goto finally;
+
+ i = 0;
+ while (PyDict_Next(state, &i, &d_key, &d_value)) {
+ if (PyObject_SetItem(dict, d_key, d_value) < 0)
+ goto finally;
+ }
+ Py_DECREF(dict);
+ }
+
+ /* Also set instance attributes from the slotstate dict (if any). */
+ if (slotstate != NULL) {
+ if (! PyDict_Check(slotstate)) {
+ PyErr_SetString(UnpicklingError, "slot state is not "
+ "a dictionary");
+ goto finally;
+ }
+ i = 0;
+ while (PyDict_Next(slotstate, &i, &d_key, &d_value)) {
+ if (PyObject_SetAttr(inst, d_key, d_value) < 0)
+ goto finally;
+ }
+ }
+ res = 0;
finally:
- Py_DECREF(state);
- Py_XDECREF(slotstate);
- return res;
+ Py_DECREF(state);
+ Py_XDECREF(slotstate);
+ return res;
}
static int
load_mark(Unpicklerobject *self)
{
- int s;
+ int s;
- /* Note that we split the (pickle.py) stack into two stacks, an
- object stack and a mark stack. Here we push a mark onto the
- mark stack.
- */
+ /* Note that we split the (pickle.py) stack into two stacks, an
+ object stack and a mark stack. Here we push a mark onto the
+ mark stack.
+ */
- if ((self->num_marks + 1) >= self->marks_size) {
- int *marks;
- s=self->marks_size+20;
- if (s <= self->num_marks) s=self->num_marks + 1;
- if (self->marks == NULL)
- marks=(int *)malloc(s * sizeof(int));
- else
- marks=(int *)realloc(self->marks,
- s * sizeof(int));
- if (!marks) {
- PyErr_NoMemory();
- return -1;
- }
- self->marks = marks;
- self->marks_size = s;
- }
+ if ((self->num_marks + 1) >= self->marks_size) {
+ int *marks;
+ s=self->marks_size+20;
+ if (s <= self->num_marks) s=self->num_marks + 1;
+ if (self->marks == NULL)
+ marks=(int *)malloc(s * sizeof(int));
+ else
+ marks=(int *)realloc(self->marks,
+ s * sizeof(int));
+ if (!marks) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ self->marks = marks;
+ self->marks_size = s;
+ }
- self->marks[self->num_marks++] = self->stack->length;
+ self->marks[self->num_marks++] = self->stack->length;
- return 0;
+ return 0;
}
static int
load_reduce(Unpicklerobject *self)
{
- PyObject *callable = 0, *arg_tup = 0, *ob = 0;
+ PyObject *callable = 0, *arg_tup = 0, *ob = 0;
- PDATA_POP(self->stack, arg_tup);
- if (! arg_tup) return -1;
- PDATA_POP(self->stack, callable);
- if (callable) {
- ob = Instance_New(callable, arg_tup);
- Py_DECREF(callable);
- }
- Py_DECREF(arg_tup);
+ PDATA_POP(self->stack, arg_tup);
+ if (! arg_tup) return -1;
+ PDATA_POP(self->stack, callable);
+ if (callable) {
+ ob = Instance_New(callable, arg_tup);
+ Py_DECREF(callable);
+ }
+ Py_DECREF(arg_tup);
- if (! ob) return -1;
+ if (! ob) return -1;
- PDATA_PUSH(self->stack, ob, -1);
- return 0;
+ PDATA_PUSH(self->stack, ob, -1);
+ return 0;
}
/* Just raises an error if we don't know the protocol specified. PROTO
@@ -4563,327 +4563,327 @@ load_reduce(Unpicklerobject *self)
static int
load_proto(Unpicklerobject *self)
{
- int i;
- char *protobyte;
+ int i;
+ char *protobyte;
- i = self->read_func(self, &protobyte, 1);
- if (i < 0)
- return -1;
+ i = self->read_func(self, &protobyte, 1);
+ if (i < 0)
+ return -1;
- i = calc_binint(protobyte, 1);
- /* No point checking for < 0, since calc_binint returns an unsigned
- * int when chewing on 1 byte.
- */
- assert(i >= 0);
- if (i <= HIGHEST_PROTOCOL)
- return 0;
+ i = calc_binint(protobyte, 1);
+ /* No point checking for < 0, since calc_binint returns an unsigned
+ * int when chewing on 1 byte.
+ */
+ assert(i >= 0);
+ if (i <= HIGHEST_PROTOCOL)
+ return 0;
- PyErr_Format(PyExc_ValueError, "unsupported pickle protocol: %d", i);
- return -1;
+ PyErr_Format(PyExc_ValueError, "unsupported pickle protocol: %d", i);
+ return -1;
}
static PyObject *
load(Unpicklerobject *self)
{
- PyObject *err = 0, *val = 0;
- char *s;
-
- self->num_marks = 0;
- if (self->stack->length) Pdata_clear(self->stack, 0);
-
- while (1) {
- if (self->read_func(self, &s, 1) < 0)
- break;
-
- switch (s[0]) {
- case NONE:
- if (load_none(self) < 0)
- break;
- continue;
-
- case BININT:
- if (load_binint(self) < 0)
- break;
- continue;
-
- case BININT1:
- if (load_binint1(self) < 0)
- break;
- continue;
-
- case BININT2:
- if (load_binint2(self) < 0)
- break;
- continue;
-
- case INT:
- if (load_int(self) < 0)
- break;
- continue;
-
- case LONG:
- if (load_long(self) < 0)
- break;
- continue;
-
- case LONG1:
- if (load_counted_long(self, 1) < 0)
- break;
- continue;
-
- case LONG4:
- if (load_counted_long(self, 4) < 0)
- break;
- continue;
-
- case FLOAT:
- if (load_float(self) < 0)
- break;
- continue;
-
- case BINFLOAT:
- if (load_binfloat(self) < 0)
- break;
- continue;
-
- case BINSTRING:
- if (load_binstring(self) < 0)
- break;
- continue;
-
- case SHORT_BINSTRING:
- if (load_short_binstring(self) < 0)
- break;
- continue;
-
- case STRING:
- if (load_string(self) < 0)
- break;
- continue;
+ PyObject *err = 0, *val = 0;
+ char *s;
+
+ self->num_marks = 0;
+ if (self->stack->length) Pdata_clear(self->stack, 0);
+
+ while (1) {
+ if (self->read_func(self, &s, 1) < 0)
+ break;
+
+ switch (s[0]) {
+ case NONE:
+ if (load_none(self) < 0)
+ break;
+ continue;
+
+ case BININT:
+ if (load_binint(self) < 0)
+ break;
+ continue;
+
+ case BININT1:
+ if (load_binint1(self) < 0)
+ break;
+ continue;
+
+ case BININT2:
+ if (load_binint2(self) < 0)
+ break;
+ continue;
+
+ case INT:
+ if (load_int(self) < 0)
+ break;
+ continue;
+
+ case LONG:
+ if (load_long(self) < 0)
+ break;
+ continue;
+
+ case LONG1:
+ if (load_counted_long(self, 1) < 0)
+ break;
+ continue;
+
+ case LONG4:
+ if (load_counted_long(self, 4) < 0)
+ break;
+ continue;
+
+ case FLOAT:
+ if (load_float(self) < 0)
+ break;
+ continue;
+
+ case BINFLOAT:
+ if (load_binfloat(self) < 0)
+ break;
+ continue;
+
+ case BINSTRING:
+ if (load_binstring(self) < 0)
+ break;
+ continue;
+
+ case SHORT_BINSTRING:
+ if (load_short_binstring(self) < 0)
+ break;
+ continue;
+
+ case STRING:
+ if (load_string(self) < 0)
+ break;
+ continue;
#ifdef Py_USING_UNICODE
- case UNICODE:
- if (load_unicode(self) < 0)
- break;
- continue;
-
- case BINUNICODE:
- if (load_binunicode(self) < 0)
- break;
- continue;
+ case UNICODE:
+ if (load_unicode(self) < 0)
+ break;
+ continue;
+
+ case BINUNICODE:
+ if (load_binunicode(self) < 0)
+ break;
+ continue;
#endif
- case EMPTY_TUPLE:
- if (load_counted_tuple(self, 0) < 0)
- break;
- continue;
-
- case TUPLE1:
- if (load_counted_tuple(self, 1) < 0)
- break;
- continue;
-
- case TUPLE2:
- if (load_counted_tuple(self, 2) < 0)
- break;
- continue;
-
- case TUPLE3:
- if (load_counted_tuple(self, 3) < 0)
- break;
- continue;
-
- case TUPLE:
- if (load_tuple(self) < 0)
- break;
- continue;
-
- case EMPTY_LIST:
- if (load_empty_list(self) < 0)
- break;
- continue;
-
- case LIST:
- if (load_list(self) < 0)
- break;
- continue;
-
- case EMPTY_DICT:
- if (load_empty_dict(self) < 0)
- break;
- continue;
-
- case DICT:
- if (load_dict(self) < 0)
- break;
- continue;
-
- case OBJ:
- if (load_obj(self) < 0)
- break;
- continue;
-
- case INST:
- if (load_inst(self) < 0)
- break;
- continue;
-
- case NEWOBJ:
- if (load_newobj(self) < 0)
- break;
- continue;
-
- case GLOBAL:
- if (load_global(self) < 0)
- break;
- continue;
-
- case APPEND:
- if (load_append(self) < 0)
- break;
- continue;
-
- case APPENDS:
- if (load_appends(self) < 0)
- break;
- continue;
-
- case BUILD:
- if (load_build(self) < 0)
- break;
- continue;
-
- case DUP:
- if (load_dup(self) < 0)
- break;
- continue;
-
- case BINGET:
- if (load_binget(self) < 0)
- break;
- continue;
-
- case LONG_BINGET:
- if (load_long_binget(self) < 0)
- break;
- continue;
-
- case GET:
- if (load_get(self) < 0)
- break;
- continue;
-
- case EXT1:
- if (load_extension(self, 1) < 0)
- break;
- continue;
-
- case EXT2:
- if (load_extension(self, 2) < 0)
- break;
- continue;
-
- case EXT4:
- if (load_extension(self, 4) < 0)
- break;
- continue;
- case MARK:
- if (load_mark(self) < 0)
- break;
- continue;
-
- case BINPUT:
- if (load_binput(self) < 0)
- break;
- continue;
-
- case LONG_BINPUT:
- if (load_long_binput(self) < 0)
- break;
- continue;
-
- case PUT:
- if (load_put(self) < 0)
- break;
- continue;
-
- case POP:
- if (load_pop(self) < 0)
- break;
- continue;
-
- case POP_MARK:
- if (load_pop_mark(self) < 0)
- break;
- continue;
-
- case SETITEM:
- if (load_setitem(self) < 0)
- break;
- continue;
-
- case SETITEMS:
- if (load_setitems(self) < 0)
- break;
- continue;
-
- case STOP:
- break;
-
- case PERSID:
- if (load_persid(self) < 0)
- break;
- continue;
-
- case BINPERSID:
- if (load_binpersid(self) < 0)
- break;
- continue;
-
- case REDUCE:
- if (load_reduce(self) < 0)
- break;
- continue;
-
- case PROTO:
- if (load_proto(self) < 0)
- break;
- continue;
-
- case NEWTRUE:
- if (load_bool(self, Py_True) < 0)
- break;
- continue;
-
- case NEWFALSE:
- if (load_bool(self, Py_False) < 0)
- break;
- continue;
-
- case '\0':
- /* end of file */
- PyErr_SetNone(PyExc_EOFError);
- break;
-
- default:
- cPickle_ErrFormat(UnpicklingError,
- "invalid load key, '%s'.",
- "c", s[0]);
- return NULL;
- }
-
- break;
- }
-
- if ((err = PyErr_Occurred())) {
- if (err == PyExc_EOFError) {
- PyErr_SetNone(PyExc_EOFError);
- }
- return NULL;
- }
-
- PDATA_POP(self->stack, val);
- return val;
+ case EMPTY_TUPLE:
+ if (load_counted_tuple(self, 0) < 0)
+ break;
+ continue;
+
+ case TUPLE1:
+ if (load_counted_tuple(self, 1) < 0)
+ break;
+ continue;
+
+ case TUPLE2:
+ if (load_counted_tuple(self, 2) < 0)
+ break;
+ continue;
+
+ case TUPLE3:
+ if (load_counted_tuple(self, 3) < 0)
+ break;
+ continue;
+
+ case TUPLE:
+ if (load_tuple(self) < 0)
+ break;
+ continue;
+
+ case EMPTY_LIST:
+ if (load_empty_list(self) < 0)
+ break;
+ continue;
+
+ case LIST:
+ if (load_list(self) < 0)
+ break;
+ continue;
+
+ case EMPTY_DICT:
+ if (load_empty_dict(self) < 0)
+ break;
+ continue;
+
+ case DICT:
+ if (load_dict(self) < 0)
+ break;
+ continue;
+
+ case OBJ:
+ if (load_obj(self) < 0)
+ break;
+ continue;
+
+ case INST:
+ if (load_inst(self) < 0)
+ break;
+ continue;
+
+ case NEWOBJ:
+ if (load_newobj(self) < 0)
+ break;
+ continue;
+
+ case GLOBAL:
+ if (load_global(self) < 0)
+ break;
+ continue;
+
+ case APPEND:
+ if (load_append(self) < 0)
+ break;
+ continue;
+
+ case APPENDS:
+ if (load_appends(self) < 0)
+ break;
+ continue;
+
+ case BUILD:
+ if (load_build(self) < 0)
+ break;
+ continue;
+
+ case DUP:
+ if (load_dup(self) < 0)
+ break;
+ continue;
+
+ case BINGET:
+ if (load_binget(self) < 0)
+ break;
+ continue;
+
+ case LONG_BINGET:
+ if (load_long_binget(self) < 0)
+ break;
+ continue;
+
+ case GET:
+ if (load_get(self) < 0)
+ break;
+ continue;
+
+ case EXT1:
+ if (load_extension(self, 1) < 0)
+ break;
+ continue;
+
+ case EXT2:
+ if (load_extension(self, 2) < 0)
+ break;
+ continue;
+
+ case EXT4:
+ if (load_extension(self, 4) < 0)
+ break;
+ continue;
+ case MARK:
+ if (load_mark(self) < 0)
+ break;
+ continue;
+
+ case BINPUT:
+ if (load_binput(self) < 0)
+ break;
+ continue;
+
+ case LONG_BINPUT:
+ if (load_long_binput(self) < 0)
+ break;
+ continue;
+
+ case PUT:
+ if (load_put(self) < 0)
+ break;
+ continue;
+
+ case POP:
+ if (load_pop(self) < 0)
+ break;
+ continue;
+
+ case POP_MARK:
+ if (load_pop_mark(self) < 0)
+ break;
+ continue;
+
+ case SETITEM:
+ if (load_setitem(self) < 0)
+ break;
+ continue;
+
+ case SETITEMS:
+ if (load_setitems(self) < 0)
+ break;
+ continue;
+
+ case STOP:
+ break;
+
+ case PERSID:
+ if (load_persid(self) < 0)
+ break;
+ continue;
+
+ case BINPERSID:
+ if (load_binpersid(self) < 0)
+ break;
+ continue;
+
+ case REDUCE:
+ if (load_reduce(self) < 0)
+ break;
+ continue;
+
+ case PROTO:
+ if (load_proto(self) < 0)
+ break;
+ continue;
+
+ case NEWTRUE:
+ if (load_bool(self, Py_True) < 0)
+ break;
+ continue;
+
+ case NEWFALSE:
+ if (load_bool(self, Py_False) < 0)
+ break;
+ continue;
+
+ case '\0':
+ /* end of file */
+ PyErr_SetNone(PyExc_EOFError);
+ break;
+
+ default:
+ cPickle_ErrFormat(UnpicklingError,
+ "invalid load key, '%s'.",
+ "c", s[0]);
+ return NULL;
+ }
+
+ break;
+ }
+
+ if ((err = PyErr_Occurred())) {
+ if (err == PyExc_EOFError) {
+ PyErr_SetNone(PyExc_EOFError);
+ }
+ return NULL;
+ }
+
+ PDATA_POP(self->stack, val);
+ return val;
}
@@ -4893,63 +4893,63 @@ load(Unpicklerobject *self)
static int
noload_obj(Unpicklerobject *self)
{
- int i;
+ int i;
- if ((i = marker(self)) < 0) return -1;
- return Pdata_clear(self->stack, i+1);
+ if ((i = marker(self)) < 0) return -1;
+ return Pdata_clear(self->stack, i+1);
}
static int
noload_inst(Unpicklerobject *self)
{
- int i;
- char *s;
+ int i;
+ char *s;
- if ((i = marker(self)) < 0) return -1;
- Pdata_clear(self->stack, i);
- if (self->readline_func(self, &s) < 0) return -1;
- if (self->readline_func(self, &s) < 0) return -1;
- PDATA_APPEND(self->stack, Py_None, -1);
- return 0;
+ if ((i = marker(self)) < 0) return -1;
+ Pdata_clear(self->stack, i);
+ if (self->readline_func(self, &s) < 0) return -1;
+ if (self->readline_func(self, &s) < 0) return -1;
+ PDATA_APPEND(self->stack, Py_None, -1);
+ return 0;
}
static int
noload_newobj(Unpicklerobject *self)
{
- PyObject *obj;
+ PyObject *obj;
- PDATA_POP(self->stack, obj); /* pop argtuple */
- if (obj == NULL) return -1;
- Py_DECREF(obj);
+ PDATA_POP(self->stack, obj); /* pop argtuple */
+ if (obj == NULL) return -1;
+ Py_DECREF(obj);
- PDATA_POP(self->stack, obj); /* pop cls */
- if (obj == NULL) return -1;
- Py_DECREF(obj);
+ PDATA_POP(self->stack, obj); /* pop cls */
+ if (obj == NULL) return -1;
+ Py_DECREF(obj);
- PDATA_APPEND(self->stack, Py_None, -1);
- return 0;
+ PDATA_APPEND(self->stack, Py_None, -1);
+ return 0;
}
static int
noload_global(Unpicklerobject *self)
{
- char *s;
+ char *s;
- if (self->readline_func(self, &s) < 0) return -1;
- if (self->readline_func(self, &s) < 0) return -1;
- PDATA_APPEND(self->stack, Py_None,-1);
- return 0;
+ if (self->readline_func(self, &s) < 0) return -1;
+ if (self->readline_func(self, &s) < 0) return -1;
+ PDATA_APPEND(self->stack, Py_None,-1);
+ return 0;
}
static int
noload_reduce(Unpicklerobject *self)
{
- if (self->stack->length < 2) return stackUnderflow();
- Pdata_clear(self->stack, self->stack->length-2);
- PDATA_APPEND(self->stack, Py_None,-1);
- return 0;
+ if (self->stack->length < 2) return stackUnderflow();
+ Pdata_clear(self->stack, self->stack->length-2);
+ PDATA_APPEND(self->stack, Py_None,-1);
+ return 0;
}
static int
@@ -4963,325 +4963,325 @@ noload_build(Unpicklerobject *self) {
static int
noload_extension(Unpicklerobject *self, int nbytes)
{
- char *codebytes;
+ char *codebytes;
- assert(nbytes == 1 || nbytes == 2 || nbytes == 4);
- if (self->read_func(self, &codebytes, nbytes) < 0) return -1;
- PDATA_APPEND(self->stack, Py_None, -1);
- return 0;
+ assert(nbytes == 1 || nbytes == 2 || nbytes == 4);
+ if (self->read_func(self, &codebytes, nbytes) < 0) return -1;
+ PDATA_APPEND(self->stack, Py_None, -1);
+ return 0;
}
static PyObject *
noload(Unpicklerobject *self)
{
- PyObject *err = 0, *val = 0;
- char *s;
-
- self->num_marks = 0;
- Pdata_clear(self->stack, 0);
-
- while (1) {
- if (self->read_func(self, &s, 1) < 0)
- break;
-
- switch (s[0]) {
- case NONE:
- if (load_none(self) < 0)
- break;
- continue;
-
- case BININT:
- if (load_binint(self) < 0)
- break;
- continue;
-
- case BININT1:
- if (load_binint1(self) < 0)
- break;
- continue;
-
- case BININT2:
- if (load_binint2(self) < 0)
- break;
- continue;
-
- case INT:
- if (load_int(self) < 0)
- break;
- continue;
-
- case LONG:
- if (load_long(self) < 0)
- break;
- continue;
-
- case LONG1:
- if (load_counted_long(self, 1) < 0)
- break;
- continue;
-
- case LONG4:
- if (load_counted_long(self, 4) < 0)
- break;
- continue;
-
- case FLOAT:
- if (load_float(self) < 0)
- break;
- continue;
-
- case BINFLOAT:
- if (load_binfloat(self) < 0)
- break;
- continue;
-
- case BINSTRING:
- if (load_binstring(self) < 0)
- break;
- continue;
-
- case SHORT_BINSTRING:
- if (load_short_binstring(self) < 0)
- break;
- continue;
-
- case STRING:
- if (load_string(self) < 0)
- break;
- continue;
+ PyObject *err = 0, *val = 0;
+ char *s;
+
+ self->num_marks = 0;
+ Pdata_clear(self->stack, 0);
+
+ while (1) {
+ if (self->read_func(self, &s, 1) < 0)
+ break;
+
+ switch (s[0]) {
+ case NONE:
+ if (load_none(self) < 0)
+ break;
+ continue;
+
+ case BININT:
+ if (load_binint(self) < 0)
+ break;
+ continue;
+
+ case BININT1:
+ if (load_binint1(self) < 0)
+ break;
+ continue;
+
+ case BININT2:
+ if (load_binint2(self) < 0)
+ break;
+ continue;
+
+ case INT:
+ if (load_int(self) < 0)
+ break;
+ continue;
+
+ case LONG:
+ if (load_long(self) < 0)
+ break;
+ continue;
+
+ case LONG1:
+ if (load_counted_long(self, 1) < 0)
+ break;
+ continue;
+
+ case LONG4:
+ if (load_counted_long(self, 4) < 0)
+ break;
+ continue;
+
+ case FLOAT:
+ if (load_float(self) < 0)
+ break;
+ continue;
+
+ case BINFLOAT:
+ if (load_binfloat(self) < 0)
+ break;
+ continue;
+
+ case BINSTRING:
+ if (load_binstring(self) < 0)
+ break;
+ continue;
+
+ case SHORT_BINSTRING:
+ if (load_short_binstring(self) < 0)
+ break;
+ continue;
+
+ case STRING:
+ if (load_string(self) < 0)
+ break;
+ continue;
#ifdef Py_USING_UNICODE
- case UNICODE:
- if (load_unicode(self) < 0)
- break;
- continue;
-
- case BINUNICODE:
- if (load_binunicode(self) < 0)
- break;
- continue;
+ case UNICODE:
+ if (load_unicode(self) < 0)
+ break;
+ continue;
+
+ case BINUNICODE:
+ if (load_binunicode(self) < 0)
+ break;
+ continue;
#endif
- case EMPTY_TUPLE:
- if (load_counted_tuple(self, 0) < 0)
- break;
- continue;
-
- case TUPLE1:
- if (load_counted_tuple(self, 1) < 0)
- break;
- continue;
-
- case TUPLE2:
- if (load_counted_tuple(self, 2) < 0)
- break;
- continue;
-
- case TUPLE3:
- if (load_counted_tuple(self, 3) < 0)
- break;
- continue;
-
- case TUPLE:
- if (load_tuple(self) < 0)
- break;
- continue;
-
- case EMPTY_LIST:
- if (load_empty_list(self) < 0)
- break;
- continue;
-
- case LIST:
- if (load_list(self) < 0)
- break;
- continue;
-
- case EMPTY_DICT:
- if (load_empty_dict(self) < 0)
- break;
- continue;
-
- case DICT:
- if (load_dict(self) < 0)
- break;
- continue;
-
- case OBJ:
- if (noload_obj(self) < 0)
- break;
- continue;
-
- case INST:
- if (noload_inst(self) < 0)
- break;
- continue;
-
- case NEWOBJ:
- if (noload_newobj(self) < 0)
- break;
- continue;
-
- case GLOBAL:
- if (noload_global(self) < 0)
- break;
- continue;
-
- case APPEND:
- if (load_append(self) < 0)
- break;
- continue;
-
- case APPENDS:
- if (load_appends(self) < 0)
- break;
- continue;
-
- case BUILD:
- if (noload_build(self) < 0)
- break;
- continue;
-
- case DUP:
- if (load_dup(self) < 0)
- break;
- continue;
-
- case BINGET:
- if (load_binget(self) < 0)
- break;
- continue;
-
- case LONG_BINGET:
- if (load_long_binget(self) < 0)
- break;
- continue;
-
- case GET:
- if (load_get(self) < 0)
- break;
- continue;
-
- case EXT1:
- if (noload_extension(self, 1) < 0)
- break;
- continue;
-
- case EXT2:
- if (noload_extension(self, 2) < 0)
- break;
- continue;
-
- case EXT4:
- if (noload_extension(self, 4) < 0)
- break;
- continue;
-
- case MARK:
- if (load_mark(self) < 0)
- break;
- continue;
-
- case BINPUT:
- if (load_binput(self) < 0)
- break;
- continue;
-
- case LONG_BINPUT:
- if (load_long_binput(self) < 0)
- break;
- continue;
-
- case PUT:
- if (load_put(self) < 0)
- break;
- continue;
-
- case POP:
- if (load_pop(self) < 0)
- break;
- continue;
-
- case POP_MARK:
- if (load_pop_mark(self) < 0)
- break;
- continue;
-
- case SETITEM:
- if (load_setitem(self) < 0)
- break;
- continue;
-
- case SETITEMS:
- if (load_setitems(self) < 0)
- break;
- continue;
-
- case STOP:
- break;
-
- case PERSID:
- if (load_persid(self) < 0)
- break;
- continue;
-
- case BINPERSID:
- if (load_binpersid(self) < 0)
- break;
- continue;
-
- case REDUCE:
- if (noload_reduce(self) < 0)
- break;
- continue;
-
- case PROTO:
- if (load_proto(self) < 0)
- break;
- continue;
-
- case NEWTRUE:
- if (load_bool(self, Py_True) < 0)
- break;
- continue;
-
- case NEWFALSE:
- if (load_bool(self, Py_False) < 0)
- break;
- continue;
- default:
- cPickle_ErrFormat(UnpicklingError,
- "invalid load key, '%s'.",
- "c", s[0]);
- return NULL;
- }
-
- break;
- }
-
- if ((err = PyErr_Occurred())) {
- if (err == PyExc_EOFError) {
- PyErr_SetNone(PyExc_EOFError);
- }
- return NULL;
- }
-
- PDATA_POP(self->stack, val);
- return val;
+ case EMPTY_TUPLE:
+ if (load_counted_tuple(self, 0) < 0)
+ break;
+ continue;
+
+ case TUPLE1:
+ if (load_counted_tuple(self, 1) < 0)
+ break;
+ continue;
+
+ case TUPLE2:
+ if (load_counted_tuple(self, 2) < 0)
+ break;
+ continue;
+
+ case TUPLE3:
+ if (load_counted_tuple(self, 3) < 0)
+ break;
+ continue;
+
+ case TUPLE:
+ if (load_tuple(self) < 0)
+ break;
+ continue;
+
+ case EMPTY_LIST:
+ if (load_empty_list(self) < 0)
+ break;
+ continue;
+
+ case LIST:
+ if (load_list(self) < 0)
+ break;
+ continue;
+
+ case EMPTY_DICT:
+ if (load_empty_dict(self) < 0)
+ break;
+ continue;
+
+ case DICT:
+ if (load_dict(self) < 0)
+ break;
+ continue;
+
+ case OBJ:
+ if (noload_obj(self) < 0)
+ break;
+ continue;
+
+ case INST:
+ if (noload_inst(self) < 0)
+ break;
+ continue;
+
+ case NEWOBJ:
+ if (noload_newobj(self) < 0)
+ break;
+ continue;
+
+ case GLOBAL:
+ if (noload_global(self) < 0)
+ break;
+ continue;
+
+ case APPEND:
+ if (load_append(self) < 0)
+ break;
+ continue;
+
+ case APPENDS:
+ if (load_appends(self) < 0)
+ break;
+ continue;
+
+ case BUILD:
+ if (noload_build(self) < 0)
+ break;
+ continue;
+
+ case DUP:
+ if (load_dup(self) < 0)
+ break;
+ continue;
+
+ case BINGET:
+ if (load_binget(self) < 0)
+ break;
+ continue;
+
+ case LONG_BINGET:
+ if (load_long_binget(self) < 0)
+ break;
+ continue;
+
+ case GET:
+ if (load_get(self) < 0)
+ break;
+ continue;
+
+ case EXT1:
+ if (noload_extension(self, 1) < 0)
+ break;
+ continue;
+
+ case EXT2:
+ if (noload_extension(self, 2) < 0)
+ break;
+ continue;
+
+ case EXT4:
+ if (noload_extension(self, 4) < 0)
+ break;
+ continue;
+
+ case MARK:
+ if (load_mark(self) < 0)
+ break;
+ continue;
+
+ case BINPUT:
+ if (load_binput(self) < 0)
+ break;
+ continue;
+
+ case LONG_BINPUT:
+ if (load_long_binput(self) < 0)
+ break;
+ continue;
+
+ case PUT:
+ if (load_put(self) < 0)
+ break;
+ continue;
+
+ case POP:
+ if (load_pop(self) < 0)
+ break;
+ continue;
+
+ case POP_MARK:
+ if (load_pop_mark(self) < 0)
+ break;
+ continue;
+
+ case SETITEM:
+ if (load_setitem(self) < 0)
+ break;
+ continue;
+
+ case SETITEMS:
+ if (load_setitems(self) < 0)
+ break;
+ continue;
+
+ case STOP:
+ break;
+
+ case PERSID:
+ if (load_persid(self) < 0)
+ break;
+ continue;
+
+ case BINPERSID:
+ if (load_binpersid(self) < 0)
+ break;
+ continue;
+
+ case REDUCE:
+ if (noload_reduce(self) < 0)
+ break;
+ continue;
+
+ case PROTO:
+ if (load_proto(self) < 0)
+ break;
+ continue;
+
+ case NEWTRUE:
+ if (load_bool(self, Py_True) < 0)
+ break;
+ continue;
+
+ case NEWFALSE:
+ if (load_bool(self, Py_False) < 0)
+ break;
+ continue;
+ default:
+ cPickle_ErrFormat(UnpicklingError,
+ "invalid load key, '%s'.",
+ "c", s[0]);
+ return NULL;
+ }
+
+ break;
+ }
+
+ if ((err = PyErr_Occurred())) {
+ if (err == PyExc_EOFError) {
+ PyErr_SetNone(PyExc_EOFError);
+ }
+ return NULL;
+ }
+
+ PDATA_POP(self->stack, val);
+ return val;
}
static PyObject *
Unpickler_load(Unpicklerobject *self, PyObject *unused)
{
- return load(self);
+ return load(self);
}
static PyObject *
Unpickler_noload(Unpicklerobject *self, PyObject *unused)
{
- return noload(self);
+ return noload(self);
}
@@ -5305,175 +5305,175 @@ static struct PyMethodDef Unpickler_methods[] = {
static Unpicklerobject *
newUnpicklerobject(PyObject *f)
{
- Unpicklerobject *self;
-
- if (!( self = PyObject_GC_New(Unpicklerobject, &Unpicklertype)))
- return NULL;
-
- self->file = NULL;
- self->arg = NULL;
- self->stack = (Pdata*)Pdata_New();
- self->pers_func = NULL;
- self->last_string = NULL;
- self->marks = NULL;
- self->num_marks = 0;
- self->marks_size = 0;
- self->buf_size = 0;
- self->read = NULL;
- self->readline = NULL;
- self->find_class = NULL;
-
- if (!( self->memo = PyDict_New()))
- goto err;
-
- if (!self->stack)
- goto err;
-
- Py_INCREF(f);
- self->file = f;
-
- /* Set read, readline based on type of f */
- if (PyFile_Check(f)) {
- self->fp = PyFile_AsFile(f);
- if (self->fp == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto err;
- }
- self->read_func = read_file;
- self->readline_func = readline_file;
- }
- else if (PycStringIO_InputCheck(f)) {
- self->fp = NULL;
- self->read_func = read_cStringIO;
- self->readline_func = readline_cStringIO;
- }
- else {
-
- self->fp = NULL;
- self->read_func = read_other;
- self->readline_func = readline_other;
-
- if (!( (self->readline = PyObject_GetAttr(f, readline_str)) &&
- (self->read = PyObject_GetAttr(f, read_str)))) {
- PyErr_Clear();
- PyErr_SetString( PyExc_TypeError,
- "argument must have 'read' and "
- "'readline' attributes" );
- goto err;
- }
- }
- PyObject_GC_Track(self);
-
- return self;
+ Unpicklerobject *self;
+
+ if (!( self = PyObject_GC_New(Unpicklerobject, &Unpicklertype)))
+ return NULL;
+
+ self->file = NULL;
+ self->arg = NULL;
+ self->stack = (Pdata*)Pdata_New();
+ self->pers_func = NULL;
+ self->last_string = NULL;
+ self->marks = NULL;
+ self->num_marks = 0;
+ self->marks_size = 0;
+ self->buf_size = 0;
+ self->read = NULL;
+ self->readline = NULL;
+ self->find_class = NULL;
+
+ if (!( self->memo = PyDict_New()))
+ goto err;
+
+ if (!self->stack)
+ goto err;
+
+ Py_INCREF(f);
+ self->file = f;
+
+ /* Set read, readline based on type of f */
+ if (PyFile_Check(f)) {
+ self->fp = PyFile_AsFile(f);
+ if (self->fp == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto err;
+ }
+ self->read_func = read_file;
+ self->readline_func = readline_file;
+ }
+ else if (PycStringIO_InputCheck(f)) {
+ self->fp = NULL;
+ self->read_func = read_cStringIO;
+ self->readline_func = readline_cStringIO;
+ }
+ else {
+
+ self->fp = NULL;
+ self->read_func = read_other;
+ self->readline_func = readline_other;
+
+ if (!( (self->readline = PyObject_GetAttr(f, readline_str)) &&
+ (self->read = PyObject_GetAttr(f, read_str)))) {
+ PyErr_Clear();
+ PyErr_SetString( PyExc_TypeError,
+ "argument must have 'read' and "
+ "'readline' attributes" );
+ goto err;
+ }
+ }
+ PyObject_GC_Track(self);
+
+ return self;
err:
- Py_DECREF((PyObject *)self);
- return NULL;
+ Py_DECREF((PyObject *)self);
+ return NULL;
}
static PyObject *
get_Unpickler(PyObject *self, PyObject *file)
{
- return (PyObject *)newUnpicklerobject(file);
+ return (PyObject *)newUnpicklerobject(file);
}
static void
Unpickler_dealloc(Unpicklerobject *self)
{
- PyObject_GC_UnTrack((PyObject *)self);
- Py_XDECREF(self->readline);
- Py_XDECREF(self->read);
- Py_XDECREF(self->file);
- Py_XDECREF(self->memo);
- Py_XDECREF(self->stack);
- Py_XDECREF(self->pers_func);
- Py_XDECREF(self->arg);
- Py_XDECREF(self->last_string);
- Py_XDECREF(self->find_class);
-
- if (self->marks) {
- free(self->marks);
- }
+ PyObject_GC_UnTrack((PyObject *)self);
+ Py_XDECREF(self->readline);
+ Py_XDECREF(self->read);
+ Py_XDECREF(self->file);
+ Py_XDECREF(self->memo);
+ Py_XDECREF(self->stack);
+ Py_XDECREF(self->pers_func);
+ Py_XDECREF(self->arg);
+ Py_XDECREF(self->last_string);
+ Py_XDECREF(self->find_class);
+
+ if (self->marks) {
+ free(self->marks);
+ }
- if (self->buf_size) {
- free(self->buf);
- }
+ if (self->buf_size) {
+ free(self->buf);
+ }
- Py_TYPE(self)->tp_free((PyObject *)self);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static int
Unpickler_traverse(Unpicklerobject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->readline);
- Py_VISIT(self->read);
- Py_VISIT(self->file);
- Py_VISIT(self->memo);
- Py_VISIT(self->stack);
- Py_VISIT(self->pers_func);
- Py_VISIT(self->arg);
- Py_VISIT(self->last_string);
- Py_VISIT(self->find_class);
- return 0;
+ Py_VISIT(self->readline);
+ Py_VISIT(self->read);
+ Py_VISIT(self->file);
+ Py_VISIT(self->memo);
+ Py_VISIT(self->stack);
+ Py_VISIT(self->pers_func);
+ Py_VISIT(self->arg);
+ Py_VISIT(self->last_string);
+ Py_VISIT(self->find_class);
+ return 0;
}
static int
Unpickler_clear(Unpicklerobject *self)
{
- Py_CLEAR(self->readline);
- Py_CLEAR(self->read);
- Py_CLEAR(self->file);
- Py_CLEAR(self->memo);
- Py_CLEAR(self->stack);
- Py_CLEAR(self->pers_func);
- Py_CLEAR(self->arg);
- Py_CLEAR(self->last_string);
- Py_CLEAR(self->find_class);
- return 0;
+ Py_CLEAR(self->readline);
+ Py_CLEAR(self->read);
+ Py_CLEAR(self->file);
+ Py_CLEAR(self->memo);
+ Py_CLEAR(self->stack);
+ Py_CLEAR(self->pers_func);
+ Py_CLEAR(self->arg);
+ Py_CLEAR(self->last_string);
+ Py_CLEAR(self->find_class);
+ return 0;
}
static PyObject *
Unpickler_getattr(Unpicklerobject *self, char *name)
{
- if (!strcmp(name, "persistent_load")) {
- if (!self->pers_func) {
- PyErr_SetString(PyExc_AttributeError, name);
- return NULL;
- }
+ if (!strcmp(name, "persistent_load")) {
+ if (!self->pers_func) {
+ PyErr_SetString(PyExc_AttributeError, name);
+ return NULL;
+ }
- Py_INCREF(self->pers_func);
- return self->pers_func;
- }
+ Py_INCREF(self->pers_func);
+ return self->pers_func;
+ }
- if (!strcmp(name, "find_global")) {
- if (!self->find_class) {
- PyErr_SetString(PyExc_AttributeError, name);
- return NULL;
- }
+ if (!strcmp(name, "find_global")) {
+ if (!self->find_class) {
+ PyErr_SetString(PyExc_AttributeError, name);
+ return NULL;
+ }
- Py_INCREF(self->find_class);
- return self->find_class;
- }
+ Py_INCREF(self->find_class);
+ return self->find_class;
+ }
- if (!strcmp(name, "memo")) {
- if (!self->memo) {
- PyErr_SetString(PyExc_AttributeError, name);
- return NULL;
- }
+ if (!strcmp(name, "memo")) {
+ if (!self->memo) {
+ PyErr_SetString(PyExc_AttributeError, name);
+ return NULL;
+ }
- Py_INCREF(self->memo);
- return self->memo;
- }
+ Py_INCREF(self->memo);
+ return self->memo;
+ }
- if (!strcmp(name, "UnpicklingError")) {
- Py_INCREF(UnpicklingError);
- return UnpicklingError;
- }
+ if (!strcmp(name, "UnpicklingError")) {
+ Py_INCREF(UnpicklingError);
+ return UnpicklingError;
+ }
- return Py_FindMethod(Unpickler_methods, (PyObject *)self, name);
+ return Py_FindMethod(Unpickler_methods, (PyObject *)self, name);
}
@@ -5481,40 +5481,40 @@ static int
Unpickler_setattr(Unpicklerobject *self, char *name, PyObject *value)
{
- if (!strcmp(name, "persistent_load")) {
- Py_XDECREF(self->pers_func);
- self->pers_func = value;
- Py_XINCREF(value);
- return 0;
- }
-
- if (!strcmp(name, "find_global")) {
- Py_XDECREF(self->find_class);
- self->find_class = value;
- Py_XINCREF(value);
- return 0;
- }
-
- if (! value) {
- PyErr_SetString(PyExc_TypeError,
- "attribute deletion is not supported");
- return -1;
- }
-
- if (strcmp(name, "memo") == 0) {
- if (!PyDict_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "memo must be a dictionary");
- return -1;
- }
- Py_XDECREF(self->memo);
- self->memo = value;
- Py_INCREF(value);
- return 0;
- }
-
- PyErr_SetString(PyExc_AttributeError, name);
- return -1;
+ if (!strcmp(name, "persistent_load")) {
+ Py_XDECREF(self->pers_func);
+ self->pers_func = value;
+ Py_XINCREF(value);
+ return 0;
+ }
+
+ if (!strcmp(name, "find_global")) {
+ Py_XDECREF(self->find_class);
+ self->find_class = value;
+ Py_XINCREF(value);
+ return 0;
+ }
+
+ if (! value) {
+ PyErr_SetString(PyExc_TypeError,
+ "attribute deletion is not supported");
+ return -1;
+ }
+
+ if (strcmp(name, "memo") == 0) {
+ if (!PyDict_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "memo must be a dictionary");
+ return -1;
+ }
+ Py_XDECREF(self->memo);
+ self->memo = value;
+ Py_INCREF(value);
+ return 0;
+ }
+
+ PyErr_SetString(PyExc_AttributeError, name);
+ return -1;
}
/* ---------------------------------------------------------------------------
@@ -5525,28 +5525,28 @@ Unpickler_setattr(Unpicklerobject *self, char *name, PyObject *value)
static PyObject *
cpm_dump(PyObject *self, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"obj", "file", "protocol", NULL};
- PyObject *ob, *file, *res = NULL;
- Picklerobject *pickler = 0;
- int proto = 0;
+ static char *kwlist[] = {"obj", "file", "protocol", NULL};
+ PyObject *ob, *file, *res = NULL;
+ Picklerobject *pickler = 0;
+ int proto = 0;
- if (!( PyArg_ParseTupleAndKeywords(args, kwds, "OO|i", kwlist,
- &ob, &file, &proto)))
- goto finally;
+ if (!( PyArg_ParseTupleAndKeywords(args, kwds, "OO|i", kwlist,
+ &ob, &file, &proto)))
+ goto finally;
- if (!( pickler = newPicklerobject(file, proto)))
- goto finally;
+ if (!( pickler = newPicklerobject(file, proto)))
+ goto finally;
- if (dump(pickler, ob) < 0)
- goto finally;
+ if (dump(pickler, ob) < 0)
+ goto finally;
- Py_INCREF(Py_None);
- res = Py_None;
+ Py_INCREF(Py_None);
+ res = Py_None;
finally:
- Py_XDECREF(pickler);
+ Py_XDECREF(pickler);
- return res;
+ return res;
}
@@ -5554,31 +5554,31 @@ cpm_dump(PyObject *self, PyObject *args, PyObject *kwds)
static PyObject *
cpm_dumps(PyObject *self, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"obj", "protocol", NULL};
- PyObject *ob, *file = 0, *res = NULL;
- Picklerobject *pickler = 0;
- int proto = 0;
+ static char *kwlist[] = {"obj", "protocol", NULL};
+ PyObject *ob, *file = 0, *res = NULL;
+ Picklerobject *pickler = 0;
+ int proto = 0;
- if (!( PyArg_ParseTupleAndKeywords(args, kwds, "O|i:dumps", kwlist,
- &ob, &proto)))
- goto finally;
+ if (!( PyArg_ParseTupleAndKeywords(args, kwds, "O|i:dumps", kwlist,
+ &ob, &proto)))
+ goto finally;
- if (!( file = PycStringIO->NewOutput(128)))
- goto finally;
+ if (!( file = PycStringIO->NewOutput(128)))
+ goto finally;
- if (!( pickler = newPicklerobject(file, proto)))
- goto finally;
+ if (!( pickler = newPicklerobject(file, proto)))
+ goto finally;
- if (dump(pickler, ob) < 0)
- goto finally;
+ if (dump(pickler, ob) < 0)
+ goto finally;
- res = PycStringIO->cgetvalue(file);
+ res = PycStringIO->cgetvalue(file);
finally:
- Py_XDECREF(pickler);
- Py_XDECREF(file);
+ Py_XDECREF(pickler);
+ Py_XDECREF(file);
- return res;
+ return res;
}
@@ -5586,18 +5586,18 @@ cpm_dumps(PyObject *self, PyObject *args, PyObject *kwds)
static PyObject *
cpm_load(PyObject *self, PyObject *ob)
{
- Unpicklerobject *unpickler = 0;
- PyObject *res = NULL;
+ Unpicklerobject *unpickler = 0;
+ PyObject *res = NULL;
- if (!( unpickler = newUnpicklerobject(ob)))
- goto finally;
+ if (!( unpickler = newUnpicklerobject(ob)))
+ goto finally;
- res = load(unpickler);
+ res = load(unpickler);
finally:
- Py_XDECREF(unpickler);
+ Py_XDECREF(unpickler);
- return res;
+ return res;
}
@@ -5605,25 +5605,25 @@ cpm_load(PyObject *self, PyObject *ob)
static PyObject *
cpm_loads(PyObject *self, PyObject *args)
{
- PyObject *ob, *file = 0, *res = NULL;
- Unpicklerobject *unpickler = 0;
+ PyObject *ob, *file = 0, *res = NULL;
+ Unpicklerobject *unpickler = 0;
- if (!( PyArg_ParseTuple(args, "S:loads", &ob)))
- goto finally;
+ if (!( PyArg_ParseTuple(args, "S:loads", &ob)))
+ goto finally;
- if (!( file = PycStringIO->NewInput(ob)))
- goto finally;
+ if (!( file = PycStringIO->NewInput(ob)))
+ goto finally;
- if (!( unpickler = newUnpicklerobject(file)))
- goto finally;
+ if (!( unpickler = newUnpicklerobject(file)))
+ goto finally;
- res = load(unpickler);
+ res = load(unpickler);
finally:
- Py_XDECREF(file);
- Py_XDECREF(unpickler);
+ Py_XDECREF(file);
+ Py_XDECREF(unpickler);
- return res;
+ return res;
}
@@ -5632,28 +5632,28 @@ PyDoc_STRVAR(Unpicklertype__doc__,
static PyTypeObject Unpicklertype = {
PyVarObject_HEAD_INIT(NULL, 0)
- "cPickle.Unpickler", /*tp_name*/
+ "cPickle.Unpickler", /*tp_name*/
sizeof(Unpicklerobject), /*tp_basicsize*/
0,
- (destructor)Unpickler_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- (getattrfunc)Unpickler_getattr, /* tp_getattr */
- (setattrfunc)Unpickler_setattr, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
+ (destructor)Unpickler_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ (getattrfunc)Unpickler_getattr, /* tp_getattr */
+ (setattrfunc)Unpickler_setattr, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
- Unpicklertype__doc__, /* tp_doc */
- (traverseproc)Unpickler_traverse, /* tp_traverse */
- (inquiry)Unpickler_clear, /* tp_clear */
+ Unpicklertype__doc__, /* tp_doc */
+ (traverseproc)Unpickler_traverse, /* tp_traverse */
+ (inquiry)Unpickler_clear, /* tp_clear */
};
static struct PyMethodDef cPickle_methods[] = {
@@ -5711,198 +5711,198 @@ static struct PyMethodDef cPickle_methods[] = {
static int
init_stuff(PyObject *module_dict)
{
- PyObject *copyreg, *t, *r;
+ PyObject *copyreg, *t, *r;
#define INIT_STR(S) if (!( S ## _str=PyString_InternFromString(#S))) return -1;
- if (PyType_Ready(&Unpicklertype) < 0)
- return -1;
- if (PyType_Ready(&Picklertype) < 0)
- return -1;
-
- INIT_STR(__class__);
- INIT_STR(__getinitargs__);
- INIT_STR(__dict__);
- INIT_STR(__getstate__);
- INIT_STR(__setstate__);
- INIT_STR(__name__);
- INIT_STR(__main__);
- INIT_STR(__reduce__);
- INIT_STR(__reduce_ex__);
- INIT_STR(write);
- INIT_STR(append);
- INIT_STR(read);
- INIT_STR(readline);
- INIT_STR(dispatch_table);
-
- if (!( copyreg = PyImport_ImportModule("copy_reg")))
- return -1;
-
- /* This is special because we want to use a different
- one in restricted mode. */
- dispatch_table = PyObject_GetAttr(copyreg, dispatch_table_str);
- if (!dispatch_table) return -1;
-
- extension_registry = PyObject_GetAttrString(copyreg,
- "_extension_registry");
- if (!extension_registry) return -1;
-
- inverted_registry = PyObject_GetAttrString(copyreg,
- "_inverted_registry");
- if (!inverted_registry) return -1;
-
- extension_cache = PyObject_GetAttrString(copyreg,
- "_extension_cache");
- if (!extension_cache) return -1;
-
- Py_DECREF(copyreg);
-
- if (!(empty_tuple = PyTuple_New(0)))
- return -1;
-
- two_tuple = PyTuple_New(2);
- if (two_tuple == NULL)
- return -1;
- /* We use this temp container with no regard to refcounts, or to
- * keeping containees alive. Exempt from GC, because we don't
- * want anything looking at two_tuple() by magic.
- */
- PyObject_GC_UnTrack(two_tuple);
-
- /* Ugh */
- if (!( t=PyImport_ImportModule("__builtin__"))) return -1;
- if (PyDict_SetItemString(module_dict, "__builtins__", t) < 0)
- return -1;
-
- if (!( t=PyDict_New())) return -1;
- if (!( r=PyRun_String(
- "def __str__(self):\n"
- " return self.args and ('%s' % self.args[0]) or '(what)'\n",
- Py_file_input,
- module_dict, t) )) return -1;
- Py_DECREF(r);
-
- PickleError = PyErr_NewException("cPickle.PickleError", NULL, t);
- if (!PickleError)
- return -1;
-
- Py_DECREF(t);
-
- PicklingError = PyErr_NewException("cPickle.PicklingError",
- PickleError, NULL);
- if (!PicklingError)
- return -1;
-
- if (!( t=PyDict_New())) return -1;
- if (!( r=PyRun_String(
- "def __str__(self):\n"
- " a=self.args\n"
- " a=a and type(a[0]) or '(what)'\n"
- " return 'Cannot pickle %s objects' % a\n"
- , Py_file_input,
- module_dict, t) )) return -1;
- Py_DECREF(r);
-
- if (!( UnpickleableError = PyErr_NewException(
- "cPickle.UnpickleableError", PicklingError, t)))
- return -1;
-
- Py_DECREF(t);
-
- if (!( UnpicklingError = PyErr_NewException("cPickle.UnpicklingError",
- PickleError, NULL)))
- return -1;
-
- if (!( BadPickleGet = PyErr_NewException("cPickle.BadPickleGet",
- UnpicklingError, NULL)))
- return -1;
-
- if (PyDict_SetItemString(module_dict, "PickleError",
- PickleError) < 0)
- return -1;
-
- if (PyDict_SetItemString(module_dict, "PicklingError",
- PicklingError) < 0)
- return -1;
-
- if (PyDict_SetItemString(module_dict, "UnpicklingError",
- UnpicklingError) < 0)
- return -1;
+ if (PyType_Ready(&Unpicklertype) < 0)
+ return -1;
+ if (PyType_Ready(&Picklertype) < 0)
+ return -1;
+
+ INIT_STR(__class__);
+ INIT_STR(__getinitargs__);
+ INIT_STR(__dict__);
+ INIT_STR(__getstate__);
+ INIT_STR(__setstate__);
+ INIT_STR(__name__);
+ INIT_STR(__main__);
+ INIT_STR(__reduce__);
+ INIT_STR(__reduce_ex__);
+ INIT_STR(write);
+ INIT_STR(append);
+ INIT_STR(read);
+ INIT_STR(readline);
+ INIT_STR(dispatch_table);
+
+ if (!( copyreg = PyImport_ImportModule("copy_reg")))
+ return -1;
+
+ /* This is special because we want to use a different
+ one in restricted mode. */
+ dispatch_table = PyObject_GetAttr(copyreg, dispatch_table_str);
+ if (!dispatch_table) return -1;
+
+ extension_registry = PyObject_GetAttrString(copyreg,
+ "_extension_registry");
+ if (!extension_registry) return -1;
+
+ inverted_registry = PyObject_GetAttrString(copyreg,
+ "_inverted_registry");
+ if (!inverted_registry) return -1;
+
+ extension_cache = PyObject_GetAttrString(copyreg,
+ "_extension_cache");
+ if (!extension_cache) return -1;
+
+ Py_DECREF(copyreg);
+
+ if (!(empty_tuple = PyTuple_New(0)))
+ return -1;
+
+ two_tuple = PyTuple_New(2);
+ if (two_tuple == NULL)
+ return -1;
+ /* We use this temp container with no regard to refcounts, or to
+ * keeping containees alive. Exempt from GC, because we don't
+ * want anything looking at two_tuple() by magic.
+ */
+ PyObject_GC_UnTrack(two_tuple);
+
+ /* Ugh */
+ if (!( t=PyImport_ImportModule("__builtin__"))) return -1;
+ if (PyDict_SetItemString(module_dict, "__builtins__", t) < 0)
+ return -1;
+
+ if (!( t=PyDict_New())) return -1;
+ if (!( r=PyRun_String(
+ "def __str__(self):\n"
+ " return self.args and ('%s' % self.args[0]) or '(what)'\n",
+ Py_file_input,
+ module_dict, t) )) return -1;
+ Py_DECREF(r);
+
+ PickleError = PyErr_NewException("cPickle.PickleError", NULL, t);
+ if (!PickleError)
+ return -1;
+
+ Py_DECREF(t);
+
+ PicklingError = PyErr_NewException("cPickle.PicklingError",
+ PickleError, NULL);
+ if (!PicklingError)
+ return -1;
+
+ if (!( t=PyDict_New())) return -1;
+ if (!( r=PyRun_String(
+ "def __str__(self):\n"
+ " a=self.args\n"
+ " a=a and type(a[0]) or '(what)'\n"
+ " return 'Cannot pickle %s objects' % a\n"
+ , Py_file_input,
+ module_dict, t) )) return -1;
+ Py_DECREF(r);
+
+ if (!( UnpickleableError = PyErr_NewException(
+ "cPickle.UnpickleableError", PicklingError, t)))
+ return -1;
+
+ Py_DECREF(t);
+
+ if (!( UnpicklingError = PyErr_NewException("cPickle.UnpicklingError",
+ PickleError, NULL)))
+ return -1;
+
+ if (!( BadPickleGet = PyErr_NewException("cPickle.BadPickleGet",
+ UnpicklingError, NULL)))
+ return -1;
+
+ if (PyDict_SetItemString(module_dict, "PickleError",
+ PickleError) < 0)
+ return -1;
+
+ if (PyDict_SetItemString(module_dict, "PicklingError",
+ PicklingError) < 0)
+ return -1;
+
+ if (PyDict_SetItemString(module_dict, "UnpicklingError",
+ UnpicklingError) < 0)
+ return -1;
+
+ if (PyDict_SetItemString(module_dict, "UnpickleableError",
+ UnpickleableError) < 0)
+ return -1;
- if (PyDict_SetItemString(module_dict, "UnpickleableError",
- UnpickleableError) < 0)
- return -1;
+ if (PyDict_SetItemString(module_dict, "BadPickleGet",
+ BadPickleGet) < 0)
+ return -1;
- if (PyDict_SetItemString(module_dict, "BadPickleGet",
- BadPickleGet) < 0)
- return -1;
-
- PycString_IMPORT;
-
- return 0;
+ PycString_IMPORT;
+
+ return 0;
}
-#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
+#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initcPickle(void)
{
- PyObject *m, *d, *di, *v, *k;
- Py_ssize_t i;
- char *rev = "1.71"; /* XXX when does this change? */
- PyObject *format_version;
- PyObject *compatible_formats;
-
- Py_TYPE(&Picklertype) = &PyType_Type;
- Py_TYPE(&Unpicklertype) = &PyType_Type;
- Py_TYPE(&PdataType) = &PyType_Type;
-
- /* Initialize some pieces. We need to do this before module creation,
- * so we're forced to use a temporary dictionary. :(
- */
- di = PyDict_New();
- if (!di) return;
- if (init_stuff(di) < 0) return;
-
- /* Create the module and add the functions */
- m = Py_InitModule4("cPickle", cPickle_methods,
- cPickle_module_documentation,
- (PyObject*)NULL,PYTHON_API_VERSION);
- if (m == NULL)
- return;
-
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
- v = PyString_FromString(rev);
- PyDict_SetItemString(d, "__version__", v);
- Py_XDECREF(v);
-
- /* Copy data from di. Waaa. */
- for (i=0; PyDict_Next(di, &i, &k, &v); ) {
- if (PyObject_SetItem(d, k, v) < 0) {
- Py_DECREF(di);
- return;
- }
- }
- Py_DECREF(di);
-
- i = PyModule_AddIntConstant(m, "HIGHEST_PROTOCOL", HIGHEST_PROTOCOL);
- if (i < 0)
- return;
-
- /* These are purely informational; no code uses them. */
- /* File format version we write. */
- format_version = PyString_FromString("2.0");
- /* Format versions we can read. */
- compatible_formats = Py_BuildValue("[sssss]",
- "1.0", /* Original protocol 0 */
- "1.1", /* Protocol 0 + INST */
- "1.2", /* Original protocol 1 */
- "1.3", /* Protocol 1 + BINFLOAT */
- "2.0"); /* Original protocol 2 */
- PyDict_SetItemString(d, "format_version", format_version);
- PyDict_SetItemString(d, "compatible_formats", compatible_formats);
- Py_XDECREF(format_version);
- Py_XDECREF(compatible_formats);
+ PyObject *m, *d, *di, *v, *k;
+ Py_ssize_t i;
+ char *rev = "1.71"; /* XXX when does this change? */
+ PyObject *format_version;
+ PyObject *compatible_formats;
+
+ Py_TYPE(&Picklertype) = &PyType_Type;
+ Py_TYPE(&Unpicklertype) = &PyType_Type;
+ Py_TYPE(&PdataType) = &PyType_Type;
+
+ /* Initialize some pieces. We need to do this before module creation,
+ * so we're forced to use a temporary dictionary. :(
+ */
+ di = PyDict_New();
+ if (!di) return;
+ if (init_stuff(di) < 0) return;
+
+ /* Create the module and add the functions */
+ m = Py_InitModule4("cPickle", cPickle_methods,
+ cPickle_module_documentation,
+ (PyObject*)NULL,PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
+
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
+ v = PyString_FromString(rev);
+ PyDict_SetItemString(d, "__version__", v);
+ Py_XDECREF(v);
+
+ /* Copy data from di. Waaa. */
+ for (i=0; PyDict_Next(di, &i, &k, &v); ) {
+ if (PyObject_SetItem(d, k, v) < 0) {
+ Py_DECREF(di);
+ return;
+ }
+ }
+ Py_DECREF(di);
+
+ i = PyModule_AddIntConstant(m, "HIGHEST_PROTOCOL", HIGHEST_PROTOCOL);
+ if (i < 0)
+ return;
+
+ /* These are purely informational; no code uses them. */
+ /* File format version we write. */
+ format_version = PyString_FromString("2.0");
+ /* Format versions we can read. */
+ compatible_formats = Py_BuildValue("[sssss]",
+ "1.0", /* Original protocol 0 */
+ "1.1", /* Protocol 0 + INST */
+ "1.2", /* Original protocol 1 */
+ "1.3", /* Protocol 1 + BINFLOAT */
+ "2.0"); /* Original protocol 2 */
+ PyDict_SetItemString(d, "format_version", format_version);
+ PyDict_SetItemString(d, "compatible_formats", compatible_formats);
+ Py_XDECREF(format_version);
+ Py_XDECREF(compatible_formats);
}
diff --git a/Modules/cStringIO.c b/Modules/cStringIO.c
index 237d8c2..7e33033 100644
--- a/Modules/cStringIO.c
+++ b/Modules/cStringIO.c
@@ -33,7 +33,7 @@ PyDoc_STRVAR(cStringIO_module_documentation,
"\n"
"cStringIO.c,v 1.29 1999/06/15 14:10:27 jim Exp\n");
-/* Declaration for file-like objects that manage data as strings
+/* Declaration for file-like objects that manage data as strings
The IOobject type should be though of as a common base type for
Iobjects, which provide input (read-only) StringIO objects and
@@ -77,37 +77,37 @@ PyDoc_STRVAR(IO_flush__doc__, "flush(): does nothing.");
static int
IO__opencheck(IOobject *self) {
- if (!self->buf) {
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- return 0;
- }
- return 1;
+ if (!self->buf) {
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ return 0;
+ }
+ return 1;
}
static PyObject *
IO_get_closed(IOobject *self, void *closure)
{
- PyObject *result = Py_False;
+ PyObject *result = Py_False;
- if (self->buf == NULL)
- result = Py_True;
- Py_INCREF(result);
- return result;
+ if (self->buf == NULL)
+ result = Py_True;
+ Py_INCREF(result);
+ return result;
}
static PyGetSetDef file_getsetlist[] = {
- {"closed", (getter)IO_get_closed, NULL, "True if the file is closed"},
- {0},
+ {"closed", (getter)IO_get_closed, NULL, "True if the file is closed"},
+ {0},
};
static PyObject *
IO_flush(IOobject *self, PyObject *unused) {
- if (!IO__opencheck(self)) return NULL;
+ if (!IO__opencheck(self)) return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(IO_getval__doc__,
@@ -118,37 +118,37 @@ PyDoc_STRVAR(IO_getval__doc__,
static PyObject *
IO_cgetval(PyObject *self) {
- if (!IO__opencheck(IOOOBJECT(self))) return NULL;
- assert(IOOOBJECT(self)->pos >= 0);
- return PyString_FromStringAndSize(((IOobject*)self)->buf,
- ((IOobject*)self)->pos);
+ if (!IO__opencheck(IOOOBJECT(self))) return NULL;
+ assert(IOOOBJECT(self)->pos >= 0);
+ return PyString_FromStringAndSize(((IOobject*)self)->buf,
+ ((IOobject*)self)->pos);
}
static PyObject *
IO_getval(IOobject *self, PyObject *args) {
- PyObject *use_pos=Py_None;
- Py_ssize_t s;
-
- if (!IO__opencheck(self)) return NULL;
- if (!PyArg_UnpackTuple(args,"getval", 0, 1,&use_pos)) return NULL;
-
- if (PyObject_IsTrue(use_pos)) {
- s=self->pos;
- if (s > self->string_size) s=self->string_size;
- }
- else
- s=self->string_size;
- assert(self->pos >= 0);
- return PyString_FromStringAndSize(self->buf, s);
+ PyObject *use_pos=Py_None;
+ Py_ssize_t s;
+
+ if (!IO__opencheck(self)) return NULL;
+ if (!PyArg_UnpackTuple(args,"getval", 0, 1,&use_pos)) return NULL;
+
+ if (PyObject_IsTrue(use_pos)) {
+ s=self->pos;
+ if (s > self->string_size) s=self->string_size;
+ }
+ else
+ s=self->string_size;
+ assert(self->pos >= 0);
+ return PyString_FromStringAndSize(self->buf, s);
}
PyDoc_STRVAR(IO_isatty__doc__, "isatty(): always returns 0");
static PyObject *
IO_isatty(IOobject *self, PyObject *unused) {
- if (!IO__opencheck(self)) return NULL;
- Py_INCREF(Py_False);
- return Py_False;
+ if (!IO__opencheck(self)) return NULL;
+ Py_INCREF(Py_False);
+ return Py_False;
}
PyDoc_STRVAR(IO_read__doc__,
@@ -156,114 +156,114 @@ PyDoc_STRVAR(IO_read__doc__,
static int
IO_cread(PyObject *self, char **output, Py_ssize_t n) {
- Py_ssize_t l;
-
- if (!IO__opencheck(IOOOBJECT(self))) return -1;
- assert(IOOOBJECT(self)->pos >= 0);
- assert(IOOOBJECT(self)->string_size >= 0);
- l = ((IOobject*)self)->string_size - ((IOobject*)self)->pos;
- if (n < 0 || n > l) {
- n = l;
- if (n < 0) n=0;
- }
-
- *output=((IOobject*)self)->buf + ((IOobject*)self)->pos;
- ((IOobject*)self)->pos += n;
- return n;
+ Py_ssize_t l;
+
+ if (!IO__opencheck(IOOOBJECT(self))) return -1;
+ assert(IOOOBJECT(self)->pos >= 0);
+ assert(IOOOBJECT(self)->string_size >= 0);
+ l = ((IOobject*)self)->string_size - ((IOobject*)self)->pos;
+ if (n < 0 || n > l) {
+ n = l;
+ if (n < 0) n=0;
+ }
+
+ *output=((IOobject*)self)->buf + ((IOobject*)self)->pos;
+ ((IOobject*)self)->pos += n;
+ return n;
}
static PyObject *
IO_read(IOobject *self, PyObject *args) {
- Py_ssize_t n = -1;
- char *output = NULL;
+ Py_ssize_t n = -1;
+ char *output = NULL;
- if (!PyArg_ParseTuple(args, "|n:read", &n)) return NULL;
+ if (!PyArg_ParseTuple(args, "|n:read", &n)) return NULL;
- if ( (n=IO_cread((PyObject*)self,&output,n)) < 0) return NULL;
+ if ( (n=IO_cread((PyObject*)self,&output,n)) < 0) return NULL;
- return PyString_FromStringAndSize(output, n);
+ return PyString_FromStringAndSize(output, n);
}
PyDoc_STRVAR(IO_readline__doc__, "readline() -- Read one line");
static int
IO_creadline(PyObject *self, char **output) {
- char *n, *s;
- Py_ssize_t l;
+ char *n, *s;
+ Py_ssize_t l;
- if (!IO__opencheck(IOOOBJECT(self))) return -1;
+ if (!IO__opencheck(IOOOBJECT(self))) return -1;
- for (n = ((IOobject*)self)->buf + ((IOobject*)self)->pos,
- s = ((IOobject*)self)->buf + ((IOobject*)self)->string_size;
- n < s && *n != '\n'; n++);
+ for (n = ((IOobject*)self)->buf + ((IOobject*)self)->pos,
+ s = ((IOobject*)self)->buf + ((IOobject*)self)->string_size;
+ n < s && *n != '\n'; n++);
- if (n < s) n++;
+ if (n < s) n++;
- *output=((IOobject*)self)->buf + ((IOobject*)self)->pos;
- l = n - ((IOobject*)self)->buf - ((IOobject*)self)->pos;
+ *output=((IOobject*)self)->buf + ((IOobject*)self)->pos;
+ l = n - ((IOobject*)self)->buf - ((IOobject*)self)->pos;
- assert(IOOOBJECT(self)->pos <= PY_SSIZE_T_MAX - l);
- assert(IOOOBJECT(self)->pos >= 0);
- assert(IOOOBJECT(self)->string_size >= 0);
+ assert(IOOOBJECT(self)->pos <= PY_SSIZE_T_MAX - l);
+ assert(IOOOBJECT(self)->pos >= 0);
+ assert(IOOOBJECT(self)->string_size >= 0);
- ((IOobject*)self)->pos += l;
- return (int)l;
+ ((IOobject*)self)->pos += l;
+ return (int)l;
}
static PyObject *
IO_readline(IOobject *self, PyObject *args) {
- int n, m=-1;
- char *output;
-
- if (args)
- if (!PyArg_ParseTuple(args, "|i:readline", &m)) return NULL;
-
- if( (n=IO_creadline((PyObject*)self,&output)) < 0) return NULL;
- if (m >= 0 && m < n) {
- m = n - m;
- n -= m;
- self->pos -= m;
- }
- assert(IOOOBJECT(self)->pos >= 0);
- return PyString_FromStringAndSize(output, n);
+ int n, m=-1;
+ char *output;
+
+ if (args)
+ if (!PyArg_ParseTuple(args, "|i:readline", &m)) return NULL;
+
+ if( (n=IO_creadline((PyObject*)self,&output)) < 0) return NULL;
+ if (m >= 0 && m < n) {
+ m = n - m;
+ n -= m;
+ self->pos -= m;
+ }
+ assert(IOOOBJECT(self)->pos >= 0);
+ return PyString_FromStringAndSize(output, n);
}
PyDoc_STRVAR(IO_readlines__doc__, "readlines() -- Read all lines");
static PyObject *
IO_readlines(IOobject *self, PyObject *args) {
- int n;
- char *output;
- PyObject *result, *line;
- int hint = 0, length = 0;
-
- if (!PyArg_ParseTuple(args, "|i:readlines", &hint)) return NULL;
-
- result = PyList_New(0);
- if (!result)
- return NULL;
-
- while (1){
- if ( (n = IO_creadline((PyObject*)self,&output)) < 0)
- goto err;
- if (n == 0)
- break;
- line = PyString_FromStringAndSize (output, n);
- if (!line)
- goto err;
- if (PyList_Append (result, line) == -1) {
- Py_DECREF (line);
- goto err;
- }
- Py_DECREF (line);
- length += n;
- if (hint > 0 && length >= hint)
- break;
- }
- return result;
- err:
- Py_DECREF(result);
+ int n;
+ char *output;
+ PyObject *result, *line;
+ int hint = 0, length = 0;
+
+ if (!PyArg_ParseTuple(args, "|i:readlines", &hint)) return NULL;
+
+ result = PyList_New(0);
+ if (!result)
return NULL;
+
+ while (1){
+ if ( (n = IO_creadline((PyObject*)self,&output)) < 0)
+ goto err;
+ if (n == 0)
+ break;
+ line = PyString_FromStringAndSize (output, n);
+ if (!line)
+ goto err;
+ if (PyList_Append (result, line) == -1) {
+ Py_DECREF (line);
+ goto err;
+ }
+ Py_DECREF (line);
+ length += n;
+ if (hint > 0 && length >= hint)
+ break;
+ }
+ return result;
+ err:
+ Py_DECREF(result);
+ return NULL;
}
PyDoc_STRVAR(IO_reset__doc__,
@@ -272,12 +272,12 @@ PyDoc_STRVAR(IO_reset__doc__,
static PyObject *
IO_reset(IOobject *self, PyObject *unused) {
- if (!IO__opencheck(self)) return NULL;
+ if (!IO__opencheck(self)) return NULL;
- self->pos = 0;
+ self->pos = 0;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(IO_tell__doc__, "tell() -- get the current position.");
@@ -285,10 +285,10 @@ PyDoc_STRVAR(IO_tell__doc__, "tell() -- get the current position.");
static PyObject *
IO_tell(IOobject *self, PyObject *unused) {
- if (!IO__opencheck(self)) return NULL;
+ if (!IO__opencheck(self)) return NULL;
- assert(self->pos >= 0);
- return PyInt_FromSsize_t(self->pos);
+ assert(self->pos >= 0);
+ return PyInt_FromSsize_t(self->pos);
}
PyDoc_STRVAR(IO_truncate__doc__,
@@ -296,42 +296,42 @@ PyDoc_STRVAR(IO_truncate__doc__,
static PyObject *
IO_truncate(IOobject *self, PyObject *args) {
- Py_ssize_t pos = -1;
-
- if (!IO__opencheck(self)) return NULL;
- if (!PyArg_ParseTuple(args, "|n:truncate", &pos)) return NULL;
-
- if (PyTuple_Size(args) == 0) {
- /* No argument passed, truncate to current position */
- pos = self->pos;
- }
-
- if (pos < 0) {
- errno = EINVAL;
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
-
- if (self->string_size > pos) self->string_size = pos;
- self->pos = self->string_size;
-
- Py_INCREF(Py_None);
- return Py_None;
+ Py_ssize_t pos = -1;
+
+ if (!IO__opencheck(self)) return NULL;
+ if (!PyArg_ParseTuple(args, "|n:truncate", &pos)) return NULL;
+
+ if (PyTuple_Size(args) == 0) {
+ /* No argument passed, truncate to current position */
+ pos = self->pos;
+ }
+
+ if (pos < 0) {
+ errno = EINVAL;
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+
+ if (self->string_size > pos) self->string_size = pos;
+ self->pos = self->string_size;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
IO_iternext(Iobject *self)
{
- PyObject *next;
- next = IO_readline((IOobject *)self, NULL);
- if (!next)
- return NULL;
- if (!PyString_GET_SIZE(next)) {
- Py_DECREF(next);
- PyErr_SetNone(PyExc_StopIteration);
- return NULL;
- }
- return next;
+ PyObject *next;
+ next = IO_readline((IOobject *)self, NULL);
+ if (!next)
+ return NULL;
+ if (!PyString_GET_SIZE(next)) {
+ Py_DECREF(next);
+ PyErr_SetNone(PyExc_StopIteration);
+ return NULL;
+ }
+ return next;
}
@@ -345,41 +345,41 @@ PyDoc_STRVAR(O_seek__doc__,
static PyObject *
O_seek(Oobject *self, PyObject *args) {
- Py_ssize_t position;
- int mode = 0;
-
- if (!IO__opencheck(IOOOBJECT(self))) return NULL;
- if (!PyArg_ParseTuple(args, "n|i:seek", &position, &mode))
- return NULL;
-
- if (mode == 2) {
- position += self->string_size;
- }
- else if (mode == 1) {
- position += self->pos;
- }
+ Py_ssize_t position;
+ int mode = 0;
- if (position > self->buf_size) {
- char *newbuf;
- self->buf_size*=2;
- if (self->buf_size <= position) self->buf_size=position+1;
- newbuf = (char*) realloc(self->buf,self->buf_size);
- if (!newbuf) {
- free(self->buf);
- self->buf = 0;
- self->buf_size=self->pos=0;
- return PyErr_NoMemory();
- }
- self->buf = newbuf;
- }
- else if (position < 0) position=0;
-
- self->pos=position;
-
- while (--position >= self->string_size) self->buf[position]=0;
+ if (!IO__opencheck(IOOOBJECT(self))) return NULL;
+ if (!PyArg_ParseTuple(args, "n|i:seek", &position, &mode))
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (mode == 2) {
+ position += self->string_size;
+ }
+ else if (mode == 1) {
+ position += self->pos;
+ }
+
+ if (position > self->buf_size) {
+ char *newbuf;
+ self->buf_size*=2;
+ if (self->buf_size <= position) self->buf_size=position+1;
+ newbuf = (char*) realloc(self->buf,self->buf_size);
+ if (!newbuf) {
+ free(self->buf);
+ self->buf = 0;
+ self->buf_size=self->pos=0;
+ return PyErr_NoMemory();
+ }
+ self->buf = newbuf;
+ }
+ else if (position < 0) position=0;
+
+ self->pos=position;
+
+ while (--position >= self->string_size) self->buf[position]=0;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(O_write__doc__,
@@ -389,67 +389,67 @@ PyDoc_STRVAR(O_write__doc__,
static int
O_cwrite(PyObject *self, const char *c, Py_ssize_t l) {
- Py_ssize_t newl;
- Oobject *oself;
- char *newbuf;
-
- if (!IO__opencheck(IOOOBJECT(self))) return -1;
- oself = (Oobject *)self;
-
- newl = oself->pos+l;
- if (newl >= oself->buf_size) {
- oself->buf_size *= 2;
- if (oself->buf_size <= newl) {
- assert(newl + 1 < INT_MAX);
- oself->buf_size = (int)(newl+1);
- }
- newbuf = (char*)realloc(oself->buf, oself->buf_size);
- if (!newbuf) {
- PyErr_SetString(PyExc_MemoryError,"out of memory");
- free(oself->buf);
- oself->buf = 0;
- oself->buf_size = oself->pos = 0;
- return -1;
- }
- oself->buf = newbuf;
+ Py_ssize_t newl;
+ Oobject *oself;
+ char *newbuf;
+
+ if (!IO__opencheck(IOOOBJECT(self))) return -1;
+ oself = (Oobject *)self;
+
+ newl = oself->pos+l;
+ if (newl >= oself->buf_size) {
+ oself->buf_size *= 2;
+ if (oself->buf_size <= newl) {
+ assert(newl + 1 < INT_MAX);
+ oself->buf_size = (int)(newl+1);
+ }
+ newbuf = (char*)realloc(oself->buf, oself->buf_size);
+ if (!newbuf) {
+ PyErr_SetString(PyExc_MemoryError,"out of memory");
+ free(oself->buf);
+ oself->buf = 0;
+ oself->buf_size = oself->pos = 0;
+ return -1;
}
+ oself->buf = newbuf;
+ }
- memcpy(oself->buf+oself->pos,c,l);
+ memcpy(oself->buf+oself->pos,c,l);
- assert(oself->pos + l < INT_MAX);
- oself->pos += (int)l;
+ assert(oself->pos + l < INT_MAX);
+ oself->pos += (int)l;
- if (oself->string_size < oself->pos) {
- oself->string_size = oself->pos;
- }
+ if (oself->string_size < oself->pos) {
+ oself->string_size = oself->pos;
+ }
- return (int)l;
+ return (int)l;
}
static PyObject *
O_write(Oobject *self, PyObject *args) {
- char *c;
- int l;
+ char *c;
+ int l;
- if (!PyArg_ParseTuple(args, "t#:write", &c, &l)) return NULL;
+ if (!PyArg_ParseTuple(args, "t#:write", &c, &l)) return NULL;
- if (O_cwrite((PyObject*)self,c,l) < 0) return NULL;
+ if (O_cwrite((PyObject*)self,c,l) < 0) return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(O_close__doc__, "close(): explicitly release resources held.");
static PyObject *
O_close(Oobject *self, PyObject *unused) {
- if (self->buf != NULL) free(self->buf);
- self->buf = NULL;
+ if (self->buf != NULL) free(self->buf);
+ self->buf = NULL;
- self->pos = self->string_size = self->buf_size = 0;
+ self->pos = self->string_size = self->buf_size = 0;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(O_writelines__doc__,
@@ -459,32 +459,32 @@ PyDoc_STRVAR(O_writelines__doc__,
"producing strings. This is equivalent to calling write() for each string.");
static PyObject *
O_writelines(Oobject *self, PyObject *args) {
- PyObject *it, *s;
-
- it = PyObject_GetIter(args);
- if (it == NULL)
- return NULL;
- while ((s = PyIter_Next(it)) != NULL) {
- Py_ssize_t n;
- char *c;
- if (PyString_AsStringAndSize(s, &c, &n) == -1) {
- Py_DECREF(it);
- Py_DECREF(s);
- return NULL;
- }
- if (O_cwrite((PyObject *)self, c, n) == -1) {
- Py_DECREF(it);
- Py_DECREF(s);
- return NULL;
- }
- Py_DECREF(s);
+ PyObject *it, *s;
+
+ it = PyObject_GetIter(args);
+ if (it == NULL)
+ return NULL;
+ while ((s = PyIter_Next(it)) != NULL) {
+ Py_ssize_t n;
+ char *c;
+ if (PyString_AsStringAndSize(s, &c, &n) == -1) {
+ Py_DECREF(it);
+ Py_DECREF(s);
+ return NULL;
+ }
+ if (O_cwrite((PyObject *)self, c, n) == -1) {
+ Py_DECREF(it);
+ Py_DECREF(s);
+ return NULL;
+ }
+ Py_DECREF(s);
}
Py_DECREF(it);
/* See if PyIter_Next failed */
if (PyErr_Occurred())
- return NULL;
+ return NULL;
Py_RETURN_NONE;
}
@@ -493,92 +493,92 @@ static struct PyMethodDef O_methods[] = {
{"flush", (PyCFunction)IO_flush, METH_NOARGS, IO_flush__doc__},
{"getvalue", (PyCFunction)IO_getval, METH_VARARGS, IO_getval__doc__},
{"isatty", (PyCFunction)IO_isatty, METH_NOARGS, IO_isatty__doc__},
- {"read", (PyCFunction)IO_read, METH_VARARGS, IO_read__doc__},
- {"readline", (PyCFunction)IO_readline, METH_VARARGS, IO_readline__doc__},
- {"readlines", (PyCFunction)IO_readlines,METH_VARARGS, IO_readlines__doc__},
- {"reset", (PyCFunction)IO_reset, METH_NOARGS, IO_reset__doc__},
+ {"read", (PyCFunction)IO_read, METH_VARARGS, IO_read__doc__},
+ {"readline", (PyCFunction)IO_readline, METH_VARARGS, IO_readline__doc__},
+ {"readlines", (PyCFunction)IO_readlines,METH_VARARGS, IO_readlines__doc__},
+ {"reset", (PyCFunction)IO_reset, METH_NOARGS, IO_reset__doc__},
{"tell", (PyCFunction)IO_tell, METH_NOARGS, IO_tell__doc__},
{"truncate", (PyCFunction)IO_truncate, METH_VARARGS, IO_truncate__doc__},
/* Read-write StringIO specific methods: */
{"close", (PyCFunction)O_close, METH_NOARGS, O_close__doc__},
{"seek", (PyCFunction)O_seek, METH_VARARGS, O_seek__doc__},
- {"write", (PyCFunction)O_write, METH_VARARGS, O_write__doc__},
- {"writelines", (PyCFunction)O_writelines, METH_O, O_writelines__doc__},
- {NULL, NULL} /* sentinel */
+ {"write", (PyCFunction)O_write, METH_VARARGS, O_write__doc__},
+ {"writelines", (PyCFunction)O_writelines, METH_O, O_writelines__doc__},
+ {NULL, NULL} /* sentinel */
};
static PyMemberDef O_memberlist[] = {
- {"softspace", T_INT, offsetof(Oobject, softspace), 0,
- "flag indicating that a space needs to be printed; used by print"},
- /* getattr(f, "closed") is implemented without this table */
- {NULL} /* Sentinel */
+ {"softspace", T_INT, offsetof(Oobject, softspace), 0,
+ "flag indicating that a space needs to be printed; used by print"},
+ /* getattr(f, "closed") is implemented without this table */
+ {NULL} /* Sentinel */
};
static void
O_dealloc(Oobject *self) {
- if (self->buf != NULL)
- free(self->buf);
- PyObject_Del(self);
+ if (self->buf != NULL)
+ free(self->buf);
+ PyObject_Del(self);
}
PyDoc_STRVAR(Otype__doc__, "Simple type for output to strings.");
static PyTypeObject Otype = {
PyVarObject_HEAD_INIT(NULL, 0)
- "cStringIO.StringO", /*tp_name*/
- sizeof(Oobject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
+ "cStringIO.StringO", /*tp_name*/
+ sizeof(Oobject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
/* methods */
- (destructor)O_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr */
- 0, /*tp_setattr */
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0 , /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro */
- 0, /*tp_setattro */
- 0, /*tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- Otype__doc__, /*tp_doc */
- 0, /*tp_traverse */
- 0, /*tp_clear */
- 0, /*tp_richcompare */
- 0, /*tp_weaklistoffset */
- PyObject_SelfIter, /*tp_iter */
- (iternextfunc)IO_iternext, /*tp_iternext */
- O_methods, /*tp_methods */
- O_memberlist, /*tp_members */
- file_getsetlist, /*tp_getset */
+ (destructor)O_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr */
+ 0, /*tp_setattr */
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0 , /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro */
+ 0, /*tp_setattro */
+ 0, /*tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ Otype__doc__, /*tp_doc */
+ 0, /*tp_traverse */
+ 0, /*tp_clear */
+ 0, /*tp_richcompare */
+ 0, /*tp_weaklistoffset */
+ PyObject_SelfIter, /*tp_iter */
+ (iternextfunc)IO_iternext, /*tp_iternext */
+ O_methods, /*tp_methods */
+ O_memberlist, /*tp_members */
+ file_getsetlist, /*tp_getset */
};
static PyObject *
newOobject(int size) {
- Oobject *self;
-
- self = PyObject_New(Oobject, &Otype);
- if (self == NULL)
- return NULL;
- self->pos=0;
- self->string_size = 0;
- self->softspace = 0;
-
- self->buf = (char *)malloc(size);
- if (!self->buf) {
- PyErr_SetString(PyExc_MemoryError,"out of memory");
- self->buf_size = 0;
- Py_DECREF(self);
- return NULL;
- }
+ Oobject *self;
- self->buf_size=size;
- return (PyObject*)self;
+ self = PyObject_New(Oobject, &Otype);
+ if (self == NULL)
+ return NULL;
+ self->pos=0;
+ self->string_size = 0;
+ self->softspace = 0;
+
+ self->buf = (char *)malloc(size);
+ if (!self->buf) {
+ PyErr_SetString(PyExc_MemoryError,"out of memory");
+ self->buf_size = 0;
+ Py_DECREF(self);
+ return NULL;
+ }
+
+ self->buf_size=size;
+ return (PyObject*)self;
}
/* End of code for StringO objects */
@@ -586,33 +586,33 @@ newOobject(int size) {
static PyObject *
I_close(Iobject *self, PyObject *unused) {
- Py_CLEAR(self->pbuf);
- self->buf = NULL;
+ Py_CLEAR(self->pbuf);
+ self->buf = NULL;
- self->pos = self->string_size = 0;
+ self->pos = self->string_size = 0;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
I_seek(Iobject *self, PyObject *args) {
- Py_ssize_t position;
- int mode = 0;
+ Py_ssize_t position;
+ int mode = 0;
- if (!IO__opencheck(IOOOBJECT(self))) return NULL;
- if (!PyArg_ParseTuple(args, "n|i:seek", &position, &mode))
- return NULL;
+ if (!IO__opencheck(IOOOBJECT(self))) return NULL;
+ if (!PyArg_ParseTuple(args, "n|i:seek", &position, &mode))
+ return NULL;
- if (mode == 2) position += self->string_size;
- else if (mode == 1) position += self->pos;
+ if (mode == 2) position += self->string_size;
+ else if (mode == 1) position += self->pos;
- if (position < 0) position=0;
+ if (position < 0) position=0;
- self->pos=position;
+ self->pos=position;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static struct PyMethodDef I_methods[] = {
@@ -620,17 +620,17 @@ static struct PyMethodDef I_methods[] = {
{"flush", (PyCFunction)IO_flush, METH_NOARGS, IO_flush__doc__},
{"getvalue", (PyCFunction)IO_getval, METH_VARARGS, IO_getval__doc__},
{"isatty", (PyCFunction)IO_isatty, METH_NOARGS, IO_isatty__doc__},
- {"read", (PyCFunction)IO_read, METH_VARARGS, IO_read__doc__},
- {"readline", (PyCFunction)IO_readline, METH_VARARGS, IO_readline__doc__},
- {"readlines", (PyCFunction)IO_readlines,METH_VARARGS, IO_readlines__doc__},
- {"reset", (PyCFunction)IO_reset, METH_NOARGS, IO_reset__doc__},
+ {"read", (PyCFunction)IO_read, METH_VARARGS, IO_read__doc__},
+ {"readline", (PyCFunction)IO_readline, METH_VARARGS, IO_readline__doc__},
+ {"readlines", (PyCFunction)IO_readlines,METH_VARARGS, IO_readlines__doc__},
+ {"reset", (PyCFunction)IO_reset, METH_NOARGS, IO_reset__doc__},
{"tell", (PyCFunction)IO_tell, METH_NOARGS, IO_tell__doc__},
{"truncate", (PyCFunction)IO_truncate, METH_VARARGS, IO_truncate__doc__},
/* Read-only StringIO specific methods: */
{"close", (PyCFunction)I_close, METH_NOARGS, O_close__doc__},
- {"seek", (PyCFunction)I_seek, METH_VARARGS, O_seek__doc__},
- {NULL, NULL}
+ {"seek", (PyCFunction)I_seek, METH_VARARGS, O_seek__doc__},
+ {NULL, NULL}
};
static void
@@ -645,36 +645,36 @@ PyDoc_STRVAR(Itype__doc__,
static PyTypeObject Itype = {
PyVarObject_HEAD_INIT(NULL, 0)
- "cStringIO.StringI", /*tp_name*/
- sizeof(Iobject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
+ "cStringIO.StringI", /*tp_name*/
+ sizeof(Iobject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
/* methods */
- (destructor)I_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /* tp_getattr */
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- Itype__doc__, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)IO_iternext, /* tp_iternext */
- I_methods, /* tp_methods */
- 0, /* tp_members */
- file_getsetlist, /* tp_getset */
+ (destructor)I_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /* tp_getattr */
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ Itype__doc__, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)IO_iternext, /* tp_iternext */
+ I_methods, /* tp_methods */
+ 0, /* tp_members */
+ file_getsetlist, /* tp_getset */
};
static PyObject *
@@ -696,7 +696,7 @@ newIobject(PyObject *s) {
self->string_size=size;
self->pbuf=s;
self->pos=0;
-
+
return (PyObject*)self;
}
@@ -720,9 +720,9 @@ IO_StringIO(PyObject *self, PyObject *args) {
/* List of methods defined in the module */
static struct PyMethodDef IO_methods[] = {
- {"StringIO", (PyCFunction)IO_StringIO,
- METH_VARARGS, IO_StringIO__doc__},
- {NULL, NULL} /* sentinel */
+ {"StringIO", (PyCFunction)IO_StringIO,
+ METH_VARARGS, IO_StringIO__doc__},
+ {NULL, NULL} /* sentinel */
};
@@ -739,7 +739,7 @@ static struct PycStringIO_CAPI CAPI = {
&Otype,
};
-#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
+#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
@@ -749,20 +749,20 @@ initcStringIO(void) {
/* Create the module and add the functions */
m = Py_InitModule4("cStringIO", IO_methods,
- cStringIO_module_documentation,
- (PyObject*)NULL,PYTHON_API_VERSION);
+ cStringIO_module_documentation,
+ (PyObject*)NULL,PYTHON_API_VERSION);
if (m == NULL) return;
/* Add some symbolic constants to the module */
d = PyModule_GetDict(m);
-
+
/* Export C API */
Py_TYPE(&Itype)=&PyType_Type;
Py_TYPE(&Otype)=&PyType_Type;
if (PyType_Ready(&Otype) < 0) return;
if (PyType_Ready(&Itype) < 0) return;
PyDict_SetItemString(d,"cStringIO_CAPI",
- v = PyCObject_FromVoidPtr(&CAPI,NULL));
+ v = PyCObject_FromVoidPtr(&CAPI,NULL));
Py_XDECREF(v);
/* Export Types */
diff --git a/Modules/cdmodule.c b/Modules/cdmodule.c
index f09b0a4..8dfb769 100644
--- a/Modules/cdmodule.c
+++ b/Modules/cdmodule.c
@@ -5,796 +5,796 @@
#include <cdaudio.h>
#include "Python.h"
-#define NCALLBACKS 8
+#define NCALLBACKS 8
typedef struct {
- PyObject_HEAD
- CDPLAYER *ob_cdplayer;
+ PyObject_HEAD
+ CDPLAYER *ob_cdplayer;
} cdplayerobject;
-static PyObject *CdError; /* exception cd.error */
+static PyObject *CdError; /* exception cd.error */
static PyObject *
CD_allowremoval(cdplayerobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":allowremoval"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":allowremoval"))
+ return NULL;
- CDallowremoval(self->ob_cdplayer);
+ CDallowremoval(self->ob_cdplayer);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_preventremoval(cdplayerobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":preventremoval"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":preventremoval"))
+ return NULL;
- CDpreventremoval(self->ob_cdplayer);
+ CDpreventremoval(self->ob_cdplayer);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_bestreadsize(cdplayerobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":bestreadsize"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":bestreadsize"))
+ return NULL;
- return PyInt_FromLong((long) CDbestreadsize(self->ob_cdplayer));
+ return PyInt_FromLong((long) CDbestreadsize(self->ob_cdplayer));
}
static PyObject *
CD_close(cdplayerobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":close"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":close"))
+ return NULL;
- if (!CDclose(self->ob_cdplayer)) {
- PyErr_SetFromErrno(CdError); /* XXX - ??? */
- return NULL;
- }
- self->ob_cdplayer = NULL;
+ if (!CDclose(self->ob_cdplayer)) {
+ PyErr_SetFromErrno(CdError); /* XXX - ??? */
+ return NULL;
+ }
+ self->ob_cdplayer = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_eject(cdplayerobject *self, PyObject *args)
{
- CDSTATUS status;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, ":eject"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":eject"))
+ return NULL;
- if (!CDeject(self->ob_cdplayer)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "eject failed");
- return NULL;
- }
+ if (!CDeject(self->ob_cdplayer)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "eject failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject *
CD_getstatus(cdplayerobject *self, PyObject *args)
{
- CDSTATUS status;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, ":getstatus"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":getstatus"))
+ return NULL;
- if (!CDgetstatus(self->ob_cdplayer, &status)) {
- PyErr_SetFromErrno(CdError); /* XXX - ??? */
- return NULL;
- }
+ if (!CDgetstatus(self->ob_cdplayer, &status)) {
+ PyErr_SetFromErrno(CdError); /* XXX - ??? */
+ return NULL;
+ }
- return Py_BuildValue("(ii(iii)(iii)(iii)iiii)", status.state,
- status.track, status.min, status.sec, status.frame,
- status.abs_min, status.abs_sec, status.abs_frame,
- status.total_min, status.total_sec, status.total_frame,
- status.first, status.last, status.scsi_audio,
- status.cur_block);
+ return Py_BuildValue("(ii(iii)(iii)(iii)iiii)", status.state,
+ status.track, status.min, status.sec, status.frame,
+ status.abs_min, status.abs_sec, status.abs_frame,
+ status.total_min, status.total_sec, status.total_frame,
+ status.first, status.last, status.scsi_audio,
+ status.cur_block);
}
-
+
static PyObject *
CD_gettrackinfo(cdplayerobject *self, PyObject *args)
{
- int track;
- CDTRACKINFO info;
- CDSTATUS status;
+ int track;
+ CDTRACKINFO info;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, "i:gettrackinfo", &track))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:gettrackinfo", &track))
+ return NULL;
- if (!CDgettrackinfo(self->ob_cdplayer, track, &info)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "gettrackinfo failed");
- return NULL;
- }
+ if (!CDgettrackinfo(self->ob_cdplayer, track, &info)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "gettrackinfo failed");
+ return NULL;
+ }
- return Py_BuildValue("((iii)(iii))",
- info.start_min, info.start_sec, info.start_frame,
- info.total_min, info.total_sec, info.total_frame);
+ return Py_BuildValue("((iii)(iii))",
+ info.start_min, info.start_sec, info.start_frame,
+ info.total_min, info.total_sec, info.total_frame);
}
-
+
static PyObject *
CD_msftoblock(cdplayerobject *self, PyObject *args)
{
- int min, sec, frame;
+ int min, sec, frame;
- if (!PyArg_ParseTuple(args, "iii:msftoblock", &min, &sec, &frame))
- return NULL;
+ if (!PyArg_ParseTuple(args, "iii:msftoblock", &min, &sec, &frame))
+ return NULL;
- return PyInt_FromLong((long) CDmsftoblock(self->ob_cdplayer,
- min, sec, frame));
+ return PyInt_FromLong((long) CDmsftoblock(self->ob_cdplayer,
+ min, sec, frame));
}
-
+
static PyObject *
CD_play(cdplayerobject *self, PyObject *args)
{
- int start, play;
- CDSTATUS status;
+ int start, play;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, "ii:play", &start, &play))
- return NULL;
+ if (!PyArg_ParseTuple(args, "ii:play", &start, &play))
+ return NULL;
- if (!CDplay(self->ob_cdplayer, start, play)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "play failed");
- return NULL;
- }
+ if (!CDplay(self->ob_cdplayer, start, play)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "play failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject *
CD_playabs(cdplayerobject *self, PyObject *args)
{
- int min, sec, frame, play;
- CDSTATUS status;
+ int min, sec, frame, play;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, "iiii:playabs", &min, &sec, &frame, &play))
- return NULL;
+ if (!PyArg_ParseTuple(args, "iiii:playabs", &min, &sec, &frame, &play))
+ return NULL;
- if (!CDplayabs(self->ob_cdplayer, min, sec, frame, play)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "playabs failed");
- return NULL;
- }
+ if (!CDplayabs(self->ob_cdplayer, min, sec, frame, play)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "playabs failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject *
CD_playtrack(cdplayerobject *self, PyObject *args)
{
- int start, play;
- CDSTATUS status;
+ int start, play;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, "ii:playtrack", &start, &play))
- return NULL;
+ if (!PyArg_ParseTuple(args, "ii:playtrack", &start, &play))
+ return NULL;
- if (!CDplaytrack(self->ob_cdplayer, start, play)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "playtrack failed");
- return NULL;
- }
+ if (!CDplaytrack(self->ob_cdplayer, start, play)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "playtrack failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject *
CD_playtrackabs(cdplayerobject *self, PyObject *args)
{
- int track, min, sec, frame, play;
- CDSTATUS status;
+ int track, min, sec, frame, play;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, "iiiii:playtrackabs", &track, &min, &sec,
- &frame, &play))
- return NULL;
+ if (!PyArg_ParseTuple(args, "iiiii:playtrackabs", &track, &min, &sec,
+ &frame, &play))
+ return NULL;
- if (!CDplaytrackabs(self->ob_cdplayer, track, min, sec, frame, play)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "playtrackabs failed");
- return NULL;
- }
+ if (!CDplaytrackabs(self->ob_cdplayer, track, min, sec, frame, play)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "playtrackabs failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject *
CD_readda(cdplayerobject *self, PyObject *args)
{
- int numframes, n;
- PyObject *result;
+ int numframes, n;
+ PyObject *result;
- if (!PyArg_ParseTuple(args, "i:readda", &numframes))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:readda", &numframes))
+ return NULL;
- result = PyString_FromStringAndSize(NULL, numframes * sizeof(CDFRAME));
- if (result == NULL)
- return NULL;
+ result = PyString_FromStringAndSize(NULL, numframes * sizeof(CDFRAME));
+ if (result == NULL)
+ return NULL;
- n = CDreadda(self->ob_cdplayer,
- (CDFRAME *) PyString_AsString(result), numframes);
- if (n == -1) {
- Py_DECREF(result);
- PyErr_SetFromErrno(CdError);
- return NULL;
- }
- if (n < numframes)
- _PyString_Resize(&result, n * sizeof(CDFRAME));
+ n = CDreadda(self->ob_cdplayer,
+ (CDFRAME *) PyString_AsString(result), numframes);
+ if (n == -1) {
+ Py_DECREF(result);
+ PyErr_SetFromErrno(CdError);
+ return NULL;
+ }
+ if (n < numframes)
+ _PyString_Resize(&result, n * sizeof(CDFRAME));
- return result;
+ return result;
}
static PyObject *
CD_seek(cdplayerobject *self, PyObject *args)
{
- int min, sec, frame;
- long PyTryBlock;
+ int min, sec, frame;
+ long PyTryBlock;
- if (!PyArg_ParseTuple(args, "iii:seek", &min, &sec, &frame))
- return NULL;
+ if (!PyArg_ParseTuple(args, "iii:seek", &min, &sec, &frame))
+ return NULL;
- PyTryBlock = CDseek(self->ob_cdplayer, min, sec, frame);
- if (PyTryBlock == -1) {
- PyErr_SetFromErrno(CdError);
- return NULL;
- }
+ PyTryBlock = CDseek(self->ob_cdplayer, min, sec, frame);
+ if (PyTryBlock == -1) {
+ PyErr_SetFromErrno(CdError);
+ return NULL;
+ }
- return PyInt_FromLong(PyTryBlock);
+ return PyInt_FromLong(PyTryBlock);
}
-
+
static PyObject *
CD_seektrack(cdplayerobject *self, PyObject *args)
{
- int track;
- long PyTryBlock;
+ int track;
+ long PyTryBlock;
- if (!PyArg_ParseTuple(args, "i:seektrack", &track))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:seektrack", &track))
+ return NULL;
- PyTryBlock = CDseektrack(self->ob_cdplayer, track);
- if (PyTryBlock == -1) {
- PyErr_SetFromErrno(CdError);
- return NULL;
- }
+ PyTryBlock = CDseektrack(self->ob_cdplayer, track);
+ if (PyTryBlock == -1) {
+ PyErr_SetFromErrno(CdError);
+ return NULL;
+ }
- return PyInt_FromLong(PyTryBlock);
+ return PyInt_FromLong(PyTryBlock);
}
-
+
static PyObject *
CD_seekblock(cdplayerobject *self, PyObject *args)
{
- unsigned long PyTryBlock;
+ unsigned long PyTryBlock;
- if (!PyArg_ParseTuple(args, "l:seekblock", &PyTryBlock))
- return NULL;
+ if (!PyArg_ParseTuple(args, "l:seekblock", &PyTryBlock))
+ return NULL;
- PyTryBlock = CDseekblock(self->ob_cdplayer, PyTryBlock);
- if (PyTryBlock == (unsigned long) -1) {
- PyErr_SetFromErrno(CdError);
- return NULL;
- }
+ PyTryBlock = CDseekblock(self->ob_cdplayer, PyTryBlock);
+ if (PyTryBlock == (unsigned long) -1) {
+ PyErr_SetFromErrno(CdError);
+ return NULL;
+ }
- return PyInt_FromLong(PyTryBlock);
+ return PyInt_FromLong(PyTryBlock);
}
-
+
static PyObject *
CD_stop(cdplayerobject *self, PyObject *args)
{
- CDSTATUS status;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, ":stop"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":stop"))
+ return NULL;
- if (!CDstop(self->ob_cdplayer)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "stop failed");
- return NULL;
- }
+ if (!CDstop(self->ob_cdplayer)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "stop failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject *
CD_togglepause(cdplayerobject *self, PyObject *args)
{
- CDSTATUS status;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, ":togglepause"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":togglepause"))
+ return NULL;
- if (!CDtogglepause(self->ob_cdplayer)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "togglepause failed");
- return NULL;
- }
+ if (!CDtogglepause(self->ob_cdplayer)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "togglepause failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyMethodDef cdplayer_methods[] = {
- {"allowremoval", (PyCFunction)CD_allowremoval, METH_VARARGS},
- {"bestreadsize", (PyCFunction)CD_bestreadsize, METH_VARARGS},
- {"close", (PyCFunction)CD_close, METH_VARARGS},
- {"eject", (PyCFunction)CD_eject, METH_VARARGS},
- {"getstatus", (PyCFunction)CD_getstatus, METH_VARARGS},
- {"gettrackinfo", (PyCFunction)CD_gettrackinfo, METH_VARARGS},
- {"msftoblock", (PyCFunction)CD_msftoblock, METH_VARARGS},
- {"play", (PyCFunction)CD_play, METH_VARARGS},
- {"playabs", (PyCFunction)CD_playabs, METH_VARARGS},
- {"playtrack", (PyCFunction)CD_playtrack, METH_VARARGS},
- {"playtrackabs", (PyCFunction)CD_playtrackabs, METH_VARARGS},
- {"preventremoval", (PyCFunction)CD_preventremoval, METH_VARARGS},
- {"readda", (PyCFunction)CD_readda, METH_VARARGS},
- {"seek", (PyCFunction)CD_seek, METH_VARARGS},
- {"seekblock", (PyCFunction)CD_seekblock, METH_VARARGS},
- {"seektrack", (PyCFunction)CD_seektrack, METH_VARARGS},
- {"stop", (PyCFunction)CD_stop, METH_VARARGS},
- {"togglepause", (PyCFunction)CD_togglepause, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"allowremoval", (PyCFunction)CD_allowremoval, METH_VARARGS},
+ {"bestreadsize", (PyCFunction)CD_bestreadsize, METH_VARARGS},
+ {"close", (PyCFunction)CD_close, METH_VARARGS},
+ {"eject", (PyCFunction)CD_eject, METH_VARARGS},
+ {"getstatus", (PyCFunction)CD_getstatus, METH_VARARGS},
+ {"gettrackinfo", (PyCFunction)CD_gettrackinfo, METH_VARARGS},
+ {"msftoblock", (PyCFunction)CD_msftoblock, METH_VARARGS},
+ {"play", (PyCFunction)CD_play, METH_VARARGS},
+ {"playabs", (PyCFunction)CD_playabs, METH_VARARGS},
+ {"playtrack", (PyCFunction)CD_playtrack, METH_VARARGS},
+ {"playtrackabs", (PyCFunction)CD_playtrackabs, METH_VARARGS},
+ {"preventremoval", (PyCFunction)CD_preventremoval, METH_VARARGS},
+ {"readda", (PyCFunction)CD_readda, METH_VARARGS},
+ {"seek", (PyCFunction)CD_seek, METH_VARARGS},
+ {"seekblock", (PyCFunction)CD_seekblock, METH_VARARGS},
+ {"seektrack", (PyCFunction)CD_seektrack, METH_VARARGS},
+ {"stop", (PyCFunction)CD_stop, METH_VARARGS},
+ {"togglepause", (PyCFunction)CD_togglepause, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
static void
cdplayer_dealloc(cdplayerobject *self)
{
- if (self->ob_cdplayer != NULL)
- CDclose(self->ob_cdplayer);
- PyObject_Del(self);
+ if (self->ob_cdplayer != NULL)
+ CDclose(self->ob_cdplayer);
+ PyObject_Del(self);
}
static PyObject *
cdplayer_getattr(cdplayerobject *self, char *name)
{
- if (self->ob_cdplayer == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "no player active");
- return NULL;
- }
- return Py_FindMethod(cdplayer_methods, (PyObject *)self, name);
+ if (self->ob_cdplayer == NULL) {
+ PyErr_SetString(PyExc_RuntimeError, "no player active");
+ return NULL;
+ }
+ return Py_FindMethod(cdplayer_methods, (PyObject *)self, name);
}
PyTypeObject CdPlayertype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "cd.cdplayer", /*tp_name*/
- sizeof(cdplayerobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)cdplayer_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)cdplayer_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "cd.cdplayer", /*tp_name*/
+ sizeof(cdplayerobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)cdplayer_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)cdplayer_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
static PyObject *
newcdplayerobject(CDPLAYER *cdp)
{
- cdplayerobject *p;
+ cdplayerobject *p;
- p = PyObject_New(cdplayerobject, &CdPlayertype);
- if (p == NULL)
- return NULL;
- p->ob_cdplayer = cdp;
- return (PyObject *) p;
+ p = PyObject_New(cdplayerobject, &CdPlayertype);
+ if (p == NULL)
+ return NULL;
+ p->ob_cdplayer = cdp;
+ return (PyObject *) p;
}
static PyObject *
CD_open(PyObject *self, PyObject *args)
{
- char *dev, *direction;
- CDPLAYER *cdp;
+ char *dev, *direction;
+ CDPLAYER *cdp;
- /*
- * Variable number of args.
- * First defaults to "None", second defaults to "r".
- */
- dev = NULL;
- direction = "r";
- if (!PyArg_ParseTuple(args, "|zs:open", &dev, &direction))
- return NULL;
+ /*
+ * Variable number of args.
+ * First defaults to "None", second defaults to "r".
+ */
+ dev = NULL;
+ direction = "r";
+ if (!PyArg_ParseTuple(args, "|zs:open", &dev, &direction))
+ return NULL;
- cdp = CDopen(dev, direction);
- if (cdp == NULL) {
- PyErr_SetFromErrno(CdError);
- return NULL;
- }
+ cdp = CDopen(dev, direction);
+ if (cdp == NULL) {
+ PyErr_SetFromErrno(CdError);
+ return NULL;
+ }
- return newcdplayerobject(cdp);
+ return newcdplayerobject(cdp);
}
typedef struct {
- PyObject_HEAD
- CDPARSER *ob_cdparser;
- struct {
- PyObject *ob_cdcallback;
- PyObject *ob_cdcallbackarg;
- } ob_cdcallbacks[NCALLBACKS];
+ PyObject_HEAD
+ CDPARSER *ob_cdparser;
+ struct {
+ PyObject *ob_cdcallback;
+ PyObject *ob_cdcallbackarg;
+ } ob_cdcallbacks[NCALLBACKS];
} cdparserobject;
static void
CD_callback(void *arg, CDDATATYPES type, void *data)
{
- PyObject *result, *args, *v = NULL;
- char *p;
- int i;
- cdparserobject *self;
-
- self = (cdparserobject *) arg;
- args = PyTuple_New(3);
- if (args == NULL)
- return;
- Py_INCREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
- PyTuple_SetItem(args, 0, self->ob_cdcallbacks[type].ob_cdcallbackarg);
- PyTuple_SetItem(args, 1, PyInt_FromLong((long) type));
- switch (type) {
- case cd_audio:
- v = PyString_FromStringAndSize(data, CDDA_DATASIZE);
- break;
- case cd_pnum:
- case cd_index:
- v = PyInt_FromLong(((CDPROGNUM *) data)->value);
- break;
- case cd_ptime:
- case cd_atime:
+ PyObject *result, *args, *v = NULL;
+ char *p;
+ int i;
+ cdparserobject *self;
+
+ self = (cdparserobject *) arg;
+ args = PyTuple_New(3);
+ if (args == NULL)
+ return;
+ Py_INCREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
+ PyTuple_SetItem(args, 0, self->ob_cdcallbacks[type].ob_cdcallbackarg);
+ PyTuple_SetItem(args, 1, PyInt_FromLong((long) type));
+ switch (type) {
+ case cd_audio:
+ v = PyString_FromStringAndSize(data, CDDA_DATASIZE);
+ break;
+ case cd_pnum:
+ case cd_index:
+ v = PyInt_FromLong(((CDPROGNUM *) data)->value);
+ break;
+ case cd_ptime:
+ case cd_atime:
#define ptr ((struct cdtimecode *) data)
- v = Py_BuildValue("(iii)",
- ptr->mhi * 10 + ptr->mlo,
- ptr->shi * 10 + ptr->slo,
- ptr->fhi * 10 + ptr->flo);
+ v = Py_BuildValue("(iii)",
+ ptr->mhi * 10 + ptr->mlo,
+ ptr->shi * 10 + ptr->slo,
+ ptr->fhi * 10 + ptr->flo);
#undef ptr
- break;
- case cd_catalog:
- v = PyString_FromStringAndSize(NULL, 13);
- p = PyString_AsString(v);
- for (i = 0; i < 13; i++)
- *p++ = ((char *) data)[i] + '0';
- break;
- case cd_ident:
+ break;
+ case cd_catalog:
+ v = PyString_FromStringAndSize(NULL, 13);
+ p = PyString_AsString(v);
+ for (i = 0; i < 13; i++)
+ *p++ = ((char *) data)[i] + '0';
+ break;
+ case cd_ident:
#define ptr ((struct cdident *) data)
- v = PyString_FromStringAndSize(NULL, 12);
- p = PyString_AsString(v);
- CDsbtoa(p, ptr->country, 2);
- p += 2;
- CDsbtoa(p, ptr->owner, 3);
- p += 3;
- *p++ = ptr->year[0] + '0';
- *p++ = ptr->year[1] + '0';
- *p++ = ptr->serial[0] + '0';
- *p++ = ptr->serial[1] + '0';
- *p++ = ptr->serial[2] + '0';
- *p++ = ptr->serial[3] + '0';
- *p++ = ptr->serial[4] + '0';
+ v = PyString_FromStringAndSize(NULL, 12);
+ p = PyString_AsString(v);
+ CDsbtoa(p, ptr->country, 2);
+ p += 2;
+ CDsbtoa(p, ptr->owner, 3);
+ p += 3;
+ *p++ = ptr->year[0] + '0';
+ *p++ = ptr->year[1] + '0';
+ *p++ = ptr->serial[0] + '0';
+ *p++ = ptr->serial[1] + '0';
+ *p++ = ptr->serial[2] + '0';
+ *p++ = ptr->serial[3] + '0';
+ *p++ = ptr->serial[4] + '0';
#undef ptr
- break;
- case cd_control:
- v = PyInt_FromLong((long) *((unchar *) data));
- break;
- }
- PyTuple_SetItem(args, 2, v);
- if (PyErr_Occurred()) {
- Py_DECREF(args);
- return;
- }
-
- result = PyEval_CallObject(self->ob_cdcallbacks[type].ob_cdcallback,
- args);
- Py_DECREF(args);
- Py_XDECREF(result);
+ break;
+ case cd_control:
+ v = PyInt_FromLong((long) *((unchar *) data));
+ break;
+ }
+ PyTuple_SetItem(args, 2, v);
+ if (PyErr_Occurred()) {
+ Py_DECREF(args);
+ return;
+ }
+
+ result = PyEval_CallObject(self->ob_cdcallbacks[type].ob_cdcallback,
+ args);
+ Py_DECREF(args);
+ Py_XDECREF(result);
}
static PyObject *
CD_deleteparser(cdparserobject *self, PyObject *args)
{
- int i;
+ int i;
- if (!PyArg_ParseTuple(args, ":deleteparser"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":deleteparser"))
+ return NULL;
- CDdeleteparser(self->ob_cdparser);
- self->ob_cdparser = NULL;
+ CDdeleteparser(self->ob_cdparser);
+ self->ob_cdparser = NULL;
- /* no sense in keeping the callbacks, so remove them */
- for (i = 0; i < NCALLBACKS; i++) {
- Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallback);
- self->ob_cdcallbacks[i].ob_cdcallback = NULL;
- Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg);
- self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
- }
+ /* no sense in keeping the callbacks, so remove them */
+ for (i = 0; i < NCALLBACKS; i++) {
+ Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallback);
+ self->ob_cdcallbacks[i].ob_cdcallback = NULL;
+ Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg);
+ self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_parseframe(cdparserobject *self, PyObject *args)
{
- char *cdfp;
- int length;
- CDFRAME *p;
+ char *cdfp;
+ int length;
+ CDFRAME *p;
- if (!PyArg_ParseTuple(args, "s#:parseframe", &cdfp, &length))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s#:parseframe", &cdfp, &length))
+ return NULL;
- if (length % sizeof(CDFRAME) != 0) {
- PyErr_SetString(PyExc_TypeError, "bad length");
- return NULL;
- }
+ if (length % sizeof(CDFRAME) != 0) {
+ PyErr_SetString(PyExc_TypeError, "bad length");
+ return NULL;
+ }
- p = (CDFRAME *) cdfp;
- while (length > 0) {
- CDparseframe(self->ob_cdparser, p);
- length -= sizeof(CDFRAME);
- p++;
- if (PyErr_Occurred())
- return NULL;
- }
+ p = (CDFRAME *) cdfp;
+ while (length > 0) {
+ CDparseframe(self->ob_cdparser, p);
+ length -= sizeof(CDFRAME);
+ p++;
+ if (PyErr_Occurred())
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_removecallback(cdparserobject *self, PyObject *args)
{
- int type;
+ int type;
- if (!PyArg_ParseTuple(args, "i:removecallback", &type))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:removecallback", &type))
+ return NULL;
- if (type < 0 || type >= NCALLBACKS) {
- PyErr_SetString(PyExc_TypeError, "bad type");
- return NULL;
- }
+ if (type < 0 || type >= NCALLBACKS) {
+ PyErr_SetString(PyExc_TypeError, "bad type");
+ return NULL;
+ }
- CDremovecallback(self->ob_cdparser, (CDDATATYPES) type);
+ CDremovecallback(self->ob_cdparser, (CDDATATYPES) type);
- Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallback);
- self->ob_cdcallbacks[type].ob_cdcallback = NULL;
+ Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallback);
+ self->ob_cdcallbacks[type].ob_cdcallback = NULL;
- Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
- self->ob_cdcallbacks[type].ob_cdcallbackarg = NULL;
+ Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
+ self->ob_cdcallbacks[type].ob_cdcallbackarg = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_resetparser(cdparserobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":resetparser"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":resetparser"))
+ return NULL;
- CDresetparser(self->ob_cdparser);
+ CDresetparser(self->ob_cdparser);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_addcallback(cdparserobject *self, PyObject *args)
{
- int type;
- PyObject *func, *funcarg;
+ int type;
+ PyObject *func, *funcarg;
- /* XXX - more work here */
- if (!PyArg_ParseTuple(args, "iOO:addcallback", &type, &func, &funcarg))
- return NULL;
+ /* XXX - more work here */
+ if (!PyArg_ParseTuple(args, "iOO:addcallback", &type, &func, &funcarg))
+ return NULL;
- if (type < 0 || type >= NCALLBACKS) {
- PyErr_SetString(PyExc_TypeError, "argument out of range");
- return NULL;
- }
+ if (type < 0 || type >= NCALLBACKS) {
+ PyErr_SetString(PyExc_TypeError, "argument out of range");
+ return NULL;
+ }
#ifdef CDsetcallback
- CDaddcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback,
- (void *) self);
+ CDaddcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback,
+ (void *) self);
#else
- CDsetcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback,
- (void *) self);
+ CDsetcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback,
+ (void *) self);
#endif
- Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallback);
- Py_INCREF(func);
- self->ob_cdcallbacks[type].ob_cdcallback = func;
- Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
- Py_INCREF(funcarg);
- self->ob_cdcallbacks[type].ob_cdcallbackarg = funcarg;
+ Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallback);
+ Py_INCREF(func);
+ self->ob_cdcallbacks[type].ob_cdcallback = func;
+ Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
+ Py_INCREF(funcarg);
+ self->ob_cdcallbacks[type].ob_cdcallbackarg = funcarg;
/*
- if (type == cd_audio) {
- sigfpe_[_UNDERFL].repls = _ZERO;
- handle_sigfpes(_ON, _EN_UNDERFL, NULL,
- _ABORT_ON_ERROR, NULL);
- }
+ if (type == cd_audio) {
+ sigfpe_[_UNDERFL].repls = _ZERO;
+ handle_sigfpes(_ON, _EN_UNDERFL, NULL,
+ _ABORT_ON_ERROR, NULL);
+ }
*/
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef cdparser_methods[] = {
- {"addcallback", (PyCFunction)CD_addcallback, METH_VARARGS},
- {"deleteparser", (PyCFunction)CD_deleteparser, METH_VARARGS},
- {"parseframe", (PyCFunction)CD_parseframe, METH_VARARGS},
- {"removecallback", (PyCFunction)CD_removecallback, METH_VARARGS},
- {"resetparser", (PyCFunction)CD_resetparser, METH_VARARGS},
- /* backward compatibility */
- {"setcallback", (PyCFunction)CD_addcallback, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"addcallback", (PyCFunction)CD_addcallback, METH_VARARGS},
+ {"deleteparser", (PyCFunction)CD_deleteparser, METH_VARARGS},
+ {"parseframe", (PyCFunction)CD_parseframe, METH_VARARGS},
+ {"removecallback", (PyCFunction)CD_removecallback, METH_VARARGS},
+ {"resetparser", (PyCFunction)CD_resetparser, METH_VARARGS},
+ /* backward compatibility */
+ {"setcallback", (PyCFunction)CD_addcallback, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
static void
cdparser_dealloc(cdparserobject *self)
{
- int i;
+ int i;
- for (i = 0; i < NCALLBACKS; i++) {
- Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallback);
- self->ob_cdcallbacks[i].ob_cdcallback = NULL;
- Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg);
- self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
- }
- CDdeleteparser(self->ob_cdparser);
- PyObject_Del(self);
+ for (i = 0; i < NCALLBACKS; i++) {
+ Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallback);
+ self->ob_cdcallbacks[i].ob_cdcallback = NULL;
+ Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg);
+ self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
+ }
+ CDdeleteparser(self->ob_cdparser);
+ PyObject_Del(self);
}
static PyObject *
cdparser_getattr(cdparserobject *self, char *name)
{
- if (self->ob_cdparser == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "no parser active");
- return NULL;
- }
+ if (self->ob_cdparser == NULL) {
+ PyErr_SetString(PyExc_RuntimeError, "no parser active");
+ return NULL;
+ }
- return Py_FindMethod(cdparser_methods, (PyObject *)self, name);
+ return Py_FindMethod(cdparser_methods, (PyObject *)self, name);
}
PyTypeObject CdParsertype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "cd.cdparser", /*tp_name*/
- sizeof(cdparserobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)cdparser_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)cdparser_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "cd.cdparser", /*tp_name*/
+ sizeof(cdparserobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)cdparser_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)cdparser_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
static PyObject *
newcdparserobject(CDPARSER *cdp)
{
- cdparserobject *p;
- int i;
+ cdparserobject *p;
+ int i;
- p = PyObject_New(cdparserobject, &CdParsertype);
- if (p == NULL)
- return NULL;
- p->ob_cdparser = cdp;
- for (i = 0; i < NCALLBACKS; i++) {
- p->ob_cdcallbacks[i].ob_cdcallback = NULL;
- p->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
- }
- return (PyObject *) p;
+ p = PyObject_New(cdparserobject, &CdParsertype);
+ if (p == NULL)
+ return NULL;
+ p->ob_cdparser = cdp;
+ for (i = 0; i < NCALLBACKS; i++) {
+ p->ob_cdcallbacks[i].ob_cdcallback = NULL;
+ p->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
+ }
+ return (PyObject *) p;
}
static PyObject *
CD_createparser(PyObject *self, PyObject *args)
{
- CDPARSER *cdp;
+ CDPARSER *cdp;
- if (!PyArg_ParseTuple(args, ":createparser"))
- return NULL;
- cdp = CDcreateparser();
- if (cdp == NULL) {
- PyErr_SetString(CdError, "createparser failed");
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, ":createparser"))
+ return NULL;
+ cdp = CDcreateparser();
+ if (cdp == NULL) {
+ PyErr_SetString(CdError, "createparser failed");
+ return NULL;
+ }
- return newcdparserobject(cdp);
+ return newcdparserobject(cdp);
}
static PyObject *
CD_msftoframe(PyObject *self, PyObject *args)
{
- int min, sec, frame;
+ int min, sec, frame;
- if (!PyArg_ParseTuple(args, "iii:msftoframe", &min, &sec, &frame))
- return NULL;
+ if (!PyArg_ParseTuple(args, "iii:msftoframe", &min, &sec, &frame))
+ return NULL;
- return PyInt_FromLong((long) CDmsftoframe(min, sec, frame));
+ return PyInt_FromLong((long) CDmsftoframe(min, sec, frame));
}
-
+
static PyMethodDef CD_methods[] = {
- {"open", (PyCFunction)CD_open, METH_VARARGS},
- {"createparser", (PyCFunction)CD_createparser, METH_VARARGS},
- {"msftoframe", (PyCFunction)CD_msftoframe, METH_VARARGS},
- {NULL, NULL} /* Sentinel */
+ {"open", (PyCFunction)CD_open, METH_VARARGS},
+ {"createparser", (PyCFunction)CD_createparser, METH_VARARGS},
+ {"msftoframe", (PyCFunction)CD_msftoframe, METH_VARARGS},
+ {NULL, NULL} /* Sentinel */
};
void
initcd(void)
{
- PyObject *m, *d;
-
- if (PyErr_WarnPy3k("the cd module has been removed in "
- "Python 3.0", 2) < 0)
- return;
-
- m = Py_InitModule("cd", CD_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
-
- CdError = PyErr_NewException("cd.error", NULL, NULL);
- PyDict_SetItemString(d, "error", CdError);
-
- /* Identifiers for the different types of callbacks from the parser */
- PyDict_SetItemString(d, "audio", PyInt_FromLong((long) cd_audio));
- PyDict_SetItemString(d, "pnum", PyInt_FromLong((long) cd_pnum));
- PyDict_SetItemString(d, "index", PyInt_FromLong((long) cd_index));
- PyDict_SetItemString(d, "ptime", PyInt_FromLong((long) cd_ptime));
- PyDict_SetItemString(d, "atime", PyInt_FromLong((long) cd_atime));
- PyDict_SetItemString(d, "catalog", PyInt_FromLong((long) cd_catalog));
- PyDict_SetItemString(d, "ident", PyInt_FromLong((long) cd_ident));
- PyDict_SetItemString(d, "control", PyInt_FromLong((long) cd_control));
-
- /* Block size information for digital audio data */
- PyDict_SetItemString(d, "DATASIZE",
- PyInt_FromLong((long) CDDA_DATASIZE));
- PyDict_SetItemString(d, "BLOCKSIZE",
- PyInt_FromLong((long) CDDA_BLOCKSIZE));
-
- /* Possible states for the cd player */
- PyDict_SetItemString(d, "ERROR", PyInt_FromLong((long) CD_ERROR));
- PyDict_SetItemString(d, "NODISC", PyInt_FromLong((long) CD_NODISC));
- PyDict_SetItemString(d, "READY", PyInt_FromLong((long) CD_READY));
- PyDict_SetItemString(d, "PLAYING", PyInt_FromLong((long) CD_PLAYING));
- PyDict_SetItemString(d, "PAUSED", PyInt_FromLong((long) CD_PAUSED));
- PyDict_SetItemString(d, "STILL", PyInt_FromLong((long) CD_STILL));
-#ifdef CD_CDROM /* only newer versions of the library */
- PyDict_SetItemString(d, "CDROM", PyInt_FromLong((long) CD_CDROM));
+ PyObject *m, *d;
+
+ if (PyErr_WarnPy3k("the cd module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
+
+ m = Py_InitModule("cd", CD_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+
+ CdError = PyErr_NewException("cd.error", NULL, NULL);
+ PyDict_SetItemString(d, "error", CdError);
+
+ /* Identifiers for the different types of callbacks from the parser */
+ PyDict_SetItemString(d, "audio", PyInt_FromLong((long) cd_audio));
+ PyDict_SetItemString(d, "pnum", PyInt_FromLong((long) cd_pnum));
+ PyDict_SetItemString(d, "index", PyInt_FromLong((long) cd_index));
+ PyDict_SetItemString(d, "ptime", PyInt_FromLong((long) cd_ptime));
+ PyDict_SetItemString(d, "atime", PyInt_FromLong((long) cd_atime));
+ PyDict_SetItemString(d, "catalog", PyInt_FromLong((long) cd_catalog));
+ PyDict_SetItemString(d, "ident", PyInt_FromLong((long) cd_ident));
+ PyDict_SetItemString(d, "control", PyInt_FromLong((long) cd_control));
+
+ /* Block size information for digital audio data */
+ PyDict_SetItemString(d, "DATASIZE",
+ PyInt_FromLong((long) CDDA_DATASIZE));
+ PyDict_SetItemString(d, "BLOCKSIZE",
+ PyInt_FromLong((long) CDDA_BLOCKSIZE));
+
+ /* Possible states for the cd player */
+ PyDict_SetItemString(d, "ERROR", PyInt_FromLong((long) CD_ERROR));
+ PyDict_SetItemString(d, "NODISC", PyInt_FromLong((long) CD_NODISC));
+ PyDict_SetItemString(d, "READY", PyInt_FromLong((long) CD_READY));
+ PyDict_SetItemString(d, "PLAYING", PyInt_FromLong((long) CD_PLAYING));
+ PyDict_SetItemString(d, "PAUSED", PyInt_FromLong((long) CD_PAUSED));
+ PyDict_SetItemString(d, "STILL", PyInt_FromLong((long) CD_STILL));
+#ifdef CD_CDROM /* only newer versions of the library */
+ PyDict_SetItemString(d, "CDROM", PyInt_FromLong((long) CD_CDROM));
#endif
}
diff --git a/Modules/cgensupport.c b/Modules/cgensupport.c
index 7e7d0ff..aad43a2 100644
--- a/Modules/cgensupport.c
+++ b/Modules/cgensupport.c
@@ -13,158 +13,158 @@
int
PyArg_GetObject(register PyObject *args, int nargs, int i, PyObject **p_arg)
{
- if (nargs != 1) {
- if (args == NULL || !PyTuple_Check(args) ||
- nargs != PyTuple_Size(args) ||
- i < 0 || i >= nargs) {
- return PyErr_BadArgument();
- }
- else {
- args = PyTuple_GetItem(args, i);
- }
- }
- if (args == NULL) {
- return PyErr_BadArgument();
- }
- *p_arg = args;
- return 1;
+ if (nargs != 1) {
+ if (args == NULL || !PyTuple_Check(args) ||
+ nargs != PyTuple_Size(args) ||
+ i < 0 || i >= nargs) {
+ return PyErr_BadArgument();
+ }
+ else {
+ args = PyTuple_GetItem(args, i);
+ }
+ }
+ if (args == NULL) {
+ return PyErr_BadArgument();
+ }
+ *p_arg = args;
+ return 1;
}
int
PyArg_GetLong(register PyObject *args, int nargs, int i, long *p_arg)
{
- if (nargs != 1) {
- if (args == NULL || !PyTuple_Check(args) ||
- nargs != PyTuple_Size(args) ||
- i < 0 || i >= nargs) {
- return PyErr_BadArgument();
- }
- args = PyTuple_GetItem(args, i);
- }
- if (args == NULL || !PyInt_Check(args)) {
- return PyErr_BadArgument();
- }
- *p_arg = PyInt_AsLong(args);
- return 1;
+ if (nargs != 1) {
+ if (args == NULL || !PyTuple_Check(args) ||
+ nargs != PyTuple_Size(args) ||
+ i < 0 || i >= nargs) {
+ return PyErr_BadArgument();
+ }
+ args = PyTuple_GetItem(args, i);
+ }
+ if (args == NULL || !PyInt_Check(args)) {
+ return PyErr_BadArgument();
+ }
+ *p_arg = PyInt_AsLong(args);
+ return 1;
}
int
PyArg_GetShort(register PyObject *args, int nargs, int i, short *p_arg)
{
- long x;
- if (!PyArg_GetLong(args, nargs, i, &x))
- return 0;
- *p_arg = (short) x;
- return 1;
+ long x;
+ if (!PyArg_GetLong(args, nargs, i, &x))
+ return 0;
+ *p_arg = (short) x;
+ return 1;
}
static int
extractdouble(register PyObject *v, double *p_arg)
{
- if (v == NULL) {
- /* Fall through to error return at end of function */
- }
- else if (PyFloat_Check(v)) {
- *p_arg = PyFloat_AS_DOUBLE((PyFloatObject *)v);
- return 1;
- }
- else if (PyInt_Check(v)) {
- *p_arg = PyInt_AS_LONG((PyIntObject *)v);
- return 1;
- }
- else if (PyLong_Check(v)) {
- *p_arg = PyLong_AsDouble(v);
- return 1;
- }
- return PyErr_BadArgument();
+ if (v == NULL) {
+ /* Fall through to error return at end of function */
+ }
+ else if (PyFloat_Check(v)) {
+ *p_arg = PyFloat_AS_DOUBLE((PyFloatObject *)v);
+ return 1;
+ }
+ else if (PyInt_Check(v)) {
+ *p_arg = PyInt_AS_LONG((PyIntObject *)v);
+ return 1;
+ }
+ else if (PyLong_Check(v)) {
+ *p_arg = PyLong_AsDouble(v);
+ return 1;
+ }
+ return PyErr_BadArgument();
}
static int
extractfloat(register PyObject *v, float *p_arg)
{
- if (v == NULL) {
- /* Fall through to error return at end of function */
- }
- else if (PyFloat_Check(v)) {
- *p_arg = (float) PyFloat_AS_DOUBLE((PyFloatObject *)v);
- return 1;
- }
- else if (PyInt_Check(v)) {
- *p_arg = (float) PyInt_AS_LONG((PyIntObject *)v);
- return 1;
- }
- else if (PyLong_Check(v)) {
- *p_arg = (float) PyLong_AsDouble(v);
- return 1;
- }
- return PyErr_BadArgument();
+ if (v == NULL) {
+ /* Fall through to error return at end of function */
+ }
+ else if (PyFloat_Check(v)) {
+ *p_arg = (float) PyFloat_AS_DOUBLE((PyFloatObject *)v);
+ return 1;
+ }
+ else if (PyInt_Check(v)) {
+ *p_arg = (float) PyInt_AS_LONG((PyIntObject *)v);
+ return 1;
+ }
+ else if (PyLong_Check(v)) {
+ *p_arg = (float) PyLong_AsDouble(v);
+ return 1;
+ }
+ return PyErr_BadArgument();
}
int
PyArg_GetFloat(register PyObject *args, int nargs, int i, float *p_arg)
{
- PyObject *v;
- float x;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (!extractfloat(v, &x))
- return 0;
- *p_arg = x;
- return 1;
+ PyObject *v;
+ float x;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (!extractfloat(v, &x))
+ return 0;
+ *p_arg = x;
+ return 1;
}
int
PyArg_GetString(PyObject *args, int nargs, int i, string *p_arg)
{
- PyObject *v;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (!PyString_Check(v)) {
- return PyErr_BadArgument();
- }
- *p_arg = PyString_AsString(v);
- return 1;
+ PyObject *v;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (!PyString_Check(v)) {
+ return PyErr_BadArgument();
+ }
+ *p_arg = PyString_AsString(v);
+ return 1;
}
int
PyArg_GetChar(PyObject *args, int nargs, int i, char *p_arg)
{
- string x;
- if (!PyArg_GetString(args, nargs, i, &x))
- return 0;
- if (x[0] == '\0' || x[1] != '\0') {
- /* Not exactly one char */
- return PyErr_BadArgument();
- }
- *p_arg = x[0];
- return 1;
+ string x;
+ if (!PyArg_GetString(args, nargs, i, &x))
+ return 0;
+ if (x[0] == '\0' || x[1] != '\0') {
+ /* Not exactly one char */
+ return PyErr_BadArgument();
+ }
+ *p_arg = x[0];
+ return 1;
}
int
PyArg_GetLongArraySize(PyObject *args, int nargs, int i, long *p_arg)
{
- PyObject *v;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (PyTuple_Check(v)) {
- *p_arg = PyTuple_Size(v);
- return 1;
- }
- if (PyList_Check(v)) {
- *p_arg = PyList_Size(v);
- return 1;
- }
- return PyErr_BadArgument();
+ PyObject *v;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (PyTuple_Check(v)) {
+ *p_arg = PyTuple_Size(v);
+ return 1;
+ }
+ if (PyList_Check(v)) {
+ *p_arg = PyList_Size(v);
+ return 1;
+ }
+ return PyErr_BadArgument();
}
int
PyArg_GetShortArraySize(PyObject *args, int nargs, int i, short *p_arg)
{
- long x;
- if (!PyArg_GetLongArraySize(args, nargs, i, &x))
- return 0;
- *p_arg = (short) x;
- return 1;
+ long x;
+ if (!PyArg_GetLongArraySize(args, nargs, i, &x))
+ return 0;
+ *p_arg = (short) x;
+ return 1;
}
/* XXX The following four are too similar. Should share more code. */
@@ -172,139 +172,139 @@ PyArg_GetShortArraySize(PyObject *args, int nargs, int i, short *p_arg)
int
PyArg_GetLongArray(PyObject *args, int nargs, int i, int n, long *p_arg)
{
- PyObject *v, *w;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (PyTuple_Check(v)) {
- if (PyTuple_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyTuple_GetItem(v, i);
- if (!PyInt_Check(w)) {
- return PyErr_BadArgument();
- }
- p_arg[i] = PyInt_AsLong(w);
- }
- return 1;
- }
- else if (PyList_Check(v)) {
- if (PyList_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyList_GetItem(v, i);
- if (!PyInt_Check(w)) {
- return PyErr_BadArgument();
- }
- p_arg[i] = PyInt_AsLong(w);
- }
- return 1;
- }
- else {
- return PyErr_BadArgument();
- }
+ PyObject *v, *w;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (PyTuple_Check(v)) {
+ if (PyTuple_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyTuple_GetItem(v, i);
+ if (!PyInt_Check(w)) {
+ return PyErr_BadArgument();
+ }
+ p_arg[i] = PyInt_AsLong(w);
+ }
+ return 1;
+ }
+ else if (PyList_Check(v)) {
+ if (PyList_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyList_GetItem(v, i);
+ if (!PyInt_Check(w)) {
+ return PyErr_BadArgument();
+ }
+ p_arg[i] = PyInt_AsLong(w);
+ }
+ return 1;
+ }
+ else {
+ return PyErr_BadArgument();
+ }
}
int
PyArg_GetShortArray(PyObject *args, int nargs, int i, int n, short *p_arg)
{
- PyObject *v, *w;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (PyTuple_Check(v)) {
- if (PyTuple_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyTuple_GetItem(v, i);
- if (!PyInt_Check(w)) {
- return PyErr_BadArgument();
- }
- p_arg[i] = (short) PyInt_AsLong(w);
- }
- return 1;
- }
- else if (PyList_Check(v)) {
- if (PyList_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyList_GetItem(v, i);
- if (!PyInt_Check(w)) {
- return PyErr_BadArgument();
- }
- p_arg[i] = (short) PyInt_AsLong(w);
- }
- return 1;
- }
- else {
- return PyErr_BadArgument();
- }
+ PyObject *v, *w;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (PyTuple_Check(v)) {
+ if (PyTuple_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyTuple_GetItem(v, i);
+ if (!PyInt_Check(w)) {
+ return PyErr_BadArgument();
+ }
+ p_arg[i] = (short) PyInt_AsLong(w);
+ }
+ return 1;
+ }
+ else if (PyList_Check(v)) {
+ if (PyList_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyList_GetItem(v, i);
+ if (!PyInt_Check(w)) {
+ return PyErr_BadArgument();
+ }
+ p_arg[i] = (short) PyInt_AsLong(w);
+ }
+ return 1;
+ }
+ else {
+ return PyErr_BadArgument();
+ }
}
int
PyArg_GetDoubleArray(PyObject *args, int nargs, int i, int n, double *p_arg)
{
- PyObject *v, *w;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (PyTuple_Check(v)) {
- if (PyTuple_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyTuple_GetItem(v, i);
- if (!extractdouble(w, &p_arg[i]))
- return 0;
- }
- return 1;
- }
- else if (PyList_Check(v)) {
- if (PyList_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyList_GetItem(v, i);
- if (!extractdouble(w, &p_arg[i]))
- return 0;
- }
- return 1;
- }
- else {
- return PyErr_BadArgument();
- }
+ PyObject *v, *w;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (PyTuple_Check(v)) {
+ if (PyTuple_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyTuple_GetItem(v, i);
+ if (!extractdouble(w, &p_arg[i]))
+ return 0;
+ }
+ return 1;
+ }
+ else if (PyList_Check(v)) {
+ if (PyList_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyList_GetItem(v, i);
+ if (!extractdouble(w, &p_arg[i]))
+ return 0;
+ }
+ return 1;
+ }
+ else {
+ return PyErr_BadArgument();
+ }
}
int
PyArg_GetFloatArray(PyObject *args, int nargs, int i, int n, float *p_arg)
{
- PyObject *v, *w;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (PyTuple_Check(v)) {
- if (PyTuple_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyTuple_GetItem(v, i);
- if (!extractfloat(w, &p_arg[i]))
- return 0;
- }
- return 1;
- }
- else if (PyList_Check(v)) {
- if (PyList_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyList_GetItem(v, i);
- if (!extractfloat(w, &p_arg[i]))
- return 0;
- }
- return 1;
- }
- else {
- return PyErr_BadArgument();
- }
+ PyObject *v, *w;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (PyTuple_Check(v)) {
+ if (PyTuple_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyTuple_GetItem(v, i);
+ if (!extractfloat(w, &p_arg[i]))
+ return 0;
+ }
+ return 1;
+ }
+ else if (PyList_Check(v)) {
+ if (PyList_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyList_GetItem(v, i);
+ if (!extractfloat(w, &p_arg[i]))
+ return 0;
+ }
+ return 1;
+ }
+ else {
+ return PyErr_BadArgument();
+ }
}
diff --git a/Modules/cgensupport.h b/Modules/cgensupport.h
index bc901f6..27e1261 100644
--- a/Modules/cgensupport.h
+++ b/Modules/cgensupport.h
@@ -30,33 +30,33 @@ typedef char *string;
#define getistringarg PyArg_GetString
extern int PyArg_GetObject(PyObject *args, int nargs,
- int i, PyObject **p_a);
+ int i, PyObject **p_a);
extern int PyArg_GetLong(PyObject *args, int nargs,
- int i, long *p_a);
+ int i, long *p_a);
extern int PyArg_GetShort(PyObject *args, int nargs,
- int i, short *p_a);
+ int i, short *p_a);
extern int PyArg_GetFloat(PyObject *args, int nargs,
- int i, float *p_a);
+ int i, float *p_a);
extern int PyArg_GetString(PyObject *args, int nargs,
- int i, string *p_a);
+ int i, string *p_a);
extern int PyArg_GetChar(PyObject *args, int nargs,
- int i, char *p_a);
+ int i, char *p_a);
extern int PyArg_GetLongArray(PyObject *args, int nargs,
- int i, int n, long *p_a);
+ int i, int n, long *p_a);
extern int PyArg_GetShortArray(PyObject *args, int nargs,
- int i, int n, short *p_a);
+ int i, int n, short *p_a);
extern int PyArg_GetDoubleArray(PyObject *args, int nargs,
- int i, int n, double *p_a);
+ int i, int n, double *p_a);
extern int PyArg_GetFloatArray(PyObject *args, int nargs,
- int i, int n, float *p_a);
+ int i, int n, float *p_a);
extern int PyArg_GetLongArraySize(PyObject *args, int nargs,
- int i, long *p_a);
+ int i, long *p_a);
extern int PyArg_GetShortArraySize(PyObject *args, int nargs,
- int i, short *p_a);
+ int i, short *p_a);
extern int PyArg_GetDoubleArraySize(PyObject *args, int nargs,
- int i, double *p_a);
+ int i, double *p_a);
extern int PyArg_GetFloatArraySize(PyObject *args, int nargs,
- int i, float *p_a);
+ int i, float *p_a);
#ifdef __cplusplus
}
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 4005bcf..fae0c62 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,273 +126,273 @@ 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 (!PyString_Check(encoding)) {
- PyErr_SetString(PyExc_TypeError,
- "encoding name must be a string.");
- return NULL;
- }
-
- cofunc = getmultibytecodec();
- if (cofunc == NULL)
- return NULL;
-
- enc = PyString_AS_STRING(encoding);
- 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 = PyCObject_FromVoidPtr((void *)codec, 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 (!PyString_Check(encoding)) {
+ PyErr_SetString(PyExc_TypeError,
+ "encoding name must be a string.");
+ return NULL;
+ }
+
+ cofunc = getmultibytecodec();
+ if (cofunc == NULL)
+ return NULL;
+
+ enc = PyString_AS_STRING(encoding);
+ 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 = PyCObject_FromVoidPtr((void *)codec, 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,
- PyCObject_FromVoidPtr((void *)h, 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,
+ PyCObject_FromVoidPtr((void *)h, 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 (!PyCObject_Check(o)) {
- PyErr_SetString(PyExc_ValueError,
- "map data must be a CObject.");
- goto errorexit;
- }
- else {
- struct dbcs_map *map;
- map = PyCObject_AsVoidPtr(o);
- 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 (!PyCObject_Check(o)) {
+ PyErr_SetString(PyExc_ValueError,
+ "map data must be a CObject.");
+ goto errorexit;
+ }
+ else {
+ struct dbcs_map *map;
+ map = PyCObject_AsVoidPtr(o);
+ 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) \
- void \
- init_codecs_##loc(void) \
- { \
- PyObject *m = Py_InitModule("_codecs_" #loc, __methods);\
- if (m != NULL) \
- (void)register_maps(m); \
- }
+#define I_AM_A_MODULE_FOR(loc) \
+ void \
+ init_codecs_##loc(void) \
+ { \
+ PyObject *m = Py_InitModule("_codecs_" #loc, __methods);\
+ if (m != NULL) \
+ (void)register_maps(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 5fb5ec0..9856f04 100644
--- a/Modules/cjkcodecs/multibytecodec.c
+++ b/Modules/cjkcodecs/multibytecodec.c
@@ -45,170 +45,170 @@ 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 = PyInt_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 = PyInt_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 PyString_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 PyString_FromString(errors);
}
static PyObject *
call_error_callback(PyObject *errors, PyObject *exc)
{
- PyObject *args, *cb, *r;
-
- assert(PyString_Check(errors));
- cb = PyCodec_LookupError(PyString_AS_STRING(errors));
- 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;
+
+ assert(PyString_Check(errors));
+ cb = PyCodec_LookupError(PyString_AS_STRING(errors));
+ 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 PyString_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 PyString_FromString(errors);
}
static int
codecctx_errors_set(MultibyteStatefulCodecContext *self, PyObject *value,
- void *closure)
+ void *closure)
{
- PyObject *cb;
+ PyObject *cb;
- if (!PyString_Check(value)) {
- PyErr_SetString(PyExc_TypeError, "errors must be a string");
- return -1;
- }
+ if (!PyString_Check(value)) {
+ PyErr_SetString(PyExc_TypeError, "errors must be a string");
+ return -1;
+ }
- cb = internal_error_callback(PyString_AS_STRING(value));
- if (cb == NULL)
- return -1;
+ cb = internal_error_callback(PyString_AS_STRING(value));
+ 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 -
- PyString_AS_STRING(buf->outobj));
- orgsize = PyString_GET_SIZE(buf->outobj);
- incsize = (esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize);
+ orgpos = (Py_ssize_t)((char *)buf->outbuf -
+ PyString_AS_STRING(buf->outobj));
+ orgsize = PyString_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 (_PyString_Resize(&buf->outobj, orgsize + incsize) == -1)
- return -1;
+ if (_PyString_Resize(&buf->outobj, orgsize + incsize) == -1)
+ return -1;
- buf->outbuf = (unsigned char *)PyString_AS_STRING(buf->outobj) +orgpos;
- buf->outbuf_end = (unsigned char *)PyString_AS_STRING(buf->outobj)
- + PyString_GET_SIZE(buf->outobj);
+ buf->outbuf = (unsigned char *)PyString_AS_STRING(buf->outobj) +orgpos;
+ buf->outbuf_end = (unsigned char *)PyString_AS_STRING(buf->outobj)
+ + PyString_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; \
}
@@ -218,505 +218,505 @@ 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))) ||
- !(PyInt_Check(PyTuple_GET_ITEM(retobj, 1)) ||
- 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;
- }
-
- retstrsize = PyString_GET_SIZE(retstr);
- REQUIRE_ENCODEBUFFER(buf, retstrsize);
-
- memcpy(buf->outbuf, PyString_AS_STRING(retstr), retstrsize);
- buf->outbuf += retstrsize;
-
- newpos = PyInt_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))) ||
+ !(PyInt_Check(PyTuple_GET_ITEM(retobj, 1)) ||
+ 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;
+ }
+
+ retstrsize = PyString_GET_SIZE(retstr);
+ REQUIRE_ENCODEBUFFER(buf, retstrsize);
+
+ memcpy(buf->outbuf, PyString_AS_STRING(retstr), retstrsize);
+ buf->outbuf += retstrsize;
+
+ newpos = PyInt_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))) ||
- !(PyInt_Check(PyTuple_GET_ITEM(retobj, 1)) ||
- 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 = PyInt_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))) ||
+ !(PyInt_Check(PyTuple_GET_ITEM(retobj, 1)) ||
+ 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 = PyInt_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 PyString_FromString("");
-
- 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 = PyString_FromStringAndSize(NULL, datalen * 2 + 16);
- if (buf.outobj == NULL)
- goto errorexit;
- buf.outbuf = (unsigned char *)PyString_AS_STRING(buf.outobj);
- buf.outbuf_end = buf.outbuf + PyString_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);
- *data = buf.inbuf;
- 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 -
- PyString_AS_STRING(buf.outobj));
-
- if (finalsize != PyString_GET_SIZE(buf.outobj))
- if (_PyString_Resize(&buf.outobj, finalsize) == -1)
- goto errorexit;
-
- Py_XDECREF(buf.excobj);
- return buf.outobj;
+ MultibyteEncodeBuffer buf;
+ Py_ssize_t finalsize, r = 0;
+
+ if (datalen == 0)
+ return PyString_FromString("");
+
+ 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 = PyString_FromStringAndSize(NULL, datalen * 2 + 16);
+ if (buf.outobj == NULL)
+ goto errorexit;
+ buf.outbuf = (unsigned char *)PyString_AS_STRING(buf.outobj);
+ buf.outbuf_end = buf.outbuf + PyString_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);
+ *data = buf.inbuf;
+ 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 -
+ PyString_AS_STRING(buf.outobj));
+
+ if (finalsize != PyString_GET_SIZE(buf.outobj))
+ if (_PyString_Resize(&buf.outobj, finalsize) == -1)
+ goto errorexit;
+
+ 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_Unicode(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_Unicode(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, "s*|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, "s*|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_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 */
- 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_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 */
+ 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 */
};
@@ -724,150 +724,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_Unicode(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_Unicode(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;
}
@@ -877,142 +877,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_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 */
- 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_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 */
+ 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 */
};
@@ -1022,206 +1022,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, "s*|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, "s*|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_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 */
- 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_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 */
+ 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 */
};
@@ -1231,317 +1231,317 @@ 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 (!PyString_Check(cres)) {
- PyErr_SetString(PyExc_TypeError,
- "stream function returned a "
- "non-string object");
- goto errorexit;
- }
-
- endoffile = (PyString_GET_SIZE(cres) == 0);
-
- if (self->pendingsize > 0) {
- PyObject *ctr;
- char *ctrdata;
-
- if (PyString_GET_SIZE(cres) > PY_SSIZE_T_MAX - self->pendingsize) {
- PyErr_NoMemory();
- goto errorexit;
- }
- rsize = PyString_GET_SIZE(cres) + self->pendingsize;
- ctr = PyString_FromStringAndSize(NULL, rsize);
- if (ctr == NULL)
- goto errorexit;
- ctrdata = PyString_AS_STRING(ctr);
- memcpy(ctrdata, self->pending, self->pendingsize);
- memcpy(ctrdata + self->pendingsize,
- PyString_AS_STRING(cres),
- PyString_GET_SIZE(cres));
- Py_DECREF(cres);
- cres = ctr;
- self->pendingsize = 0;
- }
-
- rsize = PyString_GET_SIZE(cres);
- if (decoder_prepare_buffer(&buf, PyString_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 (!PyString_Check(cres)) {
+ PyErr_SetString(PyExc_TypeError,
+ "stream function returned a "
+ "non-string object");
+ goto errorexit;
+ }
+
+ endoffile = (PyString_GET_SIZE(cres) == 0);
+
+ if (self->pendingsize > 0) {
+ PyObject *ctr;
+ char *ctrdata;
+
+ if (PyString_GET_SIZE(cres) > PY_SSIZE_T_MAX - self->pendingsize) {
+ PyErr_NoMemory();
+ goto errorexit;
+ }
+ rsize = PyString_GET_SIZE(cres) + self->pendingsize;
+ ctr = PyString_FromStringAndSize(NULL, rsize);
+ if (ctr == NULL)
+ goto errorexit;
+ ctrdata = PyString_AS_STRING(ctr);
+ memcpy(ctrdata, self->pending, self->pendingsize);
+ memcpy(ctrdata + self->pendingsize,
+ PyString_AS_STRING(cres),
+ PyString_GET_SIZE(cres));
+ Py_DECREF(cres);
+ cres = ctr;
+ self->pendingsize = 0;
+ }
+
+ rsize = PyString_GET_SIZE(cres);
+ if (decoder_prepare_buffer(&buf, PyString_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;
-
- if (!PyArg_UnpackTuple(args, "read", 0, 1, &sizeobj))
- return NULL;
-
- if (sizeobj == Py_None || sizeobj == NULL)
- size = -1;
- else if (PyInt_Check(sizeobj))
- size = PyInt_AsSsize_t(sizeobj);
- else {
- PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
- return NULL;
- }
-
- return mbstreamreader_iread(self, "read", size);
+ PyObject *sizeobj = NULL;
+ Py_ssize_t size;
+
+ if (!PyArg_UnpackTuple(args, "read", 0, 1, &sizeobj))
+ return NULL;
+
+ if (sizeobj == Py_None || sizeobj == NULL)
+ size = -1;
+ else if (PyInt_Check(sizeobj))
+ size = PyInt_AsSsize_t(sizeobj);
+ else {
+ PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
+ return NULL;
+ }
+
+ return mbstreamreader_iread(self, "read", size);
}
static PyObject *
mbstreamreader_readline(MultibyteStreamReaderObject *self, PyObject *args)
{
- PyObject *sizeobj = NULL;
- Py_ssize_t size;
-
- if (!PyArg_UnpackTuple(args, "readline", 0, 1, &sizeobj))
- return NULL;
-
- if (sizeobj == Py_None || sizeobj == NULL)
- size = -1;
- else if (PyInt_Check(sizeobj))
- size = PyInt_AsSsize_t(sizeobj);
- else {
- PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
- return NULL;
- }
-
- return mbstreamreader_iread(self, "readline", size);
+ PyObject *sizeobj = NULL;
+ Py_ssize_t size;
+
+ if (!PyArg_UnpackTuple(args, "readline", 0, 1, &sizeobj))
+ return NULL;
+
+ if (sizeobj == Py_None || sizeobj == NULL)
+ size = -1;
+ else if (PyInt_Check(sizeobj))
+ size = PyInt_AsSsize_t(sizeobj);
+ else {
+ PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
+ return NULL;
+ }
+
+ 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 (PyInt_Check(sizehintobj))
- sizehint = PyInt_AsSsize_t(sizehintobj);
- else {
- PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
- 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 (PyInt_Check(sizehintobj))
+ sizehint = PyInt_AsSsize_t(sizehintobj);
+ else {
+ PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
+ 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_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 */
- 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_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 */
+ 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 */
};
@@ -1551,216 +1551,216 @@ 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;
-
- if (PyString_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;
+
+ if (PyString_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_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 */
- 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_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 */
+ 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 */
};
@@ -1771,59 +1771,59 @@ static PyTypeObject MultibyteStreamWriter_Type = {
static PyObject *
__create_codec(PyObject *ignore, PyObject *arg)
{
- MultibyteCodecObject *self;
- MultibyteCodec *codec;
+ MultibyteCodecObject *self;
+ MultibyteCodec *codec;
- if (!PyCObject_Check(arg)) {
- PyErr_SetString(PyExc_ValueError, "argument type invalid");
- return NULL;
- }
+ if (!PyCObject_Check(arg)) {
+ PyErr_SetString(PyExc_ValueError, "argument type invalid");
+ return NULL;
+ }
- codec = PyCObject_AsVoidPtr(arg);
- if (codec->codecinit != NULL && codec->codecinit(codec->config) != 0)
- return NULL;
+ codec = PyCObject_AsVoidPtr(arg);
+ 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},
};
PyMODINIT_FUNC
init_multibytecodec(void)
{
- int i;
- PyObject *m;
- PyTypeObject *typelist[] = {
- &MultibyteIncrementalEncoder_Type,
- &MultibyteIncrementalDecoder_Type,
- &MultibyteStreamReader_Type,
- &MultibyteStreamWriter_Type,
- NULL
- };
-
- if (PyType_Ready(&MultibyteCodec_Type) < 0)
- return;
-
- m = Py_InitModule("_multibytecodec", __methods);
- if (m == NULL)
- return;
-
- for (i = 0; typelist[i] != NULL; i++) {
- if (PyType_Ready(typelist[i]) < 0)
- return;
- 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");
+ int i;
+ PyObject *m;
+ PyTypeObject *typelist[] = {
+ &MultibyteIncrementalEncoder_Type,
+ &MultibyteIncrementalDecoder_Type,
+ &MultibyteStreamReader_Type,
+ &MultibyteStreamWriter_Type,
+ NULL
+ };
+
+ if (PyType_Ready(&MultibyteCodec_Type) < 0)
+ return;
+
+ m = Py_InitModule("_multibytecodec", __methods);
+ if (m == NULL)
+ return;
+
+ for (i = 0; typelist[i] != NULL; i++) {
+ if (PyType_Ready(typelist[i]) < 0)
+ return;
+ 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");
}
diff --git a/Modules/cjkcodecs/multibytecodec.h b/Modules/cjkcodecs/multibytecodec.h
index 22ea5d4..f20c07d 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
#ifdef __cplusplus
}
diff --git a/Modules/clmodule.c b/Modules/clmodule.c
index d3e0edf..e5d568f 100644
--- a/Modules/clmodule.c
+++ b/Modules/clmodule.c
@@ -12,14 +12,14 @@
#include "Python.h"
typedef struct {
- PyObject_HEAD
- int ob_isCompressor; /* Compressor or Decompressor */
- CL_Handle ob_compressorHdl;
- int *ob_paramtypes;
- int ob_nparams;
+ PyObject_HEAD
+ int ob_isCompressor; /* Compressor or Decompressor */
+ CL_Handle ob_compressorHdl;
+ int *ob_paramtypes;
+ int ob_nparams;
} clobject;
-static PyObject *ClError; /* exception cl.error */
+static PyObject *ClError; /* exception cl.error */
static int error_handler_called = 0;
@@ -30,28 +30,28 @@ static int error_handler_called = 0;
* even though they are really "clobject *". Therefore we cast the
* argument to the proper type using this macro.
*/
-#define SELF ((clobject *) self)
+#define SELF ((clobject *) self)
/********************************************************************
- Utility routines.
+ Utility routines.
********************************************************************/
static void
cl_ErrorHandler(CL_Handle handle, int code, const char *fmt, ...)
{
- va_list ap;
- char errbuf[BUFSIZ]; /* hopefully big enough */
- char *p;
-
- if (PyErr_Occurred()) /* don't change existing error */
- return;
- error_handler_called = 1;
- va_start(ap, fmt);
- vsprintf(errbuf, fmt, ap);
- va_end(ap);
- p = &errbuf[strlen(errbuf) - 1]; /* swat the line feed */
- if (*p == '\n')
- *p = 0;
- PyErr_SetString(ClError, errbuf);
+ va_list ap;
+ char errbuf[BUFSIZ]; /* hopefully big enough */
+ char *p;
+
+ if (PyErr_Occurred()) /* don't change existing error */
+ return;
+ error_handler_called = 1;
+ va_start(ap, fmt);
+ vsprintf(errbuf, fmt, ap);
+ va_end(ap);
+ p = &errbuf[strlen(errbuf) - 1]; /* swat the line feed */
+ if (*p == '\n')
+ *p = 0;
+ PyErr_SetString(ClError, errbuf);
}
/*
@@ -60,839 +60,839 @@ cl_ErrorHandler(CL_Handle handle, int code, const char *fmt, ...)
static int
param_type_is_float(clobject *self, int param)
{
- int bufferlength;
-
- if (self->ob_paramtypes == NULL) {
- error_handler_called = 0;
- bufferlength = clQueryParams(self->ob_compressorHdl, 0, 0);
- if (error_handler_called)
- return -1;
-
- self->ob_paramtypes = PyMem_NEW(int, bufferlength);
- if (self->ob_paramtypes == NULL)
- return -1;
- self->ob_nparams = bufferlength / 2;
-
- (void) clQueryParams(self->ob_compressorHdl,
- self->ob_paramtypes, bufferlength);
- if (error_handler_called) {
- PyMem_DEL(self->ob_paramtypes);
- self->ob_paramtypes = NULL;
- return -1;
- }
- }
-
- if (param < 0 || param >= self->ob_nparams)
- return -1;
-
- if (self->ob_paramtypes[param*2 + 1] == CL_FLOATING_ENUM_VALUE ||
- self->ob_paramtypes[param*2 + 1] == CL_FLOATING_RANGE_VALUE)
- return 1;
- else
- return 0;
+ int bufferlength;
+
+ if (self->ob_paramtypes == NULL) {
+ error_handler_called = 0;
+ bufferlength = clQueryParams(self->ob_compressorHdl, 0, 0);
+ if (error_handler_called)
+ return -1;
+
+ self->ob_paramtypes = PyMem_NEW(int, bufferlength);
+ if (self->ob_paramtypes == NULL)
+ return -1;
+ self->ob_nparams = bufferlength / 2;
+
+ (void) clQueryParams(self->ob_compressorHdl,
+ self->ob_paramtypes, bufferlength);
+ if (error_handler_called) {
+ PyMem_DEL(self->ob_paramtypes);
+ self->ob_paramtypes = NULL;
+ return -1;
+ }
+ }
+
+ if (param < 0 || param >= self->ob_nparams)
+ return -1;
+
+ if (self->ob_paramtypes[param*2 + 1] == CL_FLOATING_ENUM_VALUE ||
+ self->ob_paramtypes[param*2 + 1] == CL_FLOATING_RANGE_VALUE)
+ return 1;
+ else
+ return 0;
}
/********************************************************************
- Single image compression/decompression.
+ Single image compression/decompression.
********************************************************************/
static PyObject *
cl_CompressImage(PyObject *self, PyObject *args)
{
- int compressionScheme, width, height, originalFormat;
- float compressionRatio;
- int frameBufferSize, compressedBufferSize;
- char *frameBuffer;
- PyObject *compressedBuffer;
-
- if (!PyArg_ParseTuple(args, "iiiifs#", &compressionScheme,
- &width, &height,
- &originalFormat, &compressionRatio, &frameBuffer,
- &frameBufferSize))
- return NULL;
+ int compressionScheme, width, height, originalFormat;
+ float compressionRatio;
+ int frameBufferSize, compressedBufferSize;
+ char *frameBuffer;
+ PyObject *compressedBuffer;
+
+ if (!PyArg_ParseTuple(args, "iiiifs#", &compressionScheme,
+ &width, &height,
+ &originalFormat, &compressionRatio, &frameBuffer,
+ &frameBufferSize))
+ return NULL;
retry:
- compressedBuffer = PyString_FromStringAndSize(NULL, frameBufferSize);
- if (compressedBuffer == NULL)
- return NULL;
-
- compressedBufferSize = frameBufferSize;
- error_handler_called = 0;
- if (clCompressImage(compressionScheme, width, height, originalFormat,
- compressionRatio, (void *) frameBuffer,
- &compressedBufferSize,
- (void *) PyString_AsString(compressedBuffer))
- == FAILURE || error_handler_called) {
- Py_DECREF(compressedBuffer);
- if (!error_handler_called)
- PyErr_SetString(ClError, "clCompressImage failed");
- return NULL;
- }
-
- if (compressedBufferSize > frameBufferSize) {
- frameBufferSize = compressedBufferSize;
- Py_DECREF(compressedBuffer);
- goto retry;
- }
-
- if (compressedBufferSize < frameBufferSize)
- _PyString_Resize(&compressedBuffer, compressedBufferSize);
-
- return compressedBuffer;
+ compressedBuffer = PyString_FromStringAndSize(NULL, frameBufferSize);
+ if (compressedBuffer == NULL)
+ return NULL;
+
+ compressedBufferSize = frameBufferSize;
+ error_handler_called = 0;
+ if (clCompressImage(compressionScheme, width, height, originalFormat,
+ compressionRatio, (void *) frameBuffer,
+ &compressedBufferSize,
+ (void *) PyString_AsString(compressedBuffer))
+ == FAILURE || error_handler_called) {
+ Py_DECREF(compressedBuffer);
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "clCompressImage failed");
+ return NULL;
+ }
+
+ if (compressedBufferSize > frameBufferSize) {
+ frameBufferSize = compressedBufferSize;
+ Py_DECREF(compressedBuffer);
+ goto retry;
+ }
+
+ if (compressedBufferSize < frameBufferSize)
+ _PyString_Resize(&compressedBuffer, compressedBufferSize);
+
+ return compressedBuffer;
}
static PyObject *
cl_DecompressImage(PyObject *self, PyObject *args)
{
- int compressionScheme, width, height, originalFormat;
- char *compressedBuffer;
- int compressedBufferSize, frameBufferSize;
- PyObject *frameBuffer;
-
- if (!PyArg_ParseTuple(args, "iiiis#", &compressionScheme, &width, &height,
- &originalFormat, &compressedBuffer,
- &compressedBufferSize))
- return NULL;
-
- frameBufferSize = width * height * CL_BytesPerPixel(originalFormat);
-
- frameBuffer = PyString_FromStringAndSize(NULL, frameBufferSize);
- if (frameBuffer == NULL)
- return NULL;
-
- error_handler_called = 0;
- if (clDecompressImage(compressionScheme, width, height, originalFormat,
- compressedBufferSize, compressedBuffer,
- (void *) PyString_AsString(frameBuffer))
- == FAILURE || error_handler_called) {
- Py_DECREF(frameBuffer);
- if (!error_handler_called)
- PyErr_SetString(ClError, "clDecompressImage failed");
- return NULL;
- }
-
- return frameBuffer;
+ int compressionScheme, width, height, originalFormat;
+ char *compressedBuffer;
+ int compressedBufferSize, frameBufferSize;
+ PyObject *frameBuffer;
+
+ if (!PyArg_ParseTuple(args, "iiiis#", &compressionScheme, &width, &height,
+ &originalFormat, &compressedBuffer,
+ &compressedBufferSize))
+ return NULL;
+
+ frameBufferSize = width * height * CL_BytesPerPixel(originalFormat);
+
+ frameBuffer = PyString_FromStringAndSize(NULL, frameBufferSize);
+ if (frameBuffer == NULL)
+ return NULL;
+
+ error_handler_called = 0;
+ if (clDecompressImage(compressionScheme, width, height, originalFormat,
+ compressedBufferSize, compressedBuffer,
+ (void *) PyString_AsString(frameBuffer))
+ == FAILURE || error_handler_called) {
+ Py_DECREF(frameBuffer);
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "clDecompressImage failed");
+ return NULL;
+ }
+
+ return frameBuffer;
}
/********************************************************************
- Sequential compression/decompression.
+ Sequential compression/decompression.
********************************************************************/
-#define CheckCompressor(self) if ((self)->ob_compressorHdl == NULL) { \
- PyErr_SetString(PyExc_RuntimeError, "(de)compressor not active"); \
- return NULL; \
+#define CheckCompressor(self) if ((self)->ob_compressorHdl == NULL) { \
+ PyErr_SetString(PyExc_RuntimeError, "(de)compressor not active"); \
+ return NULL; \
}
static PyObject *
doClose(clobject *self, int (*close_func)(CL_Handle))
{
- CheckCompressor(self);
+ CheckCompressor(self);
- error_handler_called = 0;
- if ((*close_func)(self->ob_compressorHdl) == FAILURE ||
- error_handler_called) {
- if (!error_handler_called)
- PyErr_SetString(ClError, "close failed");
- return NULL;
- }
+ error_handler_called = 0;
+ if ((*close_func)(self->ob_compressorHdl) == FAILURE ||
+ error_handler_called) {
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "close failed");
+ return NULL;
+ }
- self->ob_compressorHdl = NULL;
+ self->ob_compressorHdl = NULL;
- if (self->ob_paramtypes)
- PyMem_DEL(self->ob_paramtypes);
- self->ob_paramtypes = NULL;
+ if (self->ob_paramtypes)
+ PyMem_DEL(self->ob_paramtypes);
+ self->ob_paramtypes = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
clm_CloseCompressor(PyObject *self)
{
- return doClose(SELF, clCloseCompressor);
+ return doClose(SELF, clCloseCompressor);
}
static PyObject *
clm_CloseDecompressor(PyObject *self)
{
- return doClose(SELF, clCloseDecompressor);
+ return doClose(SELF, clCloseDecompressor);
}
static PyObject *
clm_Compress(PyObject *self, PyObject *args)
{
- int numberOfFrames;
- int frameBufferSize, compressedBufferSize, size;
- char *frameBuffer;
- PyObject *data;
-
- CheckCompressor(SELF);
-
- if (!PyArg_Parse(args, "(is#)", &numberOfFrames,
- &frameBuffer, &frameBufferSize))
- return NULL;
-
- error_handler_called = 0;
- size = clGetParam(SELF->ob_compressorHdl, CL_COMPRESSED_BUFFER_SIZE);
- compressedBufferSize = size;
- if (error_handler_called)
- return NULL;
-
- data = PyString_FromStringAndSize(NULL, size);
- if (data == NULL)
- return NULL;
-
- error_handler_called = 0;
- if (clCompress(SELF->ob_compressorHdl, numberOfFrames,
- (void *) frameBuffer, &compressedBufferSize,
- (void *) PyString_AsString(data)) == FAILURE ||
- error_handler_called) {
- Py_DECREF(data);
- if (!error_handler_called)
- PyErr_SetString(ClError, "compress failed");
- return NULL;
- }
-
- if (compressedBufferSize < size)
- if (_PyString_Resize(&data, compressedBufferSize))
- return NULL;
-
- if (compressedBufferSize > size) {
- /* we didn't get all "compressed" data */
- Py_DECREF(data);
- PyErr_SetString(ClError,
- "compressed data is more than fitted");
- return NULL;
- }
-
- return data;
+ int numberOfFrames;
+ int frameBufferSize, compressedBufferSize, size;
+ char *frameBuffer;
+ PyObject *data;
+
+ CheckCompressor(SELF);
+
+ if (!PyArg_Parse(args, "(is#)", &numberOfFrames,
+ &frameBuffer, &frameBufferSize))
+ return NULL;
+
+ error_handler_called = 0;
+ size = clGetParam(SELF->ob_compressorHdl, CL_COMPRESSED_BUFFER_SIZE);
+ compressedBufferSize = size;
+ if (error_handler_called)
+ return NULL;
+
+ data = PyString_FromStringAndSize(NULL, size);
+ if (data == NULL)
+ return NULL;
+
+ error_handler_called = 0;
+ if (clCompress(SELF->ob_compressorHdl, numberOfFrames,
+ (void *) frameBuffer, &compressedBufferSize,
+ (void *) PyString_AsString(data)) == FAILURE ||
+ error_handler_called) {
+ Py_DECREF(data);
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "compress failed");
+ return NULL;
+ }
+
+ if (compressedBufferSize < size)
+ if (_PyString_Resize(&data, compressedBufferSize))
+ return NULL;
+
+ if (compressedBufferSize > size) {
+ /* we didn't get all "compressed" data */
+ Py_DECREF(data);
+ PyErr_SetString(ClError,
+ "compressed data is more than fitted");
+ return NULL;
+ }
+
+ return data;
}
static PyObject *
clm_Decompress(PyObject *self, PyObject *args)
{
- PyObject *data;
- int numberOfFrames;
- char *compressedData;
- int compressedDataSize, dataSize;
-
- CheckCompressor(SELF);
-
- if (!PyArg_Parse(args, "(is#)", &numberOfFrames, &compressedData,
- &compressedDataSize))
- return NULL;
-
- error_handler_called = 0;
- dataSize = clGetParam(SELF->ob_compressorHdl, CL_FRAME_BUFFER_SIZE);
- if (error_handler_called)
- return NULL;
-
- data = PyString_FromStringAndSize(NULL, dataSize);
- if (data == NULL)
- return NULL;
-
- error_handler_called = 0;
- if (clDecompress(SELF->ob_compressorHdl, numberOfFrames,
- compressedDataSize, (void *) compressedData,
- (void *) PyString_AsString(data)) == FAILURE ||
- error_handler_called) {
- Py_DECREF(data);
- if (!error_handler_called)
- PyErr_SetString(ClError, "decompress failed");
- return NULL;
- }
-
- return data;
+ PyObject *data;
+ int numberOfFrames;
+ char *compressedData;
+ int compressedDataSize, dataSize;
+
+ CheckCompressor(SELF);
+
+ if (!PyArg_Parse(args, "(is#)", &numberOfFrames, &compressedData,
+ &compressedDataSize))
+ return NULL;
+
+ error_handler_called = 0;
+ dataSize = clGetParam(SELF->ob_compressorHdl, CL_FRAME_BUFFER_SIZE);
+ if (error_handler_called)
+ return NULL;
+
+ data = PyString_FromStringAndSize(NULL, dataSize);
+ if (data == NULL)
+ return NULL;
+
+ error_handler_called = 0;
+ if (clDecompress(SELF->ob_compressorHdl, numberOfFrames,
+ compressedDataSize, (void *) compressedData,
+ (void *) PyString_AsString(data)) == FAILURE ||
+ error_handler_called) {
+ Py_DECREF(data);
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "decompress failed");
+ return NULL;
+ }
+
+ return data;
}
static PyObject *
doParams(clobject *self, PyObject *args, int (*func)(CL_Handle, int *, int),
- int modified)
+ int modified)
{
- PyObject *list, *v;
- int *PVbuffer;
- int length;
- int i;
- float number;
-
- CheckCompressor(self);
-
- if (!PyArg_Parse(args, "O", &list))
- return NULL;
- if (!PyList_Check(list)) {
- PyErr_BadArgument();
- return NULL;
- }
- length = PyList_Size(list);
- PVbuffer = PyMem_NEW(int, length);
- if (PVbuffer == NULL)
- return PyErr_NoMemory();
- for (i = 0; i < length; i++) {
- v = PyList_GetItem(list, i);
- if (PyFloat_Check(v)) {
- number = PyFloat_AsDouble(v);
- PVbuffer[i] = CL_TypeIsInt(number);
- } else if (PyInt_Check(v)) {
- PVbuffer[i] = PyInt_AsLong(v);
- if ((i & 1) &&
- param_type_is_float(self, PVbuffer[i-1]) > 0) {
- number = PVbuffer[i];
- PVbuffer[i] = CL_TypeIsInt(number);
- }
- } else {
- PyMem_DEL(PVbuffer);
- PyErr_BadArgument();
- return NULL;
- }
- }
-
- error_handler_called = 0;
- (*func)(self->ob_compressorHdl, PVbuffer, length);
- if (error_handler_called) {
- PyMem_DEL(PVbuffer);
- return NULL;
- }
-
- if (modified) {
- for (i = 0; i < length; i++) {
- if ((i & 1) &&
- param_type_is_float(self, PVbuffer[i-1]) > 0) {
- number = CL_TypeIsFloat(PVbuffer[i]);
- v = PyFloat_FromDouble(number);
- } else
- v = PyInt_FromLong(PVbuffer[i]);
- PyList_SetItem(list, i, v);
- }
- }
-
- PyMem_DEL(PVbuffer);
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *list, *v;
+ int *PVbuffer;
+ int length;
+ int i;
+ float number;
+
+ CheckCompressor(self);
+
+ if (!PyArg_Parse(args, "O", &list))
+ return NULL;
+ if (!PyList_Check(list)) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ length = PyList_Size(list);
+ PVbuffer = PyMem_NEW(int, length);
+ if (PVbuffer == NULL)
+ return PyErr_NoMemory();
+ for (i = 0; i < length; i++) {
+ v = PyList_GetItem(list, i);
+ if (PyFloat_Check(v)) {
+ number = PyFloat_AsDouble(v);
+ PVbuffer[i] = CL_TypeIsInt(number);
+ } else if (PyInt_Check(v)) {
+ PVbuffer[i] = PyInt_AsLong(v);
+ if ((i & 1) &&
+ param_type_is_float(self, PVbuffer[i-1]) > 0) {
+ number = PVbuffer[i];
+ PVbuffer[i] = CL_TypeIsInt(number);
+ }
+ } else {
+ PyMem_DEL(PVbuffer);
+ PyErr_BadArgument();
+ return NULL;
+ }
+ }
+
+ error_handler_called = 0;
+ (*func)(self->ob_compressorHdl, PVbuffer, length);
+ if (error_handler_called) {
+ PyMem_DEL(PVbuffer);
+ return NULL;
+ }
+
+ if (modified) {
+ for (i = 0; i < length; i++) {
+ if ((i & 1) &&
+ param_type_is_float(self, PVbuffer[i-1]) > 0) {
+ number = CL_TypeIsFloat(PVbuffer[i]);
+ v = PyFloat_FromDouble(number);
+ } else
+ v = PyInt_FromLong(PVbuffer[i]);
+ PyList_SetItem(list, i, v);
+ }
+ }
+
+ PyMem_DEL(PVbuffer);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
clm_GetParams(PyObject *self, PyObject *args)
{
- return doParams(SELF, args, clGetParams, 1);
+ return doParams(SELF, args, clGetParams, 1);
}
static PyObject *
clm_SetParams(PyObject *self, PyObject *args)
{
- return doParams(SELF, args, clSetParams, 0);
+ return doParams(SELF, args, clSetParams, 0);
}
static PyObject *
do_get(clobject *self, PyObject *args, int (*func)(CL_Handle, int))
{
- int paramID, value;
- float fvalue;
+ int paramID, value;
+ float fvalue;
- CheckCompressor(self);
+ CheckCompressor(self);
- if (!PyArg_Parse(args, "i", &paramID))
- return NULL;
+ if (!PyArg_Parse(args, "i", &paramID))
+ return NULL;
- error_handler_called = 0;
- value = (*func)(self->ob_compressorHdl, paramID);
- if (error_handler_called)
- return NULL;
+ error_handler_called = 0;
+ value = (*func)(self->ob_compressorHdl, paramID);
+ if (error_handler_called)
+ return NULL;
- if (param_type_is_float(self, paramID) > 0) {
- fvalue = CL_TypeIsFloat(value);
- return PyFloat_FromDouble(fvalue);
- }
+ if (param_type_is_float(self, paramID) > 0) {
+ fvalue = CL_TypeIsFloat(value);
+ return PyFloat_FromDouble(fvalue);
+ }
- return PyInt_FromLong(value);
+ return PyInt_FromLong(value);
}
static PyObject *
clm_GetParam(PyObject *self, PyObject *args)
{
- return do_get(SELF, args, clGetParam);
+ return do_get(SELF, args, clGetParam);
}
static PyObject *
clm_GetDefault(PyObject *self, PyObject *args)
{
- return do_get(SELF, args, clGetDefault);
+ return do_get(SELF, args, clGetDefault);
}
static PyObject *
clm_SetParam(PyObject *self, PyObject *args)
{
- int paramID, value;
- float fvalue;
-
- CheckCompressor(SELF);
-
- if (!PyArg_Parse(args, "(ii)", &paramID, &value)) {
- PyErr_Clear();
- if (!PyArg_Parse(args, "(if)", &paramID, &fvalue)) {
- PyErr_Clear();
- PyErr_SetString(PyExc_TypeError,
- "bad argument list (format '(ii)' or '(if)')");
- return NULL;
- }
- value = CL_TypeIsInt(fvalue);
- } else {
- if (param_type_is_float(SELF, paramID) > 0) {
- fvalue = value;
- value = CL_TypeIsInt(fvalue);
- }
- }
-
- error_handler_called = 0;
- value = clSetParam(SELF->ob_compressorHdl, paramID, value);
- if (error_handler_called)
- return NULL;
-
- if (param_type_is_float(SELF, paramID) > 0)
- return PyFloat_FromDouble(CL_TypeIsFloat(value));
- else
- return PyInt_FromLong(value);
+ int paramID, value;
+ float fvalue;
+
+ CheckCompressor(SELF);
+
+ if (!PyArg_Parse(args, "(ii)", &paramID, &value)) {
+ PyErr_Clear();
+ if (!PyArg_Parse(args, "(if)", &paramID, &fvalue)) {
+ PyErr_Clear();
+ PyErr_SetString(PyExc_TypeError,
+ "bad argument list (format '(ii)' or '(if)')");
+ return NULL;
+ }
+ value = CL_TypeIsInt(fvalue);
+ } else {
+ if (param_type_is_float(SELF, paramID) > 0) {
+ fvalue = value;
+ value = CL_TypeIsInt(fvalue);
+ }
+ }
+
+ error_handler_called = 0;
+ value = clSetParam(SELF->ob_compressorHdl, paramID, value);
+ if (error_handler_called)
+ return NULL;
+
+ if (param_type_is_float(SELF, paramID) > 0)
+ return PyFloat_FromDouble(CL_TypeIsFloat(value));
+ else
+ return PyInt_FromLong(value);
}
static PyObject *
clm_GetParamID(PyObject *self, PyObject *args)
{
- char *name;
- int value;
+ char *name;
+ int value;
- CheckCompressor(SELF);
+ CheckCompressor(SELF);
- if (!PyArg_Parse(args, "s", &name))
- return NULL;
+ if (!PyArg_Parse(args, "s", &name))
+ return NULL;
- error_handler_called = 0;
- value = clGetParamID(SELF->ob_compressorHdl, name);
- if (value == FAILURE || error_handler_called) {
- if (!error_handler_called)
- PyErr_SetString(ClError, "getparamid failed");
- return NULL;
- }
+ error_handler_called = 0;
+ value = clGetParamID(SELF->ob_compressorHdl, name);
+ if (value == FAILURE || error_handler_called) {
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "getparamid failed");
+ return NULL;
+ }
- return PyInt_FromLong(value);
+ return PyInt_FromLong(value);
}
static PyObject *
clm_QueryParams(PyObject *self)
{
- int bufferlength;
- int *PVbuffer;
- PyObject *list;
- int i;
-
- CheckCompressor(SELF);
-
- error_handler_called = 0;
- bufferlength = clQueryParams(SELF->ob_compressorHdl, 0, 0);
- if (error_handler_called)
- return NULL;
-
- PVbuffer = PyMem_NEW(int, bufferlength);
- if (PVbuffer == NULL)
- return PyErr_NoMemory();
-
- bufferlength = clQueryParams(SELF->ob_compressorHdl, PVbuffer,
- bufferlength);
- if (error_handler_called) {
- PyMem_DEL(PVbuffer);
- return NULL;
- }
-
- list = PyList_New(bufferlength);
- if (list == NULL) {
- PyMem_DEL(PVbuffer);
- return NULL;
- }
-
- for (i = 0; i < bufferlength; i++) {
- if (i & 1)
- PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
- else if (PVbuffer[i] == 0) {
- Py_INCREF(Py_None);
- PyList_SetItem(list, i, Py_None);
- } else
- PyList_SetItem(list, i,
- PyString_FromString((char *) PVbuffer[i]));
- }
-
- PyMem_DEL(PVbuffer);
-
- return list;
+ int bufferlength;
+ int *PVbuffer;
+ PyObject *list;
+ int i;
+
+ CheckCompressor(SELF);
+
+ error_handler_called = 0;
+ bufferlength = clQueryParams(SELF->ob_compressorHdl, 0, 0);
+ if (error_handler_called)
+ return NULL;
+
+ PVbuffer = PyMem_NEW(int, bufferlength);
+ if (PVbuffer == NULL)
+ return PyErr_NoMemory();
+
+ bufferlength = clQueryParams(SELF->ob_compressorHdl, PVbuffer,
+ bufferlength);
+ if (error_handler_called) {
+ PyMem_DEL(PVbuffer);
+ return NULL;
+ }
+
+ list = PyList_New(bufferlength);
+ if (list == NULL) {
+ PyMem_DEL(PVbuffer);
+ return NULL;
+ }
+
+ for (i = 0; i < bufferlength; i++) {
+ if (i & 1)
+ PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
+ else if (PVbuffer[i] == 0) {
+ Py_INCREF(Py_None);
+ PyList_SetItem(list, i, Py_None);
+ } else
+ PyList_SetItem(list, i,
+ PyString_FromString((char *) PVbuffer[i]));
+ }
+
+ PyMem_DEL(PVbuffer);
+
+ return list;
}
static PyObject *
clm_GetMinMax(PyObject *self, PyObject *args)
{
- int param, min, max;
- float fmin, fmax;
+ int param, min, max;
+ float fmin, fmax;
- CheckCompressor(SELF);
+ CheckCompressor(SELF);
- if (!PyArg_Parse(args, "i", &param))
- return NULL;
+ if (!PyArg_Parse(args, "i", &param))
+ return NULL;
- clGetMinMax(SELF->ob_compressorHdl, param, &min, &max);
+ clGetMinMax(SELF->ob_compressorHdl, param, &min, &max);
- if (param_type_is_float(SELF, param) > 0) {
- fmin = CL_TypeIsFloat(min);
- fmax = CL_TypeIsFloat(max);
- return Py_BuildValue("(ff)", fmin, fmax);
- }
+ if (param_type_is_float(SELF, param) > 0) {
+ fmin = CL_TypeIsFloat(min);
+ fmax = CL_TypeIsFloat(max);
+ return Py_BuildValue("(ff)", fmin, fmax);
+ }
- return Py_BuildValue("(ii)", min, max);
+ return Py_BuildValue("(ii)", min, max);
}
static PyObject *
clm_GetName(PyObject *self, PyObject *args)
{
- int param;
- char *name;
+ int param;
+ char *name;
- CheckCompressor(SELF);
+ CheckCompressor(SELF);
- if (!PyArg_Parse(args, "i", &param))
- return NULL;
+ if (!PyArg_Parse(args, "i", &param))
+ return NULL;
- error_handler_called = 0;
- name = clGetName(SELF->ob_compressorHdl, param);
- if (name == NULL || error_handler_called) {
- if (!error_handler_called)
- PyErr_SetString(ClError, "getname failed");
- return NULL;
- }
+ error_handler_called = 0;
+ name = clGetName(SELF->ob_compressorHdl, param);
+ if (name == NULL || error_handler_called) {
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "getname failed");
+ return NULL;
+ }
- return PyString_FromString(name);
+ return PyString_FromString(name);
}
static PyObject *
clm_QuerySchemeFromHandle(PyObject *self)
{
- CheckCompressor(SELF);
- return PyInt_FromLong(clQuerySchemeFromHandle(SELF->ob_compressorHdl));
+ CheckCompressor(SELF);
+ return PyInt_FromLong(clQuerySchemeFromHandle(SELF->ob_compressorHdl));
}
static PyObject *
clm_ReadHeader(PyObject *self, PyObject *args)
{
- char *header;
- int headerSize;
+ char *header;
+ int headerSize;
- CheckCompressor(SELF);
+ CheckCompressor(SELF);
- if (!PyArg_Parse(args, "s#", &header, &headerSize))
- return NULL;
+ if (!PyArg_Parse(args, "s#", &header, &headerSize))
+ return NULL;
- return PyInt_FromLong(clReadHeader(SELF->ob_compressorHdl,
- headerSize, header));
+ return PyInt_FromLong(clReadHeader(SELF->ob_compressorHdl,
+ headerSize, header));
}
static PyMethodDef compressor_methods[] = {
- {"close", clm_CloseCompressor, METH_NOARGS}, /* alias */
- {"CloseCompressor", clm_CloseCompressor, METH_NOARGS},
- {"Compress", clm_Compress, METH_OLDARGS},
- {"GetDefault", clm_GetDefault, METH_OLDARGS},
- {"GetMinMax", clm_GetMinMax, METH_OLDARGS},
- {"GetName", clm_GetName, METH_OLDARGS},
- {"GetParam", clm_GetParam, METH_OLDARGS},
- {"GetParamID", clm_GetParamID, METH_OLDARGS},
- {"GetParams", clm_GetParams, METH_OLDARGS},
- {"QueryParams", clm_QueryParams, METH_NOARGS},
- {"QuerySchemeFromHandle",clm_QuerySchemeFromHandle, METH_NOARGS},
- {"SetParam", clm_SetParam, METH_OLDARGS},
- {"SetParams", clm_SetParams, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"close", clm_CloseCompressor, METH_NOARGS}, /* alias */
+ {"CloseCompressor", clm_CloseCompressor, METH_NOARGS},
+ {"Compress", clm_Compress, METH_OLDARGS},
+ {"GetDefault", clm_GetDefault, METH_OLDARGS},
+ {"GetMinMax", clm_GetMinMax, METH_OLDARGS},
+ {"GetName", clm_GetName, METH_OLDARGS},
+ {"GetParam", clm_GetParam, METH_OLDARGS},
+ {"GetParamID", clm_GetParamID, METH_OLDARGS},
+ {"GetParams", clm_GetParams, METH_OLDARGS},
+ {"QueryParams", clm_QueryParams, METH_NOARGS},
+ {"QuerySchemeFromHandle",clm_QuerySchemeFromHandle, METH_NOARGS},
+ {"SetParam", clm_SetParam, METH_OLDARGS},
+ {"SetParams", clm_SetParams, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
static PyMethodDef decompressor_methods[] = {
- {"close", clm_CloseDecompressor, METH_NOARGS}, /* alias */
- {"CloseDecompressor", clm_CloseDecompressor, METH_NOARGS},
- {"Decompress", clm_Decompress, METH_OLDARGS},
- {"GetDefault", clm_GetDefault, METH_OLDARGS},
- {"GetMinMax", clm_GetMinMax, METH_OLDARGS},
- {"GetName", clm_GetName, METH_OLDARGS},
- {"GetParam", clm_GetParam, METH_OLDARGS},
- {"GetParamID", clm_GetParamID, METH_OLDARGS},
- {"GetParams", clm_GetParams, METH_OLDARGS},
- {"ReadHeader", clm_ReadHeader, METH_OLDARGS},
- {"QueryParams", clm_QueryParams, METH_NOARGS},
- {"QuerySchemeFromHandle",clm_QuerySchemeFromHandle, METH_NOARGS},
- {"SetParam", clm_SetParam, METH_OLDARGS},
- {"SetParams", clm_SetParams, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"close", clm_CloseDecompressor, METH_NOARGS}, /* alias */
+ {"CloseDecompressor", clm_CloseDecompressor, METH_NOARGS},
+ {"Decompress", clm_Decompress, METH_OLDARGS},
+ {"GetDefault", clm_GetDefault, METH_OLDARGS},
+ {"GetMinMax", clm_GetMinMax, METH_OLDARGS},
+ {"GetName", clm_GetName, METH_OLDARGS},
+ {"GetParam", clm_GetParam, METH_OLDARGS},
+ {"GetParamID", clm_GetParamID, METH_OLDARGS},
+ {"GetParams", clm_GetParams, METH_OLDARGS},
+ {"ReadHeader", clm_ReadHeader, METH_OLDARGS},
+ {"QueryParams", clm_QueryParams, METH_NOARGS},
+ {"QuerySchemeFromHandle",clm_QuerySchemeFromHandle, METH_NOARGS},
+ {"SetParam", clm_SetParam, METH_OLDARGS},
+ {"SetParams", clm_SetParams, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
static void
cl_dealloc(PyObject *self)
{
- if (SELF->ob_compressorHdl) {
- if (SELF->ob_isCompressor)
- clCloseCompressor(SELF->ob_compressorHdl);
- else
- clCloseDecompressor(SELF->ob_compressorHdl);
- }
- PyObject_Del(self);
+ if (SELF->ob_compressorHdl) {
+ if (SELF->ob_isCompressor)
+ clCloseCompressor(SELF->ob_compressorHdl);
+ else
+ clCloseDecompressor(SELF->ob_compressorHdl);
+ }
+ PyObject_Del(self);
}
static PyObject *
cl_getattr(PyObject *self, char *name)
{
- if (SELF->ob_isCompressor)
- return Py_FindMethod(compressor_methods, self, name);
- else
- return Py_FindMethod(decompressor_methods, self, name);
+ if (SELF->ob_isCompressor)
+ return Py_FindMethod(compressor_methods, self, name);
+ else
+ return Py_FindMethod(decompressor_methods, self, name);
}
static PyTypeObject Cltype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "cl.cl", /*tp_name*/
- sizeof(clobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)cl_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)cl_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "cl.cl", /*tp_name*/
+ sizeof(clobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)cl_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)cl_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
};
static PyObject *
doOpen(PyObject *self, PyObject *args, int (*open_func)(int, CL_Handle *),
int iscompressor)
{
- int scheme;
- clobject *new;
-
- if (!PyArg_ParseTuple(args, "i", &scheme))
- return NULL;
-
- new = PyObject_New(clobject, &Cltype);
- if (new == NULL)
- return NULL;
-
- new->ob_compressorHdl = NULL;
- new->ob_isCompressor = iscompressor;
- new->ob_paramtypes = NULL;
-
- error_handler_called = 0;
- if ((*open_func)(scheme, &new->ob_compressorHdl) == FAILURE ||
- error_handler_called) {
- Py_DECREF(new);
- if (!error_handler_called)
- PyErr_SetString(ClError, "Open(De)Compressor failed");
- return NULL;
- }
- return (PyObject *)new;
+ int scheme;
+ clobject *new;
+
+ if (!PyArg_ParseTuple(args, "i", &scheme))
+ return NULL;
+
+ new = PyObject_New(clobject, &Cltype);
+ if (new == NULL)
+ return NULL;
+
+ new->ob_compressorHdl = NULL;
+ new->ob_isCompressor = iscompressor;
+ new->ob_paramtypes = NULL;
+
+ error_handler_called = 0;
+ if ((*open_func)(scheme, &new->ob_compressorHdl) == FAILURE ||
+ error_handler_called) {
+ Py_DECREF(new);
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "Open(De)Compressor failed");
+ return NULL;
+ }
+ return (PyObject *)new;
}
static PyObject *
cl_OpenCompressor(PyObject *self, PyObject *args)
{
- return doOpen(self, args, clOpenCompressor, 1);
+ return doOpen(self, args, clOpenCompressor, 1);
}
static PyObject *
cl_OpenDecompressor(PyObject *self, PyObject *args)
{
- return doOpen(self, args, clOpenDecompressor, 0);
+ return doOpen(self, args, clOpenDecompressor, 0);
}
static PyObject *
cl_QueryScheme(PyObject *self, PyObject *args)
{
- char *header;
- int headerlen;
- int scheme;
+ char *header;
+ int headerlen;
+ int scheme;
- if (!PyArg_ParseTuple(args, "s#", &header, &headerlen))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s#", &header, &headerlen))
+ return NULL;
- scheme = clQueryScheme(header);
- if (scheme < 0) {
- PyErr_SetString(ClError, "unknown compression scheme");
- return NULL;
- }
+ scheme = clQueryScheme(header);
+ if (scheme < 0) {
+ PyErr_SetString(ClError, "unknown compression scheme");
+ return NULL;
+ }
- return PyInt_FromLong(scheme);
+ return PyInt_FromLong(scheme);
}
static PyObject *
cl_QueryMaxHeaderSize(PyObject *self, PyObject *args)
{
- int scheme;
+ int scheme;
- if (!PyArg_ParseTuple(args, "i", &scheme))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i", &scheme))
+ return NULL;
- return PyInt_FromLong(clQueryMaxHeaderSize(scheme));
+ return PyInt_FromLong(clQueryMaxHeaderSize(scheme));
}
static PyObject *
cl_QueryAlgorithms(PyObject *self, PyObject *args)
{
- int algorithmMediaType;
- int bufferlength;
- int *PVbuffer;
- PyObject *list;
- int i;
-
- if (!PyArg_ParseTuple(args, "i", &algorithmMediaType))
- return NULL;
-
- error_handler_called = 0;
- bufferlength = clQueryAlgorithms(algorithmMediaType, 0, 0);
- if (error_handler_called)
- return NULL;
-
- PVbuffer = PyMem_NEW(int, bufferlength);
- if (PVbuffer == NULL)
- return PyErr_NoMemory();
-
- bufferlength = clQueryAlgorithms(algorithmMediaType, PVbuffer,
- bufferlength);
- if (error_handler_called) {
- PyMem_DEL(PVbuffer);
- return NULL;
- }
-
- list = PyList_New(bufferlength);
- if (list == NULL) {
- PyMem_DEL(PVbuffer);
- return NULL;
- }
-
- for (i = 0; i < bufferlength; i++) {
- if (i & 1)
- PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
- else if (PVbuffer[i] == 0) {
- Py_INCREF(Py_None);
- PyList_SetItem(list, i, Py_None);
- } else
- PyList_SetItem(list, i,
- PyString_FromString((char *) PVbuffer[i]));
- }
-
- PyMem_DEL(PVbuffer);
-
- return list;
+ int algorithmMediaType;
+ int bufferlength;
+ int *PVbuffer;
+ PyObject *list;
+ int i;
+
+ if (!PyArg_ParseTuple(args, "i", &algorithmMediaType))
+ return NULL;
+
+ error_handler_called = 0;
+ bufferlength = clQueryAlgorithms(algorithmMediaType, 0, 0);
+ if (error_handler_called)
+ return NULL;
+
+ PVbuffer = PyMem_NEW(int, bufferlength);
+ if (PVbuffer == NULL)
+ return PyErr_NoMemory();
+
+ bufferlength = clQueryAlgorithms(algorithmMediaType, PVbuffer,
+ bufferlength);
+ if (error_handler_called) {
+ PyMem_DEL(PVbuffer);
+ return NULL;
+ }
+
+ list = PyList_New(bufferlength);
+ if (list == NULL) {
+ PyMem_DEL(PVbuffer);
+ return NULL;
+ }
+
+ for (i = 0; i < bufferlength; i++) {
+ if (i & 1)
+ PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
+ else if (PVbuffer[i] == 0) {
+ Py_INCREF(Py_None);
+ PyList_SetItem(list, i, Py_None);
+ } else
+ PyList_SetItem(list, i,
+ PyString_FromString((char *) PVbuffer[i]));
+ }
+
+ PyMem_DEL(PVbuffer);
+
+ return list;
}
static PyObject *
cl_QuerySchemeFromName(PyObject *self, PyObject *args)
{
- int algorithmMediaType;
- char *name;
- int scheme;
+ int algorithmMediaType;
+ char *name;
+ int scheme;
- if (!PyArg_ParseTuple(args, "is", &algorithmMediaType, &name))
- return NULL;
+ if (!PyArg_ParseTuple(args, "is", &algorithmMediaType, &name))
+ return NULL;
- error_handler_called = 0;
- scheme = clQuerySchemeFromName(algorithmMediaType, name);
- if (error_handler_called) {
- PyErr_SetString(ClError, "unknown compression scheme");
- return NULL;
- }
+ error_handler_called = 0;
+ scheme = clQuerySchemeFromName(algorithmMediaType, name);
+ if (error_handler_called) {
+ PyErr_SetString(ClError, "unknown compression scheme");
+ return NULL;
+ }
- return PyInt_FromLong(scheme);
+ return PyInt_FromLong(scheme);
}
static PyObject *
cl_GetAlgorithmName(PyObject *self, PyObject *args)
{
- int scheme;
- char *name;
+ int scheme;
+ char *name;
- if (!PyArg_ParseTuple(args, "i", &scheme))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i", &scheme))
+ return NULL;
- name = clGetAlgorithmName(scheme);
- if (name == 0) {
- PyErr_SetString(ClError, "unknown compression scheme");
- return NULL;
- }
+ name = clGetAlgorithmName(scheme);
+ if (name == 0) {
+ PyErr_SetString(ClError, "unknown compression scheme");
+ return NULL;
+ }
- return PyString_FromString(name);
+ return PyString_FromString(name);
}
static PyObject *
do_set(PyObject *self, PyObject *args, int (*func)(int, int, int))
{
- int scheme, paramID, value;
- float fvalue;
- int is_float = 0;
-
- if (!PyArg_ParseTuple(args, "iii", &scheme, &paramID, &value)) {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "iif", &scheme, &paramID, &fvalue)) {
- PyErr_Clear();
- PyErr_SetString(PyExc_TypeError,
- "bad argument list (format '(iii)' or '(iif)')");
- return NULL;
- }
- value = CL_TypeIsInt(fvalue);
- is_float = 1;
- } else {
- /* check some parameters which we know to be floats */
- switch (scheme) {
- case CL_COMPRESSION_RATIO:
- case CL_SPEED:
- fvalue = value;
- value = CL_TypeIsInt(fvalue);
- is_float = 1;
- break;
- }
- }
-
- error_handler_called = 0;
- value = (*func)(scheme, paramID, value);
- if (error_handler_called)
- return NULL;
-
- if (is_float)
- return PyFloat_FromDouble(CL_TypeIsFloat(value));
- else
- return PyInt_FromLong(value);
+ int scheme, paramID, value;
+ float fvalue;
+ int is_float = 0;
+
+ if (!PyArg_ParseTuple(args, "iii", &scheme, &paramID, &value)) {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "iif", &scheme, &paramID, &fvalue)) {
+ PyErr_Clear();
+ PyErr_SetString(PyExc_TypeError,
+ "bad argument list (format '(iii)' or '(iif)')");
+ return NULL;
+ }
+ value = CL_TypeIsInt(fvalue);
+ is_float = 1;
+ } else {
+ /* check some parameters which we know to be floats */
+ switch (scheme) {
+ case CL_COMPRESSION_RATIO:
+ case CL_SPEED:
+ fvalue = value;
+ value = CL_TypeIsInt(fvalue);
+ is_float = 1;
+ break;
+ }
+ }
+
+ error_handler_called = 0;
+ value = (*func)(scheme, paramID, value);
+ if (error_handler_called)
+ return NULL;
+
+ if (is_float)
+ return PyFloat_FromDouble(CL_TypeIsFloat(value));
+ else
+ return PyInt_FromLong(value);
}
static PyObject *
cl_SetDefault(PyObject *self, PyObject *args)
{
- return do_set(self, args, clSetDefault);
+ return do_set(self, args, clSetDefault);
}
static PyObject *
cl_SetMin(PyObject *self, PyObject *args)
{
- return do_set(self, args, clSetMin);
+ return do_set(self, args, clSetMin);
}
static PyObject *
cl_SetMax(PyObject *self, PyObject *args)
{
- return do_set(self, args, clSetMax);
+ return do_set(self, args, clSetMax);
}
-#define func(name, handler) \
+#define func(name, handler) \
static PyObject *cl_##name(PyObject *self, PyObject *args) \
{ \
- int x; \
- if (!PyArg_ParseTuple(args, "i", &x)) return NULL; \
- return Py##handler(CL_##name(x)); \
+ int x; \
+ if (!PyArg_ParseTuple(args, "i", &x)) return NULL; \
+ return Py##handler(CL_##name(x)); \
}
-#define func2(name, handler) \
+#define func2(name, handler) \
static PyObject *cl_##name(PyObject *self, PyObject *args) \
{ \
- int a1, a2; \
- if (!PyArg_ParseTuple(args, "ii", &a1, &a2)) return NULL; \
- return Py##handler(CL_##name(a1, a2)); \
+ int a1, a2; \
+ if (!PyArg_ParseTuple(args, "ii", &a1, &a2)) return NULL; \
+ return Py##handler(CL_##name(a1, a2)); \
}
func(BytesPerSample, Int_FromLong)
@@ -907,50 +907,50 @@ func(ParamType, Int_FromLong)
func2(ParamID, Int_FromLong)
#ifdef CLDEBUG
- static PyObject *
+ static PyObject *
cvt_type(PyObject *self, PyObject *args)
{
- int number;
- float fnumber;
-
- if (PyArg_Parse(args, "i", &number))
- return PyFloat_FromDouble(CL_TypeIsFloat(number));
- else {
- PyErr_Clear();
- if (PyArg_Parse(args, "f", &fnumber))
- return PyInt_FromLong(CL_TypeIsInt(fnumber));
- return NULL;
- }
+ int number;
+ float fnumber;
+
+ if (PyArg_Parse(args, "i", &number))
+ return PyFloat_FromDouble(CL_TypeIsFloat(number));
+ else {
+ PyErr_Clear();
+ if (PyArg_Parse(args, "f", &fnumber))
+ return PyInt_FromLong(CL_TypeIsInt(fnumber));
+ return NULL;
+ }
}
#endif
static PyMethodDef cl_methods[] = {
- {"CompressImage", cl_CompressImage, METH_VARARGS},
- {"DecompressImage", cl_DecompressImage, METH_VARARGS},
- {"GetAlgorithmName", cl_GetAlgorithmName, METH_VARARGS},
- {"OpenCompressor", cl_OpenCompressor, METH_VARARGS},
- {"OpenDecompressor", cl_OpenDecompressor, METH_VARARGS},
- {"QueryAlgorithms", cl_QueryAlgorithms, METH_VARARGS},
- {"QueryMaxHeaderSize", cl_QueryMaxHeaderSize, METH_VARARGS},
- {"QueryScheme", cl_QueryScheme, METH_VARARGS},
- {"QuerySchemeFromName", cl_QuerySchemeFromName, METH_VARARGS},
- {"SetDefault", cl_SetDefault, METH_VARARGS},
- {"SetMax", cl_SetMax, METH_VARARGS},
- {"SetMin", cl_SetMin, METH_VARARGS},
- {"BytesPerSample", cl_BytesPerSample, METH_VARARGS},
- {"BytesPerPixel", cl_BytesPerPixel, METH_VARARGS},
- {"AudioFormatName", cl_AudioFormatName, METH_VARARGS},
- {"VideoFormatName", cl_VideoFormatName, METH_VARARGS},
- {"AlgorithmNumber", cl_AlgorithmNumber, METH_VARARGS},
- {"AlgorithmType", cl_AlgorithmType, METH_VARARGS},
- {"Algorithm", cl_Algorithm, METH_VARARGS},
- {"ParamNumber", cl_ParamNumber, METH_VARARGS},
- {"ParamType", cl_ParamType, METH_VARARGS},
- {"ParamID", cl_ParamID, METH_VARARGS},
+ {"CompressImage", cl_CompressImage, METH_VARARGS},
+ {"DecompressImage", cl_DecompressImage, METH_VARARGS},
+ {"GetAlgorithmName", cl_GetAlgorithmName, METH_VARARGS},
+ {"OpenCompressor", cl_OpenCompressor, METH_VARARGS},
+ {"OpenDecompressor", cl_OpenDecompressor, METH_VARARGS},
+ {"QueryAlgorithms", cl_QueryAlgorithms, METH_VARARGS},
+ {"QueryMaxHeaderSize", cl_QueryMaxHeaderSize, METH_VARARGS},
+ {"QueryScheme", cl_QueryScheme, METH_VARARGS},
+ {"QuerySchemeFromName", cl_QuerySchemeFromName, METH_VARARGS},
+ {"SetDefault", cl_SetDefault, METH_VARARGS},
+ {"SetMax", cl_SetMax, METH_VARARGS},
+ {"SetMin", cl_SetMin, METH_VARARGS},
+ {"BytesPerSample", cl_BytesPerSample, METH_VARARGS},
+ {"BytesPerPixel", cl_BytesPerPixel, METH_VARARGS},
+ {"AudioFormatName", cl_AudioFormatName, METH_VARARGS},
+ {"VideoFormatName", cl_VideoFormatName, METH_VARARGS},
+ {"AlgorithmNumber", cl_AlgorithmNumber, METH_VARARGS},
+ {"AlgorithmType", cl_AlgorithmType, METH_VARARGS},
+ {"Algorithm", cl_Algorithm, METH_VARARGS},
+ {"ParamNumber", cl_ParamNumber, METH_VARARGS},
+ {"ParamType", cl_ParamType, METH_VARARGS},
+ {"ParamID", cl_ParamID, METH_VARARGS},
#ifdef CLDEBUG
- {"cvt_type", cvt_type, METH_VARARGS},
+ {"cvt_type", cvt_type, METH_VARARGS},
#endif
- {NULL, NULL} /* Sentinel */
+ {NULL, NULL} /* Sentinel */
};
#ifdef CL_JPEG_SOFTWARE
@@ -960,1604 +960,1604 @@ static PyMethodDef cl_methods[] = {
void
initcl(void)
{
- PyObject *m, *d, *x;
-
+ PyObject *m, *d, *x;
+
if (PyErr_WarnPy3k("the cl module has been removed in "
"Python 3.0", 2) < 0)
+ return;
+
+ m = Py_InitModule("cl", cl_methods);
+ if (m == NULL)
return;
-
- m = Py_InitModule("cl", cl_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
+ d = PyModule_GetDict(m);
- ClError = PyErr_NewException("cl.error", NULL, NULL);
- (void) PyDict_SetItemString(d, "error", ClError);
+ ClError = PyErr_NewException("cl.error", NULL, NULL);
+ (void) PyDict_SetItemString(d, "error", ClError);
#ifdef CL_ADDED_ALGORITHM_ERROR
- x = PyInt_FromLong(CL_ADDED_ALGORITHM_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "ADDED_ALGORITHM_ERROR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ADDED_ALGORITHM_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "ADDED_ALGORITHM_ERROR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ALAW
- x = PyInt_FromLong(CL_ALAW);
- if (x == NULL || PyDict_SetItemString(d, "ALAW", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ALAW);
+ if (x == NULL || PyDict_SetItemString(d, "ALAW", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ALGORITHM_ID
- x = PyInt_FromLong(CL_ALGORITHM_ID);
- if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_ID", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ALGORITHM_ID);
+ if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_ID", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ALGORITHM_TABLE_FULL
- x = PyInt_FromLong(CL_ALGORITHM_TABLE_FULL);
- if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_TABLE_FULL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ALGORITHM_TABLE_FULL);
+ if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_TABLE_FULL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ALGORITHM_VERSION
- x = PyInt_FromLong(CL_ALGORITHM_VERSION);
- if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_VERSION", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ALGORITHM_VERSION);
+ if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_VERSION", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ALG_AUDIO
- x = PyInt_FromLong(CL_ALG_AUDIO);
- if (x == NULL || PyDict_SetItemString(d, "ALG_AUDIO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ALG_AUDIO);
+ if (x == NULL || PyDict_SetItemString(d, "ALG_AUDIO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ALG_VIDEO
- x = PyInt_FromLong(CL_ALG_VIDEO);
- if (x == NULL || PyDict_SetItemString(d, "ALG_VIDEO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ALG_VIDEO);
+ if (x == NULL || PyDict_SetItemString(d, "ALG_VIDEO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AUDIO
- x = PyInt_FromLong(CL_AUDIO);
- if (x == NULL || PyDict_SetItemString(d, "AUDIO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AUDIO);
+ if (x == NULL || PyDict_SetItemString(d, "AUDIO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_BITRATE_POLICY
- x = PyInt_FromLong(CL_AWARE_BITRATE_POLICY);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_BITRATE_POLICY", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_BITRATE_POLICY);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_BITRATE_POLICY", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_BITRATE_TARGET
- x = PyInt_FromLong(CL_AWARE_BITRATE_TARGET);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_BITRATE_TARGET", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_BITRATE_TARGET);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_BITRATE_TARGET", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_CHANNEL_POLICY
- x = PyInt_FromLong(CL_AWARE_CHANNEL_POLICY);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_CHANNEL_POLICY", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_CHANNEL_POLICY);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_CHANNEL_POLICY", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_CONST_QUAL
- x = PyInt_FromLong(CL_AWARE_CONST_QUAL);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_CONST_QUAL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_CONST_QUAL);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_CONST_QUAL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_ERROR
- x = PyInt_FromLong(CL_AWARE_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_ERROR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_ERROR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_FIXED_RATE
- x = PyInt_FromLong(CL_AWARE_FIXED_RATE);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_FIXED_RATE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_FIXED_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_FIXED_RATE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_INDEPENDENT
- x = PyInt_FromLong(CL_AWARE_INDEPENDENT);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_INDEPENDENT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_INDEPENDENT);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_INDEPENDENT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_JOINT_STEREO
- x = PyInt_FromLong(CL_AWARE_JOINT_STEREO);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_JOINT_STEREO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_JOINT_STEREO);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_JOINT_STEREO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_LAYER
- x = PyInt_FromLong(CL_AWARE_LAYER);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_LAYER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_LAYER);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_LAYER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_LOSSLESS
- x = PyInt_FromLong(CL_AWARE_LOSSLESS);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_LOSSLESS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_LOSSLESS);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_LOSSLESS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_MPEG_AUDIO
- x = PyInt_FromLong(CL_AWARE_MPEG_AUDIO);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_AUDIO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_MPEG_AUDIO);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_AUDIO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_MPEG_LAYER_I
- x = PyInt_FromLong(CL_AWARE_MPEG_LAYER_I);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_LAYER_I", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_MPEG_LAYER_I);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_LAYER_I", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_MPEG_LAYER_II
- x = PyInt_FromLong(CL_AWARE_MPEG_LAYER_II);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_LAYER_II", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_MPEG_LAYER_II);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_LAYER_II", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_MULTIRATE
- x = PyInt_FromLong(CL_AWARE_MULTIRATE);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_MULTIRATE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_MULTIRATE);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_MULTIRATE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_NOISE_MARGIN
- x = PyInt_FromLong(CL_AWARE_NOISE_MARGIN);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_NOISE_MARGIN", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_NOISE_MARGIN);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_NOISE_MARGIN", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_STEREO
- x = PyInt_FromLong(CL_AWARE_STEREO);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_STEREO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_STEREO);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_STEREO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_ALGORITHM_NAME
- x = PyInt_FromLong(CL_BAD_ALGORITHM_NAME);
- if (x == NULL || PyDict_SetItemString(d, "BAD_ALGORITHM_NAME", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_ALGORITHM_NAME);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_ALGORITHM_NAME", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_ALGORITHM_TYPE
- x = PyInt_FromLong(CL_BAD_ALGORITHM_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_ALGORITHM_TYPE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_ALGORITHM_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_ALGORITHM_TYPE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BLOCK_SIZE
- x = PyInt_FromLong(CL_BAD_BLOCK_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BLOCK_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BLOCK_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BLOCK_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BOARD
- x = PyInt_FromLong(CL_BAD_BOARD);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BOARD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BOARD);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BOARD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFERING
- x = PyInt_FromLong(CL_BAD_BUFFERING);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERING", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFERING);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERING", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFERLENGTH_NEG
- x = PyInt_FromLong(CL_BAD_BUFFERLENGTH_NEG);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_NEG", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFERLENGTH_NEG);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_NEG", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFERLENGTH_ODD
- x = PyInt_FromLong(CL_BAD_BUFFERLENGTH_ODD);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_ODD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFERLENGTH_ODD);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_ODD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_EXISTS
- x = PyInt_FromLong(CL_BAD_BUFFER_EXISTS);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_EXISTS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_EXISTS);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_EXISTS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_HANDLE
- x = PyInt_FromLong(CL_BAD_BUFFER_HANDLE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_HANDLE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_HANDLE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_HANDLE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_POINTER
- x = PyInt_FromLong(CL_BAD_BUFFER_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_QUERY_SIZE
- x = PyInt_FromLong(CL_BAD_BUFFER_QUERY_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_QUERY_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_QUERY_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_QUERY_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_SIZE
- x = PyInt_FromLong(CL_BAD_BUFFER_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_SIZE_POINTER
- x = PyInt_FromLong(CL_BAD_BUFFER_SIZE_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_SIZE_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_SIZE_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_SIZE_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_TYPE
- x = PyInt_FromLong(CL_BAD_BUFFER_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_TYPE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_TYPE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_COMPRESSION_SCHEME
- x = PyInt_FromLong(CL_BAD_COMPRESSION_SCHEME);
- if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSION_SCHEME", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_COMPRESSION_SCHEME);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSION_SCHEME", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_COMPRESSOR_HANDLE
- x = PyInt_FromLong(CL_BAD_COMPRESSOR_HANDLE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSOR_HANDLE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_COMPRESSOR_HANDLE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSOR_HANDLE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_COMPRESSOR_HANDLE_POINTER
- x = PyInt_FromLong(CL_BAD_COMPRESSOR_HANDLE_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSOR_HANDLE_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_COMPRESSOR_HANDLE_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSOR_HANDLE_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_FRAME_SIZE
- x = PyInt_FromLong(CL_BAD_FRAME_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_FRAME_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_FRAME_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_FRAME_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_FUNCTIONALITY
- x = PyInt_FromLong(CL_BAD_FUNCTIONALITY);
- if (x == NULL || PyDict_SetItemString(d, "BAD_FUNCTIONALITY", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_FUNCTIONALITY);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_FUNCTIONALITY", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_FUNCTION_POINTER
- x = PyInt_FromLong(CL_BAD_FUNCTION_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_FUNCTION_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_FUNCTION_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_FUNCTION_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_HEADER_SIZE
- x = PyInt_FromLong(CL_BAD_HEADER_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_HEADER_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_HEADER_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_HEADER_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_INITIAL_VALUE
- x = PyInt_FromLong(CL_BAD_INITIAL_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_INITIAL_VALUE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_INITIAL_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_INITIAL_VALUE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_INTERNAL_FORMAT
- x = PyInt_FromLong(CL_BAD_INTERNAL_FORMAT);
- if (x == NULL || PyDict_SetItemString(d, "BAD_INTERNAL_FORMAT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_INTERNAL_FORMAT);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_INTERNAL_FORMAT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_LICENSE
- x = PyInt_FromLong(CL_BAD_LICENSE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_LICENSE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_LICENSE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_LICENSE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_MIN_GT_MAX
- x = PyInt_FromLong(CL_BAD_MIN_GT_MAX);
- if (x == NULL || PyDict_SetItemString(d, "BAD_MIN_GT_MAX", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_MIN_GT_MAX);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_MIN_GT_MAX", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_NO_BUFFERSPACE
- x = PyInt_FromLong(CL_BAD_NO_BUFFERSPACE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_NO_BUFFERSPACE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_NO_BUFFERSPACE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_NO_BUFFERSPACE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_NUMBER_OF_BLOCKS
- x = PyInt_FromLong(CL_BAD_NUMBER_OF_BLOCKS);
- if (x == NULL || PyDict_SetItemString(d, "BAD_NUMBER_OF_BLOCKS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_NUMBER_OF_BLOCKS);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_NUMBER_OF_BLOCKS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_PARAM
- x = PyInt_FromLong(CL_BAD_PARAM);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_PARAM);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_PARAM_ID_POINTER
- x = PyInt_FromLong(CL_BAD_PARAM_ID_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM_ID_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_PARAM_ID_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM_ID_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_PARAM_TYPE
- x = PyInt_FromLong(CL_BAD_PARAM_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM_TYPE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_PARAM_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM_TYPE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_POINTER
- x = PyInt_FromLong(CL_BAD_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_PVBUFFER
- x = PyInt_FromLong(CL_BAD_PVBUFFER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PVBUFFER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_PVBUFFER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PVBUFFER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_SCHEME_POINTER
- x = PyInt_FromLong(CL_BAD_SCHEME_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_SCHEME_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_SCHEME_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_SCHEME_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_STREAM_HEADER
- x = PyInt_FromLong(CL_BAD_STREAM_HEADER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_STREAM_HEADER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_STREAM_HEADER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_STREAM_HEADER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_STRING_POINTER
- x = PyInt_FromLong(CL_BAD_STRING_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_STRING_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_STRING_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_STRING_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_TEXT_STRING_PTR
- x = PyInt_FromLong(CL_BAD_TEXT_STRING_PTR);
- if (x == NULL || PyDict_SetItemString(d, "BAD_TEXT_STRING_PTR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_TEXT_STRING_PTR);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_TEXT_STRING_PTR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BEST_FIT
- x = PyInt_FromLong(CL_BEST_FIT);
- if (x == NULL || PyDict_SetItemString(d, "BEST_FIT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BEST_FIT);
+ if (x == NULL || PyDict_SetItemString(d, "BEST_FIT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BIDIRECTIONAL
- x = PyInt_FromLong(CL_BIDIRECTIONAL);
- if (x == NULL || PyDict_SetItemString(d, "BIDIRECTIONAL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BIDIRECTIONAL);
+ if (x == NULL || PyDict_SetItemString(d, "BIDIRECTIONAL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BITRATE
- x = PyInt_FromLong(CL_BITRATE);
- if (x == NULL || PyDict_SetItemString(d, "BITRATE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BITRATE);
+ if (x == NULL || PyDict_SetItemString(d, "BITRATE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BITRATE_POLICY
- x = PyInt_FromLong(CL_BITRATE_POLICY);
- if (x == NULL || PyDict_SetItemString(d, "BITRATE_POLICY", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BITRATE_POLICY);
+ if (x == NULL || PyDict_SetItemString(d, "BITRATE_POLICY", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BITRATE_TARGET
- x = PyInt_FromLong(CL_BITRATE_TARGET);
- if (x == NULL || PyDict_SetItemString(d, "BITRATE_TARGET", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BITRATE_TARGET);
+ if (x == NULL || PyDict_SetItemString(d, "BITRATE_TARGET", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BITS_PER_COMPONENT
- x = PyInt_FromLong(CL_BITS_PER_COMPONENT);
- if (x == NULL || PyDict_SetItemString(d, "BITS_PER_COMPONENT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BITS_PER_COMPONENT);
+ if (x == NULL || PyDict_SetItemString(d, "BITS_PER_COMPONENT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BLENDING
- x = PyInt_FromLong(CL_BLENDING);
- if (x == NULL || PyDict_SetItemString(d, "BLENDING", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BLENDING);
+ if (x == NULL || PyDict_SetItemString(d, "BLENDING", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BLOCK_SIZE
- x = PyInt_FromLong(CL_BLOCK_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BLOCK_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BLOCK_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BLOCK_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BOTTOM_UP
- x = PyInt_FromLong(CL_BOTTOM_UP);
- if (x == NULL || PyDict_SetItemString(d, "BOTTOM_UP", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BOTTOM_UP);
+ if (x == NULL || PyDict_SetItemString(d, "BOTTOM_UP", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BUFFER_NOT_CREATED
- x = PyInt_FromLong(CL_BUFFER_NOT_CREATED);
- if (x == NULL || PyDict_SetItemString(d, "BUFFER_NOT_CREATED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BUFFER_NOT_CREATED);
+ if (x == NULL || PyDict_SetItemString(d, "BUFFER_NOT_CREATED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BUF_COMPRESSED
- x = PyInt_FromLong(CL_BUF_COMPRESSED);
- if (x == NULL || PyDict_SetItemString(d, "BUF_COMPRESSED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BUF_COMPRESSED);
+ if (x == NULL || PyDict_SetItemString(d, "BUF_COMPRESSED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BUF_DATA
- x = PyInt_FromLong(CL_BUF_DATA);
- if (x == NULL || PyDict_SetItemString(d, "BUF_DATA", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BUF_DATA);
+ if (x == NULL || PyDict_SetItemString(d, "BUF_DATA", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BUF_FRAME
- x = PyInt_FromLong(CL_BUF_FRAME);
- if (x == NULL || PyDict_SetItemString(d, "BUF_FRAME", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BUF_FRAME);
+ if (x == NULL || PyDict_SetItemString(d, "BUF_FRAME", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_CHANNEL_POLICY
- x = PyInt_FromLong(CL_CHANNEL_POLICY);
- if (x == NULL || PyDict_SetItemString(d, "CHANNEL_POLICY", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_CHANNEL_POLICY);
+ if (x == NULL || PyDict_SetItemString(d, "CHANNEL_POLICY", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_CHROMA_THRESHOLD
- x = PyInt_FromLong(CL_CHROMA_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "CHROMA_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_CHROMA_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "CHROMA_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_CODEC
- x = PyInt_FromLong(CL_CODEC);
- if (x == NULL || PyDict_SetItemString(d, "CODEC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_CODEC);
+ if (x == NULL || PyDict_SetItemString(d, "CODEC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COMPONENTS
- x = PyInt_FromLong(CL_COMPONENTS);
- if (x == NULL || PyDict_SetItemString(d, "COMPONENTS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COMPONENTS);
+ if (x == NULL || PyDict_SetItemString(d, "COMPONENTS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COMPRESSED_BUFFER_SIZE
- x = PyInt_FromLong(CL_COMPRESSED_BUFFER_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "COMPRESSED_BUFFER_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COMPRESSED_BUFFER_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "COMPRESSED_BUFFER_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COMPRESSION_RATIO
- x = PyInt_FromLong(CL_COMPRESSION_RATIO);
- if (x == NULL || PyDict_SetItemString(d, "COMPRESSION_RATIO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COMPRESSION_RATIO);
+ if (x == NULL || PyDict_SetItemString(d, "COMPRESSION_RATIO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COMPRESSOR
- x = PyInt_FromLong(CL_COMPRESSOR);
- if (x == NULL || PyDict_SetItemString(d, "COMPRESSOR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COMPRESSOR);
+ if (x == NULL || PyDict_SetItemString(d, "COMPRESSOR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_CONTINUOUS_BLOCK
- x = PyInt_FromLong(CL_CONTINUOUS_BLOCK);
- if (x == NULL || PyDict_SetItemString(d, "CONTINUOUS_BLOCK", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_CONTINUOUS_BLOCK);
+ if (x == NULL || PyDict_SetItemString(d, "CONTINUOUS_BLOCK", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_CONTINUOUS_NONBLOCK
- x = PyInt_FromLong(CL_CONTINUOUS_NONBLOCK);
- if (x == NULL || PyDict_SetItemString(d, "CONTINUOUS_NONBLOCK", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_CONTINUOUS_NONBLOCK);
+ if (x == NULL || PyDict_SetItemString(d, "CONTINUOUS_NONBLOCK", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COSMO_CODEC_CONTROL
- x = PyInt_FromLong(CL_COSMO_CODEC_CONTROL);
- if (x == NULL || PyDict_SetItemString(d, "COSMO_CODEC_CONTROL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COSMO_CODEC_CONTROL);
+ if (x == NULL || PyDict_SetItemString(d, "COSMO_CODEC_CONTROL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COSMO_NUM_PARAMS
- x = PyInt_FromLong(CL_COSMO_NUM_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "COSMO_NUM_PARAMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COSMO_NUM_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "COSMO_NUM_PARAMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COSMO_VALUE_BASE
- x = PyInt_FromLong(CL_COSMO_VALUE_BASE);
- if (x == NULL || PyDict_SetItemString(d, "COSMO_VALUE_BASE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COSMO_VALUE_BASE);
+ if (x == NULL || PyDict_SetItemString(d, "COSMO_VALUE_BASE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COSMO_VIDEO_MANUAL_CONTROL
- x = PyInt_FromLong(CL_COSMO_VIDEO_MANUAL_CONTROL);
- if (x == NULL || PyDict_SetItemString(d, "COSMO_VIDEO_MANUAL_CONTROL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COSMO_VIDEO_MANUAL_CONTROL);
+ if (x == NULL || PyDict_SetItemString(d, "COSMO_VIDEO_MANUAL_CONTROL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COSMO_VIDEO_TRANSFER_MODE
- x = PyInt_FromLong(CL_COSMO_VIDEO_TRANSFER_MODE);
- if (x == NULL || PyDict_SetItemString(d, "COSMO_VIDEO_TRANSFER_MODE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COSMO_VIDEO_TRANSFER_MODE);
+ if (x == NULL || PyDict_SetItemString(d, "COSMO_VIDEO_TRANSFER_MODE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_DATA
- x = PyInt_FromLong(CL_DATA);
- if (x == NULL || PyDict_SetItemString(d, "DATA", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_DATA);
+ if (x == NULL || PyDict_SetItemString(d, "DATA", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_DECOMPRESSOR
- x = PyInt_FromLong(CL_DECOMPRESSOR);
- if (x == NULL || PyDict_SetItemString(d, "DECOMPRESSOR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_DECOMPRESSOR);
+ if (x == NULL || PyDict_SetItemString(d, "DECOMPRESSOR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_DSO_ERROR
- x = PyInt_FromLong(CL_DSO_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "DSO_ERROR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_DSO_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "DSO_ERROR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_EDGE_THRESHOLD
- x = PyInt_FromLong(CL_EDGE_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "EDGE_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_EDGE_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "EDGE_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ENABLE_IMAGEINFO
- x = PyInt_FromLong(CL_ENABLE_IMAGEINFO);
- if (x == NULL || PyDict_SetItemString(d, "ENABLE_IMAGEINFO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ENABLE_IMAGEINFO);
+ if (x == NULL || PyDict_SetItemString(d, "ENABLE_IMAGEINFO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_END_OF_SEQUENCE
- x = PyInt_FromLong(CL_END_OF_SEQUENCE);
- if (x == NULL || PyDict_SetItemString(d, "END_OF_SEQUENCE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_END_OF_SEQUENCE);
+ if (x == NULL || PyDict_SetItemString(d, "END_OF_SEQUENCE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ENUM_VALUE
- x = PyInt_FromLong(CL_ENUM_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "ENUM_VALUE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ENUM_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "ENUM_VALUE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_EXACT_COMPRESSION_RATIO
- x = PyInt_FromLong(CL_EXACT_COMPRESSION_RATIO);
- if (x == NULL || PyDict_SetItemString(d, "EXACT_COMPRESSION_RATIO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_EXACT_COMPRESSION_RATIO);
+ if (x == NULL || PyDict_SetItemString(d, "EXACT_COMPRESSION_RATIO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_EXTERNAL_DEVICE
- x = PyInt_FromLong((long) CL_EXTERNAL_DEVICE);
- if (x == NULL || PyDict_SetItemString(d, "EXTERNAL_DEVICE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) CL_EXTERNAL_DEVICE);
+ if (x == NULL || PyDict_SetItemString(d, "EXTERNAL_DEVICE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FLOATING_ENUM_VALUE
- x = PyInt_FromLong(CL_FLOATING_ENUM_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "FLOATING_ENUM_VALUE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FLOATING_ENUM_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "FLOATING_ENUM_VALUE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FLOATING_RANGE_VALUE
- x = PyInt_FromLong(CL_FLOATING_RANGE_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "FLOATING_RANGE_VALUE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FLOATING_RANGE_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "FLOATING_RANGE_VALUE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT
- x = PyInt_FromLong(CL_FORMAT);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_ABGR
- x = PyInt_FromLong(CL_FORMAT_ABGR);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_ABGR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_ABGR);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_ABGR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_BGR
- x = PyInt_FromLong(CL_FORMAT_BGR);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_BGR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_BGR);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_BGR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_BGR233
- x = PyInt_FromLong(CL_FORMAT_BGR233);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_BGR233", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_BGR233);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_BGR233", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_GRAYSCALE
- x = PyInt_FromLong(CL_FORMAT_GRAYSCALE);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_GRAYSCALE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_GRAYSCALE);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_GRAYSCALE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_MONO
- x = PyInt_FromLong(CL_FORMAT_MONO);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_MONO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_MONO);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_MONO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_RBG323
- x = PyInt_FromLong(CL_FORMAT_RBG323);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_RBG323", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_RBG323);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_RBG323", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_STEREO_INTERLEAVED
- x = PyInt_FromLong(CL_FORMAT_STEREO_INTERLEAVED);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_STEREO_INTERLEAVED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_STEREO_INTERLEAVED);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_STEREO_INTERLEAVED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_XBGR
- x = PyInt_FromLong(CL_FORMAT_XBGR);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_XBGR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_XBGR);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_XBGR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_YCbCr
- x = PyInt_FromLong(CL_FORMAT_YCbCr);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_YCbCr);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_YCbCr422
- x = PyInt_FromLong(CL_FORMAT_YCbCr422);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr422", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_YCbCr422);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr422", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_YCbCr422DC
- x = PyInt_FromLong(CL_FORMAT_YCbCr422DC);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr422DC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_YCbCr422DC);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr422DC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME
- x = PyInt_FromLong(CL_FRAME);
- if (x == NULL || PyDict_SetItemString(d, "FRAME", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAMES_PER_CHUNK
- x = PyInt_FromLong(CL_FRAMES_PER_CHUNK);
- if (x == NULL || PyDict_SetItemString(d, "FRAMES_PER_CHUNK", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAMES_PER_CHUNK);
+ if (x == NULL || PyDict_SetItemString(d, "FRAMES_PER_CHUNK", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME_BUFFER_SIZE
- x = PyInt_FromLong(CL_FRAME_BUFFER_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "FRAME_BUFFER_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME_BUFFER_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME_BUFFER_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME_BUFFER_SIZE_ZERO
- x = PyInt_FromLong(CL_FRAME_BUFFER_SIZE_ZERO);
- if (x == NULL || PyDict_SetItemString(d, "FRAME_BUFFER_SIZE_ZERO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME_BUFFER_SIZE_ZERO);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME_BUFFER_SIZE_ZERO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME_INDEX
- x = PyInt_FromLong(CL_FRAME_INDEX);
- if (x == NULL || PyDict_SetItemString(d, "FRAME_INDEX", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME_INDEX);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME_INDEX", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME_RATE
- x = PyInt_FromLong(CL_FRAME_RATE);
- if (x == NULL || PyDict_SetItemString(d, "FRAME_RATE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME_RATE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME_SIZE
- x = PyInt_FromLong(CL_FRAME_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "FRAME_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME_TYPE
- x = PyInt_FromLong(CL_FRAME_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "FRAME_TYPE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME_TYPE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_G711_ALAW
- x = PyInt_FromLong(CL_G711_ALAW);
- if (x == NULL || PyDict_SetItemString(d, "G711_ALAW", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_G711_ALAW);
+ if (x == NULL || PyDict_SetItemString(d, "G711_ALAW", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_G711_ALAW_SOFTWARE
- x = PyInt_FromLong(CL_G711_ALAW_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "G711_ALAW_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_G711_ALAW_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "G711_ALAW_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_G711_ULAW
- x = PyInt_FromLong(CL_G711_ULAW);
- if (x == NULL || PyDict_SetItemString(d, "G711_ULAW", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_G711_ULAW);
+ if (x == NULL || PyDict_SetItemString(d, "G711_ULAW", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_G711_ULAW_SOFTWARE
- x = PyInt_FromLong(CL_G711_ULAW_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "G711_ULAW_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_G711_ULAW_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "G711_ULAW_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_GRAYSCALE
- x = PyInt_FromLong(CL_GRAYSCALE);
- if (x == NULL || PyDict_SetItemString(d, "GRAYSCALE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_GRAYSCALE);
+ if (x == NULL || PyDict_SetItemString(d, "GRAYSCALE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_HDCC
- x = PyInt_FromLong(CL_HDCC);
- if (x == NULL || PyDict_SetItemString(d, "HDCC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_HDCC);
+ if (x == NULL || PyDict_SetItemString(d, "HDCC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_HDCC_SAMPLES_PER_TILE
- x = PyInt_FromLong(CL_HDCC_SAMPLES_PER_TILE);
- if (x == NULL || PyDict_SetItemString(d, "HDCC_SAMPLES_PER_TILE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_HDCC_SAMPLES_PER_TILE);
+ if (x == NULL || PyDict_SetItemString(d, "HDCC_SAMPLES_PER_TILE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_HDCC_SOFTWARE
- x = PyInt_FromLong(CL_HDCC_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "HDCC_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_HDCC_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "HDCC_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_HDCC_TILE_THRESHOLD
- x = PyInt_FromLong(CL_HDCC_TILE_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "HDCC_TILE_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_HDCC_TILE_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "HDCC_TILE_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_HEADER_START_CODE
- x = PyInt_FromLong(CL_HEADER_START_CODE);
- if (x == NULL || PyDict_SetItemString(d, "HEADER_START_CODE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_HEADER_START_CODE);
+ if (x == NULL || PyDict_SetItemString(d, "HEADER_START_CODE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGEINFO_FIELDMASK
- x = PyInt_FromLong(CL_IMAGEINFO_FIELDMASK);
- if (x == NULL || PyDict_SetItemString(d, "IMAGEINFO_FIELDMASK", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGEINFO_FIELDMASK);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGEINFO_FIELDMASK", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGE_CROP_BOTTOM
- x = PyInt_FromLong(CL_IMAGE_CROP_BOTTOM);
- if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_BOTTOM", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGE_CROP_BOTTOM);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_BOTTOM", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGE_CROP_LEFT
- x = PyInt_FromLong(CL_IMAGE_CROP_LEFT);
- if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_LEFT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGE_CROP_LEFT);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_LEFT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGE_CROP_RIGHT
- x = PyInt_FromLong(CL_IMAGE_CROP_RIGHT);
- if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_RIGHT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGE_CROP_RIGHT);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_RIGHT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGE_CROP_TOP
- x = PyInt_FromLong(CL_IMAGE_CROP_TOP);
- if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_TOP", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGE_CROP_TOP);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_TOP", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGE_HEIGHT
- x = PyInt_FromLong(CL_IMAGE_HEIGHT);
- if (x == NULL || PyDict_SetItemString(d, "IMAGE_HEIGHT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGE_HEIGHT);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGE_HEIGHT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGE_WIDTH
- x = PyInt_FromLong(CL_IMAGE_WIDTH);
- if (x == NULL || PyDict_SetItemString(d, "IMAGE_WIDTH", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGE_WIDTH);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGE_WIDTH", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMPACT_CODEC_CONTROL
- x = PyInt_FromLong(CL_IMPACT_CODEC_CONTROL);
- if (x == NULL || PyDict_SetItemString(d, "IMPACT_CODEC_CONTROL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMPACT_CODEC_CONTROL);
+ if (x == NULL || PyDict_SetItemString(d, "IMPACT_CODEC_CONTROL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMPACT_FRAME_INTERLEAVE
- x = PyInt_FromLong(CL_IMPACT_FRAME_INTERLEAVE);
- if (x == NULL || PyDict_SetItemString(d, "IMPACT_FRAME_INTERLEAVE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMPACT_FRAME_INTERLEAVE);
+ if (x == NULL || PyDict_SetItemString(d, "IMPACT_FRAME_INTERLEAVE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMPACT_NUM_PARAMS
- x = PyInt_FromLong(CL_IMPACT_NUM_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "IMPACT_NUM_PARAMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMPACT_NUM_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "IMPACT_NUM_PARAMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_INTERNAL_FORMAT
- x = PyInt_FromLong(CL_INTERNAL_FORMAT);
- if (x == NULL || PyDict_SetItemString(d, "INTERNAL_FORMAT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_INTERNAL_FORMAT);
+ if (x == NULL || PyDict_SetItemString(d, "INTERNAL_FORMAT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_INTERNAL_IMAGE_HEIGHT
- x = PyInt_FromLong(CL_INTERNAL_IMAGE_HEIGHT);
- if (x == NULL || PyDict_SetItemString(d, "INTERNAL_IMAGE_HEIGHT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_INTERNAL_IMAGE_HEIGHT);
+ if (x == NULL || PyDict_SetItemString(d, "INTERNAL_IMAGE_HEIGHT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_INTERNAL_IMAGE_WIDTH
- x = PyInt_FromLong(CL_INTERNAL_IMAGE_WIDTH);
- if (x == NULL || PyDict_SetItemString(d, "INTERNAL_IMAGE_WIDTH", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_INTERNAL_IMAGE_WIDTH);
+ if (x == NULL || PyDict_SetItemString(d, "INTERNAL_IMAGE_WIDTH", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_INTRA
- x = PyInt_FromLong(CL_INTRA);
- if (x == NULL || PyDict_SetItemString(d, "INTRA", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_INTRA);
+ if (x == NULL || PyDict_SetItemString(d, "INTRA", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG
- x = PyInt_FromLong(CL_JPEG);
- if (x == NULL || PyDict_SetItemString(d, "JPEG", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_COSMO
- x = PyInt_FromLong(CL_JPEG_COSMO);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_COSMO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_COSMO);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_COSMO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_ERROR
- x = PyInt_FromLong(CL_JPEG_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_ERROR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_ERROR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_IMPACT
- x = PyInt_FromLong(CL_JPEG_IMPACT);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_IMPACT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_IMPACT);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_IMPACT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_NUM_PARAMS
- x = PyInt_FromLong(CL_JPEG_NUM_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_NUM_PARAMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_NUM_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_NUM_PARAMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_QUALITY_FACTOR
- x = PyInt_FromLong(CL_JPEG_QUALITY_FACTOR);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_QUALITY_FACTOR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_QUALITY_FACTOR);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_QUALITY_FACTOR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_QUANTIZATION_TABLES
- x = PyInt_FromLong(CL_JPEG_QUANTIZATION_TABLES);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_QUANTIZATION_TABLES", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_QUANTIZATION_TABLES);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_QUANTIZATION_TABLES", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_SOFTWARE
- x = PyInt_FromLong(CL_JPEG_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_STREAM_HEADERS
- x = PyInt_FromLong(CL_JPEG_STREAM_HEADERS);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_STREAM_HEADERS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_STREAM_HEADERS);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_STREAM_HEADERS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_KEYFRAME
- x = PyInt_FromLong(CL_KEYFRAME);
- if (x == NULL || PyDict_SetItemString(d, "KEYFRAME", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_KEYFRAME);
+ if (x == NULL || PyDict_SetItemString(d, "KEYFRAME", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_KEYFRAME_DISTANCE
- x = PyInt_FromLong(CL_KEYFRAME_DISTANCE);
- if (x == NULL || PyDict_SetItemString(d, "KEYFRAME_DISTANCE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_KEYFRAME_DISTANCE);
+ if (x == NULL || PyDict_SetItemString(d, "KEYFRAME_DISTANCE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_LAST_FRAME_INDEX
- x = PyInt_FromLong(CL_LAST_FRAME_INDEX);
- if (x == NULL || PyDict_SetItemString(d, "LAST_FRAME_INDEX", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_LAST_FRAME_INDEX);
+ if (x == NULL || PyDict_SetItemString(d, "LAST_FRAME_INDEX", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_LAYER
- x = PyInt_FromLong(CL_LAYER);
- if (x == NULL || PyDict_SetItemString(d, "LAYER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_LAYER);
+ if (x == NULL || PyDict_SetItemString(d, "LAYER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_LUMA_THRESHOLD
- x = PyInt_FromLong(CL_LUMA_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "LUMA_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_LUMA_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "LUMA_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MAX_NUMBER_OF_AUDIO_ALGORITHMS
- x = PyInt_FromLong(CL_MAX_NUMBER_OF_AUDIO_ALGORITHMS);
- if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_AUDIO_ALGORITHMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MAX_NUMBER_OF_AUDIO_ALGORITHMS);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_AUDIO_ALGORITHMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MAX_NUMBER_OF_FORMATS
- x = PyInt_FromLong(CL_MAX_NUMBER_OF_FORMATS);
- if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_FORMATS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MAX_NUMBER_OF_FORMATS);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_FORMATS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MAX_NUMBER_OF_ORIGINAL_FORMATS
- x = PyInt_FromLong(CL_MAX_NUMBER_OF_ORIGINAL_FORMATS);
- if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_ORIGINAL_FORMATS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MAX_NUMBER_OF_ORIGINAL_FORMATS);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_ORIGINAL_FORMATS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MAX_NUMBER_OF_PARAMS
- x = PyInt_FromLong(CL_MAX_NUMBER_OF_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_PARAMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MAX_NUMBER_OF_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_PARAMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MAX_NUMBER_OF_VIDEO_ALGORITHMS
- x = PyInt_FromLong(CL_MAX_NUMBER_OF_VIDEO_ALGORITHMS);
- if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_VIDEO_ALGORITHMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MAX_NUMBER_OF_VIDEO_ALGORITHMS);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_VIDEO_ALGORITHMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MONO
- x = PyInt_FromLong(CL_MONO);
- if (x == NULL || PyDict_SetItemString(d, "MONO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MONO);
+ if (x == NULL || PyDict_SetItemString(d, "MONO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_AWARE
- x = PyInt_FromLong(CL_MPEG1_AUDIO_AWARE);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_AWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_AWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_AWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_LAYER
- x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_LAYER_I
- x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER_I);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER_I", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER_I);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER_I", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_LAYER_II
- x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER_II);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER_II", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER_II);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER_II", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_MODE
- x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_MODE_DUAL
- x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_DUAL);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_DUAL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_DUAL);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_DUAL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_MODE_JOINT
- x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_JOINT);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_JOINT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_JOINT);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_JOINT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_MODE_SINGLE
- x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_SINGLE);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_SINGLE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_SINGLE);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_SINGLE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_MODE_STEREO
- x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_STEREO);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_STEREO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_STEREO);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_STEREO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_SOFTWARE
- x = PyInt_FromLong(CL_MPEG1_AUDIO_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_END_OF_STREAM
- x = PyInt_FromLong(CL_MPEG1_END_OF_STREAM);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_END_OF_STREAM", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_END_OF_STREAM);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_END_OF_STREAM", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_ERROR
- x = PyInt_FromLong(CL_MPEG1_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_ERROR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_ERROR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_NUM_PARAMS
- x = PyInt_FromLong(CL_MPEG1_NUM_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_NUM_PARAMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_NUM_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_NUM_PARAMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_M
- x = PyInt_FromLong(CL_MPEG1_VIDEO_M);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_M", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_M);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_M", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_X
- x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_X);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_X", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_X);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_X", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_Y
- x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_Y);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_Y", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_Y);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_Y", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_X
- x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_X);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_X", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_X);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_X", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_Y
- x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_Y);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_Y", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_Y);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_Y", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_N
- x = PyInt_FromLong(CL_MPEG1_VIDEO_N);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_N", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_N);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_N", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_SOFTNESS
- x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_SOFTNESS_MAXIMUM
- x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_MAXIMUM);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_MAXIMUM", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_MAXIMUM);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_MAXIMUM", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_SOFTNESS_MEDIUM
- x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_MEDIUM);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_MEDIUM", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_MEDIUM);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_MEDIUM", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_SOFTNESS_NONE
- x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_NONE);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_NONE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_NONE);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_NONE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_SOFTWARE
- x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG_VIDEO
- x = PyInt_FromLong(CL_MPEG_VIDEO);
- if (x == NULL || PyDict_SetItemString(d, "MPEG_VIDEO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG_VIDEO);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG_VIDEO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MULTIRATE_AWARE
- x = PyInt_FromLong(CL_MULTIRATE_AWARE);
- if (x == NULL || PyDict_SetItemString(d, "MULTIRATE_AWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MULTIRATE_AWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MULTIRATE_AWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC1
- x = PyInt_FromLong(CL_MVC1);
- if (x == NULL || PyDict_SetItemString(d, "MVC1", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC1);
+ if (x == NULL || PyDict_SetItemString(d, "MVC1", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC1_SOFTWARE
- x = PyInt_FromLong(CL_MVC1_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "MVC1_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC1_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MVC1_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2
- x = PyInt_FromLong(CL_MVC2);
- if (x == NULL || PyDict_SetItemString(d, "MVC2", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_BLENDING
- x = PyInt_FromLong(CL_MVC2_BLENDING);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_BLENDING);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_BLENDING_OFF
- x = PyInt_FromLong(CL_MVC2_BLENDING_OFF);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING_OFF", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_BLENDING_OFF);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING_OFF", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_BLENDING_ON
- x = PyInt_FromLong(CL_MVC2_BLENDING_ON);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING_ON", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_BLENDING_ON);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING_ON", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_CHROMA_THRESHOLD
- x = PyInt_FromLong(CL_MVC2_CHROMA_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_CHROMA_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_CHROMA_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_CHROMA_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_EDGE_THRESHOLD
- x = PyInt_FromLong(CL_MVC2_EDGE_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_EDGE_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_EDGE_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_EDGE_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_ERROR
- x = PyInt_FromLong(CL_MVC2_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_ERROR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_ERROR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_LUMA_THRESHOLD
- x = PyInt_FromLong(CL_MVC2_LUMA_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_LUMA_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_LUMA_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_LUMA_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_SOFTWARE
- x = PyInt_FromLong(CL_MVC2_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC3_QUALITY_LEVEL
- x = PyInt_FromLong(CL_MVC3_QUALITY_LEVEL);
- if (x == NULL || PyDict_SetItemString(d, "MVC3_QUALITY_LEVEL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC3_QUALITY_LEVEL);
+ if (x == NULL || PyDict_SetItemString(d, "MVC3_QUALITY_LEVEL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC3_SOFTWARE
- x = PyInt_FromLong(CL_MVC3_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "MVC3_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC3_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MVC3_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NEXT_NOT_AVAILABLE
- x = PyInt_FromLong(CL_NEXT_NOT_AVAILABLE);
- if (x == NULL || PyDict_SetItemString(d, "NEXT_NOT_AVAILABLE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NEXT_NOT_AVAILABLE);
+ if (x == NULL || PyDict_SetItemString(d, "NEXT_NOT_AVAILABLE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NOISE_MARGIN
- x = PyInt_FromLong(CL_NOISE_MARGIN);
- if (x == NULL || PyDict_SetItemString(d, "NOISE_MARGIN", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NOISE_MARGIN);
+ if (x == NULL || PyDict_SetItemString(d, "NOISE_MARGIN", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NONE
- x = PyInt_FromLong(CL_NONE);
- if (x == NULL || PyDict_SetItemString(d, "NONE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NONE);
+ if (x == NULL || PyDict_SetItemString(d, "NONE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NUMBER_OF_FORMATS
- x = PyInt_FromLong(CL_NUMBER_OF_FORMATS);
- if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_FORMATS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NUMBER_OF_FORMATS);
+ if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_FORMATS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NUMBER_OF_FRAMES
- x = PyInt_FromLong(CL_NUMBER_OF_FRAMES);
- if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_FRAMES", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NUMBER_OF_FRAMES);
+ if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_FRAMES", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NUMBER_OF_PARAMS
- x = PyInt_FromLong(CL_NUMBER_OF_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_PARAMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NUMBER_OF_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_PARAMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NUMBER_OF_PARAMS_FREEZE
- x = PyInt_FromLong(CL_NUMBER_OF_PARAMS_FREEZE);
- if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_PARAMS_FREEZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NUMBER_OF_PARAMS_FREEZE);
+ if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_PARAMS_FREEZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NUMBER_OF_VIDEO_FORMATS
- x = PyInt_FromLong(CL_NUMBER_OF_VIDEO_FORMATS);
- if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_VIDEO_FORMATS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NUMBER_OF_VIDEO_FORMATS);
+ if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_VIDEO_FORMATS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ORIENTATION
- x = PyInt_FromLong(CL_ORIENTATION);
- if (x == NULL || PyDict_SetItemString(d, "ORIENTATION", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ORIENTATION);
+ if (x == NULL || PyDict_SetItemString(d, "ORIENTATION", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ORIGINAL_FORMAT
- x = PyInt_FromLong(CL_ORIGINAL_FORMAT);
- if (x == NULL || PyDict_SetItemString(d, "ORIGINAL_FORMAT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ORIGINAL_FORMAT);
+ if (x == NULL || PyDict_SetItemString(d, "ORIGINAL_FORMAT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_PARAM_OUT_OF_RANGE
- x = PyInt_FromLong(CL_PARAM_OUT_OF_RANGE);
- if (x == NULL || PyDict_SetItemString(d, "PARAM_OUT_OF_RANGE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_PARAM_OUT_OF_RANGE);
+ if (x == NULL || PyDict_SetItemString(d, "PARAM_OUT_OF_RANGE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_PIXEL_ASPECT
- x = PyInt_FromLong(CL_PIXEL_ASPECT);
- if (x == NULL || PyDict_SetItemString(d, "PIXEL_ASPECT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_PIXEL_ASPECT);
+ if (x == NULL || PyDict_SetItemString(d, "PIXEL_ASPECT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_PREDICTED
- x = PyInt_FromLong(CL_PREDICTED);
- if (x == NULL || PyDict_SetItemString(d, "PREDICTED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_PREDICTED);
+ if (x == NULL || PyDict_SetItemString(d, "PREDICTED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_PREROLL
- x = PyInt_FromLong(CL_PREROLL);
- if (x == NULL || PyDict_SetItemString(d, "PREROLL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_PREROLL);
+ if (x == NULL || PyDict_SetItemString(d, "PREROLL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_QUALITY_FACTOR
- x = PyInt_FromLong(CL_QUALITY_FACTOR);
- if (x == NULL || PyDict_SetItemString(d, "QUALITY_FACTOR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_QUALITY_FACTOR);
+ if (x == NULL || PyDict_SetItemString(d, "QUALITY_FACTOR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_QUALITY_LEVEL
- x = PyInt_FromLong(CL_QUALITY_LEVEL);
- if (x == NULL || PyDict_SetItemString(d, "QUALITY_LEVEL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_QUALITY_LEVEL);
+ if (x == NULL || PyDict_SetItemString(d, "QUALITY_LEVEL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_QUALITY_SPATIAL
- x = PyInt_FromLong(CL_QUALITY_SPATIAL);
- if (x == NULL || PyDict_SetItemString(d, "QUALITY_SPATIAL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_QUALITY_SPATIAL);
+ if (x == NULL || PyDict_SetItemString(d, "QUALITY_SPATIAL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_QUALITY_TEMPORAL
- x = PyInt_FromLong(CL_QUALITY_TEMPORAL);
- if (x == NULL || PyDict_SetItemString(d, "QUALITY_TEMPORAL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_QUALITY_TEMPORAL);
+ if (x == NULL || PyDict_SetItemString(d, "QUALITY_TEMPORAL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_QUANTIZATION_TABLES
- x = PyInt_FromLong(CL_QUANTIZATION_TABLES);
- if (x == NULL || PyDict_SetItemString(d, "QUANTIZATION_TABLES", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_QUANTIZATION_TABLES);
+ if (x == NULL || PyDict_SetItemString(d, "QUANTIZATION_TABLES", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RANGE_VALUE
- x = PyInt_FromLong(CL_RANGE_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "RANGE_VALUE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RANGE_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "RANGE_VALUE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RGB
- x = PyInt_FromLong(CL_RGB);
- if (x == NULL || PyDict_SetItemString(d, "RGB", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RGB);
+ if (x == NULL || PyDict_SetItemString(d, "RGB", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RGB332
- x = PyInt_FromLong(CL_RGB332);
- if (x == NULL || PyDict_SetItemString(d, "RGB332", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RGB332);
+ if (x == NULL || PyDict_SetItemString(d, "RGB332", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RGB8
- x = PyInt_FromLong(CL_RGB8);
- if (x == NULL || PyDict_SetItemString(d, "RGB8", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RGB8);
+ if (x == NULL || PyDict_SetItemString(d, "RGB8", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RGBA
- x = PyInt_FromLong(CL_RGBA);
- if (x == NULL || PyDict_SetItemString(d, "RGBA", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RGBA);
+ if (x == NULL || PyDict_SetItemString(d, "RGBA", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RGBX
- x = PyInt_FromLong(CL_RGBX);
- if (x == NULL || PyDict_SetItemString(d, "RGBX", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RGBX);
+ if (x == NULL || PyDict_SetItemString(d, "RGBX", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RLE
- x = PyInt_FromLong(CL_RLE);
- if (x == NULL || PyDict_SetItemString(d, "RLE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RLE);
+ if (x == NULL || PyDict_SetItemString(d, "RLE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RLE24
- x = PyInt_FromLong(CL_RLE24);
- if (x == NULL || PyDict_SetItemString(d, "RLE24", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RLE24);
+ if (x == NULL || PyDict_SetItemString(d, "RLE24", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RLE24_SOFTWARE
- x = PyInt_FromLong(CL_RLE24_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "RLE24_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RLE24_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "RLE24_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RLE_SOFTWARE
- x = PyInt_FromLong(CL_RLE_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "RLE_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RLE_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "RLE_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RTR
- x = PyInt_FromLong(CL_RTR);
- if (x == NULL || PyDict_SetItemString(d, "RTR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RTR);
+ if (x == NULL || PyDict_SetItemString(d, "RTR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RTR1
- x = PyInt_FromLong(CL_RTR1);
- if (x == NULL || PyDict_SetItemString(d, "RTR1", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RTR1);
+ if (x == NULL || PyDict_SetItemString(d, "RTR1", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RTR_QUALITY_LEVEL
- x = PyInt_FromLong(CL_RTR_QUALITY_LEVEL);
- if (x == NULL || PyDict_SetItemString(d, "RTR_QUALITY_LEVEL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RTR_QUALITY_LEVEL);
+ if (x == NULL || PyDict_SetItemString(d, "RTR_QUALITY_LEVEL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_SAMPLES_PER_TILE
- x = PyInt_FromLong(CL_SAMPLES_PER_TILE);
- if (x == NULL || PyDict_SetItemString(d, "SAMPLES_PER_TILE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_SAMPLES_PER_TILE);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPLES_PER_TILE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_SCHEME_BUSY
- x = PyInt_FromLong(CL_SCHEME_BUSY);
- if (x == NULL || PyDict_SetItemString(d, "SCHEME_BUSY", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_SCHEME_BUSY);
+ if (x == NULL || PyDict_SetItemString(d, "SCHEME_BUSY", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_SCHEME_NOT_AVAILABLE
- x = PyInt_FromLong(CL_SCHEME_NOT_AVAILABLE);
- if (x == NULL || PyDict_SetItemString(d, "SCHEME_NOT_AVAILABLE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_SCHEME_NOT_AVAILABLE);
+ if (x == NULL || PyDict_SetItemString(d, "SCHEME_NOT_AVAILABLE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_SPEED
- x = PyInt_FromLong(CL_SPEED);
- if (x == NULL || PyDict_SetItemString(d, "SPEED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_SPEED);
+ if (x == NULL || PyDict_SetItemString(d, "SPEED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_STEREO_INTERLEAVED
- x = PyInt_FromLong(CL_STEREO_INTERLEAVED);
- if (x == NULL || PyDict_SetItemString(d, "STEREO_INTERLEAVED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_STEREO_INTERLEAVED);
+ if (x == NULL || PyDict_SetItemString(d, "STEREO_INTERLEAVED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_STREAM_HEADERS
- x = PyInt_FromLong(CL_STREAM_HEADERS);
- if (x == NULL || PyDict_SetItemString(d, "STREAM_HEADERS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_STREAM_HEADERS);
+ if (x == NULL || PyDict_SetItemString(d, "STREAM_HEADERS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_TILE_THRESHOLD
- x = PyInt_FromLong(CL_TILE_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "TILE_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_TILE_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "TILE_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_TOP_DOWN
- x = PyInt_FromLong(CL_TOP_DOWN);
- if (x == NULL || PyDict_SetItemString(d, "TOP_DOWN", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_TOP_DOWN);
+ if (x == NULL || PyDict_SetItemString(d, "TOP_DOWN", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ULAW
- x = PyInt_FromLong(CL_ULAW);
- if (x == NULL || PyDict_SetItemString(d, "ULAW", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ULAW);
+ if (x == NULL || PyDict_SetItemString(d, "ULAW", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_UNCOMPRESSED
- x = PyInt_FromLong(CL_UNCOMPRESSED);
- if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_UNCOMPRESSED);
+ if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_UNCOMPRESSED_AUDIO
- x = PyInt_FromLong(CL_UNCOMPRESSED_AUDIO);
- if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED_AUDIO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_UNCOMPRESSED_AUDIO);
+ if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED_AUDIO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_UNCOMPRESSED_VIDEO
- x = PyInt_FromLong(CL_UNCOMPRESSED_VIDEO);
- if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED_VIDEO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_UNCOMPRESSED_VIDEO);
+ if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED_VIDEO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_UNKNOWN_SCHEME
- x = PyInt_FromLong(CL_UNKNOWN_SCHEME);
- if (x == NULL || PyDict_SetItemString(d, "UNKNOWN_SCHEME", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_UNKNOWN_SCHEME);
+ if (x == NULL || PyDict_SetItemString(d, "UNKNOWN_SCHEME", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_VIDEO
- x = PyInt_FromLong(CL_VIDEO);
- if (x == NULL || PyDict_SetItemString(d, "VIDEO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_VIDEO);
+ if (x == NULL || PyDict_SetItemString(d, "VIDEO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_Y
- x = PyInt_FromLong(CL_Y);
- if (x == NULL || PyDict_SetItemString(d, "Y", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_Y);
+ if (x == NULL || PyDict_SetItemString(d, "Y", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YCbCr
- x = PyInt_FromLong(CL_YCbCr);
- if (x == NULL || PyDict_SetItemString(d, "YCbCr", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YCbCr);
+ if (x == NULL || PyDict_SetItemString(d, "YCbCr", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YCbCr422
- x = PyInt_FromLong(CL_YCbCr422);
- if (x == NULL || PyDict_SetItemString(d, "YCbCr422", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YCbCr422);
+ if (x == NULL || PyDict_SetItemString(d, "YCbCr422", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YCbCr422DC
- x = PyInt_FromLong(CL_YCbCr422DC);
- if (x == NULL || PyDict_SetItemString(d, "YCbCr422DC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YCbCr422DC);
+ if (x == NULL || PyDict_SetItemString(d, "YCbCr422DC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YCbCr422HC
- x = PyInt_FromLong(CL_YCbCr422HC);
- if (x == NULL || PyDict_SetItemString(d, "YCbCr422HC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YCbCr422HC);
+ if (x == NULL || PyDict_SetItemString(d, "YCbCr422HC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YUV
- x = PyInt_FromLong(CL_YUV);
- if (x == NULL || PyDict_SetItemString(d, "YUV", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YUV);
+ if (x == NULL || PyDict_SetItemString(d, "YUV", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YUV422
- x = PyInt_FromLong(CL_YUV422);
- if (x == NULL || PyDict_SetItemString(d, "YUV422", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YUV422);
+ if (x == NULL || PyDict_SetItemString(d, "YUV422", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YUV422DC
- x = PyInt_FromLong(CL_YUV422DC);
- if (x == NULL || PyDict_SetItemString(d, "YUV422DC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YUV422DC);
+ if (x == NULL || PyDict_SetItemString(d, "YUV422DC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YUV422HC
- x = PyInt_FromLong(CL_YUV422HC);
- if (x == NULL || PyDict_SetItemString(d, "YUV422HC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YUV422HC);
+ if (x == NULL || PyDict_SetItemString(d, "YUV422HC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_STEREO
- x = PyInt_FromLong(AWCMP_STEREO);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_STEREO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_STEREO);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_STEREO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_JOINT_STEREO
- x = PyInt_FromLong(AWCMP_JOINT_STEREO);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_JOINT_STEREO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_JOINT_STEREO);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_JOINT_STEREO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_INDEPENDENT
- x = PyInt_FromLong(AWCMP_INDEPENDENT);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_INDEPENDENT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_INDEPENDENT);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_INDEPENDENT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_FIXED_RATE
- x = PyInt_FromLong(AWCMP_FIXED_RATE);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_FIXED_RATE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_FIXED_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_FIXED_RATE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_CONST_QUAL
- x = PyInt_FromLong(AWCMP_CONST_QUAL);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_CONST_QUAL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_CONST_QUAL);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_CONST_QUAL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_LOSSLESS
- x = PyInt_FromLong(AWCMP_LOSSLESS);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_LOSSLESS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_LOSSLESS);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_LOSSLESS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_MPEG_LAYER_I
- x = PyInt_FromLong(AWCMP_MPEG_LAYER_I);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_MPEG_LAYER_I", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_MPEG_LAYER_I);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_MPEG_LAYER_I", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_MPEG_LAYER_II
- x = PyInt_FromLong(AWCMP_MPEG_LAYER_II);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_MPEG_LAYER_II", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_MPEG_LAYER_II);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_MPEG_LAYER_II", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
- (void) clSetErrorHandler(cl_ErrorHandler);
+ (void) clSetErrorHandler(cl_ErrorHandler);
}
diff --git a/Modules/cmathmodule.c b/Modules/cmathmodule.c
index 7b2e316..eec61c0 100644
--- a/Modules/cmathmodule.c
+++ b/Modules/cmathmodule.c
@@ -31,7 +31,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
@@ -62,46 +62,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
@@ -125,34 +125,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 = 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 = asinh(s2.real*s1.imag - s2.imag*s1.real);
+ }
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_acos_doc,
@@ -166,26 +166,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 = 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 = 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,
@@ -197,14 +197,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,
@@ -218,31 +218,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 = 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 = 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,
@@ -254,14 +254,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
@@ -269,29 +269,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,
@@ -305,48 +305,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 = 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 = 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,
@@ -358,12 +358,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,
@@ -378,51 +378,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,
@@ -438,51 +438,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,
@@ -496,85 +496,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 = 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 = 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,
@@ -586,14 +586,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,
@@ -608,50 +608,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,
@@ -665,68 +665,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,
@@ -738,14 +738,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,
@@ -760,65 +760,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,
@@ -830,23 +830,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,
@@ -859,42 +859,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)
@@ -915,18 +915,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,
@@ -936,18 +936,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,
@@ -971,51 +971,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,
@@ -1025,10 +1025,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,
@@ -1038,11 +1038,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,
@@ -1055,155 +1055,155 @@ 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 */
};
PyMODINIT_FUNC
initcmath(void)
{
- PyObject *m;
+ PyObject *m;
- m = Py_InitModule3("cmath", cmath_methods, module_doc);
- if (m == NULL)
- return;
+ m = Py_InitModule3("cmath", cmath_methods, module_doc);
+ if (m == NULL)
+ return;
- 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)
- })
+ 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)
+ })
}
diff --git a/Modules/cryptmodule.c b/Modules/cryptmodule.c
index 6377f84..76de54f 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,12 +38,12 @@ 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 */
};
PyMODINIT_FUNC
initcrypt(void)
{
- Py_InitModule("crypt", crypt_methods);
+ Py_InitModule("crypt", crypt_methods);
}
diff --git a/Modules/datetimemodule.c b/Modules/datetimemodule.c
index ee558ce..ecce52d 100644
--- a/Modules/datetimemodule.c
+++ b/Modules/datetimemodule.c
@@ -27,7 +27,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
@@ -41,59 +41,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)
@@ -113,7 +113,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
@@ -127,17 +127,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
@@ -146,11 +146,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;
}
/* ---------------------------------------------------------------------------
@@ -162,52 +162,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
@@ -216,124 +216,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
@@ -342,15 +342,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;
}
/* ---------------------------------------------------------------------------
@@ -363,12 +363,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
@@ -378,22 +378,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
@@ -402,27 +402,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;
}
/* ---------------------------------------------------------------------------
@@ -438,109 +438,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
@@ -550,17 +550,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
@@ -571,11 +571,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);
}
/* ---------------------------------------------------------------------------
@@ -602,31 +602,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;
}
/* ---------------------------------------------------------------------------
@@ -638,10 +638,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);
}
/* ---------------------------------------------------------------------------
@@ -652,71 +652,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
@@ -726,30 +726,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.
@@ -761,13 +761,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.
@@ -776,17 +776,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
@@ -796,14 +796,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
@@ -816,59 +816,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
@@ -882,34 +882,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
@@ -923,7 +923,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
@@ -934,48 +934,48 @@ call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
static PyObject *
call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
{
- PyObject *result;
+ PyObject *result;
- assert(tzinfo != NULL);
- assert(check_tzinfo_subclass(tzinfo) >= 0);
- assert(tzinfoarg != NULL);
+ 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 (tzinfo == Py_None) {
+ result = Py_None;
+ Py_INCREF(result);
+ }
+ else
+ result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
- if (result != NULL && result != Py_None && ! PyString_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;
- }
- return result;
+ if (result != NULL && result != Py_None && ! PyString_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;
+ }
+ 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
@@ -987,23 +987,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.
@@ -1017,23 +1017,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,
@@ -1044,30 +1044,30 @@ classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
static PyObject *
append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
{
- PyObject *temp;
+ PyObject *temp;
- assert(PyString_Check(repr));
- assert(tzinfo);
- if (tzinfo == Py_None)
- return repr;
- /* Get rid of the trailing ')'. */
- assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
- temp = PyString_FromStringAndSize(PyString_AsString(repr),
- PyString_Size(repr) - 1);
- Py_DECREF(repr);
- if (temp == NULL)
- return NULL;
- repr = temp;
+ assert(PyString_Check(repr));
+ assert(tzinfo);
+ if (tzinfo == Py_None)
+ return repr;
+ /* Get rid of the trailing ')'. */
+ assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
+ temp = PyString_FromStringAndSize(PyString_AsString(repr),
+ PyString_Size(repr) - 1);
+ Py_DECREF(repr);
+ if (temp == NULL)
+ return NULL;
+ repr = temp;
- /* Append ", tzinfo=". */
- PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
+ /* Append ", tzinfo=". */
+ PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
- /* Append repr(tzinfo). */
- PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
+ /* Append repr(tzinfo). */
+ PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
- /* Add a closing paren. */
- PyString_ConcatAndDel(&repr, PyString_FromString(")"));
- return repr;
+ /* Add a closing paren. */
+ PyString_ConcatAndDel(&repr, PyString_FromString(")"));
+ return repr;
}
/* ---------------------------------------------------------------------------
@@ -1077,22 +1077,22 @@ 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"
+ };
- char buffer[128];
- int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
+ char buffer[128];
+ int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
- PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
- DayNames[wday], MonthNames[GET_MONTH(date) - 1],
- GET_DAY(date), hours, minutes, seconds,
- GET_YEAR(date));
- return PyString_FromString(buffer);
+ PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
+ DayNames[wday], MonthNames[GET_MONTH(date) - 1],
+ GET_DAY(date), hours, minutes, seconds,
+ GET_YEAR(date));
+ return PyString_FromString(buffer);
}
/* Add an hours & minutes UTC offset string to buf. buf has no more than
@@ -1107,45 +1107,45 @@ 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_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 PyString_FromStringAndSize(freplacement, strlen(freplacement));
+ return PyString_FromStringAndSize(freplacement, strlen(freplacement));
}
/* I sure don't want to reproduce the strftime code from the time module,
@@ -1157,231 +1157,231 @@ make_freplacement(PyObject *object)
*/
static PyObject *
wrap_strftime(PyObject *object, const char *format, size_t format_len,
- 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 */
- 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 */
- size_t ntoappend; /* # of bytes to append to output buffer */
-
- assert(object && format && timetuple);
-
- /* 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(PyInt_Check(pyyear));
- year = PyInt_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 (format_len > INT_MAX - 1) {
- PyErr_NoMemory();
- goto Done;
- }
-
- totalnew = format_len + 1; /* realistic if no %z/%Z/%f */
- newfmt = PyString_FromStringAndSize(NULL, totalnew);
- if (newfmt == NULL) goto Done;
- pnew = PyString_AsString(newfmt);
- usednew = 0;
-
- pin = format;
- 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 = PyString_FromString("");
- 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 = PyString_FromString(buf);
- if (zreplacement == NULL) goto Done;
- }
- }
- assert(zreplacement != NULL);
- ptoappend = PyString_AS_STRING(zreplacement);
- ntoappend = PyString_GET_SIZE(zreplacement);
- }
- else if (ch == 'Z') {
- /* format tzname */
- if (Zreplacement == NULL) {
- PyObject *tzinfo = get_tzinfo_member(object);
- Zreplacement = PyString_FromString("");
- if (Zreplacement == NULL) goto Done;
- if (tzinfo != Py_None && tzinfo != NULL) {
- PyObject *temp;
- assert(tzinfoarg != NULL);
- temp = call_tzname(tzinfo, tzinfoarg);
- if (temp == NULL) goto Done;
- if (temp != Py_None) {
- assert(PyString_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)
- goto Done;
- if (!PyString_Check(Zreplacement)) {
- PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
- goto Done;
- }
- }
- else
- Py_DECREF(temp);
- }
- }
- assert(Zreplacement != NULL);
- ptoappend = PyString_AS_STRING(Zreplacement);
- ntoappend = PyString_GET_SIZE(Zreplacement);
- }
- else if (ch == 'f') {
- /* format microseconds */
- if (freplacement == NULL) {
- freplacement = make_freplacement(object);
- if (freplacement == NULL)
- goto Done;
- }
- assert(freplacement != NULL);
- assert(PyString_Check(freplacement));
- ptoappend = PyString_AS_STRING(freplacement);
- ntoappend = PyString_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.
- */
- assert(ptoappend != NULL);
- assert(ntoappend >= 0);
- if (ntoappend == 0)
- continue;
- while (usednew + ntoappend > totalnew) {
- size_t bigger = totalnew << 1;
- if ((bigger >> 1) != totalnew) { /* overflow */
- PyErr_NoMemory();
- goto Done;
- }
- if (_PyString_Resize(&newfmt, bigger) < 0)
- goto Done;
- totalnew = bigger;
- pnew = PyString_AsString(newfmt) + usednew;
- }
- memcpy(pnew, ptoappend, ntoappend);
- pnew += ntoappend;
- usednew += ntoappend;
- assert(usednew <= totalnew);
- } /* end while() */
-
- if (_PyString_Resize(&newfmt, usednew) < 0)
- goto Done;
- {
- PyObject *time = PyImport_ImportModuleNoBlock("time");
- if (time == NULL)
- goto Done;
- result = PyObject_CallMethod(time, "strftime", "OO",
- newfmt, timetuple);
- Py_DECREF(time);
- }
+ 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 */
+ 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 */
+ size_t ntoappend; /* # of bytes to append to output buffer */
+
+ assert(object && format && timetuple);
+
+ /* 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(PyInt_Check(pyyear));
+ year = PyInt_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 (format_len > INT_MAX - 1) {
+ PyErr_NoMemory();
+ goto Done;
+ }
+
+ totalnew = format_len + 1; /* realistic if no %z/%Z/%f */
+ newfmt = PyString_FromStringAndSize(NULL, totalnew);
+ if (newfmt == NULL) goto Done;
+ pnew = PyString_AsString(newfmt);
+ usednew = 0;
+
+ pin = format;
+ 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 = PyString_FromString("");
+ 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 = PyString_FromString(buf);
+ if (zreplacement == NULL) goto Done;
+ }
+ }
+ assert(zreplacement != NULL);
+ ptoappend = PyString_AS_STRING(zreplacement);
+ ntoappend = PyString_GET_SIZE(zreplacement);
+ }
+ else if (ch == 'Z') {
+ /* format tzname */
+ if (Zreplacement == NULL) {
+ PyObject *tzinfo = get_tzinfo_member(object);
+ Zreplacement = PyString_FromString("");
+ if (Zreplacement == NULL) goto Done;
+ if (tzinfo != Py_None && tzinfo != NULL) {
+ PyObject *temp;
+ assert(tzinfoarg != NULL);
+ temp = call_tzname(tzinfo, tzinfoarg);
+ if (temp == NULL) goto Done;
+ if (temp != Py_None) {
+ assert(PyString_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)
+ goto Done;
+ if (!PyString_Check(Zreplacement)) {
+ PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
+ goto Done;
+ }
+ }
+ else
+ Py_DECREF(temp);
+ }
+ }
+ assert(Zreplacement != NULL);
+ ptoappend = PyString_AS_STRING(Zreplacement);
+ ntoappend = PyString_GET_SIZE(Zreplacement);
+ }
+ else if (ch == 'f') {
+ /* format microseconds */
+ if (freplacement == NULL) {
+ freplacement = make_freplacement(object);
+ if (freplacement == NULL)
+ goto Done;
+ }
+ assert(freplacement != NULL);
+ assert(PyString_Check(freplacement));
+ ptoappend = PyString_AS_STRING(freplacement);
+ ntoappend = PyString_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.
+ */
+ assert(ptoappend != NULL);
+ assert(ntoappend >= 0);
+ if (ntoappend == 0)
+ continue;
+ while (usednew + ntoappend > totalnew) {
+ size_t bigger = totalnew << 1;
+ if ((bigger >> 1) != totalnew) { /* overflow */
+ PyErr_NoMemory();
+ goto Done;
+ }
+ if (_PyString_Resize(&newfmt, bigger) < 0)
+ goto Done;
+ totalnew = bigger;
+ pnew = PyString_AsString(newfmt) + usednew;
+ }
+ memcpy(pnew, ptoappend, ntoappend);
+ pnew += ntoappend;
+ usednew += ntoappend;
+ assert(usednew <= totalnew);
+ } /* end while() */
+
+ if (_PyString_Resize(&newfmt, usednew) < 0)
+ goto Done;
+ {
+ PyObject *time = PyImport_ImportModuleNoBlock("time");
+ if (time == NULL)
+ goto Done;
+ result = PyObject_CallMethod(time, "strftime", "OO",
+ newfmt, timetuple);
+ 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;
}
static char *
isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
{
- int x;
- x = PyOS_snprintf(buffer, bufflen,
- "%04d-%02d-%02d",
- GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
- assert(bufflen >= x);
- return buffer + x;
+ int x;
+ x = PyOS_snprintf(buffer, bufflen,
+ "%04d-%02d-%02d",
+ GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
+ assert(bufflen >= x);
+ return buffer + x;
}
static char *
isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
{
- int x;
- int us = DATE_GET_MICROSECOND(dt);
+ int x;
+ int us = DATE_GET_MICROSECOND(dt);
- x = PyOS_snprintf(buffer, bufflen,
- "%02d:%02d:%02d",
- DATE_GET_HOUR(dt),
- DATE_GET_MINUTE(dt),
- DATE_GET_SECOND(dt));
- assert(bufflen >= x);
- if (us)
- x += PyOS_snprintf(buffer + x, bufflen - x, ".%06d", us);
- assert(bufflen >= x);
- return buffer + x;
+ x = PyOS_snprintf(buffer, bufflen,
+ "%02d:%02d:%02d",
+ DATE_GET_HOUR(dt),
+ DATE_GET_MINUTE(dt),
+ DATE_GET_SECOND(dt));
+ assert(bufflen >= x);
+ if (us)
+ x += PyOS_snprintf(buffer + x, bufflen - x, ".%06d", us);
+ assert(bufflen >= x);
+ return buffer + x;
}
/* ---------------------------------------------------------------------------
@@ -1393,14 +1393,14 @@ isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
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
@@ -1409,21 +1409,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;
}
/* ---------------------------------------------------------------------------
@@ -1437,33 +1437,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;
}
/* ---------------------------------------------------------------------------
@@ -1471,13 +1471,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 */
/* ---------------------------------------------------------------------------
@@ -1489,7 +1489,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.
@@ -1497,49 +1497,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 = PyInt_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 = PyInt_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 = PyInt_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 = PyInt_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 = PyInt_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 = PyInt_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.
@@ -1547,205 +1547,205 @@ 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 *
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;
}
/* This is more natural as a tp_compare, but doesn't work then: for whatever
@@ -1755,24 +1755,24 @@ delta_subtract(PyObject *left, PyObject *right)
static PyObject *
delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
{
- int diff = 42; /* nonsense */
+ int diff = 42; /* nonsense */
- if (PyDelta_Check(other)) {
- 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);
- }
- }
- else if (op == Py_EQ || op == Py_NE)
- diff = 1; /* any non-zero value will do */
+ if (PyDelta_Check(other)) {
+ 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);
+ }
+ }
+ else if (op == Py_EQ || op == Py_NE)
+ diff = 1; /* any non-zero value will do */
- else /* stop this from falling back to address comparison */
- return cmperror((PyObject *)self, other);
+ else /* stop this from falling back to address comparison */
+ return cmperror((PyObject *)self, other);
- return diff_to_bool(diff, op);
+ return diff_to_bool(diff, op);
}
static PyObject *delta_getstate(PyDateTime_Delta *self);
@@ -1780,52 +1780,52 @@ 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 (PyInt_Check(right) || PyLong_Check(right))
- result = multiply_int_timedelta(right,
- (PyDateTime_Delta *) left);
- }
- else if (PyInt_Check(left) || PyLong_Check(left))
- result = multiply_int_timedelta(left,
- (PyDateTime_Delta *) right);
+ if (PyDelta_Check(left)) {
+ /* delta * ??? */
+ if (PyInt_Check(right) || PyLong_Check(right))
+ result = multiply_int_timedelta(right,
+ (PyDateTime_Delta *) left);
+ }
+ else if (PyInt_Check(left) || 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 (PyInt_Check(right) || PyLong_Check(right))
- result = divide_timedelta_int(
- (PyDateTime_Delta *)left,
- right);
- }
+ if (PyDelta_Check(left)) {
+ /* delta * ??? */
+ if (PyInt_Check(right) || PyLong_Check(right))
+ result = divide_timedelta_int(
+ (PyDateTime_Delta *)left,
+ right);
+ }
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
+ if (result == Py_NotImplemented)
+ Py_INCREF(result);
+ return result;
}
/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
@@ -1841,169 +1841,169 @@ static PyObject *
accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
double *leftover)
{
- PyObject *prod;
- PyObject *sum;
-
- assert(num != NULL);
-
- if (PyInt_Check(num) || 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(PyInt_Check(factor) || PyLong_Check(factor));
- if (PyInt_Check(factor))
- dnum = (double)PyInt_AsLong(factor);
- else
- 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 (PyInt_Check(num) || 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(PyInt_Check(factor) || PyLong_Check(factor));
+ if (PyInt_Check(factor))
+ dnum = (double)PyInt_AsLong(factor);
+ else
+ 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 = PyInt_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 = PyInt_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
}
@@ -2011,75 +2011,75 @@ Done:
static int
delta_nonzero(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 PyString_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 PyString_FromFormat("%s(%d, %d)",
- Py_TYPE(self)->tp_name,
- GET_TD_DAYS(self),
- GET_TD_SECONDS(self));
+ if (GET_TD_MICROSECONDS(self) != 0)
+ return PyString_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 PyString_FromFormat("%s(%d, %d)",
+ Py_TYPE(self)->tp_name,
+ GET_TD_DAYS(self),
+ GET_TD_SECONDS(self));
- return PyString_FromFormat("%s(%d)",
- Py_TYPE(self)->tp_name,
- GET_TD_DAYS(self));
+ return PyString_FromFormat("%s(%d)",
+ Py_TYPE(self)->tp_name,
+ GET_TD_DAYS(self));
}
static PyObject *
delta_str(PyDateTime_Delta *self)
{
- int days = GET_TD_DAYS(self);
- int seconds = GET_TD_SECONDS(self);
- int us = GET_TD_MICROSECONDS(self);
- int hours;
- int minutes;
- char buf[100];
- char *pbuf = buf;
- size_t buflen = sizeof(buf);
- int n;
-
- minutes = divmod(seconds, 60, &seconds);
- hours = divmod(minutes, 60, &minutes);
-
- if (days) {
- n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
- (days == 1 || days == -1) ? "" : "s");
- if (n < 0 || (size_t)n >= buflen)
- goto Fail;
- pbuf += n;
- buflen -= (size_t)n;
- }
-
- n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
- hours, minutes, seconds);
- if (n < 0 || (size_t)n >= buflen)
- goto Fail;
- pbuf += n;
- buflen -= (size_t)n;
-
- if (us) {
- n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
- if (n < 0 || (size_t)n >= buflen)
- goto Fail;
- pbuf += n;
- }
-
- return PyString_FromStringAndSize(buf, pbuf - buf);
+ int days = GET_TD_DAYS(self);
+ int seconds = GET_TD_SECONDS(self);
+ int us = GET_TD_MICROSECONDS(self);
+ int hours;
+ int minutes;
+ char buf[100];
+ char *pbuf = buf;
+ size_t buflen = sizeof(buf);
+ int n;
+
+ minutes = divmod(seconds, 60, &seconds);
+ hours = divmod(minutes, 60, &minutes);
+
+ if (days) {
+ n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
+ (days == 1 || days == -1) ? "" : "s");
+ if (n < 0 || (size_t)n >= buflen)
+ goto Fail;
+ pbuf += n;
+ buflen -= (size_t)n;
+ }
+
+ n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
+ hours, minutes, seconds);
+ if (n < 0 || (size_t)n >= buflen)
+ goto Fail;
+ pbuf += n;
+ buflen -= (size_t)n;
+
+ if (us) {
+ n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
+ if (n < 0 || (size_t)n >= buflen)
+ goto Fail;
+ pbuf += n;
+ }
+
+ return PyString_FromStringAndSize(buf, pbuf - buf);
Fail:
- PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
- return NULL;
+ PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
+ return NULL;
}
/* Pickle support, a simple use of __reduce__. */
@@ -2088,124 +2088,124 @@ 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_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[] = {
- {"__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_divide, /* nb_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- (unaryfunc)delta_negative, /* nb_negative */
- (unaryfunc)delta_positive, /* nb_positive */
- (unaryfunc)delta_abs, /* nb_absolute */
- (inquiry)delta_nonzero, /* nb_nonzero */
- 0, /*nb_invert*/
- 0, /*nb_lshift*/
- 0, /*nb_rshift*/
- 0, /*nb_and*/
- 0, /*nb_xor*/
- 0, /*nb_or*/
- 0, /*nb_coerce*/
- 0, /*nb_int*/
- 0, /*nb_long*/
- 0, /*nb_float*/
- 0, /*nb_oct*/
- 0, /*nb_hex*/
- 0, /*nb_inplace_add*/
- 0, /*nb_inplace_subtract*/
- 0, /*nb_inplace_multiply*/
- 0, /*nb_inplace_divide*/
- 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 */
- 0, /* 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_divide, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ (unaryfunc)delta_negative, /* nb_negative */
+ (unaryfunc)delta_positive, /* nb_positive */
+ (unaryfunc)delta_abs, /* nb_absolute */
+ (inquiry)delta_nonzero, /* nb_nonzero */
+ 0, /*nb_invert*/
+ 0, /*nb_lshift*/
+ 0, /*nb_rshift*/
+ 0, /*nb_and*/
+ 0, /*nb_xor*/
+ 0, /*nb_or*/
+ 0, /*nb_coerce*/
+ 0, /*nb_int*/
+ 0, /*nb_long*/
+ 0, /*nb_float*/
+ 0, /*nb_oct*/
+ 0, /*nb_hex*/
+ 0, /*nb_inplace_add*/
+ 0, /*nb_inplace_subtract*/
+ 0, /*nb_inplace_multiply*/
+ 0, /*nb_inplace_divide*/
+ 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 */
+ 0, /* 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_compare */
- (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_CHECKTYPES |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- delta_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)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_compare */
+ (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_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ delta_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)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 */
};
/*
@@ -2217,26 +2217,26 @@ static PyTypeObject PyDateTime_DeltaType = {
static PyObject *
date_year(PyDateTime_Date *self, void *unused)
{
- return PyInt_FromLong(GET_YEAR(self));
+ return PyInt_FromLong(GET_YEAR(self));
}
static PyObject *
date_month(PyDateTime_Date *self, void *unused)
{
- return PyInt_FromLong(GET_MONTH(self));
+ return PyInt_FromLong(GET_MONTH(self));
}
static PyObject *
date_day(PyDateTime_Date *self, void *unused)
{
- return PyInt_FromLong(GET_DAY(self));
+ return PyInt_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. */
@@ -2246,60 +2246,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 &&
- PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
- PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
- MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
- {
- PyDateTime_Date *me;
-
- me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
- if (me != NULL) {
- char *pdata = PyString_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 &&
+ PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
+ PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
+ MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
+ {
+ PyDateTime_Date *me;
+
+ me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
+ if (me != NULL) {
+ char *pdata = PyString_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.
@@ -2310,34 +2310,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
@@ -2346,24 +2346,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;
}
/*
@@ -2376,74 +2376,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;
}
@@ -2452,89 +2452,89 @@ date_subtract(PyObject *left, PyObject *right)
static PyObject *
date_repr(PyDateTime_Date *self)
{
- char buffer[1028];
- const char *type_name;
+ char buffer[1028];
+ const char *type_name;
- type_name = Py_TYPE(self)->tp_name;
- PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
- type_name,
- GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
+ type_name = Py_TYPE(self)->tp_name;
+ PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
+ type_name,
+ GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
- return PyString_FromString(buffer);
+ return PyString_FromString(buffer);
}
static PyObject *
date_isoformat(PyDateTime_Date *self)
{
- char buffer[128];
+ char buffer[128];
- isoformat_date(self, buffer, sizeof(buffer));
- return PyString_FromString(buffer);
+ isoformat_date(self, buffer, sizeof(buffer));
+ return PyString_FromString(buffer);
}
/* 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;
- const char *format;
- Py_ssize_t format_len;
- 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;
+ const char *format;
+ Py_ssize_t format_len;
+ static char *keywords[] = {"format", NULL};
- if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
- &format, &format_len))
- return NULL;
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
+ &format, &format_len))
+ return NULL;
- tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
- if (tuple == NULL)
- return NULL;
- result = wrap_strftime((PyObject *)self, format, format_len, 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, format_len, tuple,
+ (PyObject *)self);
+ Py_DECREF(tuple);
+ return result;
}
static PyObject *
date_format(PyDateTime_Date *self, PyObject *args)
{
- PyObject *format;
-
- if (!PyArg_ParseTuple(args, "O:__format__", &format))
- return NULL;
-
- /* Check for str or unicode */
- if (PyString_Check(format)) {
- /* If format is zero length, return str(self) */
- if (PyString_GET_SIZE(format) == 0)
- return PyObject_Str((PyObject *)self);
- } else if (PyUnicode_Check(format)) {
- /* If format is zero length, return str(self) */
- if (PyUnicode_GET_SIZE(format) == 0)
- return PyObject_Unicode((PyObject *)self);
- } else {
- PyErr_Format(PyExc_ValueError,
- "__format__ expects str or unicode, not %.200s",
- Py_TYPE(format)->tp_name);
- return NULL;
- }
- return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
+ PyObject *format;
+
+ if (!PyArg_ParseTuple(args, "O:__format__", &format))
+ return NULL;
+
+ /* Check for str or unicode */
+ if (PyString_Check(format)) {
+ /* If format is zero length, return str(self) */
+ if (PyString_GET_SIZE(format) == 0)
+ return PyObject_Str((PyObject *)self);
+ } else if (PyUnicode_Check(format)) {
+ /* If format is zero length, return str(self) */
+ if (PyUnicode_GET_SIZE(format) == 0)
+ return PyObject_Unicode((PyObject *)self);
+ } else {
+ PyErr_Format(PyExc_ValueError,
+ "__format__ expects str or unicode, not %.200s",
+ Py_TYPE(format)->tp_name);
+ return NULL;
+ }
+ return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
}
/* ISO methods. */
@@ -2542,31 +2542,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 PyInt_FromLong(dow + 1);
+ return PyInt_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. */
@@ -2578,53 +2578,53 @@ date_isocalendar(PyDateTime_Date *self)
static PyObject *
date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
{
- int diff = 42; /* nonsense */
+ int diff = 42; /* nonsense */
- if (PyDate_Check(other))
- diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
- _PyDateTime_DATE_DATASIZE);
+ if (PyDate_Check(other))
+ diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
+ _PyDateTime_DATE_DATASIZE);
- else if (PyObject_HasAttrString(other, "timetuple")) {
- /* A hook for other kinds of date objects. */
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- else if (op == Py_EQ || op == Py_NE)
- diff = 1; /* any non-zero value will do */
+ else if (PyObject_HasAttrString(other, "timetuple")) {
+ /* A hook for other kinds of date objects. */
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ else if (op == Py_EQ || op == Py_NE)
+ diff = 1; /* any non-zero value will do */
- else /* stop this from falling back to address comparison */
- return cmperror((PyObject *)self, other);
+ else /* stop this from falling back to address comparison */
+ return cmperror((PyObject *)self, other);
- return diff_to_bool(diff, op);
+ return diff_to_bool(diff, op);
}
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;
}
static PyObject *date_getstate(PyDateTime_Date *self);
@@ -2632,29 +2632,29 @@ static PyObject *date_getstate(PyDateTime_Date *self);
static long
date_hash(PyDateTime_Date *self)
{
- if (self->hashcode == -1) {
- PyObject *temp = date_getstate(self);
- if (temp != NULL) {
- self->hashcode = PyObject_Hash(temp);
- Py_DECREF(temp);
- }
- }
- return self->hashcode;
+ if (self->hashcode == -1) {
+ PyObject *temp = date_getstate(self);
+ if (temp != NULL) {
+ self->hashcode = PyObject_Hash(temp);
+ Py_DECREF(temp);
+ }
+ }
+ return self->hashcode;
}
static PyObject *
date_toordinal(PyDateTime_Date *self)
{
- return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
- GET_DAY(self)));
+ return PyInt_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 PyInt_FromLong(dow);
+ return PyInt_FromLong(dow);
}
/* Pickle support, a simple use of __reduce__. */
@@ -2663,136 +2663,136 @@ date_weekday(PyDateTime_Date *self)
static PyObject *
date_getstate(PyDateTime_Date *self)
{
- return Py_BuildValue(
- "(N)",
- PyString_FromStringAndSize((char *)self->data,
- _PyDateTime_DATE_DATASIZE));
+ return Py_BuildValue(
+ "(N)",
+ PyString_FromStringAndSize((char *)self->data,
+ _PyDateTime_DATE_DATASIZE));
}
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_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- 0, /* nb_nonzero */
+ date_add, /* nb_add */
+ date_subtract, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ 0, /* nb_nonzero */
};
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_compare */
- (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_CHECKTYPES |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- date_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)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_compare */
+ (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_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ date_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)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 */
};
/*
@@ -2815,10 +2815,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. */
@@ -2826,101 +2826,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;
}
/*
@@ -2931,124 +2931,124 @@ 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.");
statichere PyTypeObject PyDateTime_TZInfoType = {
- PyObject_HEAD_INIT(NULL)
- 0, /* ob_size */
- "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_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 */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
- 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 */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* ob_size */
+ "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_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 */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
+ 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 */
};
/*
@@ -3061,43 +3061,43 @@ statichere PyTypeObject PyDateTime_TZInfoType = {
static PyObject *
time_hour(PyDateTime_Time *self, void *unused)
{
- return PyInt_FromLong(TIME_GET_HOUR(self));
+ return PyInt_FromLong(TIME_GET_HOUR(self));
}
static PyObject *
time_minute(PyDateTime_Time *self, void *unused)
{
- return PyInt_FromLong(TIME_GET_MINUTE(self));
+ return PyInt_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 PyInt_FromLong(TIME_GET_SECOND(self));
+ return PyInt_FromLong(TIME_GET_SECOND(self));
}
static PyObject *
time_microsecond(PyDateTime_Time *self, void *unused)
{
- return PyInt_FromLong(TIME_GET_MICROSECOND(self));
+ return PyInt_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}
};
/*
@@ -3105,64 +3105,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 &&
- PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
- PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
- ((unsigned char) (PyString_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 = PyString_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 &&
+ PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
+ PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
+ ((unsigned char) (PyString_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 = PyString_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;
}
/*
@@ -3172,10 +3172,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);
}
/*
@@ -3185,20 +3185,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);
}
/*
@@ -3208,94 +3208,94 @@ time_tzname(PyDateTime_Time *self, PyObject *unused) {
static PyObject *
time_repr(PyDateTime_Time *self)
{
- char buffer[100];
- 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)
- PyOS_snprintf(buffer, sizeof(buffer),
- "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
- else if (s)
- PyOS_snprintf(buffer, sizeof(buffer),
- "%s(%d, %d, %d)", type_name, h, m, s);
- else
- PyOS_snprintf(buffer, sizeof(buffer),
- "%s(%d, %d)", type_name, h, m);
- result = PyString_FromString(buffer);
- if (result != NULL && HASTZINFO(self))
- result = append_keyword_tzinfo(result, self->tzinfo);
- return result;
+ char buffer[100];
+ 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)
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
+ else if (s)
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "%s(%d, %d, %d)", type_name, h, m, s);
+ else
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "%s(%d, %d)", type_name, h, m);
+ result = PyString_FromString(buffer);
+ 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;
- /* Reuse the time format code from the datetime type. */
- PyDateTime_DateTime datetime;
- PyDateTime_DateTime *pdatetime = &datetime;
+ char buf[100];
+ PyObject *result;
+ /* Reuse the time format code from the datetime type. */
+ PyDateTime_DateTime datetime;
+ PyDateTime_DateTime *pdatetime = &datetime;
- /* Copy over just the time bytes. */
- memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
- self->data,
- _PyDateTime_TIME_DATASIZE);
+ /* Copy over just the time bytes. */
+ memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
+ self->data,
+ _PyDateTime_TIME_DATASIZE);
- isoformat_time(pdatetime, buf, sizeof(buf));
- result = PyString_FromString(buf);
- if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
- return result;
+ isoformat_time(pdatetime, buf, sizeof(buf));
+ result = PyString_FromString(buf);
+ 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;
- }
- PyString_ConcatAndDel(&result, PyString_FromString(buf));
- 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;
+ }
+ PyString_ConcatAndDel(&result, PyString_FromString(buf));
+ return result;
}
static PyObject *
time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
{
- PyObject *result;
- PyObject *tuple;
- const char *format;
- Py_ssize_t format_len;
- static char *keywords[] = {"format", NULL};
-
- if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
- &format, &format_len))
- 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, format_len, tuple,
- Py_None);
- Py_DECREF(tuple);
- return result;
+ PyObject *result;
+ PyObject *tuple;
+ const char *format;
+ Py_ssize_t format_len;
+ static char *keywords[] = {"format", NULL};
+
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
+ &format, &format_len))
+ 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, format_len, tuple,
+ Py_None);
+ Py_DECREF(tuple);
+ return result;
}
/*
@@ -3309,146 +3309,146 @@ time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
static PyObject *
time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
{
- int diff;
- naivety n1, n2;
- int offset1, offset2;
-
- if (! PyTime_Check(other)) {
- if (op == Py_EQ || op == Py_NE) {
- PyObject *result = op == Py_EQ ? Py_False : Py_True;
- Py_INCREF(result);
- return result;
- }
- /* Stop this from falling back to address comparison. */
- return cmperror((PyObject *)self, other);
- }
- if (classify_two_utcoffsets((PyObject *)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(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)) {
+ if (op == Py_EQ || op == Py_NE) {
+ PyObject *result = op == Py_EQ ? Py_False : Py_True;
+ Py_INCREF(result);
+ return result;
+ }
+ /* Stop this from falling back to address comparison. */
+ return cmperror((PyObject *)self, other);
+ }
+ if (classify_two_utcoffsets((PyObject *)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(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)
- temp = PyString_FromStringAndSize((char *)self->data,
- _PyDateTime_TIME_DATASIZE);
- 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)
+ temp = PyString_FromStringAndSize((char *)self->data,
+ _PyDateTime_TIME_DATASIZE);
+ 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_nonzero(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__. */
@@ -3461,55 +3461,55 @@ time_nonzero(PyDateTime_Time *self)
static PyObject *
time_getstate(PyDateTime_Time *self)
{
- PyObject *basestate;
- PyObject *result = NULL;
+ PyObject *basestate;
+ PyObject *result = NULL;
- basestate = PyString_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 = PyString_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[] =
@@ -3519,61 +3519,61 @@ 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_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- (inquiry)time_nonzero, /* nb_nonzero */
+ 0, /* nb_add */
+ 0, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ (inquiry)time_nonzero, /* nb_nonzero */
};
statichere PyTypeObject PyDateTime_TimeType = {
- PyObject_HEAD_INIT(NULL)
- 0, /* ob_size */
- "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_compare */
- (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_CHECKTYPES |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- time_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)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 */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* ob_size */
+ "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_compare */
+ (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_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ time_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)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 */
};
/*
@@ -3587,42 +3587,42 @@ statichere PyTypeObject PyDateTime_TimeType = {
static PyObject *
datetime_hour(PyDateTime_DateTime *self, void *unused)
{
- return PyInt_FromLong(DATE_GET_HOUR(self));
+ return PyInt_FromLong(DATE_GET_HOUR(self));
}
static PyObject *
datetime_minute(PyDateTime_DateTime *self, void *unused)
{
- return PyInt_FromLong(DATE_GET_MINUTE(self));
+ return PyInt_FromLong(DATE_GET_MINUTE(self));
}
static PyObject *
datetime_second(PyDateTime_DateTime *self, void *unused)
{
- return PyInt_FromLong(DATE_GET_SECOND(self));
+ return PyInt_FromLong(DATE_GET_SECOND(self));
}
static PyObject *
datetime_microsecond(PyDateTime_DateTime *self, void *unused)
{
- return PyInt_FromLong(DATE_GET_MICROSECOND(self));
+ return PyInt_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}
};
/*
@@ -3630,72 +3630,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 &&
- PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
- PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
- MONTH_IS_SANE(PyString_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 = PyString_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 &&
+ PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
+ PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
+ MONTH_IS_SANE(PyString_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 = PyString_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(). */
@@ -3707,36 +3707,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.
@@ -3748,31 +3748,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.
@@ -3783,36 +3783,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
@@ -3821,26 +3821,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
@@ -3849,147 +3849,147 @@ 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 char *string, *format;
-
- if (!PyArg_ParseTuple(args, "ss: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", "ss", 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 (PyInt_Check(p))
- ia[i] = PyInt_AsLong(p);
- else
- good_timetuple = 0;
- Py_DECREF(p);
- }
- }
- else
- good_timetuple = 0;
- /* follow that up with a little dose of microseconds */
- if (PyInt_Check(frac))
- ia[6] = PyInt_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 char *string, *format;
+
+ if (!PyArg_ParseTuple(args, "ss: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", "ss", 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 (PyInt_Check(p))
+ ia[i] = PyInt_AsLong(p);
+ else
+ good_timetuple = 0;
+ Py_DECREF(p);
+ }
+ }
+ else
+ good_timetuple = 0;
+ /* follow that up with a little dose of microseconds */
+ if (PyInt_Check(frac))
+ ia[6] = PyInt_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;
}
/*
@@ -3999,10 +3999,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);
}
/*
@@ -4012,20 +4012,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);
}
/*
@@ -4037,112 +4037,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. */
@@ -4150,83 +4150,83 @@ datetime_subtract(PyObject *left, PyObject *right)
static PyObject *
datetime_repr(PyDateTime_DateTime *self)
{
- char buffer[1000];
- const char *type_name = Py_TYPE(self)->tp_name;
- PyObject *baserepr;
-
- if (DATE_GET_MICROSECOND(self)) {
- PyOS_snprintf(buffer, sizeof(buffer),
- "%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)) {
- PyOS_snprintf(buffer, sizeof(buffer),
- "%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 {
- PyOS_snprintf(buffer, sizeof(buffer),
- "%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));
- }
- baserepr = PyString_FromString(buffer);
- if (baserepr == NULL || ! HASTZINFO(self))
- return baserepr;
- return append_keyword_tzinfo(baserepr, self->tzinfo);
+ char buffer[1000];
+ const char *type_name = Py_TYPE(self)->tp_name;
+ PyObject *baserepr;
+
+ if (DATE_GET_MICROSECOND(self)) {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "%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)) {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "%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 {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "%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));
+ }
+ baserepr = PyString_FromString(buffer);
+ 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)
{
- char sep = 'T';
- static char *keywords[] = {"sep", NULL};
- char buffer[100];
- char *cp;
- PyObject *result;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
- &sep))
- return NULL;
- cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
- assert(cp != NULL);
- *cp++ = sep;
- cp = isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
- result = PyString_FromStringAndSize(buffer, cp - buffer);
- if (result == NULL || ! 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;
- }
- PyString_ConcatAndDel(&result, PyString_FromString(buffer));
- return result;
+ char sep = 'T';
+ static char *keywords[] = {"sep", NULL};
+ char buffer[100];
+ char *cp;
+ PyObject *result;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
+ &sep))
+ return NULL;
+ cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
+ assert(cp != NULL);
+ *cp++ = sep;
+ cp = isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
+ result = PyString_FromStringAndSize(buffer, cp - buffer);
+ if (result == NULL || ! 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;
+ }
+ PyString_ConcatAndDel(&result, PyString_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. */
@@ -4238,298 +4238,298 @@ datetime_ctime(PyDateTime_DateTime *self)
static PyObject *
datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
{
- int diff;
- naivety n1, n2;
- int offset1, offset2;
-
- if (! PyDateTime_Check(other)) {
- /* If other has a "timetuple" attr, that's an advertised
- * hook for other classes to ask to get comparison control.
- * However, date instances have a timetuple attr, and we
- * don't want to allow that comparison. Because datetime
- * is a subclass of date, when mixing date and datetime
- * in a comparison, Python gives datetime the first shot
- * (it's the more specific subtype). So we can stop that
- * combination here reliably.
- */
- if (PyObject_HasAttrString(other, "timetuple") &&
- ! PyDate_Check(other)) {
- /* A hook for other kinds of datetime objects. */
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- if (op == Py_EQ || op == Py_NE) {
- PyObject *result = op == Py_EQ ? Py_False : Py_True;
- Py_INCREF(result);
- return result;
- }
- /* Stop this from falling back to address comparison. */
- return cmperror((PyObject *)self, other);
- }
-
- if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1,
- (PyObject *)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(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 other has a "timetuple" attr, that's an advertised
+ * hook for other classes to ask to get comparison control.
+ * However, date instances have a timetuple attr, and we
+ * don't want to allow that comparison. Because datetime
+ * is a subclass of date, when mixing date and datetime
+ * in a comparison, Python gives datetime the first shot
+ * (it's the more specific subtype). So we can stop that
+ * combination here reliably.
+ */
+ if (PyObject_HasAttrString(other, "timetuple") &&
+ ! PyDate_Check(other)) {
+ /* A hook for other kinds of datetime objects. */
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ if (op == Py_EQ || op == Py_NE) {
+ PyObject *result = op == Py_EQ ? Py_False : Py_True;
+ Py_INCREF(result);
+ return result;
+ }
+ /* Stop this from falling back to address comparison. */
+ return cmperror((PyObject *)self, other);
+ }
+
+ if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1,
+ (PyObject *)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(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)
- temp = PyString_FromStringAndSize(
- (char *)self->data,
- _PyDateTime_DATETIME_DATASIZE);
- 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)
+ temp = PyString_FromStringAndSize(
+ (char *)self->data,
+ _PyDateTime_DATETIME_DATASIZE);
+ 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__. */
@@ -4542,102 +4542,102 @@ datetime_utctimetuple(PyDateTime_DateTime *self)
static PyObject *
datetime_getstate(PyDateTime_DateTime *self)
{
- PyObject *basestate;
- PyObject *result = NULL;
+ PyObject *basestate;
+ PyObject *result = NULL;
- basestate = PyString_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 = PyString_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[] =
@@ -4647,61 +4647,61 @@ 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_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- 0, /* nb_nonzero */
+ datetime_add, /* nb_add */
+ datetime_subtract, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ 0, /* nb_nonzero */
};
statichere PyTypeObject PyDateTime_DateTimeType = {
- PyObject_HEAD_INIT(NULL)
- 0, /* ob_size */
- "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_compare */
- (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_CHECKTYPES |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- datetime_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)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 */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* ob_size */
+ "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_compare */
+ (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_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ datetime_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)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 */
};
/* ---------------------------------------------------------------------------
@@ -4709,192 +4709,192 @@ statichere 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
};
PyMODINIT_FUNC
initdatetime(void)
{
- PyObject *m; /* a module object */
- PyObject *d; /* its dict */
- PyObject *x;
-
- m = Py_InitModule3("datetime", module_methods,
- "Fast implementation of the datetime type.");
- if (m == NULL)
- return;
-
- if (PyType_Ready(&PyDateTime_DateType) < 0)
- return;
- if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
- return;
- if (PyType_Ready(&PyDateTime_DeltaType) < 0)
- return;
- if (PyType_Ready(&PyDateTime_TimeType) < 0)
- return;
- if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
- return;
-
- /* timedelta values */
- d = PyDateTime_DeltaType.tp_dict;
-
- x = new_delta(0, 0, 1, 0);
- if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
- return;
- Py_DECREF(x);
-
- x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
- if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
- return;
- 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;
- 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;
- Py_DECREF(x);
-
- x = new_date(MAXYEAR, 12, 31);
- if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
- return;
- Py_DECREF(x);
-
- x = new_delta(1, 0, 0, 0);
- if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
- return;
- 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;
- Py_DECREF(x);
-
- x = new_time(23, 59, 59, 999999, Py_None);
- if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
- return;
- Py_DECREF(x);
-
- x = new_delta(0, 0, 1, 0);
- if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
- return;
- 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;
- 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;
- Py_DECREF(x);
-
- x = new_delta(0, 0, 1, 0);
- if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
- return;
- 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 = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
- NULL);
- if (x == NULL)
- return;
- 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 = PyInt_FromLong(1);
- us_per_ms = PyInt_FromLong(1000);
- us_per_second = PyInt_FromLong(1000000);
- us_per_minute = PyInt_FromLong(60000000);
- seconds_per_day = PyInt_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;
-
- /* 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;
+ PyObject *m; /* a module object */
+ PyObject *d; /* its dict */
+ PyObject *x;
+
+ m = Py_InitModule3("datetime", module_methods,
+ "Fast implementation of the datetime type.");
+ if (m == NULL)
+ return;
+
+ if (PyType_Ready(&PyDateTime_DateType) < 0)
+ return;
+ if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
+ return;
+ if (PyType_Ready(&PyDateTime_DeltaType) < 0)
+ return;
+ if (PyType_Ready(&PyDateTime_TimeType) < 0)
+ return;
+ if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
+ return;
+
+ /* timedelta values */
+ d = PyDateTime_DeltaType.tp_dict;
+
+ x = new_delta(0, 0, 1, 0);
+ if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
+ if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
+ return;
+ 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;
+ 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;
+ Py_DECREF(x);
+
+ x = new_date(MAXYEAR, 12, 31);
+ if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ x = new_delta(1, 0, 0, 0);
+ if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
+ return;
+ 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;
+ Py_DECREF(x);
+
+ x = new_time(23, 59, 59, 999999, Py_None);
+ if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ x = new_delta(0, 0, 1, 0);
+ if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
+ return;
+ 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;
+ 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;
+ Py_DECREF(x);
+
+ x = new_delta(0, 0, 1, 0);
+ if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
+ return;
+ 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 = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
+ NULL);
+ if (x == NULL)
+ return;
+ 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 = PyInt_FromLong(1);
+ us_per_ms = PyInt_FromLong(1000);
+ us_per_second = PyInt_FromLong(1000000);
+ us_per_minute = PyInt_FromLong(60000000);
+ seconds_per_day = PyInt_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;
+
+ /* 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;
}
/* ---------------------------------------------------------------------------
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).
@@ -5016,13 +5016,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/dbmmodule.c b/Modules/dbmmodule.c
index 0c50b54..f9c99a8 100644
--- a/Modules/dbmmodule.c
+++ b/Modules/dbmmodule.c
@@ -32,9 +32,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;
@@ -49,18 +49,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 */
@@ -68,119 +68,119 @@ 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;
- int 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_SetString(PyExc_KeyError,
- PyString_AS_STRING((PyStringObject *)key));
- return NULL;
- }
- if ( dbm_error(dp->di_dbm) ) {
- dbm_clearerr(dp->di_dbm);
- PyErr_SetString(DbmError, "");
- return NULL;
- }
- return PyString_FromStringAndSize(drec.dptr, drec.dsize);
+ datum drec, krec;
+ int 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_SetString(PyExc_KeyError,
+ PyString_AS_STRING((PyStringObject *)key));
+ return NULL;
+ }
+ if ( dbm_error(dp->di_dbm) ) {
+ dbm_clearerr(dp->di_dbm);
+ PyErr_SetString(DbmError, "");
+ return NULL;
+ }
+ return PyString_FromStringAndSize(drec.dptr, drec.dsize);
}
static int
dbm_ass_sub(dbmobject *dp, PyObject *v, PyObject *w)
{
- datum krec, drec;
- int tmp_size;
-
- if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) {
- PyErr_SetString(PyExc_TypeError,
- "dbm mappings have string indices 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;
+ int tmp_size;
+
+ if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) {
+ PyErr_SetString(PyExc_TypeError,
+ "dbm mappings have string indices 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_SetString(PyExc_KeyError,
+ PyString_AS_STRING((PyStringObject *)v));
+ return -1;
+ }
+ } else {
+ if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) {
+ PyErr_SetString(PyExc_TypeError,
+ "dbm mappings have 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_SetString(PyExc_KeyError,
- PyString_AS_STRING((PyStringObject *)v));
- return -1;
- }
- } else {
- if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) {
- PyErr_SetString(PyExc_TypeError,
- "dbm mappings have 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 int
dbm_contains(register dbmobject *dp, PyObject *v)
{
- datum key, val;
-
- if (PyString_AsStringAndSize(v, (char **)&key.dptr,
- (Py_ssize_t *)&key.dsize)) {
- return -1;
- }
-
- /* Expand check_dbmobject_open to return -1 */
- if (dp->di_dbm == NULL) {
- PyErr_SetString(DbmError, "DBM object has already been closed");
- return -1;
- }
- val = dbm_fetch(dp->di_dbm, key);
- return val.dptr != NULL;
+ datum key, val;
+
+ if (PyString_AsStringAndSize(v, (char **)&key.dptr,
+ (Py_ssize_t *)&key.dsize)) {
+ return -1;
+ }
+
+ /* Expand check_dbmobject_open to return -1 */
+ if (dp->di_dbm == NULL) {
+ PyErr_SetString(DbmError, "DBM object has already been closed");
+ return -1;
+ }
+ val = dbm_fetch(dp->di_dbm, key);
+ return val.dptr != NULL;
}
static PySequenceMethods dbm_as_sequence = {
@@ -197,159 +197,159 @@ static PySequenceMethods dbm_as_sequence = {
};
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 = PyString_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 = PyString_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 PyObject *
dbm_has_key(register dbmobject *dp, PyObject *args)
{
- char *tmp_ptr;
- datum key, val;
- int tmp_size;
-
- if (!PyArg_ParseTuple(args, "s#:has_key", &tmp_ptr, &tmp_size))
- return NULL;
- key.dptr = tmp_ptr;
- key.dsize = tmp_size;
- check_dbmobject_open(dp);
- val = dbm_fetch(dp->di_dbm, key);
- return PyInt_FromLong(val.dptr != NULL);
+ char *tmp_ptr;
+ datum key, val;
+ int tmp_size;
+
+ if (!PyArg_ParseTuple(args, "s#:has_key", &tmp_ptr, &tmp_size))
+ return NULL;
+ key.dptr = tmp_ptr;
+ key.dsize = tmp_size;
+ check_dbmobject_open(dp);
+ val = dbm_fetch(dp->di_dbm, key);
+ return PyInt_FromLong(val.dptr != NULL);
}
static PyObject *
dbm_get(register dbmobject *dp, PyObject *args)
{
- datum key, val;
- PyObject *defvalue = Py_None;
- char *tmp_ptr;
- int 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 PyString_FromStringAndSize(val.dptr, val.dsize);
- else {
- Py_INCREF(defvalue);
- return defvalue;
- }
+ datum key, val;
+ PyObject *defvalue = Py_None;
+ char *tmp_ptr;
+ int 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 PyString_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;
- int tmp_size;
-
- if (!PyArg_ParseTuple(args, "s#|S: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 PyString_FromStringAndSize(val.dptr, val.dsize);
- if (defvalue == NULL) {
- defvalue = PyString_FromStringAndSize(NULL, 0);
- if (defvalue == NULL)
- return NULL;
- }
- else
- Py_INCREF(defvalue);
- val.dptr = PyString_AS_STRING(defvalue);
- val.dsize = PyString_GET_SIZE(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");
- return NULL;
- }
- return defvalue;
+ datum key, val;
+ PyObject *defvalue = NULL;
+ char *tmp_ptr;
+ int tmp_size;
+
+ if (!PyArg_ParseTuple(args, "s#|S: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 PyString_FromStringAndSize(val.dptr, val.dsize);
+ if (defvalue == NULL) {
+ defvalue = PyString_FromStringAndSize(NULL, 0);
+ if (defvalue == NULL)
+ return NULL;
+ }
+ else
+ Py_INCREF(defvalue);
+ val.dptr = PyString_AS_STRING(defvalue);
+ val.dsize = PyString_GET_SIZE(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");
+ 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."},
- {"has_key", (PyCFunction)dbm_has_key, METH_VARARGS,
- "has_key(key} -> boolean\nReturn true iff key is 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."},
+ {"has_key", (PyCFunction)dbm_has_key, METH_VARARGS,
+ "has_key(key} -> boolean\nReturn true iff key is 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 PyObject *
dbm_getattr(dbmobject *dp, char *name)
{
- return Py_FindMethod(dbm_methods, (PyObject *)dp, name);
+ return Py_FindMethod(dbm_methods, (PyObject *)dp, name);
}
static PyTypeObject Dbmtype = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "dbm.dbm",
- sizeof(dbmobject),
- 0,
- (destructor)dbm_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)dbm_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "dbm.dbm",
+ sizeof(dbmobject),
+ 0,
+ (destructor)dbm_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)dbm_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
&dbm_as_sequence, /*tp_as_sequence*/
- &dbm_as_mapping, /*tp_as_mapping*/
+ &dbm_as_mapping, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
@@ -364,54 +364,54 @@ 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 },
};
PyMODINIT_FUNC
initdbm(void) {
- PyObject *m, *d, *s;
-
- Dbmtype.ob_type = &PyType_Type;
- m = Py_InitModule("dbm", dbmmodule_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- if (DbmError == NULL)
- DbmError = PyErr_NewException("dbm.error", NULL, NULL);
- s = PyString_FromString(which_dbm);
- if (s != NULL) {
- PyDict_SetItemString(d, "library", s);
- Py_DECREF(s);
- }
- if (DbmError != NULL)
- PyDict_SetItemString(d, "error", DbmError);
+ PyObject *m, *d, *s;
+
+ Dbmtype.ob_type = &PyType_Type;
+ m = Py_InitModule("dbm", dbmmodule_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ if (DbmError == NULL)
+ DbmError = PyErr_NewException("dbm.error", NULL, NULL);
+ s = PyString_FromString(which_dbm);
+ if (s != NULL) {
+ PyDict_SetItemString(d, "library", s);
+ Py_DECREF(s);
+ }
+ if (DbmError != NULL)
+ PyDict_SetItemString(d, "error", DbmError);
}
diff --git a/Modules/dlmodule.c b/Modules/dlmodule.c
index b2ea4f5..c349ad0 100644
--- a/Modules/dlmodule.c
+++ b/Modules/dlmodule.c
@@ -15,8 +15,8 @@
typedef void *PyUnivPtr;
typedef struct {
- PyObject_HEAD
- PyUnivPtr *dl_handle;
+ PyObject_HEAD
+ PyUnivPtr *dl_handle;
} dlobject;
static PyTypeObject Dltype;
@@ -26,196 +26,196 @@ static PyObject *Dlerror;
static PyObject *
newdlobject(PyUnivPtr *handle)
{
- dlobject *xp;
- xp = PyObject_New(dlobject, &Dltype);
- if (xp == NULL)
- return NULL;
- xp->dl_handle = handle;
- return (PyObject *)xp;
+ dlobject *xp;
+ xp = PyObject_New(dlobject, &Dltype);
+ if (xp == NULL)
+ return NULL;
+ xp->dl_handle = handle;
+ return (PyObject *)xp;
}
static void
dl_dealloc(dlobject *xp)
{
- if (xp->dl_handle != NULL)
- dlclose(xp->dl_handle);
- PyObject_Del(xp);
+ if (xp->dl_handle != NULL)
+ dlclose(xp->dl_handle);
+ PyObject_Del(xp);
}
static PyObject *
dl_close(dlobject *xp)
{
- if (xp->dl_handle != NULL) {
- dlclose(xp->dl_handle);
- xp->dl_handle = NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (xp->dl_handle != NULL) {
+ dlclose(xp->dl_handle);
+ xp->dl_handle = NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
dl_sym(dlobject *xp, PyObject *args)
{
- char *name;
- PyUnivPtr *func;
- if (PyString_Check(args)) {
- name = PyString_AS_STRING(args);
- } else {
- PyErr_Format(PyExc_TypeError, "expected string, found %.200s",
- Py_TYPE(args)->tp_name);
- return NULL;
- }
- func = dlsym(xp->dl_handle, name);
- if (func == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyInt_FromLong((long)func);
+ char *name;
+ PyUnivPtr *func;
+ if (PyString_Check(args)) {
+ name = PyString_AS_STRING(args);
+ } else {
+ PyErr_Format(PyExc_TypeError, "expected string, found %.200s",
+ Py_TYPE(args)->tp_name);
+ return NULL;
+ }
+ func = dlsym(xp->dl_handle, name);
+ if (func == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyInt_FromLong((long)func);
}
static PyObject *
dl_call(dlobject *xp, PyObject *args)
{
- PyObject *name;
- long (*func)(long, long, long, long, long,
- long, long, long, long, long);
- long alist[10];
- long res;
- Py_ssize_t i;
- Py_ssize_t n = PyTuple_Size(args);
- if (n < 1) {
- PyErr_SetString(PyExc_TypeError, "at least a name is needed");
- return NULL;
- }
- name = PyTuple_GetItem(args, 0);
- if (!PyString_Check(name)) {
- PyErr_SetString(PyExc_TypeError,
- "function name must be a string");
- return NULL;
- }
- func = (long (*)(long, long, long, long, long,
- long, long, long, long, long))
- dlsym(xp->dl_handle, PyString_AsString(name));
- if (func == NULL) {
- PyErr_SetString(PyExc_ValueError, dlerror());
- return NULL;
- }
- if (n-1 > 10) {
- PyErr_SetString(PyExc_TypeError,
- "too many arguments (max 10)");
- return NULL;
- }
- for (i = 1; i < n; i++) {
- PyObject *v = PyTuple_GetItem(args, i);
- if (PyInt_Check(v))
- alist[i-1] = PyInt_AsLong(v);
- else if (PyString_Check(v))
- alist[i-1] = (long)PyString_AsString(v);
- else if (v == Py_None)
- alist[i-1] = (long) ((char *)NULL);
- else {
- PyErr_SetString(PyExc_TypeError,
- "arguments must be int, string or None");
- return NULL;
- }
- }
- for (; i <= 10; i++)
- alist[i-1] = 0;
- res = (*func)(alist[0], alist[1], alist[2], alist[3], alist[4],
- alist[5], alist[6], alist[7], alist[8], alist[9]);
- return PyInt_FromLong(res);
+ PyObject *name;
+ long (*func)(long, long, long, long, long,
+ long, long, long, long, long);
+ long alist[10];
+ long res;
+ Py_ssize_t i;
+ Py_ssize_t n = PyTuple_Size(args);
+ if (n < 1) {
+ PyErr_SetString(PyExc_TypeError, "at least a name is needed");
+ return NULL;
+ }
+ name = PyTuple_GetItem(args, 0);
+ if (!PyString_Check(name)) {
+ PyErr_SetString(PyExc_TypeError,
+ "function name must be a string");
+ return NULL;
+ }
+ func = (long (*)(long, long, long, long, long,
+ long, long, long, long, long))
+ dlsym(xp->dl_handle, PyString_AsString(name));
+ if (func == NULL) {
+ PyErr_SetString(PyExc_ValueError, dlerror());
+ return NULL;
+ }
+ if (n-1 > 10) {
+ PyErr_SetString(PyExc_TypeError,
+ "too many arguments (max 10)");
+ return NULL;
+ }
+ for (i = 1; i < n; i++) {
+ PyObject *v = PyTuple_GetItem(args, i);
+ if (PyInt_Check(v))
+ alist[i-1] = PyInt_AsLong(v);
+ else if (PyString_Check(v))
+ alist[i-1] = (long)PyString_AsString(v);
+ else if (v == Py_None)
+ alist[i-1] = (long) ((char *)NULL);
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "arguments must be int, string or None");
+ return NULL;
+ }
+ }
+ for (; i <= 10; i++)
+ alist[i-1] = 0;
+ res = (*func)(alist[0], alist[1], alist[2], alist[3], alist[4],
+ alist[5], alist[6], alist[7], alist[8], alist[9]);
+ return PyInt_FromLong(res);
}
static PyMethodDef dlobject_methods[] = {
- {"call", (PyCFunction)dl_call, METH_VARARGS},
- {"sym", (PyCFunction)dl_sym, METH_O},
- {"close", (PyCFunction)dl_close, METH_NOARGS},
- {NULL, NULL} /* Sentinel */
+ {"call", (PyCFunction)dl_call, METH_VARARGS},
+ {"sym", (PyCFunction)dl_sym, METH_O},
+ {"close", (PyCFunction)dl_close, METH_NOARGS},
+ {NULL, NULL} /* Sentinel */
};
static PyObject *
dl_getattr(dlobject *xp, char *name)
{
- return Py_FindMethod(dlobject_methods, (PyObject *)xp, name);
+ return Py_FindMethod(dlobject_methods, (PyObject *)xp, name);
}
static PyTypeObject Dltype = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "dl.dl", /*tp_name*/
- sizeof(dlobject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)dl_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)dl_getattr,/*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*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "dl.dl", /*tp_name*/
+ sizeof(dlobject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)dl_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)dl_getattr,/*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*/
};
static PyObject *
dl_open(PyObject *self, PyObject *args)
{
- char *name;
- int mode;
- PyUnivPtr *handle;
- if (sizeof(int) != sizeof(long) ||
- sizeof(long) != sizeof(char *)) {
- PyErr_SetString(PyExc_SystemError,
+ char *name;
+ int mode;
+ PyUnivPtr *handle;
+ if (sizeof(int) != sizeof(long) ||
+ sizeof(long) != sizeof(char *)) {
+ PyErr_SetString(PyExc_SystemError,
"module dl requires sizeof(int) == sizeof(long) == sizeof(char*)");
- return NULL;
- }
+ return NULL;
+ }
- if (PyArg_ParseTuple(args, "z:open", &name))
- mode = RTLD_LAZY;
- else {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "zi:open", &name, &mode))
- return NULL;
+ if (PyArg_ParseTuple(args, "z:open", &name))
+ mode = RTLD_LAZY;
+ else {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "zi:open", &name, &mode))
+ return NULL;
#ifndef RTLD_NOW
- if (mode != RTLD_LAZY) {
- PyErr_SetString(PyExc_ValueError, "mode must be 1");
- return NULL;
- }
+ if (mode != RTLD_LAZY) {
+ PyErr_SetString(PyExc_ValueError, "mode must be 1");
+ return NULL;
+ }
#endif
- }
- handle = dlopen(name, mode);
- if (handle == NULL) {
- char *errmsg = dlerror();
- if (!errmsg)
- errmsg = "dlopen() error";
- PyErr_SetString(Dlerror, errmsg);
- return NULL;
- }
+ }
+ handle = dlopen(name, mode);
+ if (handle == NULL) {
+ char *errmsg = dlerror();
+ if (!errmsg)
+ errmsg = "dlopen() error";
+ PyErr_SetString(Dlerror, errmsg);
+ return NULL;
+ }
#ifdef __VMS
- /* Under OpenVMS dlopen doesn't do any check, just save the name
- * for later use, so we have to check if the file is readable,
- * the name can be a logical or a file from SYS$SHARE.
- */
- if (access(name, R_OK)) {
- char fname[strlen(name) + 20];
- strcpy(fname, "SYS$SHARE:");
- strcat(fname, name);
- strcat(fname, ".EXE");
- if (access(fname, R_OK)) {
- dlclose(handle);
- PyErr_SetString(Dlerror,
- "File not found or protection violation");
- return NULL;
- }
- }
+ /* Under OpenVMS dlopen doesn't do any check, just save the name
+ * for later use, so we have to check if the file is readable,
+ * the name can be a logical or a file from SYS$SHARE.
+ */
+ if (access(name, R_OK)) {
+ char fname[strlen(name) + 20];
+ strcpy(fname, "SYS$SHARE:");
+ strcat(fname, name);
+ strcat(fname, ".EXE");
+ if (access(fname, R_OK)) {
+ dlclose(handle);
+ PyErr_SetString(Dlerror,
+ "File not found or protection violation");
+ return NULL;
+ }
+ }
#endif
- return newdlobject(handle);
+ return newdlobject(handle);
}
static PyMethodDef dl_methods[] = {
- {"open", dl_open, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"open", dl_open, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
/* From socketmodule.c
@@ -226,59 +226,59 @@ static PyMethodDef dl_methods[] = {
static void
insint(PyObject *d, char *name, int value)
{
- PyObject *v = PyInt_FromLong((long) value);
- if (!v || PyDict_SetItemString(d, name, v))
- PyErr_Clear();
+ PyObject *v = PyInt_FromLong((long) value);
+ if (!v || PyDict_SetItemString(d, name, v))
+ PyErr_Clear();
- Py_XDECREF(v);
+ Py_XDECREF(v);
}
PyMODINIT_FUNC
initdl(void)
{
- PyObject *m, *d, *x;
+ PyObject *m, *d, *x;
if (PyErr_WarnPy3k("the dl module has been removed in "
"Python 3.0; use the ctypes module instead", 2) < 0)
- return;
+ return;
- /* Initialize object type */
- Py_TYPE(&Dltype) = &PyType_Type;
+ /* Initialize object type */
+ Py_TYPE(&Dltype) = &PyType_Type;
- /* Create the module and add the functions */
- m = Py_InitModule("dl", dl_methods);
- if (m == NULL)
- return;
+ /* Create the module and add the functions */
+ m = Py_InitModule("dl", dl_methods);
+ if (m == NULL)
+ return;
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
- Dlerror = x = PyErr_NewException("dl.error", NULL, NULL);
- PyDict_SetItemString(d, "error", x);
- x = PyInt_FromLong((long)RTLD_LAZY);
- PyDict_SetItemString(d, "RTLD_LAZY", x);
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
+ Dlerror = x = PyErr_NewException("dl.error", NULL, NULL);
+ PyDict_SetItemString(d, "error", x);
+ x = PyInt_FromLong((long)RTLD_LAZY);
+ PyDict_SetItemString(d, "RTLD_LAZY", x);
#define INSINT(X) insint(d,#X,X)
#ifdef RTLD_NOW
- INSINT(RTLD_NOW);
+ INSINT(RTLD_NOW);
#endif
#ifdef RTLD_NOLOAD
- INSINT(RTLD_NOLOAD);
+ INSINT(RTLD_NOLOAD);
#endif
#ifdef RTLD_GLOBAL
- INSINT(RTLD_GLOBAL);
+ INSINT(RTLD_GLOBAL);
#endif
#ifdef RTLD_LOCAL
- INSINT(RTLD_LOCAL);
+ INSINT(RTLD_LOCAL);
#endif
#ifdef RTLD_PARENT
- INSINT(RTLD_PARENT);
+ INSINT(RTLD_PARENT);
#endif
#ifdef RTLD_GROUP
- INSINT(RTLD_GROUP);
+ INSINT(RTLD_GROUP);
#endif
#ifdef RTLD_WORLD
- INSINT(RTLD_WORLD);
+ INSINT(RTLD_WORLD);
#endif
#ifdef RTLD_NODELETE
- INSINT(RTLD_NODELETE);
+ INSINT(RTLD_NODELETE);
#endif
}
diff --git a/Modules/errnomodule.c b/Modules/errnomodule.c
index 642d721..68c3c49 100644
--- a/Modules/errnomodule.c
+++ b/Modules/errnomodule.c
@@ -10,10 +10,10 @@
/*
* Pull in the system error definitions
- */
+ */
static PyMethodDef errno_methods[] = {
- {NULL, NULL}
+ {NULL, NULL}
};
/* Helper function doing the dictionary inserting */
@@ -21,21 +21,21 @@ static PyMethodDef errno_methods[] = {
static void
_inscode(PyObject *d, PyObject *de, char *name, int code)
{
- PyObject *u = PyString_FromString(name);
- PyObject *v = PyInt_FromLong((long) code);
+ PyObject *u = PyString_FromString(name);
+ PyObject *v = PyInt_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__,
@@ -55,734 +55,734 @@ e.g. os.strerror(2) could return 'No such file or directory'.");
PyMODINIT_FUNC
initerrno(void)
{
- PyObject *m, *d, *de;
- m = Py_InitModule3("errno", errno_methods, errno__doc__);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- de = PyDict_New();
- if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0)
- return;
+ PyObject *m, *d, *de;
+ m = Py_InitModule3("errno", errno_methods, errno__doc__);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ de = PyDict_New();
+ if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0)
+ return;
/* 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);
+ Py_DECREF(de);
}
diff --git a/Modules/fcntlmodule.c b/Modules/fcntlmodule.c
index a333a34..63d06d3 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 PyString_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 PyInt_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 PyString_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 PyInt_FromLong((long)ret);
}
PyDoc_STRVAR(fcntl_doc,
@@ -96,118 +96,118 @@ 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;
- 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,
- &str, &len, &mutate_arg)) {
- char *arg;
-
- if (mutate_arg) {
- if (len <= IOCTL_BUFSZ) {
- memcpy(buf, str, len);
- buf[len] = '\0';
- arg = buf;
- }
- else {
- arg = str;
- }
- }
- else {
- if (len > IOCTL_BUFSZ) {
- 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);
- }
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- if (mutate_arg) {
- return PyInt_FromLong(ret);
- }
- else {
- return PyString_FromStringAndSize(buf, len);
- }
- }
-
- PyErr_Clear();
- if (PyArg_ParseTuple(args, "O&Is#:ioctl",
- conv_descriptor, &fd, &code, &str, &len)) {
- if (len > IOCTL_BUFSZ) {
- 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) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return PyString_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;
+ 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,
+ &str, &len, &mutate_arg)) {
+ char *arg;
+
+ if (mutate_arg) {
+ if (len <= IOCTL_BUFSZ) {
+ memcpy(buf, str, len);
+ buf[len] = '\0';
+ arg = buf;
+ }
+ else {
+ arg = str;
+ }
+ }
+ else {
+ if (len > IOCTL_BUFSZ) {
+ 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);
+ }
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ if (mutate_arg) {
+ return PyInt_FromLong(ret);
+ }
+ else {
+ return PyString_FromStringAndSize(buf, len);
+ }
+ }
+
+ PyErr_Clear();
+ if (PyArg_ParseTuple(args, "O&Is#:ioctl",
+ conv_descriptor, &fd, &code, &str, &len)) {
+ if (len > IOCTL_BUFSZ) {
+ 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) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return PyString_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 PyInt_FromLong((long)ret);
+ ret = ioctl(fd, code, arg);
+#endif
+ Py_END_ALLOW_THREADS
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return PyInt_FromLong((long)ret);
#undef IOCTL_BUFSZ
}
@@ -248,51 +248,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,
@@ -307,72 +307,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 = PyInt_AsLong(startobj);
+ l.l_start = PyInt_AsLong(startobj);
#else
- l.l_start = PyLong_Check(startobj) ?
- PyLong_AsLongLong(startobj) :
- PyInt_AsLong(startobj);
-#endif
- if (PyErr_Occurred())
- return NULL;
- }
- if (lenobj != NULL) {
+ l.l_start = PyLong_Check(startobj) ?
+ PyLong_AsLongLong(startobj) :
+ PyInt_AsLong(startobj);
+#endif
+ if (PyErr_Occurred())
+ return NULL;
+ }
+ if (lenobj != NULL) {
#if !defined(HAVE_LARGEFILE_SUPPORT)
- l.l_len = PyInt_AsLong(lenobj);
+ l.l_len = PyInt_AsLong(lenobj);
#else
- l.l_len = PyLong_Check(lenobj) ?
- PyLong_AsLongLong(lenobj) :
- PyInt_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) :
+ PyInt_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) */
}
@@ -404,11 +404,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 */
};
@@ -423,12 +423,12 @@ a file or socket object.");
static int
ins(PyObject* d, char* symbol, long value)
{
- PyObject* v = PyInt_FromLong(value);
- if (!v || PyDict_SetItemString(d, symbol, v) < 0)
- return -1;
+ PyObject* v = PyInt_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
@@ -436,185 +436,185 @@ 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;
}
PyMODINIT_FUNC
initfcntl(void)
{
- PyObject *m, *d;
+ PyObject *m, *d;
- /* Create the module and add the functions and documentation */
- m = Py_InitModule3("fcntl", fcntl_methods, module_doc);
- if (m == NULL)
- return;
+ /* Create the module and add the functions and documentation */
+ m = Py_InitModule3("fcntl", fcntl_methods, module_doc);
+ if (m == NULL)
+ return;
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
- all_ins(d);
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
+ all_ins(d);
}
diff --git a/Modules/flmodule.c b/Modules/flmodule.c
index d2c2506..b5a78cf 100644
--- a/Modules/flmodule.c
+++ b/Modules/flmodule.c
@@ -22,11 +22,11 @@
/* Generic Forms Objects */
typedef struct {
- PyObject_HEAD
- FL_OBJECT *ob_generic;
- PyMethodDef *ob_methods;
- PyObject *ob_callback;
- PyObject *ob_callback_arg;
+ PyObject_HEAD
+ FL_OBJECT *ob_generic;
+ PyMethodDef *ob_methods;
+ PyObject *ob_callback;
+ PyObject *ob_callback_arg;
} genericobject;
static PyTypeObject GenericObjecttype;
@@ -43,32 +43,32 @@ static int nfreeslots = 0;
static void
knowgeneric(genericobject *g)
{
- int i, n;
- /* Create the list if it doesn't already exist */
- if (allgenerics == NULL) {
- allgenerics = PyList_New(0);
- if (allgenerics == NULL) {
- PyErr_Clear();
- return; /* Too bad, live without allgenerics... */
- }
- }
- if (nfreeslots > 0) {
- /* Search the list for reusable slots (NULL items) */
- /* XXX This can be made faster! */
- n = PyList_Size(allgenerics);
- for (i = 0; i < n; i++) {
- if (PyList_GetItem(allgenerics, i) == NULL) {
- Py_INCREF(g);
- PyList_SetItem(allgenerics, i, (PyObject *)g);
- nfreeslots--;
- return;
- }
- }
- /* Strange... no free slots found... */
- nfreeslots = 0;
- }
- /* No free entries, append new item to the end */
- PyList_Append(allgenerics, (PyObject *)g);
+ int i, n;
+ /* Create the list if it doesn't already exist */
+ if (allgenerics == NULL) {
+ allgenerics = PyList_New(0);
+ if (allgenerics == NULL) {
+ PyErr_Clear();
+ return; /* Too bad, live without allgenerics... */
+ }
+ }
+ if (nfreeslots > 0) {
+ /* Search the list for reusable slots (NULL items) */
+ /* XXX This can be made faster! */
+ n = PyList_Size(allgenerics);
+ for (i = 0; i < n; i++) {
+ if (PyList_GetItem(allgenerics, i) == NULL) {
+ Py_INCREF(g);
+ PyList_SetItem(allgenerics, i, (PyObject *)g);
+ nfreeslots--;
+ return;
+ }
+ }
+ /* Strange... no free slots found... */
+ nfreeslots = 0;
+ }
+ /* No free entries, append new item to the end */
+ PyList_Append(allgenerics, (PyObject *)g);
}
/* Find an object in the list of known objects */
@@ -76,18 +76,18 @@ knowgeneric(genericobject *g)
static genericobject *
findgeneric(FL_OBJECT *generic)
{
- int i, n;
- genericobject *g;
-
- if (allgenerics == NULL)
- return NULL; /* No objects known yet */
- n = PyList_Size(allgenerics);
- for (i = 0; i < n; i++) {
- g = (genericobject *)PyList_GetItem(allgenerics, i);
- if (g != NULL && g->ob_generic == generic)
- return g;
- }
- return NULL; /* Unknown object */
+ int i, n;
+ genericobject *g;
+
+ if (allgenerics == NULL)
+ return NULL; /* No objects known yet */
+ n = PyList_Size(allgenerics);
+ for (i = 0; i < n; i++) {
+ g = (genericobject *)PyList_GetItem(allgenerics, i);
+ if (g != NULL && g->ob_generic == generic)
+ return g;
+ }
+ return NULL; /* Unknown object */
}
/* Remove an object from the list of known objects */
@@ -95,22 +95,22 @@ findgeneric(FL_OBJECT *generic)
static void
forgetgeneric(genericobject *g)
{
- int i, n;
-
- Py_XDECREF(g->ob_callback);
- g->ob_callback = NULL;
- Py_XDECREF(g->ob_callback_arg);
- g->ob_callback_arg = NULL;
- if (allgenerics == NULL)
- return; /* No objects known yet */
- n = PyList_Size(allgenerics);
- for (i = 0; i < n; i++) {
- if (g == (genericobject *)PyList_GetItem(allgenerics, i)) {
- PyList_SetItem(allgenerics, i, (PyObject *)NULL);
- nfreeslots++;
- break;
- }
- }
+ int i, n;
+
+ Py_XDECREF(g->ob_callback);
+ g->ob_callback = NULL;
+ Py_XDECREF(g->ob_callback_arg);
+ g->ob_callback_arg = NULL;
+ if (allgenerics == NULL)
+ return; /* No objects known yet */
+ n = PyList_Size(allgenerics);
+ for (i = 0; i < n; i++) {
+ if (g == (genericobject *)PyList_GetItem(allgenerics, i)) {
+ PyList_SetItem(allgenerics, i, (PyObject *)NULL);
+ nfreeslots++;
+ break;
+ }
+ }
}
/* Called when a form is about to be freed --
@@ -119,27 +119,27 @@ forgetgeneric(genericobject *g)
static void
releaseobjects(FL_FORM *form)
{
- int i, n;
- genericobject *g;
-
- if (allgenerics == NULL)
- return; /* No objects known yet */
- n = PyList_Size(allgenerics);
- for (i = 0; i < n; i++) {
- g = (genericobject *)PyList_GetItem(allgenerics, i);
- if (g != NULL && g->ob_generic->form == form) {
- fl_delete_object(g->ob_generic);
- /* The object is now unreachable for
- do_forms and check_forms, so
- delete it from the list of known objects */
- Py_XDECREF(g->ob_callback);
- g->ob_callback = NULL;
- Py_XDECREF(g->ob_callback_arg);
- g->ob_callback_arg = NULL;
- PyList_SetItem(allgenerics, i, (PyObject *)NULL);
- nfreeslots++;
- }
- }
+ int i, n;
+ genericobject *g;
+
+ if (allgenerics == NULL)
+ return; /* No objects known yet */
+ n = PyList_Size(allgenerics);
+ for (i = 0; i < n; i++) {
+ g = (genericobject *)PyList_GetItem(allgenerics, i);
+ if (g != NULL && g->ob_generic->form == form) {
+ fl_delete_object(g->ob_generic);
+ /* The object is now unreachable for
+ do_forms and check_forms, so
+ delete it from the list of known objects */
+ Py_XDECREF(g->ob_callback);
+ g->ob_callback = NULL;
+ Py_XDECREF(g->ob_callback_arg);
+ g->ob_callback_arg = NULL;
+ PyList_SetItem(allgenerics, i, (PyObject *)NULL);
+ nfreeslots++;
+ }
+ }
}
@@ -148,79 +148,79 @@ releaseobjects(FL_FORM *form)
static PyObject *
generic_set_call_back(genericobject *g, PyObject *args)
{
- if (PyTuple_GET_SIZE(args) == 0) {
- Py_XDECREF(g->ob_callback);
- Py_XDECREF(g->ob_callback_arg);
- g->ob_callback = NULL;
- g->ob_callback_arg = NULL;
- }
- else {
- PyObject *a, *b;
- if (!PyArg_UnpackTuple(args, "set_call_back", 2, 2, &a, &b))
- return NULL;
- Py_XDECREF(g->ob_callback);
- Py_XDECREF(g->ob_callback_arg);
- g->ob_callback = a;
- Py_INCREF(g->ob_callback);
- g->ob_callback_arg = b;
- Py_INCREF(g->ob_callback_arg);
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (PyTuple_GET_SIZE(args) == 0) {
+ Py_XDECREF(g->ob_callback);
+ Py_XDECREF(g->ob_callback_arg);
+ g->ob_callback = NULL;
+ g->ob_callback_arg = NULL;
+ }
+ else {
+ PyObject *a, *b;
+ if (!PyArg_UnpackTuple(args, "set_call_back", 2, 2, &a, &b))
+ return NULL;
+ Py_XDECREF(g->ob_callback);
+ Py_XDECREF(g->ob_callback_arg);
+ g->ob_callback = a;
+ Py_INCREF(g->ob_callback);
+ g->ob_callback_arg = b;
+ Py_INCREF(g->ob_callback_arg);
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
generic_call(genericobject *g, void (*func)(FL_OBJECT *))
{
- (*func)(g->ob_generic);
- Py_INCREF(Py_None);
- return Py_None;
+ (*func)(g->ob_generic);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
generic_delete_object(genericobject *g)
{
- PyObject *res;
- res = generic_call(g, fl_delete_object);
- if (res != NULL)
- forgetgeneric(g);
- return res;
+ PyObject *res;
+ res = generic_call(g, fl_delete_object);
+ if (res != NULL)
+ forgetgeneric(g);
+ return res;
}
static PyObject *
generic_show_object(genericobject *g)
{
- return generic_call(g, fl_show_object);
+ return generic_call(g, fl_show_object);
}
static PyObject *
generic_hide_object(genericobject *g)
{
- return generic_call(g, fl_hide_object);
+ return generic_call(g, fl_hide_object);
}
static PyObject *
generic_redraw_object(genericobject *g)
{
- return generic_call(g, fl_redraw_object);
+ return generic_call(g, fl_redraw_object);
}
#ifdef OBSOLETE_FORMS_CALLS
-
+
/* (un)freeze_object() are obsolete in FORMS 2.2 and unsupported
in 2.3. Since there's no foolproof way to tell which version we're
using, we omit them unconditionally. */
-
+
static PyObject *
generic_freeze_object(genericobject *g)
{
- return generic_call(g, fl_freeze_object);
+ return generic_call(g, fl_freeze_object);
}
static PyObject *
generic_unfreeze_object(genericobject *g)
{
- return generic_call(g, fl_unfreeze_object);
+ return generic_call(g, fl_unfreeze_object);
}
#endif /* OBSOLETE_FORMS_CALLS */
@@ -228,78 +228,78 @@ generic_unfreeze_object(genericobject *g)
static PyObject *
generic_activate_object(genericobject *g)
{
- return generic_call(g, fl_activate_object);
+ return generic_call(g, fl_activate_object);
}
static PyObject *
generic_deactivate_object(genericobject *g)
{
- return generic_call(g, fl_deactivate_object);
+ return generic_call(g, fl_deactivate_object);
}
static PyObject *
generic_set_object_shortcut(genericobject *g, PyObject *args)
{
- char *str;
- if (!PyArg_ParseTuple(args, "s:set_object_shortcut", &str))
- return NULL;
- fl_set_object_shortcut(g->ob_generic, str);
- Py_INCREF(Py_None);
- return Py_None;
+ char *str;
+ if (!PyArg_ParseTuple(args, "s:set_object_shortcut", &str))
+ return NULL;
+ fl_set_object_shortcut(g->ob_generic, str);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef generic_methods[] = {
- {"set_call_back", (PyCFunction)generic_set_call_back, METH_VARARGS},
- {"delete_object", (PyCFunction)generic_delete_object, METH_NOARGS},
- {"show_object", (PyCFunction)generic_show_object, METH_NOARGS},
- {"hide_object", (PyCFunction)generic_hide_object, METH_NOARGS},
- {"redraw_object", (PyCFunction)generic_redraw_object, METH_NOARGS},
+ {"set_call_back", (PyCFunction)generic_set_call_back, METH_VARARGS},
+ {"delete_object", (PyCFunction)generic_delete_object, METH_NOARGS},
+ {"show_object", (PyCFunction)generic_show_object, METH_NOARGS},
+ {"hide_object", (PyCFunction)generic_hide_object, METH_NOARGS},
+ {"redraw_object", (PyCFunction)generic_redraw_object, METH_NOARGS},
#ifdef OBSOLETE_FORMS_CALLS
- {"freeze_object", (PyCFunction)generic_freeze_object, METH_NOARGS},
- {"unfreeze_object", (PyCFunction)generic_unfreeze_object, METH_NOARGS},
+ {"freeze_object", (PyCFunction)generic_freeze_object, METH_NOARGS},
+ {"unfreeze_object", (PyCFunction)generic_unfreeze_object, METH_NOARGS},
#endif
- {"activate_object", (PyCFunction)generic_activate_object, METH_NOARGS},
- {"deactivate_object", (PyCFunction)generic_deactivate_object, METH_NOARGS},
- {"set_object_shortcut", (PyCFunction)generic_set_object_shortcut, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"activate_object", (PyCFunction)generic_activate_object, METH_NOARGS},
+ {"deactivate_object", (PyCFunction)generic_deactivate_object, METH_NOARGS},
+ {"set_object_shortcut", (PyCFunction)generic_set_object_shortcut, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
static void
generic_dealloc(genericobject *g)
{
- fl_free_object(g->ob_generic);
- Py_XDECREF(g->ob_callback);
- Py_XDECREF(g->ob_callback_arg);
- PyObject_Del(g);
+ fl_free_object(g->ob_generic);
+ Py_XDECREF(g->ob_callback);
+ Py_XDECREF(g->ob_callback_arg);
+ PyObject_Del(g);
}
#define OFF(x) offsetof(FL_OBJECT, x)
static struct memberlist generic_memberlist[] = {
- {"objclass", T_INT, OFF(objclass), RO},
- {"type", T_INT, OFF(type), RO},
- {"boxtype", T_INT, OFF(boxtype)},
- {"x", T_FLOAT, OFF(x)},
- {"y", T_FLOAT, OFF(y)},
- {"w", T_FLOAT, OFF(w)},
- {"h", T_FLOAT, OFF(h)},
- {"col1", T_INT, OFF(col1)},
- {"col2", T_INT, OFF(col2)},
- {"align", T_INT, OFF(align)},
- {"lcol", T_INT, OFF(lcol)},
- {"lsize", T_FLOAT, OFF(lsize)},
- /* "label" is treated specially! */
- {"lstyle", T_INT, OFF(lstyle)},
- {"pushed", T_INT, OFF(pushed), RO},
- {"focus", T_INT, OFF(focus), RO},
- {"belowmouse", T_INT, OFF(belowmouse),RO},
-/* {"frozen", T_INT, OFF(frozen), RO}, */
- {"active", T_INT, OFF(active)},
- {"input", T_INT, OFF(input)},
- {"visible", T_INT, OFF(visible), RO},
- {"radio", T_INT, OFF(radio)},
- {"automatic", T_INT, OFF(automatic)},
- {NULL} /* Sentinel */
+ {"objclass", T_INT, OFF(objclass), RO},
+ {"type", T_INT, OFF(type), RO},
+ {"boxtype", T_INT, OFF(boxtype)},
+ {"x", T_FLOAT, OFF(x)},
+ {"y", T_FLOAT, OFF(y)},
+ {"w", T_FLOAT, OFF(w)},
+ {"h", T_FLOAT, OFF(h)},
+ {"col1", T_INT, OFF(col1)},
+ {"col2", T_INT, OFF(col2)},
+ {"align", T_INT, OFF(align)},
+ {"lcol", T_INT, OFF(lcol)},
+ {"lsize", T_FLOAT, OFF(lsize)},
+ /* "label" is treated specially! */
+ {"lstyle", T_INT, OFF(lstyle)},
+ {"pushed", T_INT, OFF(pushed), RO},
+ {"focus", T_INT, OFF(focus), RO},
+ {"belowmouse", T_INT, OFF(belowmouse),RO},
+/* {"frozen", T_INT, OFF(frozen), RO}, */
+ {"active", T_INT, OFF(active)},
+ {"input", T_INT, OFF(input)},
+ {"visible", T_INT, OFF(visible), RO},
+ {"radio", T_INT, OFF(radio)},
+ {"automatic", T_INT, OFF(automatic)},
+ {NULL} /* Sentinel */
};
#undef OFF
@@ -307,99 +307,99 @@ static struct memberlist generic_memberlist[] = {
static PyObject *
generic_getattr(genericobject *g, char *name)
{
- PyObject *meth;
+ PyObject *meth;
- /* XXX Ought to special-case name "__methods__" */
- if (g-> ob_methods) {
- meth = Py_FindMethod(g->ob_methods, (PyObject *)g, name);
- if (meth != NULL) return meth;
- PyErr_Clear();
- }
+ /* XXX Ought to special-case name "__methods__" */
+ if (g-> ob_methods) {
+ meth = Py_FindMethod(g->ob_methods, (PyObject *)g, name);
+ if (meth != NULL) return meth;
+ PyErr_Clear();
+ }
- meth = Py_FindMethod(generic_methods, (PyObject *)g, name);
- if (meth != NULL)
- return meth;
- PyErr_Clear();
+ meth = Py_FindMethod(generic_methods, (PyObject *)g, name);
+ if (meth != NULL)
+ return meth;
+ PyErr_Clear();
- /* "label" is an exception, getmember only works for char pointers,
- not for char arrays */
- if (strcmp(name, "label") == 0)
- return PyString_FromString(g->ob_generic->label);
+ /* "label" is an exception, getmember only works for char pointers,
+ not for char arrays */
+ if (strcmp(name, "label") == 0)
+ return PyString_FromString(g->ob_generic->label);
- return PyMember_Get((char *)g->ob_generic, generic_memberlist, name);
+ return PyMember_Get((char *)g->ob_generic, generic_memberlist, name);
}
static int
generic_setattr(genericobject *g, char *name, PyObject *v)
{
- int ret;
+ int ret;
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete forms object attributes");
- return -1;
- }
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete forms object attributes");
+ return -1;
+ }
- /* "label" is an exception: setmember doesn't set strings;
- and FORMS wants you to call a function to set the label */
- if (strcmp(name, "label") == 0) {
- if (!PyString_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "label attr must be string");
- return -1;
- }
- fl_set_object_label(g->ob_generic, PyString_AsString(v));
- return 0;
- }
+ /* "label" is an exception: setmember doesn't set strings;
+ and FORMS wants you to call a function to set the label */
+ if (strcmp(name, "label") == 0) {
+ if (!PyString_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "label attr must be string");
+ return -1;
+ }
+ fl_set_object_label(g->ob_generic, PyString_AsString(v));
+ return 0;
+ }
- ret = PyMember_Set((char *)g->ob_generic, generic_memberlist, name, v);
+ ret = PyMember_Set((char *)g->ob_generic, generic_memberlist, name, v);
- /* Rather than calling all the various set_object_* functions,
- we call fl_redraw_object here. This is sometimes redundant
- but I doubt that's a big problem */
- if (ret == 0)
- fl_redraw_object(g->ob_generic);
+ /* Rather than calling all the various set_object_* functions,
+ we call fl_redraw_object here. This is sometimes redundant
+ but I doubt that's a big problem */
+ if (ret == 0)
+ fl_redraw_object(g->ob_generic);
- return ret;
+ return ret;
}
static PyObject *
generic_repr(genericobject *g)
{
- char buf[100];
- PyOS_snprintf(buf, sizeof(buf), "<FORMS_object at %p, objclass=%d>",
- g, g->ob_generic->objclass);
- return PyString_FromString(buf);
+ char buf[100];
+ PyOS_snprintf(buf, sizeof(buf), "<FORMS_object at %p, objclass=%d>",
+ g, g->ob_generic->objclass);
+ return PyString_FromString(buf);
}
static PyTypeObject GenericObjecttype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "fl.FORMS_object", /*tp_name*/
- sizeof(genericobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)generic_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)generic_getattr, /*tp_getattr*/
- (setattrfunc)generic_setattr, /*tp_setattr*/
- 0, /*tp_compare*/
- (reprfunc)generic_repr, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "fl.FORMS_object", /*tp_name*/
+ sizeof(genericobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)generic_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)generic_getattr, /*tp_getattr*/
+ (setattrfunc)generic_setattr, /*tp_setattr*/
+ 0, /*tp_compare*/
+ (reprfunc)generic_repr, /*tp_repr*/
};
static PyObject *
newgenericobject(FL_OBJECT *generic, PyMethodDef *methods)
{
- genericobject *g;
- g = PyObject_New(genericobject, &GenericObjecttype);
- if (g == NULL)
- return NULL;
- g-> ob_generic = generic;
- g->ob_methods = methods;
- g->ob_callback = NULL;
- g->ob_callback_arg = NULL;
- knowgeneric(g);
- return (PyObject *)g;
+ genericobject *g;
+ g = PyObject_New(genericobject, &GenericObjecttype);
+ if (g == NULL)
+ return NULL;
+ g-> ob_generic = generic;
+ g->ob_methods = methods;
+ g->ob_callback = NULL;
+ g->ob_callback_arg = NULL;
+ knowgeneric(g);
+ return (PyObject *)g;
}
/**********************************************************************/
@@ -409,70 +409,70 @@ newgenericobject(FL_OBJECT *generic, PyMethodDef *methods)
static PyObject *
call_forms_INf (void (*func)(FL_OBJECT *, float), FL_OBJECT *obj, PyObject *args)
{
- float parameter;
+ float parameter;
- if (!PyArg_Parse(args, "f", &parameter)) return NULL;
+ if (!PyArg_Parse(args, "f", &parameter)) return NULL;
- (*func) (obj, parameter);
+ (*func) (obj, parameter);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void func (object, float) */
static PyObject *
call_forms_INfINf (void (*func)(FL_OBJECT *, float, float), FL_OBJECT *obj, PyObject *args)
{
- float par1, par2;
+ float par1, par2;
- if (!PyArg_Parse(args, "(ff)", &par1, &par2)) return NULL;
+ if (!PyArg_Parse(args, "(ff)", &par1, &par2)) return NULL;
- (*func) (obj, par1, par2);
+ (*func) (obj, par1, par2);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void func (object, int) */
static PyObject *
call_forms_INi (void (*func)(FL_OBJECT *, int), FL_OBJECT *obj, PyObject *args)
{
- int parameter;
+ int parameter;
- if (!PyArg_Parse(args, "i", &parameter)) return NULL;
+ if (!PyArg_Parse(args, "i", &parameter)) return NULL;
- (*func) (obj, parameter);
+ (*func) (obj, parameter);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void func (object, char) */
static PyObject *
call_forms_INc (void (*func)(FL_OBJECT *, int), FL_OBJECT *obj, PyObject *args)
{
- char *a;
+ char *a;
- if (!PyArg_Parse(args, "s", &a)) return NULL;
+ if (!PyArg_Parse(args, "s", &a)) return NULL;
- (*func) (obj, a[0]);
+ (*func) (obj, a[0]);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void func (object, string) */
static PyObject *
call_forms_INstr (void (*func)(FL_OBJECT *, char *), FL_OBJECT *obj, PyObject *args)
{
- char *a;
+ char *a;
- if (!PyArg_Parse(args, "s", &a)) return NULL;
+ if (!PyArg_Parse(args, "s", &a)) return NULL;
- (*func) (obj, a);
+ (*func) (obj, a);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -480,15 +480,15 @@ call_forms_INstr (void (*func)(FL_OBJECT *, char *), FL_OBJECT *obj, PyObject *a
static PyObject *
call_forms_INiINstr (void (*func)(FL_OBJECT *, int, char *), FL_OBJECT *obj, PyObject *args)
{
- char *b;
- int a;
-
- if (!PyArg_Parse(args, "(is)", &a, &b)) return NULL;
-
- (*func) (obj, a, b);
-
- Py_INCREF(Py_None);
- return Py_None;
+ char *b;
+ int a;
+
+ if (!PyArg_Parse(args, "(is)", &a, &b)) return NULL;
+
+ (*func) (obj, a, b);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
#ifdef UNUSED
@@ -496,14 +496,14 @@ call_forms_INiINstr (void (*func)(FL_OBJECT *, int, char *), FL_OBJECT *obj, PyO
static PyObject *
call_forms_INiINi (void (*func)(FL_OBJECT *, int, int), FL_OBJECT *obj, PyObject *args)
{
- int par1, par2;
-
- if (!PyArg_Parse(args, "(ii)", &par1, &par2)) return NULL;
-
- (*func) (obj, par1, par2);
-
- Py_INCREF(Py_None);
- return Py_None;
+ int par1, par2;
+
+ if (!PyArg_Parse(args, "(ii)", &par1, &par2)) return NULL;
+
+ (*func) (obj, par1, par2);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif
@@ -511,58 +511,58 @@ call_forms_INiINi (void (*func)(FL_OBJECT *, int, int), FL_OBJECT *obj, PyObject
static PyObject *
call_forms_Ri (int (*func)(FL_OBJECT *), FL_OBJECT *obj)
{
- int retval;
+ int retval;
- retval = (*func) (obj);
+ retval = (*func) (obj);
- return PyInt_FromLong ((long) retval);
+ return PyInt_FromLong ((long) retval);
}
/* char * func (object) */
static PyObject *
call_forms_Rstr (char * (*func)(FL_OBJECT *), FL_OBJECT *obj)
{
- char *str;
+ char *str;
- str = (*func) (obj);
+ str = (*func) (obj);
- if (str == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString (str);
+ if (str == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString (str);
}
/* int func (object) */
static PyObject *
call_forms_Rf (float (*func)(FL_OBJECT *), FL_OBJECT *obj)
{
- float retval;
+ float retval;
- retval = (*func) (obj);
+ retval = (*func) (obj);
- return PyFloat_FromDouble (retval);
+ return PyFloat_FromDouble (retval);
}
static PyObject *
call_forms_OUTfOUTf (void (*func)(FL_OBJECT *, float *, float *), FL_OBJECT *obj)
{
- float f1, f2;
+ float f1, f2;
- (*func) (obj, &f1, &f2);
+ (*func) (obj, &f1, &f2);
- return Py_BuildValue("(ff)", f1, f2);
+ return Py_BuildValue("(ff)", f1, f2);
}
#ifdef UNUSED
static PyObject *
call_forms_OUTf (void (*func)(FL_OBJECT *, float *), FL_OBJECT *obj)
{
- float f;
+ float f;
- (*func) (obj, &f);
+ (*func) (obj, &f);
- return PyFloat_FromDouble (f);
+ return PyFloat_FromDouble (f);
}
#endif
@@ -572,172 +572,172 @@ call_forms_OUTf (void (*func)(FL_OBJECT *, float *), FL_OBJECT *obj)
static PyObject *
set_browser_topline(genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_browser_topline, g-> ob_generic, args);
+ return call_forms_INi (fl_set_browser_topline, g-> ob_generic, args);
}
static PyObject *
clear_browser(genericobject *g)
{
- return generic_call (g, fl_clear_browser);
+ return generic_call (g, fl_clear_browser);
}
static PyObject *
add_browser_line (genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_add_browser_line, g-> ob_generic, args);
+ return call_forms_INstr (fl_add_browser_line, g-> ob_generic, args);
}
static PyObject *
addto_browser (genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_addto_browser, g-> ob_generic, args);
+ return call_forms_INstr (fl_addto_browser, g-> ob_generic, args);
}
static PyObject *
insert_browser_line (genericobject *g, PyObject *args)
{
- return call_forms_INiINstr (fl_insert_browser_line,
- g-> ob_generic, args);
+ return call_forms_INiINstr (fl_insert_browser_line,
+ g-> ob_generic, args);
}
static PyObject *
delete_browser_line (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_delete_browser_line, g-> ob_generic, args);
+ return call_forms_INi (fl_delete_browser_line, g-> ob_generic, args);
}
static PyObject *
replace_browser_line (genericobject *g, PyObject *args)
{
- return call_forms_INiINstr (fl_replace_browser_line,
- g-> ob_generic, args);
+ return call_forms_INiINstr (fl_replace_browser_line,
+ g-> ob_generic, args);
}
static PyObject *
get_browser_line(genericobject *g, PyObject *args)
{
- int i;
- char *str;
+ int i;
+ char *str;
- if (!PyArg_Parse(args, "i", &i))
- return NULL;
+ if (!PyArg_Parse(args, "i", &i))
+ return NULL;
- str = fl_get_browser_line (g->ob_generic, i);
+ str = fl_get_browser_line (g->ob_generic, i);
- if (str == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString (str);
+ if (str == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString (str);
}
static PyObject *
load_browser (genericobject *g, PyObject *args)
{
- /* XXX strictly speaking this is wrong since fl_load_browser
- XXX returns int, not void */
- return call_forms_INstr (fl_load_browser, g-> ob_generic, args);
+ /* XXX strictly speaking this is wrong since fl_load_browser
+ XXX returns int, not void */
+ return call_forms_INstr (fl_load_browser, g-> ob_generic, args);
}
static PyObject *
get_browser_maxline(genericobject *g)
{
- return call_forms_Ri (fl_get_browser_maxline, g-> ob_generic);
+ return call_forms_Ri (fl_get_browser_maxline, g-> ob_generic);
}
static PyObject *
select_browser_line (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_select_browser_line, g-> ob_generic, args);
+ return call_forms_INi (fl_select_browser_line, g-> ob_generic, args);
}
static PyObject *
deselect_browser_line (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_deselect_browser_line, g-> ob_generic, args);
+ return call_forms_INi (fl_deselect_browser_line, g-> ob_generic, args);
}
static PyObject *
deselect_browser (genericobject *g)
{
- return generic_call (g, fl_deselect_browser);
+ return generic_call (g, fl_deselect_browser);
}
static PyObject *
isselected_browser_line (genericobject *g, PyObject *args)
{
- int i, j;
-
- if (!PyArg_Parse(args, "i", &i))
- return NULL;
-
- j = fl_isselected_browser_line (g->ob_generic, i);
-
- return PyInt_FromLong (j);
+ int i, j;
+
+ if (!PyArg_Parse(args, "i", &i))
+ return NULL;
+
+ j = fl_isselected_browser_line (g->ob_generic, i);
+
+ return PyInt_FromLong (j);
}
static PyObject *
get_browser (genericobject *g)
{
- return call_forms_Ri (fl_get_browser, g-> ob_generic);
+ return call_forms_Ri (fl_get_browser, g-> ob_generic);
}
static PyObject *
set_browser_fontsize (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_browser_fontsize, g-> ob_generic, args);
+ return call_forms_INf (fl_set_browser_fontsize, g-> ob_generic, args);
}
static PyObject *
set_browser_fontstyle (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_browser_fontstyle, g-> ob_generic, args);
+ return call_forms_INi (fl_set_browser_fontstyle, g-> ob_generic, args);
}
static PyObject *
set_browser_specialkey (genericobject *g, PyObject *args)
{
- return call_forms_INc(fl_set_browser_specialkey, g-> ob_generic, args);
+ return call_forms_INc(fl_set_browser_specialkey, g-> ob_generic, args);
}
static PyMethodDef browser_methods[] = {
- {"set_browser_topline", (PyCFunction)set_browser_topline,
- METH_OLDARGS},
- {"clear_browser", (PyCFunction)clear_browser,
- METH_NOARGS},
- {"add_browser_line", (PyCFunction)add_browser_line,
- METH_OLDARGS},
- {"addto_browser", (PyCFunction)addto_browser,
- METH_OLDARGS},
- {"insert_browser_line", (PyCFunction)insert_browser_line,
- METH_OLDARGS},
- {"delete_browser_line", (PyCFunction)delete_browser_line,
- METH_OLDARGS},
- {"replace_browser_line", (PyCFunction)replace_browser_line,
- METH_OLDARGS},
- {"get_browser_line", (PyCFunction)get_browser_line,
- METH_OLDARGS},
- {"load_browser", (PyCFunction)load_browser,
- METH_OLDARGS},
- {"get_browser_maxline", (PyCFunction)get_browser_maxline,
- METH_NOARGS,}
- {"select_browser_line", (PyCFunction)select_browser_line,
- METH_OLDARGS},
- {"deselect_browser_line", (PyCFunction)deselect_browser_line,
- METH_OLDARGS},
- {"deselect_browser", (PyCFunction)deselect_browser,
- METH_NOARGS,}
- {"isselected_browser_line", (PyCFunction)isselected_browser_line,
- METH_OLDARGS},
- {"get_browser", (PyCFunction)get_browser,
- METH_NOARGS,}
- {"set_browser_fontsize", (PyCFunction)set_browser_fontsize,
- METH_OLDARGS},
- {"set_browser_fontstyle", (PyCFunction)set_browser_fontstyle,
- METH_OLDARGS},
- {"set_browser_specialkey", (PyCFunction)set_browser_specialkey,
- METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_browser_topline", (PyCFunction)set_browser_topline,
+ METH_OLDARGS},
+ {"clear_browser", (PyCFunction)clear_browser,
+ METH_NOARGS},
+ {"add_browser_line", (PyCFunction)add_browser_line,
+ METH_OLDARGS},
+ {"addto_browser", (PyCFunction)addto_browser,
+ METH_OLDARGS},
+ {"insert_browser_line", (PyCFunction)insert_browser_line,
+ METH_OLDARGS},
+ {"delete_browser_line", (PyCFunction)delete_browser_line,
+ METH_OLDARGS},
+ {"replace_browser_line", (PyCFunction)replace_browser_line,
+ METH_OLDARGS},
+ {"get_browser_line", (PyCFunction)get_browser_line,
+ METH_OLDARGS},
+ {"load_browser", (PyCFunction)load_browser,
+ METH_OLDARGS},
+ {"get_browser_maxline", (PyCFunction)get_browser_maxline,
+ METH_NOARGS,}
+ {"select_browser_line", (PyCFunction)select_browser_line,
+ METH_OLDARGS},
+ {"deselect_browser_line", (PyCFunction)deselect_browser_line,
+ METH_OLDARGS},
+ {"deselect_browser", (PyCFunction)deselect_browser,
+ METH_NOARGS,}
+ {"isselected_browser_line", (PyCFunction)isselected_browser_line,
+ METH_OLDARGS},
+ {"get_browser", (PyCFunction)get_browser,
+ METH_NOARGS,}
+ {"set_browser_fontsize", (PyCFunction)set_browser_fontsize,
+ METH_OLDARGS},
+ {"set_browser_fontstyle", (PyCFunction)set_browser_fontstyle,
+ METH_OLDARGS},
+ {"set_browser_specialkey", (PyCFunction)set_browser_specialkey,
+ METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
/* Class: button */
@@ -745,33 +745,33 @@ static PyMethodDef browser_methods[] = {
static PyObject *
set_button(genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_button, g-> ob_generic, args);
+ return call_forms_INi (fl_set_button, g-> ob_generic, args);
}
static PyObject *
get_button(genericobject *g)
{
- return call_forms_Ri (fl_get_button, g-> ob_generic);
+ return call_forms_Ri (fl_get_button, g-> ob_generic);
}
static PyObject *
get_button_numb(genericobject *g)
{
- return call_forms_Ri (fl_get_button_numb, g-> ob_generic);
+ return call_forms_Ri (fl_get_button_numb, g-> ob_generic);
}
static PyObject *
set_button_shortcut(genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_set_button_shortcut, g-> ob_generic, args);
+ return call_forms_INstr (fl_set_button_shortcut, g-> ob_generic, args);
}
static PyMethodDef button_methods[] = {
- {"set_button", (PyCFunction)set_button, METH_OLDARGS},
- {"get_button", (PyCFunction)get_button, METH_NOARGS},
- {"get_button_numb", (PyCFunction)get_button_numb, METH_NOARGS},
- {"set_button_shortcut", (PyCFunction)set_button_shortcut, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_button", (PyCFunction)set_button, METH_OLDARGS},
+ {"get_button", (PyCFunction)get_button, METH_NOARGS},
+ {"get_button_numb", (PyCFunction)get_button_numb, METH_NOARGS},
+ {"set_button_shortcut", (PyCFunction)set_button_shortcut, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
/* Class: choice */
@@ -779,68 +779,68 @@ static PyMethodDef button_methods[] = {
static PyObject *
set_choice(genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_choice, g-> ob_generic, args);
+ return call_forms_INi (fl_set_choice, g-> ob_generic, args);
}
static PyObject *
get_choice(genericobject *g)
{
- return call_forms_Ri (fl_get_choice, g-> ob_generic);
+ return call_forms_Ri (fl_get_choice, g-> ob_generic);
}
static PyObject *
clear_choice (genericobject *g)
{
- return generic_call (g, fl_clear_choice);
+ return generic_call (g, fl_clear_choice);
}
static PyObject *
addto_choice (genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_addto_choice, g-> ob_generic, args);
+ return call_forms_INstr (fl_addto_choice, g-> ob_generic, args);
}
static PyObject *
replace_choice (genericobject *g, PyObject *args)
{
- return call_forms_INiINstr (fl_replace_choice, g-> ob_generic, args);
+ return call_forms_INiINstr (fl_replace_choice, g-> ob_generic, args);
}
static PyObject *
delete_choice (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_delete_choice, g-> ob_generic, args);
+ return call_forms_INi (fl_delete_choice, g-> ob_generic, args);
}
static PyObject *
get_choice_text (genericobject *g)
{
- return call_forms_Rstr (fl_get_choice_text, g-> ob_generic);
+ return call_forms_Rstr (fl_get_choice_text, g-> ob_generic);
}
static PyObject *
set_choice_fontsize (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_choice_fontsize, g-> ob_generic, args);
+ return call_forms_INf (fl_set_choice_fontsize, g-> ob_generic, args);
}
static PyObject *
set_choice_fontstyle (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_choice_fontstyle, g-> ob_generic, args);
+ return call_forms_INi (fl_set_choice_fontstyle, g-> ob_generic, args);
}
static PyMethodDef choice_methods[] = {
- {"set_choice", (PyCFunction)set_choice, METH_OLDARGS},
- {"get_choice", (PyCFunction)get_choice, METH_NOARGS},
- {"clear_choice", (PyCFunction)clear_choice, METH_NOARGS},
- {"addto_choice", (PyCFunction)addto_choice, METH_OLDARGS},
- {"replace_choice", (PyCFunction)replace_choice, METH_OLDARGS},
- {"delete_choice", (PyCFunction)delete_choice, METH_OLDARGS},
- {"get_choice_text", (PyCFunction)get_choice_text, METH_NOARGS},
- {"set_choice_fontsize", (PyCFunction)set_choice_fontsize, METH_OLDARGS},
- {"set_choice_fontstyle",(PyCFunction)set_choice_fontstyle, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_choice", (PyCFunction)set_choice, METH_OLDARGS},
+ {"get_choice", (PyCFunction)get_choice, METH_NOARGS},
+ {"clear_choice", (PyCFunction)clear_choice, METH_NOARGS},
+ {"addto_choice", (PyCFunction)addto_choice, METH_OLDARGS},
+ {"replace_choice", (PyCFunction)replace_choice, METH_OLDARGS},
+ {"delete_choice", (PyCFunction)delete_choice, METH_OLDARGS},
+ {"get_choice_text", (PyCFunction)get_choice_text, METH_NOARGS},
+ {"set_choice_fontsize", (PyCFunction)set_choice_fontsize, METH_OLDARGS},
+ {"set_choice_fontstyle",(PyCFunction)set_choice_fontstyle, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
/* Class : Clock */
@@ -848,16 +848,16 @@ static PyMethodDef choice_methods[] = {
static PyObject *
get_clock(genericobject *g)
{
- int i0, i1, i2;
+ int i0, i1, i2;
- fl_get_clock (g->ob_generic, &i0, &i1, &i2);
+ fl_get_clock (g->ob_generic, &i0, &i1, &i2);
- return Py_BuildValue("(iii)", i0, i1, i2);
+ return Py_BuildValue("(iii)", i0, i1, i2);
}
static PyMethodDef clock_methods[] = {
- {"get_clock", (PyCFunction)get_clock, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {"get_clock", (PyCFunction)get_clock, METH_NOARGS},
+ {NULL, NULL} /* sentinel */
};
/* CLass : Counters */
@@ -865,53 +865,53 @@ static PyMethodDef clock_methods[] = {
static PyObject *
get_counter_value(genericobject *g)
{
- return call_forms_Rf (fl_get_counter_value, g-> ob_generic);
+ return call_forms_Rf (fl_get_counter_value, g-> ob_generic);
}
static PyObject *
set_counter_value (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_counter_value, g-> ob_generic, args);
+ return call_forms_INf (fl_set_counter_value, g-> ob_generic, args);
}
static PyObject *
set_counter_precision (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_counter_precision, g-> ob_generic, args);
+ return call_forms_INi (fl_set_counter_precision, g-> ob_generic, args);
}
static PyObject *
set_counter_bounds (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_counter_bounds, g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_counter_bounds, g-> ob_generic, args);
}
static PyObject *
set_counter_step (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_counter_step, g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_counter_step, g-> ob_generic, args);
}
static PyObject *
set_counter_return (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_counter_return, g-> ob_generic, args);
+ return call_forms_INi (fl_set_counter_return, g-> ob_generic, args);
}
static PyMethodDef counter_methods[] = {
- {"set_counter_value", (PyCFunction)set_counter_value,
- METH_OLDARGS},
- {"get_counter_value", (PyCFunction)get_counter_value,
- METH_NOARGS},
- {"set_counter_bounds", (PyCFunction)set_counter_bounds,
- METH_OLDARGS},
- {"set_counter_step", (PyCFunction)set_counter_step,
- METH_OLDARGS},
- {"set_counter_precision", (PyCFunction)set_counter_precision,
- METH_OLDARGS},
- {"set_counter_return", (PyCFunction)set_counter_return,
- METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_counter_value", (PyCFunction)set_counter_value,
+ METH_OLDARGS},
+ {"get_counter_value", (PyCFunction)get_counter_value,
+ METH_NOARGS},
+ {"set_counter_bounds", (PyCFunction)set_counter_bounds,
+ METH_OLDARGS},
+ {"set_counter_step", (PyCFunction)set_counter_step,
+ METH_OLDARGS},
+ {"set_counter_precision", (PyCFunction)set_counter_precision,
+ METH_OLDARGS},
+ {"set_counter_return", (PyCFunction)set_counter_return,
+ METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
@@ -920,40 +920,40 @@ static PyMethodDef counter_methods[] = {
static PyObject *
get_dial_value(genericobject *g)
{
- return call_forms_Rf (fl_get_dial_value, g-> ob_generic);
+ return call_forms_Rf (fl_get_dial_value, g-> ob_generic);
}
static PyObject *
set_dial_value (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_dial_value, g-> ob_generic, args);
+ return call_forms_INf (fl_set_dial_value, g-> ob_generic, args);
}
static PyObject *
set_dial_bounds (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_dial_bounds, g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_dial_bounds, g-> ob_generic, args);
}
static PyObject *
get_dial_bounds (genericobject *g)
{
- return call_forms_OUTfOUTf (fl_get_dial_bounds, g-> ob_generic);
+ return call_forms_OUTfOUTf (fl_get_dial_bounds, g-> ob_generic);
}
static PyObject *
set_dial_step (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_dial_step, g-> ob_generic, args);
+ return call_forms_INf (fl_set_dial_step, g-> ob_generic, args);
}
static PyMethodDef dial_methods[] = {
- {"set_dial_value", (PyCFunction)set_dial_value, METH_OLDARGS},
- {"get_dial_value", (PyCFunction)get_dial_value, METH_NOARGS},
- {"set_dial_bounds", (PyCFunction)set_dial_bounds, METH_OLDARGS},
- {"get_dial_bounds", (PyCFunction)get_dial_bounds, METH_NOARGS},
- {"set_dial_step", (PyCFunction)set_dial_step, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_dial_value", (PyCFunction)set_dial_value, METH_OLDARGS},
+ {"get_dial_value", (PyCFunction)get_dial_value, METH_NOARGS},
+ {"set_dial_bounds", (PyCFunction)set_dial_bounds, METH_OLDARGS},
+ {"get_dial_bounds", (PyCFunction)get_dial_bounds, METH_NOARGS},
+ {"set_dial_step", (PyCFunction)set_dial_step, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
/* Class : Input */
@@ -961,33 +961,33 @@ static PyMethodDef dial_methods[] = {
static PyObject *
set_input (genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_set_input, g-> ob_generic, args);
+ return call_forms_INstr (fl_set_input, g-> ob_generic, args);
}
static PyObject *
get_input (genericobject *g)
{
- return call_forms_Rstr (fl_get_input, g-> ob_generic);
+ return call_forms_Rstr (fl_get_input, g-> ob_generic);
}
static PyObject *
set_input_color (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_input_color, g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_input_color, g-> ob_generic, args);
}
static PyObject *
set_input_return (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_input_return, g-> ob_generic, args);
+ return call_forms_INi (fl_set_input_return, g-> ob_generic, args);
}
static PyMethodDef input_methods[] = {
- {"set_input", (PyCFunction)set_input, METH_OLDARGS},
- {"get_input", (PyCFunction)get_input, METH_NOARGS},
- {"set_input_color", (PyCFunction)set_input_color, METH_OLDARGS},
- {"set_input_return", (PyCFunction)set_input_return, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_input", (PyCFunction)set_input, METH_OLDARGS},
+ {"get_input", (PyCFunction)get_input, METH_NOARGS},
+ {"set_input_color", (PyCFunction)set_input_color, METH_OLDARGS},
+ {"set_input_return", (PyCFunction)set_input_return, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
@@ -996,35 +996,35 @@ static PyMethodDef input_methods[] = {
static PyObject *
set_menu (genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_set_menu, g-> ob_generic, args);
+ return call_forms_INstr (fl_set_menu, g-> ob_generic, args);
}
static PyObject *
get_menu (genericobject *g)
{
- /* XXX strictly speaking this is wrong since fl_get_menu
- XXX returns long, not int */
- return call_forms_Ri (fl_get_menu, g-> ob_generic);
+ /* XXX strictly speaking this is wrong since fl_get_menu
+ XXX returns long, not int */
+ return call_forms_Ri (fl_get_menu, g-> ob_generic);
}
static PyObject *
get_menu_text (genericobject *g)
{
- return call_forms_Rstr (fl_get_menu_text, g-> ob_generic);
+ return call_forms_Rstr (fl_get_menu_text, g-> ob_generic);
}
static PyObject *
addto_menu (genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_addto_menu, g-> ob_generic, args);
+ return call_forms_INstr (fl_addto_menu, g-> ob_generic, args);
}
static PyMethodDef menu_methods[] = {
- {"set_menu", (PyCFunction)set_menu, METH_OLDARGS},
- {"get_menu", (PyCFunction)get_menu, METH_NOARGS},
- {"get_menu_text", (PyCFunction)get_menu_text, METH_NOARGS},
- {"addto_menu", (PyCFunction)addto_menu, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_menu", (PyCFunction)set_menu, METH_OLDARGS},
+ {"get_menu", (PyCFunction)get_menu, METH_NOARGS},
+ {"get_menu_text", (PyCFunction)get_menu_text, METH_NOARGS},
+ {"addto_menu", (PyCFunction)addto_menu, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
@@ -1033,132 +1033,132 @@ static PyMethodDef menu_methods[] = {
static PyObject *
get_slider_value(genericobject *g)
{
- return call_forms_Rf (fl_get_slider_value, g-> ob_generic);
+ return call_forms_Rf (fl_get_slider_value, g-> ob_generic);
}
static PyObject *
set_slider_value (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_slider_value, g-> ob_generic, args);
+ return call_forms_INf (fl_set_slider_value, g-> ob_generic, args);
}
static PyObject *
set_slider_bounds (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_slider_bounds, g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_slider_bounds, g-> ob_generic, args);
}
static PyObject *
get_slider_bounds (genericobject *g)
{
- return call_forms_OUTfOUTf(fl_get_slider_bounds, g-> ob_generic);
+ return call_forms_OUTfOUTf(fl_get_slider_bounds, g-> ob_generic);
}
static PyObject *
set_slider_return (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_slider_return, g-> ob_generic, args);
+ return call_forms_INf (fl_set_slider_return, g-> ob_generic, args);
}
static PyObject *
set_slider_size (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_slider_size, g-> ob_generic, args);
+ return call_forms_INf (fl_set_slider_size, g-> ob_generic, args);
}
static PyObject *
set_slider_precision (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_slider_precision, g-> ob_generic, args);
+ return call_forms_INi (fl_set_slider_precision, g-> ob_generic, args);
}
static PyObject *
set_slider_step (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_slider_step, g-> ob_generic, args);
+ return call_forms_INf (fl_set_slider_step, g-> ob_generic, args);
}
static PyMethodDef slider_methods[] = {
- {"set_slider_value", (PyCFunction)set_slider_value, METH_OLDARGS},
- {"get_slider_value", (PyCFunction)get_slider_value, METH_NOARGS},
- {"set_slider_bounds", (PyCFunction)set_slider_bounds, METH_OLDARGS},
- {"get_slider_bounds", (PyCFunction)get_slider_bounds, METH_NOARGS},
- {"set_slider_return", (PyCFunction)set_slider_return, METH_OLDARGS},
- {"set_slider_size", (PyCFunction)set_slider_size, METH_OLDARGS},
- {"set_slider_precision",(PyCFunction)set_slider_precision, METH_OLDARGS},
- {"set_slider_step", (PyCFunction)set_slider_step, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_slider_value", (PyCFunction)set_slider_value, METH_OLDARGS},
+ {"get_slider_value", (PyCFunction)get_slider_value, METH_NOARGS},
+ {"set_slider_bounds", (PyCFunction)set_slider_bounds, METH_OLDARGS},
+ {"get_slider_bounds", (PyCFunction)get_slider_bounds, METH_NOARGS},
+ {"set_slider_return", (PyCFunction)set_slider_return, METH_OLDARGS},
+ {"set_slider_size", (PyCFunction)set_slider_size, METH_OLDARGS},
+ {"set_slider_precision",(PyCFunction)set_slider_precision, METH_OLDARGS},
+ {"set_slider_step", (PyCFunction)set_slider_step, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
set_positioner_xvalue (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_positioner_xvalue, g-> ob_generic, args);
+ return call_forms_INf (fl_set_positioner_xvalue, g-> ob_generic, args);
}
static PyObject *
set_positioner_xbounds (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_positioner_xbounds,
- g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_positioner_xbounds,
+ g-> ob_generic, args);
}
static PyObject *
set_positioner_yvalue (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_positioner_yvalue, g-> ob_generic, args);
+ return call_forms_INf (fl_set_positioner_yvalue, g-> ob_generic, args);
}
static PyObject *
set_positioner_ybounds (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_positioner_ybounds,
- g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_positioner_ybounds,
+ g-> ob_generic, args);
}
static PyObject *
get_positioner_xvalue (genericobject *g)
{
- return call_forms_Rf (fl_get_positioner_xvalue, g-> ob_generic);
+ return call_forms_Rf (fl_get_positioner_xvalue, g-> ob_generic);
}
static PyObject *
get_positioner_xbounds (genericobject *g)
{
- return call_forms_OUTfOUTf (fl_get_positioner_xbounds, g-> ob_generic);
+ return call_forms_OUTfOUTf (fl_get_positioner_xbounds, g-> ob_generic);
}
static PyObject *
get_positioner_yvalue (genericobject *g)
{
- return call_forms_Rf (fl_get_positioner_yvalue, g-> ob_generic);
+ return call_forms_Rf (fl_get_positioner_yvalue, g-> ob_generic);
}
static PyObject *
get_positioner_ybounds (genericobject *g)
{
- return call_forms_OUTfOUTf (fl_get_positioner_ybounds, g-> ob_generic);
+ return call_forms_OUTfOUTf (fl_get_positioner_ybounds, g-> ob_generic);
}
static PyMethodDef positioner_methods[] = {
- {"set_positioner_xvalue", (PyCFunction)set_positioner_xvalue,
- METH_OLDARGS},
- {"set_positioner_yvalue", (PyCFunction)set_positioner_yvalue,
- METH_OLDARGS},
- {"set_positioner_xbounds", (PyCFunction)set_positioner_xbounds,
- METH_OLDARGS},
- {"set_positioner_ybounds", (PyCFunction)set_positioner_ybounds,
- METH_OLDARGS},
- {"get_positioner_xvalue", (PyCFunction)get_positioner_xvalue,
- METH_NOARGS},
- {"get_positioner_yvalue", (PyCFunction)get_positioner_yvalue,
- METH_NOARGS},
- {"get_positioner_xbounds", (PyCFunction)get_positioner_xbounds,
- METH_NOARGS},
- {"get_positioner_ybounds", (PyCFunction)get_positioner_ybounds,
- METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {"set_positioner_xvalue", (PyCFunction)set_positioner_xvalue,
+ METH_OLDARGS},
+ {"set_positioner_yvalue", (PyCFunction)set_positioner_yvalue,
+ METH_OLDARGS},
+ {"set_positioner_xbounds", (PyCFunction)set_positioner_xbounds,
+ METH_OLDARGS},
+ {"set_positioner_ybounds", (PyCFunction)set_positioner_ybounds,
+ METH_OLDARGS},
+ {"get_positioner_xvalue", (PyCFunction)get_positioner_xvalue,
+ METH_NOARGS},
+ {"get_positioner_yvalue", (PyCFunction)get_positioner_yvalue,
+ METH_NOARGS},
+ {"get_positioner_xbounds", (PyCFunction)get_positioner_xbounds,
+ METH_NOARGS},
+ {"get_positioner_ybounds", (PyCFunction)get_positioner_ybounds,
+ METH_NOARGS},
+ {NULL, NULL} /* sentinel */
};
/* Class timer */
@@ -1166,26 +1166,26 @@ static PyMethodDef positioner_methods[] = {
static PyObject *
set_timer (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_timer, g-> ob_generic, args);
+ return call_forms_INf (fl_set_timer, g-> ob_generic, args);
}
static PyObject *
get_timer (genericobject *g)
{
- return call_forms_Rf (fl_get_timer, g-> ob_generic);
+ return call_forms_Rf (fl_get_timer, g-> ob_generic);
}
static PyMethodDef timer_methods[] = {
- {"set_timer", (PyCFunction)set_timer, METH_OLDARGS},
- {"get_timer", (PyCFunction)get_timer, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {"set_timer", (PyCFunction)set_timer, METH_OLDARGS},
+ {"get_timer", (PyCFunction)get_timer, METH_NOARGS},
+ {NULL, NULL} /* sentinel */
};
/* Form objects */
typedef struct {
- PyObject_HEAD
- FL_FORM *ob_form;
+ PyObject_HEAD
+ FL_FORM *ob_form;
} formobject;
static PyTypeObject Formtype;
@@ -1195,371 +1195,371 @@ static PyTypeObject Formtype;
static PyObject *
form_show_form(formobject *f, PyObject *args)
{
- int place, border;
- char *name;
- if (!PyArg_Parse(args, "(iis)", &place, &border, &name))
- return NULL;
- fl_show_form(f->ob_form, place, border, name);
- Py_INCREF(Py_None);
- return Py_None;
+ int place, border;
+ char *name;
+ if (!PyArg_Parse(args, "(iis)", &place, &border, &name))
+ return NULL;
+ fl_show_form(f->ob_form, place, border, name);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
form_call(void (*func)(FL_FORM *), FL_FORM *f)
{
- (*func)(f);
+ (*func)(f);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
form_call_INiINi(void (*func)(FL_FORM *, int, int), FL_FORM *f, PyObject *args)
{
- int a, b;
+ int a, b;
- if (!PyArg_Parse(args, "(ii)", &a, &b)) return NULL;
+ if (!PyArg_Parse(args, "(ii)", &a, &b)) return NULL;
- (*func)(f, a, b);
+ (*func)(f, a, b);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
form_call_INfINf(void (*func)(FL_FORM *, float, float), FL_FORM *f, PyObject *args)
{
- float a, b;
+ float a, b;
- if (!PyArg_Parse(args, "(ff)", &a, &b)) return NULL;
+ if (!PyArg_Parse(args, "(ff)", &a, &b)) return NULL;
- (*func)(f, a, b);
+ (*func)(f, a, b);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
form_hide_form(formobject *f)
{
- return form_call(fl_hide_form, f-> ob_form);
+ return form_call(fl_hide_form, f-> ob_form);
}
static PyObject *
form_redraw_form(formobject *f)
{
- return form_call(fl_redraw_form, f-> ob_form);
+ return form_call(fl_redraw_form, f-> ob_form);
}
static PyObject *
form_set_form_position(formobject *f, PyObject *args)
{
- return form_call_INiINi(fl_set_form_position, f-> ob_form, args);
+ return form_call_INiINi(fl_set_form_position, f-> ob_form, args);
}
static PyObject *
form_set_form_size(formobject *f, PyObject *args)
{
- return form_call_INiINi(fl_set_form_size, f-> ob_form, args);
+ return form_call_INiINi(fl_set_form_size, f-> ob_form, args);
}
static PyObject *
form_scale_form(formobject *f, PyObject *args)
{
- return form_call_INfINf(fl_scale_form, f-> ob_form, args);
+ return form_call_INfINf(fl_scale_form, f-> ob_form, args);
}
static PyObject *
generic_add_object(formobject *f, PyObject *args, FL_OBJECT *(*func)(int, float, float, float, float, char*), PyMethodDef *internal_methods)
{
- int type;
- float x, y, w, h;
- char *name;
- FL_OBJECT *obj;
+ int type;
+ float x, y, w, h;
+ char *name;
+ FL_OBJECT *obj;
- if (!PyArg_Parse(args,"(iffffs)", &type,&x,&y,&w,&h,&name))
- return NULL;
+ if (!PyArg_Parse(args,"(iffffs)", &type,&x,&y,&w,&h,&name))
+ return NULL;
- fl_addto_form (f-> ob_form);
+ fl_addto_form (f-> ob_form);
- obj = (*func) (type, x, y, w, h, name);
+ obj = (*func) (type, x, y, w, h, name);
- fl_end_form();
+ fl_end_form();
- if (obj == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
+ if (obj == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
- return newgenericobject (obj, internal_methods);
+ return newgenericobject (obj, internal_methods);
}
static PyObject *
form_add_button(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_button, button_methods);
+ return generic_add_object(f, args, fl_add_button, button_methods);
}
static PyObject *
form_add_lightbutton(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_lightbutton, button_methods);
+ return generic_add_object(f, args, fl_add_lightbutton, button_methods);
}
static PyObject *
form_add_roundbutton(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_roundbutton, button_methods);
+ return generic_add_object(f, args, fl_add_roundbutton, button_methods);
}
static PyObject *
form_add_menu (formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_menu, menu_methods);
+ return generic_add_object(f, args, fl_add_menu, menu_methods);
}
static PyObject *
form_add_slider(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_slider, slider_methods);
+ return generic_add_object(f, args, fl_add_slider, slider_methods);
}
static PyObject *
form_add_valslider(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_valslider, slider_methods);
+ return generic_add_object(f, args, fl_add_valslider, slider_methods);
}
static PyObject *
form_add_dial(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_dial, dial_methods);
+ return generic_add_object(f, args, fl_add_dial, dial_methods);
}
static PyObject *
form_add_counter(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_counter, counter_methods);
+ return generic_add_object(f, args, fl_add_counter, counter_methods);
}
static PyObject *
form_add_clock(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_clock, clock_methods);
+ return generic_add_object(f, args, fl_add_clock, clock_methods);
}
static PyObject *
form_add_box(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_box,
- (PyMethodDef *)NULL);
+ return generic_add_object(f, args, fl_add_box,
+ (PyMethodDef *)NULL);
}
static PyObject *
form_add_choice(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_choice, choice_methods);
+ return generic_add_object(f, args, fl_add_choice, choice_methods);
}
static PyObject *
form_add_browser(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_browser, browser_methods);
+ return generic_add_object(f, args, fl_add_browser, browser_methods);
}
static PyObject *
form_add_positioner(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_positioner,
- positioner_methods);
+ return generic_add_object(f, args, fl_add_positioner,
+ positioner_methods);
}
static PyObject *
form_add_input(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_input, input_methods);
+ return generic_add_object(f, args, fl_add_input, input_methods);
}
static PyObject *
form_add_text(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_text,
- (PyMethodDef *)NULL);
+ return generic_add_object(f, args, fl_add_text,
+ (PyMethodDef *)NULL);
}
static PyObject *
form_add_timer(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_timer, timer_methods);
+ return generic_add_object(f, args, fl_add_timer, timer_methods);
}
static PyObject *
form_freeze_form(formobject *f)
{
- return form_call(fl_freeze_form, f-> ob_form);
+ return form_call(fl_freeze_form, f-> ob_form);
}
static PyObject *
form_unfreeze_form(formobject *f)
{
- return form_call(fl_unfreeze_form, f-> ob_form);
+ return form_call(fl_unfreeze_form, f-> ob_form);
}
static PyObject *
form_activate_form(formobject *f)
{
- return form_call(fl_activate_form, f-> ob_form);
+ return form_call(fl_activate_form, f-> ob_form);
}
static PyObject *
form_deactivate_form(formobject *f)
{
- return form_call(fl_deactivate_form, f-> ob_form);
+ return form_call(fl_deactivate_form, f-> ob_form);
}
static PyObject *
form_bgn_group(formobject *f, PyObject *args)
{
- FL_OBJECT *obj;
+ FL_OBJECT *obj;
- fl_addto_form(f-> ob_form);
- obj = fl_bgn_group();
- fl_end_form();
+ fl_addto_form(f-> ob_form);
+ obj = fl_bgn_group();
+ fl_end_form();
- if (obj == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
+ if (obj == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
- return newgenericobject (obj, (PyMethodDef *) NULL);
+ return newgenericobject (obj, (PyMethodDef *) NULL);
}
static PyObject *
form_end_group(formobject *f, PyObject *args)
{
- fl_addto_form(f-> ob_form);
- fl_end_group();
- fl_end_form();
- Py_INCREF(Py_None);
- return Py_None;
+ fl_addto_form(f-> ob_form);
+ fl_end_group();
+ fl_end_form();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_find_first_or_last(FL_OBJECT *(*func)(FL_FORM *, int, float, float), formobject *f, PyObject *args)
{
- int type;
- float mx, my;
- FL_OBJECT *generic;
- genericobject *g;
-
- if (!PyArg_Parse(args, "(iff)", &type, &mx, &my)) return NULL;
+ int type;
+ float mx, my;
+ FL_OBJECT *generic;
+ genericobject *g;
- generic = (*func) (f-> ob_form, type, mx, my);
+ if (!PyArg_Parse(args, "(iff)", &type, &mx, &my)) return NULL;
- if (generic == NULL)
- {
- Py_INCREF(Py_None);
- return Py_None;
- }
+ generic = (*func) (f-> ob_form, type, mx, my);
- g = findgeneric(generic);
- if (g == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "forms_find_{first|last} returns unknown object");
- return NULL;
- }
- Py_INCREF(g);
- return (PyObject *) g;
+ if (generic == NULL)
+ {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+
+ g = findgeneric(generic);
+ if (g == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "forms_find_{first|last} returns unknown object");
+ return NULL;
+ }
+ Py_INCREF(g);
+ return (PyObject *) g;
}
static PyObject *
form_find_first(formobject *f, PyObject *args)
{
- return forms_find_first_or_last(fl_find_first, f, args);
+ return forms_find_first_or_last(fl_find_first, f, args);
}
static PyObject *
form_find_last(formobject *f, PyObject *args)
{
- return forms_find_first_or_last(fl_find_last, f, args);
+ return forms_find_first_or_last(fl_find_last, f, args);
}
static PyObject *
form_set_object_focus(formobject *f, PyObject *args)
{
- genericobject *g;
- if (args == NULL || !is_genericobject(args)) {
- PyErr_BadArgument();
- return NULL;
- }
- g = (genericobject *)args;
- fl_set_object_focus(f->ob_form, g->ob_generic);
- Py_INCREF(Py_None);
- return Py_None;
+ genericobject *g;
+ if (args == NULL || !is_genericobject(args)) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ g = (genericobject *)args;
+ fl_set_object_focus(f->ob_form, g->ob_generic);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef form_methods[] = {
/* adm */
- {"show_form", (PyCFunction)form_show_form, METH_OLDARGS},
- {"hide_form", (PyCFunction)form_hide_form, METH_NOARGS},
- {"redraw_form", (PyCFunction)form_redraw_form, METH_NOARGS},
- {"set_form_position", (PyCFunction)form_set_form_position, METH_OLDARGS},
- {"set_form_size", (PyCFunction)form_set_form_size, METH_OLDARGS},
- {"scale_form", (PyCFunction)form_scale_form, METH_OLDARGS},
- {"freeze_form", (PyCFunction)form_freeze_form, METH_NOARGS},
- {"unfreeze_form", (PyCFunction)form_unfreeze_form, METH_NOARGS},
- {"activate_form", (PyCFunction)form_activate_form, METH_NOARGS},
- {"deactivate_form", (PyCFunction)form_deactivate_form, METH_NOARGS},
- {"bgn_group", (PyCFunction)form_bgn_group, METH_OLDARGS},
- {"end_group", (PyCFunction)form_end_group, METH_OLDARGS},
- {"find_first", (PyCFunction)form_find_first, METH_OLDARGS},
- {"find_last", (PyCFunction)form_find_last, METH_OLDARGS},
- {"set_object_focus", (PyCFunction)form_set_object_focus, METH_OLDARGS},
+ {"show_form", (PyCFunction)form_show_form, METH_OLDARGS},
+ {"hide_form", (PyCFunction)form_hide_form, METH_NOARGS},
+ {"redraw_form", (PyCFunction)form_redraw_form, METH_NOARGS},
+ {"set_form_position", (PyCFunction)form_set_form_position, METH_OLDARGS},
+ {"set_form_size", (PyCFunction)form_set_form_size, METH_OLDARGS},
+ {"scale_form", (PyCFunction)form_scale_form, METH_OLDARGS},
+ {"freeze_form", (PyCFunction)form_freeze_form, METH_NOARGS},
+ {"unfreeze_form", (PyCFunction)form_unfreeze_form, METH_NOARGS},
+ {"activate_form", (PyCFunction)form_activate_form, METH_NOARGS},
+ {"deactivate_form", (PyCFunction)form_deactivate_form, METH_NOARGS},
+ {"bgn_group", (PyCFunction)form_bgn_group, METH_OLDARGS},
+ {"end_group", (PyCFunction)form_end_group, METH_OLDARGS},
+ {"find_first", (PyCFunction)form_find_first, METH_OLDARGS},
+ {"find_last", (PyCFunction)form_find_last, METH_OLDARGS},
+ {"set_object_focus", (PyCFunction)form_set_object_focus, METH_OLDARGS},
/* basic objects */
- {"add_button", (PyCFunction)form_add_button, METH_OLDARGS},
-/* {"add_bitmap", (method)form_add_bitmap, METH_OLDARGS}, */
- {"add_lightbutton", (PyCFunction)form_add_lightbutton, METH_OLDARGS},
- {"add_roundbutton", (PyCFunction)form_add_roundbutton, METH_OLDARGS},
- {"add_menu", (PyCFunction)form_add_menu, METH_OLDARGS},
- {"add_slider", (PyCFunction)form_add_slider, METH_OLDARGS},
- {"add_positioner", (PyCFunction)form_add_positioner, METH_OLDARGS},
- {"add_valslider", (PyCFunction)form_add_valslider, METH_OLDARGS},
- {"add_dial", (PyCFunction)form_add_dial, METH_OLDARGS},
- {"add_counter", (PyCFunction)form_add_counter, METH_OLDARGS},
- {"add_box", (PyCFunction)form_add_box, METH_OLDARGS},
- {"add_clock", (PyCFunction)form_add_clock, METH_OLDARGS},
- {"add_choice", (PyCFunction)form_add_choice, METH_OLDARGS},
- {"add_browser", (PyCFunction)form_add_browser, METH_OLDARGS},
- {"add_input", (PyCFunction)form_add_input, METH_OLDARGS},
- {"add_timer", (PyCFunction)form_add_timer, METH_OLDARGS},
- {"add_text", (PyCFunction)form_add_text, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"add_button", (PyCFunction)form_add_button, METH_OLDARGS},
+/* {"add_bitmap", (method)form_add_bitmap, METH_OLDARGS}, */
+ {"add_lightbutton", (PyCFunction)form_add_lightbutton, METH_OLDARGS},
+ {"add_roundbutton", (PyCFunction)form_add_roundbutton, METH_OLDARGS},
+ {"add_menu", (PyCFunction)form_add_menu, METH_OLDARGS},
+ {"add_slider", (PyCFunction)form_add_slider, METH_OLDARGS},
+ {"add_positioner", (PyCFunction)form_add_positioner, METH_OLDARGS},
+ {"add_valslider", (PyCFunction)form_add_valslider, METH_OLDARGS},
+ {"add_dial", (PyCFunction)form_add_dial, METH_OLDARGS},
+ {"add_counter", (PyCFunction)form_add_counter, METH_OLDARGS},
+ {"add_box", (PyCFunction)form_add_box, METH_OLDARGS},
+ {"add_clock", (PyCFunction)form_add_clock, METH_OLDARGS},
+ {"add_choice", (PyCFunction)form_add_choice, METH_OLDARGS},
+ {"add_browser", (PyCFunction)form_add_browser, METH_OLDARGS},
+ {"add_input", (PyCFunction)form_add_input, METH_OLDARGS},
+ {"add_timer", (PyCFunction)form_add_timer, METH_OLDARGS},
+ {"add_text", (PyCFunction)form_add_text, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
static void
form_dealloc(formobject *f)
{
- releaseobjects(f->ob_form);
- if (f->ob_form->visible)
- fl_hide_form(f->ob_form);
- fl_free_form(f->ob_form);
- PyObject_Del(f);
+ releaseobjects(f->ob_form);
+ if (f->ob_form->visible)
+ fl_hide_form(f->ob_form);
+ fl_free_form(f->ob_form);
+ PyObject_Del(f);
}
#define OFF(x) offsetof(FL_FORM, x)
static struct memberlist form_memberlist[] = {
- {"window", T_LONG, OFF(window), RO},
- {"w", T_FLOAT, OFF(w)},
- {"h", T_FLOAT, OFF(h)},
- {"x", T_FLOAT, OFF(x), RO},
- {"y", T_FLOAT, OFF(y), RO},
- {"deactivated", T_INT, OFF(deactivated)},
- {"visible", T_INT, OFF(visible), RO},
- {"frozen", T_INT, OFF(frozen), RO},
- {"doublebuf", T_INT, OFF(doublebuf)},
- {NULL} /* Sentinel */
+ {"window", T_LONG, OFF(window), RO},
+ {"w", T_FLOAT, OFF(w)},
+ {"h", T_FLOAT, OFF(h)},
+ {"x", T_FLOAT, OFF(x), RO},
+ {"y", T_FLOAT, OFF(y), RO},
+ {"deactivated", T_INT, OFF(deactivated)},
+ {"visible", T_INT, OFF(visible), RO},
+ {"frozen", T_INT, OFF(frozen), RO},
+ {"doublebuf", T_INT, OFF(doublebuf)},
+ {NULL} /* Sentinel */
};
#undef OFF
@@ -1567,60 +1567,60 @@ static struct memberlist form_memberlist[] = {
static PyObject *
form_getattr(formobject *f, char *name)
{
- PyObject *meth;
+ PyObject *meth;
- meth = Py_FindMethod(form_methods, (PyObject *)f, name);
- if (meth != NULL)
- return meth;
- PyErr_Clear();
- return PyMember_Get((char *)f->ob_form, form_memberlist, name);
+ meth = Py_FindMethod(form_methods, (PyObject *)f, name);
+ if (meth != NULL)
+ return meth;
+ PyErr_Clear();
+ return PyMember_Get((char *)f->ob_form, form_memberlist, name);
}
static int
form_setattr(formobject *f, char *name, PyObject *v)
{
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete form attributes");
- return -1;
- }
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete form attributes");
+ return -1;
+ }
- return PyMember_Set((char *)f->ob_form, form_memberlist, name, v);
+ return PyMember_Set((char *)f->ob_form, form_memberlist, name, v);
}
static PyObject *
form_repr(formobject *f)
{
- char buf[100];
- PyOS_snprintf(buf, sizeof(buf), "<FORMS_form at %p, window=%ld>",
- f, f->ob_form->window);
- return PyString_FromString(buf);
+ char buf[100];
+ PyOS_snprintf(buf, sizeof(buf), "<FORMS_form at %p, window=%ld>",
+ f, f->ob_form->window);
+ return PyString_FromString(buf);
}
static PyTypeObject Formtype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "fl.FORMS_form", /*tp_name*/
- sizeof(formobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)form_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)form_getattr, /*tp_getattr*/
- (setattrfunc)form_setattr, /*tp_setattr*/
- 0, /*tp_compare*/
- (reprfunc)form_repr, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "fl.FORMS_form", /*tp_name*/
+ sizeof(formobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)form_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)form_getattr, /*tp_getattr*/
+ (setattrfunc)form_setattr, /*tp_setattr*/
+ 0, /*tp_compare*/
+ (reprfunc)form_repr, /*tp_repr*/
};
static PyObject *
newformobject(FL_FORM *form)
{
- formobject *f;
- f = PyObject_New(formobject, &Formtype);
- if (f == NULL)
- return NULL;
- f->ob_form = form;
- return (PyObject *)f;
+ formobject *f;
+ f = PyObject_New(formobject, &Formtype);
+ if (f == NULL)
+ return NULL;
+ f->ob_form = form;
+ return (PyObject *)f;
}
@@ -1629,35 +1629,35 @@ newformobject(FL_FORM *form)
static PyObject *
forms_make_form(PyObject *dummy, PyObject *args)
{
- int type;
- float w, h;
- FL_FORM *form;
- if (!PyArg_Parse(args, "(iff)", &type, &w, &h))
- return NULL;
- form = fl_bgn_form(type, w, h);
- if (form == NULL) {
- /* XXX Actually, cannot happen! */
- PyErr_NoMemory();
- return NULL;
- }
- fl_end_form();
- return newformobject(form);
+ int type;
+ float w, h;
+ FL_FORM *form;
+ if (!PyArg_Parse(args, "(iff)", &type, &w, &h))
+ return NULL;
+ form = fl_bgn_form(type, w, h);
+ if (form == NULL) {
+ /* XXX Actually, cannot happen! */
+ PyErr_NoMemory();
+ return NULL;
+ }
+ fl_end_form();
+ return newformobject(form);
}
static PyObject *
forms_activate_all_forms(PyObject *f, PyObject *args)
{
- fl_activate_all_forms();
- Py_INCREF(Py_None);
- return Py_None;
+ fl_activate_all_forms();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_deactivate_all_forms(PyObject *f, PyObject *args)
{
- fl_deactivate_all_forms();
- Py_INCREF(Py_None);
- return Py_None;
+ fl_deactivate_all_forms();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *my_event_callback = NULL;
@@ -1665,479 +1665,479 @@ static PyObject *my_event_callback = NULL;
static PyObject *
forms_set_event_call_back(PyObject *dummy, PyObject *args)
{
- if (args == Py_None)
- args = NULL;
- my_event_callback = args;
- Py_XINCREF(args);
- Py_INCREF(Py_None);
- return Py_None;
+ if (args == Py_None)
+ args = NULL;
+ my_event_callback = args;
+ Py_XINCREF(args);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_do_or_check_forms(PyObject *dummy, FL_OBJECT *(*func)(void))
{
- FL_OBJECT *generic;
- genericobject *g;
- PyObject *arg, *res;
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- generic = (*func)();
- Py_END_ALLOW_THREADS
- if (generic == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (generic == FL_EVENT) {
- int dev;
- short val;
- if (my_event_callback == NULL)
- return PyInt_FromLong(-1L);
- dev = fl_qread(&val);
- arg = Py_BuildValue("(ih)", dev, val);
- if (arg == NULL)
- return NULL;
- res = PyEval_CallObject(my_event_callback, arg);
- Py_XDECREF(res);
- Py_DECREF(arg);
- if (res == NULL)
- return NULL; /* Callback raised exception */
- continue;
- }
- g = findgeneric(generic);
- if (g == NULL) {
- /* Object not known to us (some dialogs cause this) */
- continue; /* Ignore it */
- }
- if (g->ob_callback == NULL) {
- Py_INCREF(g);
- return ((PyObject *) g);
- }
- arg = PyTuple_Pack(2, (PyObject *)g, g->ob_callback_arg);
- if (arg == NULL)
- return NULL;
- res = PyEval_CallObject(g->ob_callback, arg);
- Py_XDECREF(res);
- Py_DECREF(arg);
- if (res == NULL)
- return NULL; /* Callback raised exception */
- }
+ FL_OBJECT *generic;
+ genericobject *g;
+ PyObject *arg, *res;
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ generic = (*func)();
+ Py_END_ALLOW_THREADS
+ if (generic == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (generic == FL_EVENT) {
+ int dev;
+ short val;
+ if (my_event_callback == NULL)
+ return PyInt_FromLong(-1L);
+ dev = fl_qread(&val);
+ arg = Py_BuildValue("(ih)", dev, val);
+ if (arg == NULL)
+ return NULL;
+ res = PyEval_CallObject(my_event_callback, arg);
+ Py_XDECREF(res);
+ Py_DECREF(arg);
+ if (res == NULL)
+ return NULL; /* Callback raised exception */
+ continue;
+ }
+ g = findgeneric(generic);
+ if (g == NULL) {
+ /* Object not known to us (some dialogs cause this) */
+ continue; /* Ignore it */
+ }
+ if (g->ob_callback == NULL) {
+ Py_INCREF(g);
+ return ((PyObject *) g);
+ }
+ arg = PyTuple_Pack(2, (PyObject *)g, g->ob_callback_arg);
+ if (arg == NULL)
+ return NULL;
+ res = PyEval_CallObject(g->ob_callback, arg);
+ Py_XDECREF(res);
+ Py_DECREF(arg);
+ if (res == NULL)
+ return NULL; /* Callback raised exception */
+ }
}
static PyObject *
forms_do_forms(PyObject *dummy)
{
- return forms_do_or_check_forms(dummy, fl_do_forms);
+ return forms_do_or_check_forms(dummy, fl_do_forms);
}
static PyObject *
forms_check_forms(PyObject *dummy)
{
- return forms_do_or_check_forms(dummy, fl_check_forms);
+ return forms_do_or_check_forms(dummy, fl_check_forms);
}
static PyObject *
forms_do_only_forms(PyObject *dummy)
{
- return forms_do_or_check_forms(dummy, fl_do_only_forms);
+ return forms_do_or_check_forms(dummy, fl_do_only_forms);
}
static PyObject *
forms_check_only_forms(PyObject *dummy)
{
- return forms_do_or_check_forms(dummy, fl_check_only_forms);
+ return forms_do_or_check_forms(dummy, fl_check_only_forms);
}
#ifdef UNUSED
static PyObject *
fl_call(void (*func)(void))
{
- (*func)();
- Py_INCREF(Py_None);
- return Py_None;
+ (*func)();
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif
static PyObject *
forms_set_graphics_mode(PyObject *dummy, PyObject *args)
{
- int rgbmode, doublebuf;
+ int rgbmode, doublebuf;
- if (!PyArg_Parse(args, "(ii)", &rgbmode, &doublebuf))
- return NULL;
- fl_set_graphics_mode(rgbmode,doublebuf);
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_Parse(args, "(ii)", &rgbmode, &doublebuf))
+ return NULL;
+ fl_set_graphics_mode(rgbmode,doublebuf);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_get_rgbmode(PyObject *dummy, PyObject *args)
{
- extern int fl_rgbmode;
+ extern int fl_rgbmode;
- if (args != NULL) {
- PyErr_BadArgument();
- return NULL;
- }
- return PyInt_FromLong((long)fl_rgbmode);
+ if (args != NULL) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ return PyInt_FromLong((long)fl_rgbmode);
}
static PyObject *
forms_show_errors(PyObject *dummy, PyObject *args)
{
- int show;
- if (!PyArg_Parse(args, "i", &show))
- return NULL;
- fl_show_errors(show);
- Py_INCREF(Py_None);
- return Py_None;
+ int show;
+ if (!PyArg_Parse(args, "i", &show))
+ return NULL;
+ fl_show_errors(show);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_set_font_name(PyObject *dummy, PyObject *args)
{
- int numb;
- char *name;
- if (!PyArg_Parse(args, "(is)", &numb, &name))
- return NULL;
- fl_set_font_name(numb, name);
- Py_INCREF(Py_None);
- return Py_None;
+ int numb;
+ char *name;
+ if (!PyArg_Parse(args, "(is)", &numb, &name))
+ return NULL;
+ fl_set_font_name(numb, name);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_qdevice(PyObject *self, PyObject *args)
{
- short arg1;
- if (!PyArg_Parse(args, "h", &arg1))
- return NULL;
- fl_qdevice(arg1);
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1;
+ if (!PyArg_Parse(args, "h", &arg1))
+ return NULL;
+ fl_qdevice(arg1);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_unqdevice(PyObject *self, PyObject *args)
{
- short arg1;
- if (!PyArg_Parse(args, "h", &arg1))
- return NULL;
- fl_unqdevice(arg1);
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1;
+ if (!PyArg_Parse(args, "h", &arg1))
+ return NULL;
+ fl_unqdevice(arg1);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_isqueued(PyObject *self, PyObject *args)
{
- long retval;
- short arg1;
- if (!PyArg_Parse(args, "h", &arg1))
- return NULL;
- retval = fl_isqueued(arg1);
+ long retval;
+ short arg1;
+ if (!PyArg_Parse(args, "h", &arg1))
+ return NULL;
+ retval = fl_isqueued(arg1);
- return PyInt_FromLong(retval);
+ return PyInt_FromLong(retval);
}
static PyObject *
forms_qtest(PyObject *self, PyObject *args)
{
- long retval;
- retval = fl_qtest();
- return PyInt_FromLong(retval);
+ long retval;
+ retval = fl_qtest();
+ return PyInt_FromLong(retval);
}
static PyObject *
forms_qread(PyObject *self, PyObject *args)
{
- int dev;
- short val;
- Py_BEGIN_ALLOW_THREADS
- dev = fl_qread(&val);
- Py_END_ALLOW_THREADS
- return Py_BuildValue("(ih)", dev, val);
+ int dev;
+ short val;
+ Py_BEGIN_ALLOW_THREADS
+ dev = fl_qread(&val);
+ Py_END_ALLOW_THREADS
+ return Py_BuildValue("(ih)", dev, val);
}
static PyObject *
forms_qreset(PyObject *self)
{
- fl_qreset();
- Py_INCREF(Py_None);
- return Py_None;
+ fl_qreset();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_qenter(PyObject *self, PyObject *args)
{
- short arg1, arg2;
- if (!PyArg_Parse(args, "(hh)", &arg1, &arg2))
- return NULL;
- fl_qenter(arg1, arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1, arg2;
+ if (!PyArg_Parse(args, "(hh)", &arg1, &arg2))
+ return NULL;
+ fl_qenter(arg1, arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_color(PyObject *self, PyObject *args)
{
- int arg;
+ int arg;
- if (!PyArg_Parse(args, "i", &arg)) return NULL;
+ if (!PyArg_Parse(args, "i", &arg)) return NULL;
- fl_color((short) arg);
+ fl_color((short) arg);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_mapcolor(PyObject *self, PyObject *args)
{
- int arg0, arg1, arg2, arg3;
+ int arg0, arg1, arg2, arg3;
- if (!PyArg_Parse(args, "(iiii)", &arg0, &arg1, &arg2, &arg3))
- return NULL;
+ if (!PyArg_Parse(args, "(iiii)", &arg0, &arg1, &arg2, &arg3))
+ return NULL;
- fl_mapcolor(arg0, (short) arg1, (short) arg2, (short) arg3);
+ fl_mapcolor(arg0, (short) arg1, (short) arg2, (short) arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_getmcolor(PyObject *self, PyObject *args)
{
- int arg;
- short r, g, b;
+ int arg;
+ short r, g, b;
- if (!PyArg_Parse(args, "i", &arg)) return NULL;
+ if (!PyArg_Parse(args, "i", &arg)) return NULL;
- fl_getmcolor(arg, &r, &g, &b);
+ fl_getmcolor(arg, &r, &g, &b);
- return Py_BuildValue("(hhh)", r, g, b);
+ return Py_BuildValue("(hhh)", r, g, b);
}
static PyObject *
forms_get_mouse(PyObject *self)
{
- float x, y;
+ float x, y;
- fl_get_mouse(&x, &y);
+ fl_get_mouse(&x, &y);
- return Py_BuildValue("(ff)", x, y);
+ return Py_BuildValue("(ff)", x, y);
}
static PyObject *
forms_tie(PyObject *self, PyObject *args)
{
- short arg1, arg2, arg3;
- if (!PyArg_Parse(args, "(hhh)", &arg1, &arg2, &arg3))
- return NULL;
- fl_tie(arg1, arg2, arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1, arg2, arg3;
+ if (!PyArg_Parse(args, "(hhh)", &arg1, &arg2, &arg3))
+ return NULL;
+ fl_tie(arg1, arg2, arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_show_message(PyObject *f, PyObject *args)
{
- char *a, *b, *c;
+ char *a, *b, *c;
- if (!PyArg_Parse(args, "(sss)", &a, &b, &c)) return NULL;
+ if (!PyArg_Parse(args, "(sss)", &a, &b, &c)) return NULL;
- Py_BEGIN_ALLOW_THREADS
- fl_show_message(a, b, c);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ fl_show_message(a, b, c);
+ Py_END_ALLOW_THREADS
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_show_choice(PyObject *f, PyObject *args)
{
- char *m1, *m2, *m3, *b1, *b2, *b3;
- int nb;
- char *format;
- long rv;
-
- if (args == NULL || !PyTuple_Check(args)) {
- PyErr_BadArgument();
- return NULL;
- }
- nb = PyTuple_Size(args) - 3;
- if (nb <= 0) {
- PyErr_SetString(PyExc_TypeError,
- "need at least one button label");
- return NULL;
- }
- if (PyInt_Check(PyTuple_GetItem(args, 3))) {
- PyErr_SetString(PyExc_TypeError,
- "'number-of-buttons' argument not needed");
- return NULL;
- }
- switch (nb) {
- case 1: format = "(ssss)"; break;
- case 2: format = "(sssss)"; break;
- case 3: format = "(ssssss)"; break;
- default:
- PyErr_SetString(PyExc_TypeError, "too many button labels");
- return NULL;
- }
-
- if (!PyArg_Parse(args, format, &m1, &m2, &m3, &b1, &b2, &b3))
- return NULL;
-
- Py_BEGIN_ALLOW_THREADS
- rv = fl_show_choice(m1, m2, m3, nb, b1, b2, b3);
- Py_END_ALLOW_THREADS
- return PyInt_FromLong(rv);
+ char *m1, *m2, *m3, *b1, *b2, *b3;
+ int nb;
+ char *format;
+ long rv;
+
+ if (args == NULL || !PyTuple_Check(args)) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ nb = PyTuple_Size(args) - 3;
+ if (nb <= 0) {
+ PyErr_SetString(PyExc_TypeError,
+ "need at least one button label");
+ return NULL;
+ }
+ if (PyInt_Check(PyTuple_GetItem(args, 3))) {
+ PyErr_SetString(PyExc_TypeError,
+ "'number-of-buttons' argument not needed");
+ return NULL;
+ }
+ switch (nb) {
+ case 1: format = "(ssss)"; break;
+ case 2: format = "(sssss)"; break;
+ case 3: format = "(ssssss)"; break;
+ default:
+ PyErr_SetString(PyExc_TypeError, "too many button labels");
+ return NULL;
+ }
+
+ if (!PyArg_Parse(args, format, &m1, &m2, &m3, &b1, &b2, &b3))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ rv = fl_show_choice(m1, m2, m3, nb, b1, b2, b3);
+ Py_END_ALLOW_THREADS
+ return PyInt_FromLong(rv);
}
static PyObject *
forms_show_question(PyObject *f, PyObject *args)
{
- int ret;
- char *a, *b, *c;
+ int ret;
+ char *a, *b, *c;
- if (!PyArg_Parse(args, "(sss)", &a, &b, &c)) return NULL;
+ if (!PyArg_Parse(args, "(sss)", &a, &b, &c)) return NULL;
- Py_BEGIN_ALLOW_THREADS
- ret = fl_show_question(a, b, c);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ ret = fl_show_question(a, b, c);
+ Py_END_ALLOW_THREADS
- return PyInt_FromLong((long) ret);
+ return PyInt_FromLong((long) ret);
}
static PyObject *
forms_show_input(PyObject *f, PyObject *args)
{
- char *str;
- char *a, *b;
+ char *str;
+ char *a, *b;
- if (!PyArg_Parse(args, "(ss)", &a, &b)) return NULL;
+ if (!PyArg_Parse(args, "(ss)", &a, &b)) return NULL;
- Py_BEGIN_ALLOW_THREADS
- str = fl_show_input(a, b);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ str = fl_show_input(a, b);
+ Py_END_ALLOW_THREADS
- if (str == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString(str);
+ if (str == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString(str);
}
static PyObject *
forms_file_selector(PyObject *f, PyObject *args)
{
- char *str;
- char *a, *b, *c, *d;
+ char *str;
+ char *a, *b, *c, *d;
- if (!PyArg_Parse(args, "(ssss)", &a, &b, &c, &d)) return NULL;
+ if (!PyArg_Parse(args, "(ssss)", &a, &b, &c, &d)) return NULL;
- Py_BEGIN_ALLOW_THREADS
- str = fl_show_file_selector(a, b, c, d);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ str = fl_show_file_selector(a, b, c, d);
+ Py_END_ALLOW_THREADS
- if (str == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString(str);
+ if (str == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString(str);
}
static PyObject *
forms_file_selector_func(PyObject *args, char *(*func)(void))
{
- char *str;
+ char *str;
- str = (*func) ();
+ str = (*func) ();
- if (str == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString(str);
+ if (str == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString(str);
}
static PyObject *
forms_get_directory(PyObject *f, PyObject *args)
{
- return forms_file_selector_func(args, fl_get_directory);
+ return forms_file_selector_func(args, fl_get_directory);
}
static PyObject *
forms_get_pattern(PyObject *f, PyObject *args)
{
- return forms_file_selector_func(args, fl_get_pattern);
+ return forms_file_selector_func(args, fl_get_pattern);
}
static PyObject *
forms_get_filename(PyObject *f, PyObject *args)
{
- return forms_file_selector_func(args, fl_get_filename);
+ return forms_file_selector_func(args, fl_get_filename);
}
static PyMethodDef forms_methods[] = {
/* adm */
- {"make_form", forms_make_form, METH_OLDARGS},
- {"activate_all_forms", forms_activate_all_forms, METH_OLDARGS},
- {"deactivate_all_forms",forms_deactivate_all_forms, METH_OLDARGS},
+ {"make_form", forms_make_form, METH_OLDARGS},
+ {"activate_all_forms", forms_activate_all_forms, METH_OLDARGS},
+ {"deactivate_all_forms",forms_deactivate_all_forms, METH_OLDARGS},
/* gl support wrappers */
- {"qdevice", forms_qdevice, METH_OLDARGS},
- {"unqdevice", forms_unqdevice, METH_OLDARGS},
- {"isqueued", forms_isqueued, METH_OLDARGS},
- {"qtest", forms_qtest, METH_OLDARGS},
- {"qread", forms_qread, METH_OLDARGS},
-/* {"blkqread", forms_blkqread, METH_OLDARGS}, */
- {"qreset", forms_qreset, METH_NOARGS},
- {"qenter", forms_qenter, METH_OLDARGS},
- {"get_mouse", forms_get_mouse, METH_NOARGS},
- {"tie", forms_tie, METH_OLDARGS},
-/* {"new_events", forms_new_events, METH_OLDARGS}, */
- {"color", forms_color, METH_OLDARGS},
- {"mapcolor", forms_mapcolor, METH_OLDARGS},
- {"getmcolor", forms_getmcolor, METH_OLDARGS},
+ {"qdevice", forms_qdevice, METH_OLDARGS},
+ {"unqdevice", forms_unqdevice, METH_OLDARGS},
+ {"isqueued", forms_isqueued, METH_OLDARGS},
+ {"qtest", forms_qtest, METH_OLDARGS},
+ {"qread", forms_qread, METH_OLDARGS},
+/* {"blkqread", forms_blkqread, METH_OLDARGS}, */
+ {"qreset", forms_qreset, METH_NOARGS},
+ {"qenter", forms_qenter, METH_OLDARGS},
+ {"get_mouse", forms_get_mouse, METH_NOARGS},
+ {"tie", forms_tie, METH_OLDARGS},
+/* {"new_events", forms_new_events, METH_OLDARGS}, */
+ {"color", forms_color, METH_OLDARGS},
+ {"mapcolor", forms_mapcolor, METH_OLDARGS},
+ {"getmcolor", forms_getmcolor, METH_OLDARGS},
/* interaction */
- {"do_forms", forms_do_forms, METH_NOARGS},
- {"do_only_forms", forms_do_only_forms, METH_NOARGS},
- {"check_forms", forms_check_forms, METH_NOARGS},
- {"check_only_forms", forms_check_only_forms, METH_NOARGS},
- {"set_event_call_back", forms_set_event_call_back, METH_OLDARGS},
+ {"do_forms", forms_do_forms, METH_NOARGS},
+ {"do_only_forms", forms_do_only_forms, METH_NOARGS},
+ {"check_forms", forms_check_forms, METH_NOARGS},
+ {"check_only_forms", forms_check_only_forms, METH_NOARGS},
+ {"set_event_call_back", forms_set_event_call_back, METH_OLDARGS},
/* goodies */
- {"show_message", forms_show_message, METH_OLDARGS},
- {"show_question", forms_show_question, METH_OLDARGS},
- {"show_choice", forms_show_choice, METH_OLDARGS},
- {"show_input", forms_show_input, METH_OLDARGS},
- {"show_file_selector", forms_file_selector, METH_OLDARGS},
- {"file_selector", forms_file_selector, METH_OLDARGS}, /* BW compat */
- {"get_directory", forms_get_directory, METH_OLDARGS},
- {"get_pattern", forms_get_pattern, METH_OLDARGS},
- {"get_filename", forms_get_filename, METH_OLDARGS},
- {"set_graphics_mode", forms_set_graphics_mode, METH_OLDARGS},
- {"get_rgbmode", forms_get_rgbmode, METH_OLDARGS},
- {"show_errors", forms_show_errors, METH_OLDARGS},
- {"set_font_name", forms_set_font_name, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"show_message", forms_show_message, METH_OLDARGS},
+ {"show_question", forms_show_question, METH_OLDARGS},
+ {"show_choice", forms_show_choice, METH_OLDARGS},
+ {"show_input", forms_show_input, METH_OLDARGS},
+ {"show_file_selector", forms_file_selector, METH_OLDARGS},
+ {"file_selector", forms_file_selector, METH_OLDARGS}, /* BW compat */
+ {"get_directory", forms_get_directory, METH_OLDARGS},
+ {"get_pattern", forms_get_pattern, METH_OLDARGS},
+ {"get_filename", forms_get_filename, METH_OLDARGS},
+ {"set_graphics_mode", forms_set_graphics_mode, METH_OLDARGS},
+ {"get_rgbmode", forms_get_rgbmode, METH_OLDARGS},
+ {"show_errors", forms_show_errors, METH_OLDARGS},
+ {"set_font_name", forms_set_font_name, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
initfl(void)
{
-
+
if (PyErr_WarnPy3k("the fl module has been removed in "
"Python 3.0", 2) < 0)
+ return;
+
+ Py_InitModule("fl", forms_methods);
+ if (m == NULL)
return;
-
- Py_InitModule("fl", forms_methods);
- if (m == NULL)
- return;
- foreground();
- fl_init();
+ foreground();
+ fl_init();
}
diff --git a/Modules/fmmodule.c b/Modules/fmmodule.c
index f3f0dc5..3a74107 100644
--- a/Modules/fmmodule.c
+++ b/Modules/fmmodule.c
@@ -11,28 +11,28 @@
/* Font Handle object implementation */
typedef struct {
- PyObject_HEAD
- fmfonthandle fh_fh;
+ PyObject_HEAD
+ fmfonthandle fh_fh;
} fhobject;
static PyTypeObject Fhtype;
-#define is_fhobject(v) ((v)->ob_type == &Fhtype)
+#define is_fhobject(v) ((v)->ob_type == &Fhtype)
static PyObject *
newfhobject(fmfonthandle fh)
{
- fhobject *fhp;
- if (fh == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "error creating new font handle");
- return NULL;
- }
- fhp = PyObject_New(fhobject, &Fhtype);
- if (fhp == NULL)
- return NULL;
- fhp->fh_fh = fh;
- return (PyObject *)fhp;
+ fhobject *fhp;
+ if (fh == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "error creating new font handle");
+ return NULL;
+ }
+ fhp = PyObject_New(fhobject, &Fhtype);
+ if (fhp == NULL)
+ return NULL;
+ fhp->fh_fh = fh;
+ return (PyObject *)fhp;
}
/* Font Handle methods */
@@ -40,10 +40,10 @@ newfhobject(fmfonthandle fh)
static PyObject *
fh_scalefont(fhobject *self, PyObject *args)
{
- double size;
- if (!PyArg_ParseTuple(args, "d", &size))
- return NULL;
- return newfhobject(fmscalefont(self->fh_fh, size));
+ double size;
+ if (!PyArg_ParseTuple(args, "d", &size))
+ return NULL;
+ return newfhobject(fmscalefont(self->fh_fh, size));
}
/* XXX fmmakefont */
@@ -51,54 +51,54 @@ fh_scalefont(fhobject *self, PyObject *args)
static PyObject *
fh_setfont(fhobject *self)
{
- fmsetfont(self->fh_fh);
- Py_INCREF(Py_None);
- return Py_None;
+ fmsetfont(self->fh_fh);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
fh_getfontname(fhobject *self)
{
- char fontname[256];
- int len;
- len = fmgetfontname(self->fh_fh, sizeof fontname, fontname);
- if (len < 0) {
- PyErr_SetString(PyExc_RuntimeError, "error in fmgetfontname");
- return NULL;
- }
- return PyString_FromStringAndSize(fontname, len);
+ char fontname[256];
+ int len;
+ len = fmgetfontname(self->fh_fh, sizeof fontname, fontname);
+ if (len < 0) {
+ PyErr_SetString(PyExc_RuntimeError, "error in fmgetfontname");
+ return NULL;
+ }
+ return PyString_FromStringAndSize(fontname, len);
}
static PyObject *
fh_getcomment(fhobject *self)
{
- char comment[256];
- int len;
- len = fmgetcomment(self->fh_fh, sizeof comment, comment);
- if (len < 0) {
- PyErr_SetString(PyExc_RuntimeError, "error in fmgetcomment");
- return NULL;
- }
- return PyString_FromStringAndSize(comment, len);
+ char comment[256];
+ int len;
+ len = fmgetcomment(self->fh_fh, sizeof comment, comment);
+ if (len < 0) {
+ PyErr_SetString(PyExc_RuntimeError, "error in fmgetcomment");
+ return NULL;
+ }
+ return PyString_FromStringAndSize(comment, len);
}
static PyObject *
fh_getfontinfo(fhobject *self)
{
- fmfontinfo info;
- if (fmgetfontinfo(self->fh_fh, &info) < 0) {
- PyErr_SetString(PyExc_RuntimeError, "error in fmgetfontinfo");
- return NULL;
- }
- return Py_BuildValue("(llllllll)",
- info.printermatched,
- info.fixed_width,
- info.xorig,
- info.yorig,
- info.xsize,
- info.ysize,
- info.height,
- info.nglyphs);
+ fmfontinfo info;
+ if (fmgetfontinfo(self->fh_fh, &info) < 0) {
+ PyErr_SetString(PyExc_RuntimeError, "error in fmgetfontinfo");
+ return NULL;
+ }
+ return Py_BuildValue("(llllllll)",
+ info.printermatched,
+ info.fixed_width,
+ info.xorig,
+ info.yorig,
+ info.xsize,
+ info.ysize,
+ info.height,
+ info.nglyphs);
}
#if 0
@@ -111,51 +111,51 @@ fh_getwholemetrics(fhobject *self, PyObject *args)
static PyObject *
fh_getstrwidth(fhobject *self, PyObject *args)
{
- char *str;
- if (!PyArg_ParseTuple(args, "s", &str))
- return NULL;
- return PyInt_FromLong(fmgetstrwidth(self->fh_fh, str));
+ char *str;
+ if (!PyArg_ParseTuple(args, "s", &str))
+ return NULL;
+ return PyInt_FromLong(fmgetstrwidth(self->fh_fh, str));
}
static PyMethodDef fh_methods[] = {
- {"scalefont", (PyCFunction)fh_scalefont, METH_VARARGS},
- {"setfont", (PyCFunction)fh_setfont, METH_NOARGS},
- {"getfontname", (PyCFunction)fh_getfontname, METH_NOARGS},
- {"getcomment", (PyCFunction)fh_getcomment, METH_NOARGS},
- {"getfontinfo", (PyCFunction)fh_getfontinfo, METH_NOARGS},
+ {"scalefont", (PyCFunction)fh_scalefont, METH_VARARGS},
+ {"setfont", (PyCFunction)fh_setfont, METH_NOARGS},
+ {"getfontname", (PyCFunction)fh_getfontname, METH_NOARGS},
+ {"getcomment", (PyCFunction)fh_getcomment, METH_NOARGS},
+ {"getfontinfo", (PyCFunction)fh_getfontinfo, METH_NOARGS},
#if 0
- {"getwholemetrics", (PyCFunction)fh_getwholemetrics, METH_VARARGS},
+ {"getwholemetrics", (PyCFunction)fh_getwholemetrics, METH_VARARGS},
#endif
- {"getstrwidth", (PyCFunction)fh_getstrwidth, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"getstrwidth", (PyCFunction)fh_getstrwidth, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
fh_getattr(fhobject *fhp, char *name)
{
- return Py_FindMethod(fh_methods, (PyObject *)fhp, name);
+ return Py_FindMethod(fh_methods, (PyObject *)fhp, name);
}
static void
fh_dealloc(fhobject *fhp)
{
- fmfreefont(fhp->fh_fh);
- PyObject_Del(fhp);
+ fmfreefont(fhp->fh_fh);
+ PyObject_Del(fhp);
}
static PyTypeObject Fhtype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "fm.font handle", /*tp_name*/
- sizeof(fhobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)fh_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)fh_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "fm.font handle", /*tp_name*/
+ sizeof(fhobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)fh_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)fh_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
@@ -164,29 +164,29 @@ static PyTypeObject Fhtype = {
static PyObject *
fm_init(PyObject *self)
{
- fminit();
- Py_INCREF(Py_None);
- return Py_None;
+ fminit();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
fm_findfont(PyObject *self, PyObject *args)
{
- char *str;
- if (!PyArg_ParseTuple(args, "s", &str))
- return NULL;
- return newfhobject(fmfindfont(str));
+ char *str;
+ if (!PyArg_ParseTuple(args, "s", &str))
+ return NULL;
+ return newfhobject(fmfindfont(str));
}
static PyObject *
fm_prstr(PyObject *self, PyObject *args)
{
- char *str;
- if (!PyArg_ParseTuple(args, "s", &str))
- return NULL;
- fmprstr(str);
- Py_INCREF(Py_None);
- return Py_None;
+ char *str;
+ if (!PyArg_ParseTuple(args, "s", &str))
+ return NULL;
+ fmprstr(str);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* XXX This uses a global variable as temporary! Not re-entrant! */
@@ -196,74 +196,74 @@ static PyObject *fontlist;
static void
clientproc(char *fontname)
{
- int err;
- PyObject *v;
- if (fontlist == NULL)
- return;
- v = PyString_FromString(fontname);
- if (v == NULL)
- err = -1;
- else {
- err = PyList_Append(fontlist, v);
- Py_DECREF(v);
- }
- if (err != 0) {
- Py_DECREF(fontlist);
- fontlist = NULL;
- }
+ int err;
+ PyObject *v;
+ if (fontlist == NULL)
+ return;
+ v = PyString_FromString(fontname);
+ if (v == NULL)
+ err = -1;
+ else {
+ err = PyList_Append(fontlist, v);
+ Py_DECREF(v);
+ }
+ if (err != 0) {
+ Py_DECREF(fontlist);
+ fontlist = NULL;
+ }
}
static PyObject *
fm_enumerate(PyObject *self)
{
- PyObject *res;
- fontlist = PyList_New(0);
- if (fontlist == NULL)
- return NULL;
- fmenumerate(clientproc);
- res = fontlist;
- fontlist = NULL;
- return res;
+ PyObject *res;
+ fontlist = PyList_New(0);
+ if (fontlist == NULL)
+ return NULL;
+ fmenumerate(clientproc);
+ res = fontlist;
+ fontlist = NULL;
+ return res;
}
static PyObject *
fm_setpath(PyObject *self, PyObject *args)
{
- char *str;
- if (!PyArg_ParseTuple(args, "s", &str))
- return NULL;
- fmsetpath(str);
- Py_INCREF(Py_None);
- return Py_None;
+ char *str;
+ if (!PyArg_ParseTuple(args, "s", &str))
+ return NULL;
+ fmsetpath(str);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
fm_fontpath(PyObject *self)
{
- return PyString_FromString(fmfontpath());
+ return PyString_FromString(fmfontpath());
}
static PyMethodDef fm_methods[] = {
- {"init", fm_init, METH_NOARGS},
- {"findfont", fm_findfont, METH_VARARGS},
- {"enumerate", fm_enumerate, METH_NOARGS},
- {"prstr", fm_prstr, METH_VARARGS},
- {"setpath", fm_setpath, METH_VARARGS},
- {"fontpath", fm_fontpath, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {"init", fm_init, METH_NOARGS},
+ {"findfont", fm_findfont, METH_VARARGS},
+ {"enumerate", fm_enumerate, METH_NOARGS},
+ {"prstr", fm_prstr, METH_VARARGS},
+ {"setpath", fm_setpath, METH_VARARGS},
+ {"fontpath", fm_fontpath, METH_NOARGS},
+ {NULL, NULL} /* sentinel */
};
void
initfm(void)
{
-
+
if (PyErr_WarnPy3k("the fm module has been removed in "
"Python 3.0", 2) < 0)
+ return;
+
+ Py_InitModule("fm", fm_methods);
+ if (m == NULL)
return;
-
- Py_InitModule("fm", fm_methods);
- if (m == NULL)
- return;
- fminit();
+ fminit();
}
diff --git a/Modules/fpectlmodule.c b/Modules/fpectlmodule.c
index 74354ba..faa279b 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
@@ -95,8 +95,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}
};
@@ -121,19 +121,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 ----------------------------------------------------*/
@@ -194,16 +194,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)
@@ -262,13 +262,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
@@ -291,11 +291,11 @@ PyMODINIT_FUNC initfpectl(void)
PyObject *m, *d;
m = Py_InitModule("fpectl", fpectl_methods);
if (m == NULL)
- return;
+ return;
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);
}
#ifdef __cplusplus
diff --git a/Modules/future_builtins.c b/Modules/future_builtins.c
index 4c840fb..1aae2cc 100644
--- a/Modules/future_builtins.c
+++ b/Modules/future_builtins.c
@@ -24,7 +24,7 @@ from future_builtins import hex, oct\n");
static PyObject *
builtin_hex(PyObject *self, PyObject *v)
{
- return PyNumber_ToBase(v, 16);
+ return PyNumber_ToBase(v, 16);
}
PyDoc_STRVAR(hex_doc,
@@ -36,7 +36,7 @@ Return the hexadecimal representation of an integer or long integer.");
static PyObject *
builtin_oct(PyObject *self, PyObject *v)
{
- return PyNumber_ToBase(v, 8);
+ return PyNumber_ToBase(v, 8);
}
PyDoc_STRVAR(oct_doc,
@@ -48,7 +48,7 @@ Return the octal representation of an integer or long integer.");
static PyObject *
builtin_ascii(PyObject *self, PyObject *v)
{
- return PyObject_Repr(v);
+ return PyObject_Repr(v);
}
PyDoc_STRVAR(ascii_doc,
@@ -61,10 +61,10 @@ will have such characters backslash-escaped.");
/* List of functions exported by this module */
static PyMethodDef module_functions[] = {
- {"hex", builtin_hex, METH_O, hex_doc},
- {"oct", builtin_oct, METH_O, oct_doc},
- {"ascii", builtin_ascii, METH_O, ascii_doc},
- {NULL, NULL} /* Sentinel */
+ {"hex", builtin_hex, METH_O, hex_doc},
+ {"oct", builtin_oct, METH_O, oct_doc},
+ {"ascii", builtin_ascii, METH_O, ascii_doc},
+ {NULL, NULL} /* Sentinel */
};
@@ -73,24 +73,24 @@ static PyMethodDef module_functions[] = {
PyMODINIT_FUNC
initfuture_builtins(void)
{
- PyObject *m, *itertools, *iter_func;
- char *it_funcs[] = {"imap", "ifilter", "izip", NULL};
- char **cur_func;
-
- m = Py_InitModule3("future_builtins", module_functions, module_doc);
- if (m == NULL)
- return;
-
- itertools = PyImport_ImportModuleNoBlock("itertools");
- if (itertools == NULL)
- return;
-
- for (cur_func = it_funcs; *cur_func; ++cur_func){
- iter_func = PyObject_GetAttrString(itertools, *cur_func);
- if (iter_func == NULL)
- return;
- PyModule_AddObject(m, *cur_func+1, iter_func);
- }
- Py_DECREF(itertools);
- /* any other initialization needed */
+ PyObject *m, *itertools, *iter_func;
+ char *it_funcs[] = {"imap", "ifilter", "izip", NULL};
+ char **cur_func;
+
+ m = Py_InitModule3("future_builtins", module_functions, module_doc);
+ if (m == NULL)
+ return;
+
+ itertools = PyImport_ImportModuleNoBlock("itertools");
+ if (itertools == NULL)
+ return;
+
+ for (cur_func = it_funcs; *cur_func; ++cur_func){
+ iter_func = PyObject_GetAttrString(itertools, *cur_func);
+ if (iter_func == NULL)
+ return;
+ PyModule_AddObject(m, *cur_func+1, iter_func);
+ }
+ Py_DECREF(itertools);
+ /* any other initialization needed */
}
diff --git a/Modules/gcmodule.c b/Modules/gcmodule.c
index 49cf716..3ccba55 100644
--- a/Modules/gcmodule.c
+++ b/Modules/gcmodule.c
@@ -19,7 +19,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)
@@ -30,10 +30,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
@@ -41,10 +41,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);
@@ -64,17 +64,17 @@ static PyObject *gc_str = NULL;
static PyObject *delstr = NULL;
/* 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_INSTANCES (1<<3) /* print instances */
-#define DEBUG_OBJECTS (1<<4) /* print other objects */
-#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */
-#define DEBUG_LEAK DEBUG_COLLECTABLE | \
- DEBUG_UNCOLLECTABLE | \
- DEBUG_INSTANCES | \
- DEBUG_OBJECTS | \
- 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_INSTANCES (1<<3) /* print instances */
+#define DEBUG_OBJECTS (1<<4) /* print other objects */
+#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */
+#define DEBUG_LEAK DEBUG_COLLECTABLE | \
+ DEBUG_UNCOLLECTABLE | \
+ DEBUG_INSTANCES | \
+ DEBUG_OBJECTS | \
+ DEBUG_SAVEALL
static int debug;
static PyObject *tmod = NULL;
@@ -117,28 +117,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
@@ -147,10 +147,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
@@ -158,9 +158,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
@@ -170,43 +170,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.
@@ -215,16 +215,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 ***/
@@ -237,48 +237,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
@@ -289,57 +289,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,
@@ -353,52 +353,52 @@ 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;
- }
- 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;
+ }
+ 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.
@@ -411,16 +411,16 @@ move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
static int
has_finalizer(PyObject *op)
{
- if (PyInstance_Check(op)) {
- assert(delstr != NULL);
- return _PyInstance_Lookup(op, delstr) != NULL;
- }
- else if (PyType_HasFeature(op->ob_type, Py_TPFLAGS_HEAPTYPE))
- return op->ob_type->tp_del != NULL;
- else if (PyGen_CheckExact(op))
- return PyGen_NeedsFinalizing((PyGenObject *)op);
- else
- return 0;
+ if (PyInstance_Check(op)) {
+ assert(delstr != NULL);
+ return _PyInstance_Lookup(op, delstr) != NULL;
+ }
+ else if (PyType_HasFeature(op->ob_type, Py_TPFLAGS_HEAPTYPE))
+ return op->ob_type->tp_del != NULL;
+ else if (PyGen_CheckExact(op))
+ return PyGen_NeedsFinalizing((PyGenObject *)op);
+ else
+ return 0;
}
/* Move the objects in unreachable with __del__ methods into `finalizers`.
@@ -430,37 +430,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
@@ -469,15 +469,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
@@ -494,169 +494,169 @@ 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_instance(char *msg, PyInstanceObject *inst)
{
- char *cname;
- /* simple version of instance_repr */
- PyObject *classname = inst->in_class->cl_name;
- if (classname != NULL && PyString_Check(classname))
- cname = PyString_AsString(classname);
- else
- cname = "?";
- PySys_WriteStderr("gc: %.100s <%.100s instance at %p>\n",
- msg, cname, inst);
+ char *cname;
+ /* simple version of instance_repr */
+ PyObject *classname = inst->in_class->cl_name;
+ if (classname != NULL && PyString_Check(classname))
+ cname = PyString_AsString(classname);
+ else
+ cname = "?";
+ PySys_WriteStderr("gc: %.100s <%.100s instance at %p>\n",
+ msg, cname, inst);
}
static void
debug_cycle(char *msg, PyObject *op)
{
- if ((debug & DEBUG_INSTANCES) && PyInstance_Check(op)) {
- debug_instance(msg, (PyInstanceObject *)op);
- }
- else if (debug & DEBUG_OBJECTS) {
- PySys_WriteStderr("gc: %.100s <%.100s %p>\n",
- msg, Py_TYPE(op)->tp_name, op);
- }
+ if ((debug & DEBUG_INSTANCES) && PyInstance_Check(op)) {
+ debug_instance(msg, (PyInstanceObject *)op);
+ }
+ else if (debug & DEBUG_OBJECTS) {
+ PySys_WriteStderr("gc: %.100s <%.100s %p>\n",
+ msg, Py_TYPE(op)->tp_name, op);
+ }
}
/* Handle uncollectable garbage (cycles with finalizers, and stuff reachable
@@ -671,56 +671,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
@@ -731,31 +731,31 @@ 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)PyInt_ClearFreeList();
- (void)PyFloat_ClearFreeList();
+ (void)PyMethod_ClearFreeList();
+ (void)PyFrame_ClearFreeList();
+ (void)PyCFunction_ClearFreeList();
+ (void)PyTuple_ClearFreeList();
+ (void)PyUnicode_ClearFreeList();
+ (void)PyInt_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
@@ -763,169 +763,169 @@ 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 = PyString_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)
- gc_list_merge(young, old);
-
- /* 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 higest
- * generation */
- if (generation == NUM_GENERATIONS-1) {
- clear_freelists();
- }
-
- if (PyErr_Occurred()) {
- if (gc_str == NULL)
- gc_str = PyString_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 = PyString_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)
+ gc_list_merge(young, old);
+
+ /* 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 higest
+ * generation */
+ if (generation == NUM_GENERATIONS-1) {
+ clear_freelists();
+ }
+
+ if (PyErr_Occurred()) {
+ if (gc_str == NULL)
+ gc_str = PyString_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 (higest 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) {
- n = collect(i);
- break;
- }
- }
- return n;
+ int i;
+ Py_ssize_t n = 0;
+
+ /* Find the oldest generation (higest 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) {
+ n = collect(i);
+ break;
+ }
+ }
+ return n;
}
PyDoc_STRVAR(gc_enable__doc__,
@@ -936,9 +936,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__,
@@ -949,9 +949,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__,
@@ -962,7 +962,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__,
@@ -976,27 +976,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 PyInt_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 PyInt_FromSsize_t(n);
}
PyDoc_STRVAR(gc_set_debug__doc__,
@@ -1018,11 +1018,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__,
@@ -1033,7 +1033,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__,
@@ -1045,19 +1045,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__,
@@ -1068,10 +1068,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__,
@@ -1082,39 +1082,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__,
@@ -1124,24 +1124,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__,
@@ -1151,27 +1151,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__,
@@ -1183,19 +1183,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;
}
@@ -1216,66 +1216,66 @@ 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__},
- {"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__},
+ {"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 */
};
PyMODINIT_FUNC
initgc(void)
{
- PyObject *m;
-
- m = Py_InitModule4("gc",
- GcMethods,
- gc__doc__,
- NULL,
- PYTHON_API_VERSION);
- if (m == NULL)
- return;
-
- if (garbage == NULL) {
- garbage = PyList_New(0);
- if (garbage == NULL)
- return;
- }
- Py_INCREF(garbage);
- if (PyModule_AddObject(m, "garbage", garbage) < 0)
- return;
-
- /* 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 = Py_InitModule4("gc",
+ GcMethods,
+ gc__doc__,
+ NULL,
+ PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
+
+ if (garbage == NULL) {
+ garbage = PyList_New(0);
+ if (garbage == NULL)
+ return;
+ }
+ Py_INCREF(garbage);
+ if (PyModule_AddObject(m, "garbage", garbage) < 0)
+ return;
+
+ /* 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
- ADD_INT(DEBUG_STATS);
- ADD_INT(DEBUG_COLLECTABLE);
- ADD_INT(DEBUG_UNCOLLECTABLE);
- ADD_INT(DEBUG_INSTANCES);
- ADD_INT(DEBUG_OBJECTS);
- ADD_INT(DEBUG_SAVEALL);
- ADD_INT(DEBUG_LEAK);
+ ADD_INT(DEBUG_STATS);
+ ADD_INT(DEBUG_COLLECTABLE);
+ ADD_INT(DEBUG_UNCOLLECTABLE);
+ ADD_INT(DEBUG_INSTANCES);
+ ADD_INT(DEBUG_OBJECTS);
+ ADD_INT(DEBUG_SAVEALL);
+ ADD_INT(DEBUG_LEAK);
#undef ADD_INT
}
@@ -1283,24 +1283,24 @@ initgc(void)
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
@@ -1314,7 +1314,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 */
@@ -1327,11 +1327,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 */
@@ -1344,73 +1344,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 4d19c34..1d0bfbb 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 Py_PROTO((const char *, struct gai_afd *,
- struct addrinfo **, char *, struct addrinfo *,
- int));
+ struct addrinfo **, char *, struct addrinfo *,
+ int));
static int get_addr Py_PROTO((const char *, int, struct addrinfo **,
- struct addrinfo *, int));
+ struct addrinfo *, int));
static int str_isnumber Py_PROTO((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 d3c0ac5..7892ae9 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 Py_PROTO((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 682ad3e..9653d3e 100644
--- a/Modules/getpath.c
+++ b/Modules/getpath.c
@@ -216,7 +216,7 @@ joinpath(char *buffer, char *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 = strlen(stuff);
if (n + k > MAXPATHLEN)
k = MAXPATHLEN - n;
@@ -393,13 +393,13 @@ calculate_path(void)
#endif
#endif
- /* 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 (strchr(prog, SEP))
- strncpy(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 (strchr(prog, SEP))
+ strncpy(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"
@@ -414,44 +414,44 @@ calculate_path(void)
else if(0 == _NSGetExecutablePath(progpath, &nsexeclength) && progpath[0] == SEP)
;
#endif /* __APPLE__ */
- else if (path) {
- while (1) {
- char *delim = strchr(path, DELIM);
-
- if (delim) {
- size_t len = delim - path;
- if (len > MAXPATHLEN)
- len = MAXPATHLEN;
- strncpy(progpath, path, len);
- *(progpath + len) = '\0';
- }
- else
- strncpy(progpath, path, MAXPATHLEN);
-
- joinpath(progpath, prog);
- if (isxfile(progpath))
- break;
-
- if (!delim) {
- progpath[0] = '\0';
- break;
- }
- path = delim + 1;
- }
- }
- else
- progpath[0] = '\0';
- if (progpath[0] != SEP && progpath[0] != '\0')
- absolutize(progpath);
- strncpy(argv0_path, progpath, MAXPATHLEN);
- argv0_path[MAXPATHLEN] = '\0';
+ else if (path) {
+ while (1) {
+ char *delim = strchr(path, DELIM);
+
+ if (delim) {
+ size_t len = delim - path;
+ if (len > MAXPATHLEN)
+ len = MAXPATHLEN;
+ strncpy(progpath, path, len);
+ *(progpath + len) = '\0';
+ }
+ else
+ strncpy(progpath, path, MAXPATHLEN);
+
+ joinpath(progpath, prog);
+ if (isxfile(progpath))
+ break;
+
+ if (!delim) {
+ progpath[0] = '\0';
+ break;
+ }
+ path = delim + 1;
+ }
+ }
+ else
+ progpath[0] = '\0';
+ if (progpath[0] != SEP && progpath[0] != '\0')
+ absolutize(progpath);
+ strncpy(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 = (char *)NSLibraryNameForModule(pythonModule);
@@ -525,7 +525,7 @@ calculate_path(void)
else
strncpy(zip_path, PREFIX, MAXPATHLEN);
joinpath(zip_path, "lib/python00.zip");
- bufsz = strlen(zip_path); /* Replace "00" with version */
+ bufsz = strlen(zip_path); /* Replace "00" with version */
zip_path[bufsz - 6] = VERSION[0];
zip_path[bufsz - 5] = VERSION[2];
@@ -633,10 +633,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])
- strcpy(prefix, separator);
+ /* The prefix is the root directory, but reduce() chopped
+ * off the "/". */
+ if (!prefix[0])
+ strcpy(prefix, separator);
}
else
strncpy(prefix, PREFIX, MAXPATHLEN);
@@ -645,8 +645,8 @@ calculate_path(void)
reduce(exec_prefix);
reduce(exec_prefix);
reduce(exec_prefix);
- if (!exec_prefix[0])
- strcpy(exec_prefix, separator);
+ if (!exec_prefix[0])
+ strcpy(exec_prefix, separator);
}
else
strncpy(exec_prefix, EXEC_PREFIX, MAXPATHLEN);
diff --git a/Modules/glmodule.c b/Modules/glmodule.c
index 01db9fc..b9c64fb 100644
--- a/Modules/glmodule.c
+++ b/Modules/glmodule.c
@@ -10,26 +10,26 @@ Each definition must be contained on one line:
<returntype> can be: void, short, long (XXX maybe others?)
<type> can be: char, string, short, float, long, or double
- string indicates a null terminated string;
- if <type> is char and <arg> begins with a *, the * is stripped
- and <type> is changed into string
+ string indicates a null terminated string;
+ if <type> is char and <arg> begins with a *, the * is stripped
+ and <type> is changed into string
<arg> has the form <mode> or <mode>[<subscript>]
- where <mode> can be
- s: arg is sent
- r: arg is received (arg is a pointer)
- and <subscript> can be (N and I are numbers):
- N
- argI
- retval
- N*argI
- N*I
- N*retval
- In the case where the subscript consists of two parts
- separated by *, the first part is the width of the matrix, and
- the second part is the length of the matrix. This order is
- opposite from the order used in C to declare a two-dimensional
- matrix.
+ where <mode> can be
+ s: arg is sent
+ r: arg is received (arg is a pointer)
+ and <subscript> can be (N and I are numbers):
+ N
+ argI
+ retval
+ N*argI
+ N*I
+ N*retval
+ In the case where the subscript consists of two parts
+ separated by *, the first part is the width of the matrix, and
+ the second part is the length of the matrix. This order is
+ opposite from the order used in C to declare a two-dimensional
+ matrix.
*/
/*
@@ -62,17 +62,17 @@ generator can include it in the table of functions.
static PyObject *
gl_qread(PyObject *self, PyObject *args)
{
- long retval;
- short arg1 ;
- Py_BEGIN_ALLOW_THREADS
- retval = qread( & arg1 );
- Py_END_ALLOW_THREADS
- { PyObject *v = PyTuple_New( 2 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewlongobject(retval));
- PyTuple_SetItem(v, 1, mknewshortobject(arg1));
- return v;
- }
+ long retval;
+ short arg1 ;
+ Py_BEGIN_ALLOW_THREADS
+ retval = qread( & arg1 );
+ Py_END_ALLOW_THREADS
+ { PyObject *v = PyTuple_New( 2 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewlongobject(retval));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg1));
+ return v;
+ }
}
@@ -91,64 +91,64 @@ and for each point v3d() is called.
static PyObject *
gl_varray(PyObject *self, PyObject *args)
{
- PyObject *v, *w=NULL;
- int i, n, width;
- double vec[3];
- PyObject * (*getitem)(PyObject *, int);
-
- if (!PyArg_GetObject(args, 1, 0, &v))
- return NULL;
-
- if (PyList_Check(v)) {
- n = PyList_Size(v);
- getitem = PyList_GetItem;
- }
- else if (PyTuple_Check(v)) {
- n = PyTuple_Size(v);
- getitem = PyTuple_GetItem;
- }
- else {
- PyErr_BadArgument();
- return NULL;
- }
-
- if (n == 0) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (n > 0)
- w = (*getitem)(v, 0);
-
- width = 0;
- if (w == NULL) {
- }
- else if (PyList_Check(w)) {
- width = PyList_Size(w);
- }
- else if (PyTuple_Check(w)) {
- width = PyTuple_Size(w);
- }
-
- switch (width) {
- case 2:
- vec[2] = 0.0;
- /* Fall through */
- case 3:
- break;
- default:
- PyErr_BadArgument();
- return NULL;
- }
-
- for (i = 0; i < n; i++) {
- w = (*getitem)(v, i);
- if (!PyArg_GetDoubleArray(w, 1, 0, width, vec))
- return NULL;
- v3d(vec);
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *v, *w=NULL;
+ int i, n, width;
+ double vec[3];
+ PyObject * (*getitem)(PyObject *, int);
+
+ if (!PyArg_GetObject(args, 1, 0, &v))
+ return NULL;
+
+ if (PyList_Check(v)) {
+ n = PyList_Size(v);
+ getitem = PyList_GetItem;
+ }
+ else if (PyTuple_Check(v)) {
+ n = PyTuple_Size(v);
+ getitem = PyTuple_GetItem;
+ }
+ else {
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ if (n == 0) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (n > 0)
+ w = (*getitem)(v, 0);
+
+ width = 0;
+ if (w == NULL) {
+ }
+ else if (PyList_Check(w)) {
+ width = PyList_Size(w);
+ }
+ else if (PyTuple_Check(w)) {
+ width = PyTuple_Size(w);
+ }
+
+ switch (width) {
+ case 2:
+ vec[2] = 0.0;
+ /* Fall through */
+ case 3:
+ break;
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ for (i = 0; i < n; i++) {
+ w = (*getitem)(v, i);
+ if (!PyArg_GetDoubleArray(w, 1, 0, width, vec))
+ return NULL;
+ v3d(vec);
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
/*
@@ -170,14 +170,14 @@ static PyObject *gen_nvarray(); /* Forward */
static PyObject *
gl_nvarray(PyObject *self, PyObject *args)
{
- return gen_nvarray(args, 0);
+ return gen_nvarray(args, 0);
}
static PyObject *
gl_vnarray(PyObject *self, PyObject *args)
{
- return gen_nvarray(args, 1);
+ return gen_nvarray(args, 1);
}
/* Generic, internal version of {nv,nv}array: inorm indicates the
@@ -186,44 +186,44 @@ gl_vnarray(PyObject *self, PyObject *args)
static PyObject *
gen_nvarray(PyObject *args, int inorm)
{
- PyObject *v, *w, *wnorm, *wvec;
- int i, n;
- float norm[3], vec[3];
- PyObject * (*getitem)(PyObject *, int);
-
- if (!PyArg_GetObject(args, 1, 0, &v))
- return NULL;
-
- if (PyList_Check(v)) {
- n = PyList_Size(v);
- getitem = PyList_GetItem;
- }
- else if (PyTuple_Check(v)) {
- n = PyTuple_Size(v);
- getitem = PyTuple_GetItem;
- }
- else {
- PyErr_BadArgument();
- return NULL;
- }
-
- for (i = 0; i < n; i++) {
- w = (*getitem)(v, i);
- if (!PyTuple_Check(w) || PyTuple_Size(w) != 2) {
- PyErr_BadArgument();
- return NULL;
- }
- wnorm = PyTuple_GetItem(w, inorm);
- wvec = PyTuple_GetItem(w, 1 - inorm);
- if (!PyArg_GetFloatArray(wnorm, 1, 0, 3, norm) ||
- !PyArg_GetFloatArray(wvec, 1, 0, 3, vec))
- return NULL;
- n3f(norm);
- v3f(vec);
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *v, *w, *wnorm, *wvec;
+ int i, n;
+ float norm[3], vec[3];
+ PyObject * (*getitem)(PyObject *, int);
+
+ if (!PyArg_GetObject(args, 1, 0, &v))
+ return NULL;
+
+ if (PyList_Check(v)) {
+ n = PyList_Size(v);
+ getitem = PyList_GetItem;
+ }
+ else if (PyTuple_Check(v)) {
+ n = PyTuple_Size(v);
+ getitem = PyTuple_GetItem;
+ }
+ else {
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ for (i = 0; i < n; i++) {
+ w = (*getitem)(v, i);
+ if (!PyTuple_Check(w) || PyTuple_Size(w) != 2) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ wnorm = PyTuple_GetItem(w, inorm);
+ wvec = PyTuple_GetItem(w, 1 - inorm);
+ if (!PyArg_GetFloatArray(wnorm, 1, 0, 3, norm) ||
+ !PyArg_GetFloatArray(wvec, 1, 0, 3, vec))
+ return NULL;
+ n3f(norm);
+ v3f(vec);
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* nurbssurface(s_knots[], t_knots[], ctl[][], s_order, t_order, type).
@@ -235,83 +235,83 @@ gen_nvarray(PyObject *args, int inorm)
static PyObject *
gl_nurbssurface(PyObject *self, PyObject *args)
{
- long arg1 ;
- double * arg2 ;
- long arg3 ;
- double * arg4 ;
- double *arg5 ;
- long arg6 ;
- long arg7 ;
- long arg8 ;
- long ncoords;
- long s_byte_stride, t_byte_stride;
- long s_nctl, t_nctl;
- long s, t;
- PyObject *v, *w, *pt;
- double *pnext;
- if (!PyArg_GetLongArraySize(args, 6, 0, &arg1))
- return NULL;
- if ((arg2 = PyMem_NEW(double, arg1 )) == NULL) {
- return PyErr_NoMemory();
- }
- if (!PyArg_GetDoubleArray(args, 6, 0, arg1 , arg2))
- return NULL;
- if (!PyArg_GetLongArraySize(args, 6, 1, &arg3))
- return NULL;
- if ((arg4 = PyMem_NEW(double, arg3 )) == NULL) {
- return PyErr_NoMemory();
- }
- if (!PyArg_GetDoubleArray(args, 6, 1, arg3 , arg4))
- return NULL;
- if (!PyArg_GetLong(args, 6, 3, &arg6))
- return NULL;
- if (!PyArg_GetLong(args, 6, 4, &arg7))
- return NULL;
- if (!PyArg_GetLong(args, 6, 5, &arg8))
- return NULL;
- if (arg8 == N_XYZ)
- ncoords = 3;
- else if (arg8 == N_XYZW)
- ncoords = 4;
- else {
- PyErr_BadArgument();
- return NULL;
- }
- s_nctl = arg1 - arg6;
- t_nctl = arg3 - arg7;
- if (!PyArg_GetObject(args, 6, 2, &v))
- return NULL;
- if (!PyList_Check(v) || PyList_Size(v) != s_nctl) {
- PyErr_BadArgument();
- return NULL;
- }
- if ((arg5 = PyMem_NEW(double, s_nctl*t_nctl*ncoords )) == NULL) {
- return PyErr_NoMemory();
- }
- pnext = arg5;
- for (s = 0; s < s_nctl; s++) {
- w = PyList_GetItem(v, s);
- if (w == NULL || !PyList_Check(w) ||
- PyList_Size(w) != t_nctl) {
- PyErr_BadArgument();
- return NULL;
- }
- for (t = 0; t < t_nctl; t++) {
- pt = PyList_GetItem(w, t);
- if (!PyArg_GetDoubleArray(pt, 1, 0, ncoords, pnext))
- return NULL;
- pnext += ncoords;
- }
- }
- s_byte_stride = sizeof(double) * ncoords;
- t_byte_stride = s_byte_stride * s_nctl;
- nurbssurface( arg1 , arg2 , arg3 , arg4 ,
- s_byte_stride , t_byte_stride , arg5 , arg6 , arg7 , arg8 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg4);
- PyMem_DEL(arg5);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ double * arg2 ;
+ long arg3 ;
+ double * arg4 ;
+ double *arg5 ;
+ long arg6 ;
+ long arg7 ;
+ long arg8 ;
+ long ncoords;
+ long s_byte_stride, t_byte_stride;
+ long s_nctl, t_nctl;
+ long s, t;
+ PyObject *v, *w, *pt;
+ double *pnext;
+ if (!PyArg_GetLongArraySize(args, 6, 0, &arg1))
+ return NULL;
+ if ((arg2 = PyMem_NEW(double, arg1 )) == NULL) {
+ return PyErr_NoMemory();
+ }
+ if (!PyArg_GetDoubleArray(args, 6, 0, arg1 , arg2))
+ return NULL;
+ if (!PyArg_GetLongArraySize(args, 6, 1, &arg3))
+ return NULL;
+ if ((arg4 = PyMem_NEW(double, arg3 )) == NULL) {
+ return PyErr_NoMemory();
+ }
+ if (!PyArg_GetDoubleArray(args, 6, 1, arg3 , arg4))
+ return NULL;
+ if (!PyArg_GetLong(args, 6, 3, &arg6))
+ return NULL;
+ if (!PyArg_GetLong(args, 6, 4, &arg7))
+ return NULL;
+ if (!PyArg_GetLong(args, 6, 5, &arg8))
+ return NULL;
+ if (arg8 == N_XYZ)
+ ncoords = 3;
+ else if (arg8 == N_XYZW)
+ ncoords = 4;
+ else {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ s_nctl = arg1 - arg6;
+ t_nctl = arg3 - arg7;
+ if (!PyArg_GetObject(args, 6, 2, &v))
+ return NULL;
+ if (!PyList_Check(v) || PyList_Size(v) != s_nctl) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ if ((arg5 = PyMem_NEW(double, s_nctl*t_nctl*ncoords )) == NULL) {
+ return PyErr_NoMemory();
+ }
+ pnext = arg5;
+ for (s = 0; s < s_nctl; s++) {
+ w = PyList_GetItem(v, s);
+ if (w == NULL || !PyList_Check(w) ||
+ PyList_Size(w) != t_nctl) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ for (t = 0; t < t_nctl; t++) {
+ pt = PyList_GetItem(w, t);
+ if (!PyArg_GetDoubleArray(pt, 1, 0, ncoords, pnext))
+ return NULL;
+ pnext += ncoords;
+ }
+ }
+ s_byte_stride = sizeof(double) * ncoords;
+ t_byte_stride = s_byte_stride * s_nctl;
+ nurbssurface( arg1 , arg2 , arg3 , arg4 ,
+ s_byte_stride , t_byte_stride , arg5 , arg6 , arg7 , arg8 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg4);
+ PyMem_DEL(arg5);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* nurbscurve(knots, ctlpoints, order, type).
@@ -321,57 +321,57 @@ gl_nurbssurface(PyObject *self, PyObject *args)
static PyObject *
gl_nurbscurve(PyObject *self, PyObject *args)
{
- long arg1 ;
- double * arg2 ;
- long arg3 ;
- double * arg4 ;
- long arg5 ;
- long arg6 ;
- int ncoords, npoints;
- int i;
- PyObject *v;
- double *pnext;
- if (!PyArg_GetLongArraySize(args, 4, 0, &arg1))
- return NULL;
- if ((arg2 = PyMem_NEW(double, arg1 )) == NULL) {
- return PyErr_NoMemory();
- }
- if (!PyArg_GetDoubleArray(args, 4, 0, arg1 , arg2))
- return NULL;
- if (!PyArg_GetLong(args, 4, 2, &arg5))
- return NULL;
- if (!PyArg_GetLong(args, 4, 3, &arg6))
- return NULL;
- if (arg6 == N_ST)
- ncoords = 2;
- else if (arg6 == N_STW)
- ncoords = 3;
- else {
- PyErr_BadArgument();
- return NULL;
- }
- npoints = arg1 - arg5;
- if (!PyArg_GetObject(args, 4, 1, &v))
- return NULL;
- if (!PyList_Check(v) || PyList_Size(v) != npoints) {
- PyErr_BadArgument();
- return NULL;
- }
- if ((arg4 = PyMem_NEW(double, npoints*ncoords )) == NULL) {
- return PyErr_NoMemory();
- }
- pnext = arg4;
- for (i = 0; i < npoints; i++) {
- if (!PyArg_GetDoubleArray(PyList_GetItem(v, i), 1, 0, ncoords, pnext))
- return NULL;
- pnext += ncoords;
- }
- arg3 = (sizeof(double)) * ncoords;
- nurbscurve( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg4);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ double * arg2 ;
+ long arg3 ;
+ double * arg4 ;
+ long arg5 ;
+ long arg6 ;
+ int ncoords, npoints;
+ int i;
+ PyObject *v;
+ double *pnext;
+ if (!PyArg_GetLongArraySize(args, 4, 0, &arg1))
+ return NULL;
+ if ((arg2 = PyMem_NEW(double, arg1 )) == NULL) {
+ return PyErr_NoMemory();
+ }
+ if (!PyArg_GetDoubleArray(args, 4, 0, arg1 , arg2))
+ return NULL;
+ if (!PyArg_GetLong(args, 4, 2, &arg5))
+ return NULL;
+ if (!PyArg_GetLong(args, 4, 3, &arg6))
+ return NULL;
+ if (arg6 == N_ST)
+ ncoords = 2;
+ else if (arg6 == N_STW)
+ ncoords = 3;
+ else {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ npoints = arg1 - arg5;
+ if (!PyArg_GetObject(args, 4, 1, &v))
+ return NULL;
+ if (!PyList_Check(v) || PyList_Size(v) != npoints) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ if ((arg4 = PyMem_NEW(double, npoints*ncoords )) == NULL) {
+ return PyErr_NoMemory();
+ }
+ pnext = arg4;
+ for (i = 0; i < npoints; i++) {
+ if (!PyArg_GetDoubleArray(PyList_GetItem(v, i), 1, 0, ncoords, pnext))
+ return NULL;
+ pnext += ncoords;
+ }
+ arg3 = (sizeof(double)) * ncoords;
+ nurbscurve( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg4);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* pwlcurve(points, type).
@@ -381,39 +381,39 @@ gl_nurbscurve(PyObject *self, PyObject *args)
static PyObject *
gl_pwlcurve(PyObject *self, PyObject *args)
{
- PyObject *v;
- long type;
- double *data, *pnext;
- long npoints, ncoords;
- int i;
- if (!PyArg_GetObject(args, 2, 0, &v))
- return NULL;
- if (!PyArg_GetLong(args, 2, 1, &type))
- return NULL;
- if (!PyList_Check(v)) {
- PyErr_BadArgument();
- return NULL;
- }
- npoints = PyList_Size(v);
- if (type == N_ST)
- ncoords = 2;
- else {
- PyErr_BadArgument();
- return NULL;
- }
- if ((data = PyMem_NEW(double, npoints*ncoords)) == NULL) {
- return PyErr_NoMemory();
- }
- pnext = data;
- for (i = 0; i < npoints; i++) {
- if (!PyArg_GetDoubleArray(PyList_GetItem(v, i), 1, 0, ncoords, pnext))
- return NULL;
- pnext += ncoords;
- }
- pwlcurve(npoints, data, sizeof(double)*ncoords, type);
- PyMem_DEL(data);
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *v;
+ long type;
+ double *data, *pnext;
+ long npoints, ncoords;
+ int i;
+ if (!PyArg_GetObject(args, 2, 0, &v))
+ return NULL;
+ if (!PyArg_GetLong(args, 2, 1, &type))
+ return NULL;
+ if (!PyList_Check(v)) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ npoints = PyList_Size(v);
+ if (type == N_ST)
+ ncoords = 2;
+ else {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ if ((data = PyMem_NEW(double, npoints*ncoords)) == NULL) {
+ return PyErr_NoMemory();
+ }
+ pnext = data;
+ for (i = 0; i < npoints; i++) {
+ if (!PyArg_GetDoubleArray(PyList_GetItem(v, i), 1, 0, ncoords, pnext))
+ return NULL;
+ pnext += ncoords;
+ }
+ pwlcurve(npoints, data, sizeof(double)*ncoords, type);
+ PyMem_DEL(data);
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -425,56 +425,56 @@ static long pickbuffersize;
static PyObject *
pick_select(PyObject *args, void (*func)())
{
- if (!PyArg_GetLong(args, 1, 0, &pickbuffersize))
- return NULL;
- if (pickbuffer != NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "pick/gselect: already picking/selecting");
- return NULL;
- }
- if ((pickbuffer = PyMem_NEW(short, pickbuffersize)) == NULL) {
- return PyErr_NoMemory();
- }
- (*func)(pickbuffer, pickbuffersize);
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_GetLong(args, 1, 0, &pickbuffersize))
+ return NULL;
+ if (pickbuffer != NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "pick/gselect: already picking/selecting");
+ return NULL;
+ }
+ if ((pickbuffer = PyMem_NEW(short, pickbuffersize)) == NULL) {
+ return PyErr_NoMemory();
+ }
+ (*func)(pickbuffer, pickbuffersize);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
endpick_select(long (*func)())
{
- PyObject *v, *w;
- int i, nhits, n;
- if (pickbuffer == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "endpick/endselect: not in pick/select mode");
- return NULL;
- }
- nhits = (*func)(pickbuffer);
- if (nhits < 0) {
- nhits = -nhits; /* How to report buffer overflow otherwise? */
- }
- /* Scan the buffer to see how many integers */
- n = 0;
- for (; nhits > 0; nhits--) {
- n += 1 + pickbuffer[n];
- }
- v = PyList_New(n);
- if (v == NULL)
- return NULL;
- /* XXX Could do it nicer and interpret the data structure here,
- returning a list of lists. But this can be done in Python... */
- for (i = 0; i < n; i++) {
- w = PyInt_FromLong((long)pickbuffer[i]);
- if (w == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- PyList_SetItem(v, i, w);
- }
- PyMem_DEL(pickbuffer);
- pickbuffer = NULL;
- return v;
+ PyObject *v, *w;
+ int i, nhits, n;
+ if (pickbuffer == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "endpick/endselect: not in pick/select mode");
+ return NULL;
+ }
+ nhits = (*func)(pickbuffer);
+ if (nhits < 0) {
+ nhits = -nhits; /* How to report buffer overflow otherwise? */
+ }
+ /* Scan the buffer to see how many integers */
+ n = 0;
+ for (; nhits > 0; nhits--) {
+ n += 1 + pickbuffer[n];
+ }
+ v = PyList_New(n);
+ if (v == NULL)
+ return NULL;
+ /* XXX Could do it nicer and interpret the data structure here,
+ returning a list of lists. But this can be done in Python... */
+ for (i = 0; i < n; i++) {
+ w = PyInt_FromLong((long)pickbuffer[i]);
+ if (w == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyList_SetItem(v, i, w);
+ }
+ PyMem_DEL(pickbuffer);
+ pickbuffer = NULL;
+ return v;
}
extern void pick(), gselect();
@@ -482,22 +482,22 @@ extern long endpick(), endselect();
static PyObject *gl_pick(PyObject *self, PyObject *args)
{
- return pick_select(args, pick);
+ return pick_select(args, pick);
}
static PyObject *gl_endpick(PyObject *self)
{
- return endpick_select(endpick);
+ return endpick_select(endpick);
}
static PyObject *gl_gselect(PyObject *self, PyObject *args)
{
- return pick_select(args, gselect);
+ return pick_select(args, gselect);
}
static PyObject *gl_endselect(PyObject *self)
{
- return endpick_select(endselect);
+ return endpick_select(endselect);
}
@@ -509,23 +509,23 @@ static PyObject *gl_endselect(PyObject *self)
static PyObject *
gl_getmatrix(PyObject *self, PyObject *args)
{
- Matrix arg1;
- PyObject *v, *w;
- int i, j;
- getmatrix( arg1 );
- v = PyList_New(16);
- if (v == NULL) {
- return PyErr_NoMemory();
- }
- for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) {
- w = mknewfloatobject(arg1[i][j]);
- if (w == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- PyList_SetItem(v, i*4+j, w);
- }
- return v;
+ Matrix arg1;
+ PyObject *v, *w;
+ int i, j;
+ getmatrix( arg1 );
+ v = PyList_New(16);
+ if (v == NULL) {
+ return PyErr_NoMemory();
+ }
+ for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) {
+ w = mknewfloatobject(arg1[i][j]);
+ if (w == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyList_SetItem(v, i*4+j, w);
+ }
+ return v;
}
/* Here's an alternate version that returns a 4x4 matrix instead of
@@ -536,137 +536,137 @@ gl_getmatrix(PyObject *self, PyObject *args)
static PyObject *
gl_altgetmatrix(PyObject *self, PyObject *args)
{
- Matrix arg1;
- PyObject *v, *w;
- int i, j;
- getmatrix( arg1 );
- v = PyList_New(4);
- if (v == NULL) {
- return NULL;
- }
- for (i = 0; i < 4; i++) {
- w = PyList_New(4);
- if (w == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- PyList_SetItem(v, i, w);
- }
- for (i = 0; i < 4; i++) {
- for (j = 0; j < 4; j++) {
- w = mknewfloatobject(arg1[i][j]);
- if (w == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- PyList_SetItem(PyList_GetItem(v, i), j, w);
- }
- }
- return v;
+ Matrix arg1;
+ PyObject *v, *w;
+ int i, j;
+ getmatrix( arg1 );
+ v = PyList_New(4);
+ if (v == NULL) {
+ return NULL;
+ }
+ for (i = 0; i < 4; i++) {
+ w = PyList_New(4);
+ if (w == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyList_SetItem(v, i, w);
+ }
+ for (i = 0; i < 4; i++) {
+ for (j = 0; j < 4; j++) {
+ w = mknewfloatobject(arg1[i][j]);
+ if (w == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyList_SetItem(PyList_GetItem(v, i), j, w);
+ }
+ }
+ return v;
}
static PyObject *
gl_lrectwrite(PyObject *self, PyObject *args)
{
- short x1 ;
- short y1 ;
- short x2 ;
- short y2 ;
- string parray ;
- PyObject *s;
+ short x1 ;
+ short y1 ;
+ short x2 ;
+ short y2 ;
+ string parray ;
+ PyObject *s;
#if 0
- int pixcount;
+ int pixcount;
#endif
- if (!PyArg_GetShort(args, 5, 0, &x1))
- return NULL;
- if (!PyArg_GetShort(args, 5, 1, &y1))
- return NULL;
- if (!PyArg_GetShort(args, 5, 2, &x2))
- return NULL;
- if (!PyArg_GetShort(args, 5, 3, &y2))
- return NULL;
- if (!PyArg_GetString(args, 5, 4, &parray))
- return NULL;
- if (!PyArg_GetObject(args, 5, 4, &s))
- return NULL;
+ if (!PyArg_GetShort(args, 5, 0, &x1))
+ return NULL;
+ if (!PyArg_GetShort(args, 5, 1, &y1))
+ return NULL;
+ if (!PyArg_GetShort(args, 5, 2, &x2))
+ return NULL;
+ if (!PyArg_GetShort(args, 5, 3, &y2))
+ return NULL;
+ if (!PyArg_GetString(args, 5, 4, &parray))
+ return NULL;
+ if (!PyArg_GetObject(args, 5, 4, &s))
+ return NULL;
#if 0
/* Don't check this, it breaks experiments with pixmode(PM_SIZE, ...) */
- pixcount = (long)(x2+1-x1) * (long)(y2+1-y1);
- if (!PyString_Check(s) || PyString_Size(s) != pixcount*sizeof(long)) {
- PyErr_SetString(PyExc_RuntimeError,
- "string arg to lrectwrite has wrong size");
- return NULL;
- }
+ pixcount = (long)(x2+1-x1) * (long)(y2+1-y1);
+ if (!PyString_Check(s) || PyString_Size(s) != pixcount*sizeof(long)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "string arg to lrectwrite has wrong size");
+ return NULL;
+ }
#endif
- lrectwrite( x1 , y1 , x2 , y2 , (unsigned long *) parray );
- Py_INCREF(Py_None);
- return Py_None;
+ lrectwrite( x1 , y1 , x2 , y2 , (unsigned long *) parray );
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
gl_lrectread(PyObject *self, PyObject *args)
{
- short x1 ;
- short y1 ;
- short x2 ;
- short y2 ;
- PyObject *parray;
- int pixcount;
- if (!PyArg_GetShort(args, 4, 0, &x1))
- return NULL;
- if (!PyArg_GetShort(args, 4, 1, &y1))
- return NULL;
- if (!PyArg_GetShort(args, 4, 2, &x2))
- return NULL;
- if (!PyArg_GetShort(args, 4, 3, &y2))
- return NULL;
- pixcount = (long)(x2+1-x1) * (long)(y2+1-y1);
- parray = PyString_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
- if (parray == NULL)
- return NULL; /* No memory */
- lrectread(x1, y1, x2, y2, (unsigned long *) PyString_AsString(parray));
- return parray;
+ short x1 ;
+ short y1 ;
+ short x2 ;
+ short y2 ;
+ PyObject *parray;
+ int pixcount;
+ if (!PyArg_GetShort(args, 4, 0, &x1))
+ return NULL;
+ if (!PyArg_GetShort(args, 4, 1, &y1))
+ return NULL;
+ if (!PyArg_GetShort(args, 4, 2, &x2))
+ return NULL;
+ if (!PyArg_GetShort(args, 4, 3, &y2))
+ return NULL;
+ pixcount = (long)(x2+1-x1) * (long)(y2+1-y1);
+ parray = PyString_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
+ if (parray == NULL)
+ return NULL; /* No memory */
+ lrectread(x1, y1, x2, y2, (unsigned long *) PyString_AsString(parray));
+ return parray;
}
static PyObject *
gl_readdisplay(PyObject *self, PyObject *args)
{
- short x1, y1, x2, y2;
- unsigned long *parray, hints;
- long size, size_ret;
- PyObject *rv;
-
- if ( !PyArg_Parse(args, "hhhhl", &x1, &y1, &x2, &y2, &hints) )
- return 0;
- size = (long)(x2+1-x1) * (long)(y2+1-y1);
- rv = PyString_FromStringAndSize((char *)NULL, size*sizeof(long));
- if ( rv == NULL )
- return NULL;
- parray = (unsigned long *)PyString_AsString(rv);
- size_ret = readdisplay(x1, y1, x2, y2, parray, hints);
- if ( size_ret != size ) {
- printf("gl_readdisplay: got %ld pixels, expected %ld\n",
- size_ret, size);
- PyErr_SetString(PyExc_RuntimeError, "readdisplay returned unexpected length");
- return NULL;
- }
- return rv;
+ short x1, y1, x2, y2;
+ unsigned long *parray, hints;
+ long size, size_ret;
+ PyObject *rv;
+
+ if ( !PyArg_Parse(args, "hhhhl", &x1, &y1, &x2, &y2, &hints) )
+ return 0;
+ size = (long)(x2+1-x1) * (long)(y2+1-y1);
+ rv = PyString_FromStringAndSize((char *)NULL, size*sizeof(long));
+ if ( rv == NULL )
+ return NULL;
+ parray = (unsigned long *)PyString_AsString(rv);
+ size_ret = readdisplay(x1, y1, x2, y2, parray, hints);
+ if ( size_ret != size ) {
+ printf("gl_readdisplay: got %ld pixels, expected %ld\n",
+ size_ret, size);
+ PyErr_SetString(PyExc_RuntimeError, "readdisplay returned unexpected length");
+ return NULL;
+ }
+ return rv;
}
/* Desperately needed, here are tools to compress and decompress
the data manipulated by lrectread/lrectwrite.
gl.packrect(width, height, packfactor, bigdata) --> smalldata
- makes 'bigdata' 4*(packfactor**2) times smaller by:
- - turning it into B/W (a factor 4)
- - replacing squares of size pacfactor by one
- representative
+ makes 'bigdata' 4*(packfactor**2) times smaller by:
+ - turning it into B/W (a factor 4)
+ - replacing squares of size pacfactor by one
+ representative
gl.unpackrect(width, height, packfactor, smalldata) --> bigdata
- is the inverse; the numeric arguments must be *the same*.
+ is the inverse; the numeric arguments must be *the same*.
Both work best if width and height are multiples of packfactor
(in fact unpackrect will leave garbage bytes).
@@ -676,50 +676,50 @@ gl_readdisplay(PyObject *self, PyObject *args)
static PyObject *
gl_packrect(PyObject *self, PyObject *args)
{
- long width, height, packfactor;
- char *s;
- PyObject *unpacked, *packed;
- int pixcount, packedcount, x, y, r, g, b;
- unsigned long pixel;
- unsigned char *p;
- unsigned long *parray;
- if (!PyArg_GetLong(args, 4, 0, &width))
- return NULL;
- if (!PyArg_GetLong(args, 4, 1, &height))
- return NULL;
- if (!PyArg_GetLong(args, 4, 2, &packfactor))
- return NULL;
- if (!PyArg_GetString(args, 4, 3, &s)) /* For type checking only */
- return NULL;
- if (!PyArg_GetObject(args, 4, 3, &unpacked))
- return NULL;
- if (width <= 0 || height <= 0 || packfactor <= 0) {
- PyErr_SetString(PyExc_RuntimeError, "packrect args must be > 0");
- return NULL;
- }
- pixcount = width*height;
- packedcount = ((width+packfactor-1)/packfactor) *
- ((height+packfactor-1)/packfactor);
- if (PyString_Size(unpacked) != pixcount*sizeof(long)) {
- PyErr_SetString(PyExc_RuntimeError,
- "string arg to packrect has wrong size");
- return NULL;
- }
- packed = PyString_FromStringAndSize((char *)NULL, packedcount);
- if (packed == NULL)
- return NULL;
- parray = (unsigned long *) PyString_AsString(unpacked);
- p = (unsigned char *) PyString_AsString(packed);
- for (y = 0; y < height; y += packfactor, parray += packfactor*width) {
- for (x = 0; x < width; x += packfactor) {
- pixel = parray[x];
- r = pixel & 0xff;
- g = (pixel >> 8) & 0xff;
- b = (pixel >> 16) & 0xff;
- *p++ = (30*r+59*g+11*b) / 100;
- }
- }
- return packed;
+ long width, height, packfactor;
+ char *s;
+ PyObject *unpacked, *packed;
+ int pixcount, packedcount, x, y, r, g, b;
+ unsigned long pixel;
+ unsigned char *p;
+ unsigned long *parray;
+ if (!PyArg_GetLong(args, 4, 0, &width))
+ return NULL;
+ if (!PyArg_GetLong(args, 4, 1, &height))
+ return NULL;
+ if (!PyArg_GetLong(args, 4, 2, &packfactor))
+ return NULL;
+ if (!PyArg_GetString(args, 4, 3, &s)) /* For type checking only */
+ return NULL;
+ if (!PyArg_GetObject(args, 4, 3, &unpacked))
+ return NULL;
+ if (width <= 0 || height <= 0 || packfactor <= 0) {
+ PyErr_SetString(PyExc_RuntimeError, "packrect args must be > 0");
+ return NULL;
+ }
+ pixcount = width*height;
+ packedcount = ((width+packfactor-1)/packfactor) *
+ ((height+packfactor-1)/packfactor);
+ if (PyString_Size(unpacked) != pixcount*sizeof(long)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "string arg to packrect has wrong size");
+ return NULL;
+ }
+ packed = PyString_FromStringAndSize((char *)NULL, packedcount);
+ if (packed == NULL)
+ return NULL;
+ parray = (unsigned long *) PyString_AsString(unpacked);
+ p = (unsigned char *) PyString_AsString(packed);
+ for (y = 0; y < height; y += packfactor, parray += packfactor*width) {
+ for (x = 0; x < width; x += packfactor) {
+ pixel = parray[x];
+ r = pixel & 0xff;
+ g = (pixel >> 8) & 0xff;
+ b = (pixel >> 16) & 0xff;
+ *p++ = (30*r+59*g+11*b) / 100;
+ }
+ }
+ return packed;
}
@@ -729,77 +729,77 @@ static int unpacktab_inited = 0;
static PyObject *
gl_unpackrect(PyObject *self, PyObject *args)
{
- long width, height, packfactor;
- char *s;
- PyObject *unpacked, *packed;
- int pixcount, packedcount;
- register unsigned char *p;
- register unsigned long *parray;
- if (!unpacktab_inited) {
- register int white;
- for (white = 256; --white >= 0; )
- unpacktab[white] = white * 0x010101L;
- unpacktab_inited++;
- }
- if (!PyArg_GetLong(args, 4, 0, &width))
- return NULL;
- if (!PyArg_GetLong(args, 4, 1, &height))
- return NULL;
- if (!PyArg_GetLong(args, 4, 2, &packfactor))
- return NULL;
- if (!PyArg_GetString(args, 4, 3, &s)) /* For type checking only */
- return NULL;
- if (!PyArg_GetObject(args, 4, 3, &packed))
- return NULL;
- if (width <= 0 || height <= 0 || packfactor <= 0) {
- PyErr_SetString(PyExc_RuntimeError, "packrect args must be > 0");
- return NULL;
- }
- pixcount = width*height;
- packedcount = ((width+packfactor-1)/packfactor) *
- ((height+packfactor-1)/packfactor);
- if (PyString_Size(packed) != packedcount) {
- PyErr_SetString(PyExc_RuntimeError,
- "string arg to unpackrect has wrong size");
- return NULL;
- }
- unpacked = PyString_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
- if (unpacked == NULL)
- return NULL;
- parray = (unsigned long *) PyString_AsString(unpacked);
- p = (unsigned char *) PyString_AsString(packed);
- if (packfactor == 1 && width*height > 0) {
- /* Just expand bytes to longs */
- register int x = width * height;
- do {
- *parray++ = unpacktab[*p++];
- } while (--x >= 0);
- }
- else {
- register int y;
- for (y = 0; y < height-packfactor+1;
- y += packfactor, parray += packfactor*width) {
- register int x;
- for (x = 0; x < width-packfactor+1; x += packfactor) {
- register unsigned long pixel = unpacktab[*p++];
- register int i;
- for (i = packfactor*width; (i-=width) >= 0;) {
- register int j;
- for (j = packfactor; --j >= 0; )
- parray[i+x+j] = pixel;
- }
- }
- }
- }
- return unpacked;
+ long width, height, packfactor;
+ char *s;
+ PyObject *unpacked, *packed;
+ int pixcount, packedcount;
+ register unsigned char *p;
+ register unsigned long *parray;
+ if (!unpacktab_inited) {
+ register int white;
+ for (white = 256; --white >= 0; )
+ unpacktab[white] = white * 0x010101L;
+ unpacktab_inited++;
+ }
+ if (!PyArg_GetLong(args, 4, 0, &width))
+ return NULL;
+ if (!PyArg_GetLong(args, 4, 1, &height))
+ return NULL;
+ if (!PyArg_GetLong(args, 4, 2, &packfactor))
+ return NULL;
+ if (!PyArg_GetString(args, 4, 3, &s)) /* For type checking only */
+ return NULL;
+ if (!PyArg_GetObject(args, 4, 3, &packed))
+ return NULL;
+ if (width <= 0 || height <= 0 || packfactor <= 0) {
+ PyErr_SetString(PyExc_RuntimeError, "packrect args must be > 0");
+ return NULL;
+ }
+ pixcount = width*height;
+ packedcount = ((width+packfactor-1)/packfactor) *
+ ((height+packfactor-1)/packfactor);
+ if (PyString_Size(packed) != packedcount) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "string arg to unpackrect has wrong size");
+ return NULL;
+ }
+ unpacked = PyString_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
+ if (unpacked == NULL)
+ return NULL;
+ parray = (unsigned long *) PyString_AsString(unpacked);
+ p = (unsigned char *) PyString_AsString(packed);
+ if (packfactor == 1 && width*height > 0) {
+ /* Just expand bytes to longs */
+ register int x = width * height;
+ do {
+ *parray++ = unpacktab[*p++];
+ } while (--x >= 0);
+ }
+ else {
+ register int y;
+ for (y = 0; y < height-packfactor+1;
+ y += packfactor, parray += packfactor*width) {
+ register int x;
+ for (x = 0; x < width-packfactor+1; x += packfactor) {
+ register unsigned long pixel = unpacktab[*p++];
+ register int i;
+ for (i = packfactor*width; (i-=width) >= 0;) {
+ register int j;
+ for (j = packfactor; --j >= 0; )
+ parray[i+x+j] = pixel;
+ }
+ }
+ }
+ }
+ return unpacked;
}
static PyObject *
gl_gversion(PyObject *self, PyObject *args)
{
- char buf[20];
- gversion(buf);
- return PyString_FromString(buf);
+ char buf[20];
+ gversion(buf);
+ return PyString_FromString(buf);
}
@@ -807,9 +807,9 @@ gl_gversion(PyObject *self, PyObject *args)
static PyObject *
gl_clear(PyObject *self, PyObject *args)
{
- __GLclear( );
- Py_INCREF(Py_None);
- return Py_None;
+ __GLclear( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* End of manually written stubs */
@@ -820,9 +820,9 @@ gl_clear(PyObject *self, PyObject *args)
static PyObject *
gl_getshade(PyObject *self, PyObject *args)
{
- long retval;
- retval = getshade( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getshade( );
+ return mknewlongobject(retval);
}
/* void devport short s long s */
@@ -830,15 +830,15 @@ gl_getshade(PyObject *self, PyObject *args)
static PyObject *
gl_devport(PyObject *self, PyObject *args)
{
- short arg1 ;
- long arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- devport( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ long arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ devport( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rdr2i long s long s */
@@ -846,15 +846,15 @@ gl_devport(PyObject *self, PyObject *args)
static PyObject *
gl_rdr2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- rdr2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ rdr2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rectfs short s short s short s short s */
@@ -862,21 +862,21 @@ gl_rdr2i(PyObject *self, PyObject *args)
static PyObject *
gl_rectfs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- rectfs( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ rectfs( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rects short s short s short s short s */
@@ -884,21 +884,21 @@ gl_rectfs(PyObject *self, PyObject *args)
static PyObject *
gl_rects(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- rects( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ rects( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rmv2i long s long s */
@@ -906,15 +906,15 @@ gl_rects(PyObject *self, PyObject *args)
static PyObject *
gl_rmv2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- rmv2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ rmv2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void noport */
@@ -922,9 +922,9 @@ gl_rmv2i(PyObject *self, PyObject *args)
static PyObject *
gl_noport(PyObject *self, PyObject *args)
{
- noport( );
- Py_INCREF(Py_None);
- return Py_None;
+ noport( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void popviewport */
@@ -932,9 +932,9 @@ gl_noport(PyObject *self, PyObject *args)
static PyObject *
gl_popviewport(PyObject *self, PyObject *args)
{
- popviewport( );
- Py_INCREF(Py_None);
- return Py_None;
+ popviewport( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void clearhitcode */
@@ -942,9 +942,9 @@ gl_popviewport(PyObject *self, PyObject *args)
static PyObject *
gl_clearhitcode(PyObject *self, PyObject *args)
{
- clearhitcode( );
- Py_INCREF(Py_None);
- return Py_None;
+ clearhitcode( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void closeobj */
@@ -952,9 +952,9 @@ gl_clearhitcode(PyObject *self, PyObject *args)
static PyObject *
gl_closeobj(PyObject *self, PyObject *args)
{
- closeobj( );
- Py_INCREF(Py_None);
- return Py_None;
+ closeobj( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cursoff */
@@ -962,9 +962,9 @@ gl_closeobj(PyObject *self, PyObject *args)
static PyObject *
gl_cursoff(PyObject *self, PyObject *args)
{
- cursoff( );
- Py_INCREF(Py_None);
- return Py_None;
+ cursoff( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void curson */
@@ -972,9 +972,9 @@ gl_cursoff(PyObject *self, PyObject *args)
static PyObject *
gl_curson(PyObject *self, PyObject *args)
{
- curson( );
- Py_INCREF(Py_None);
- return Py_None;
+ curson( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void doublebuffer */
@@ -982,9 +982,9 @@ gl_curson(PyObject *self, PyObject *args)
static PyObject *
gl_doublebuffer(PyObject *self, PyObject *args)
{
- doublebuffer( );
- Py_INCREF(Py_None);
- return Py_None;
+ doublebuffer( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void finish */
@@ -992,9 +992,9 @@ gl_doublebuffer(PyObject *self, PyObject *args)
static PyObject *
gl_finish(PyObject *self, PyObject *args)
{
- finish( );
- Py_INCREF(Py_None);
- return Py_None;
+ finish( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gconfig */
@@ -1002,9 +1002,9 @@ gl_finish(PyObject *self, PyObject *args)
static PyObject *
gl_gconfig(PyObject *self, PyObject *args)
{
- gconfig( );
- Py_INCREF(Py_None);
- return Py_None;
+ gconfig( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void ginit */
@@ -1012,9 +1012,9 @@ gl_gconfig(PyObject *self, PyObject *args)
static PyObject *
gl_ginit(PyObject *self, PyObject *args)
{
- ginit( );
- Py_INCREF(Py_None);
- return Py_None;
+ ginit( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void greset */
@@ -1022,9 +1022,9 @@ gl_ginit(PyObject *self, PyObject *args)
static PyObject *
gl_greset(PyObject *self, PyObject *args)
{
- greset( );
- Py_INCREF(Py_None);
- return Py_None;
+ greset( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void multimap */
@@ -1032,9 +1032,9 @@ gl_greset(PyObject *self, PyObject *args)
static PyObject *
gl_multimap(PyObject *self, PyObject *args)
{
- multimap( );
- Py_INCREF(Py_None);
- return Py_None;
+ multimap( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void onemap */
@@ -1042,9 +1042,9 @@ gl_multimap(PyObject *self, PyObject *args)
static PyObject *
gl_onemap(PyObject *self, PyObject *args)
{
- onemap( );
- Py_INCREF(Py_None);
- return Py_None;
+ onemap( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void popattributes */
@@ -1052,9 +1052,9 @@ gl_onemap(PyObject *self, PyObject *args)
static PyObject *
gl_popattributes(PyObject *self, PyObject *args)
{
- popattributes( );
- Py_INCREF(Py_None);
- return Py_None;
+ popattributes( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void popmatrix */
@@ -1062,9 +1062,9 @@ gl_popattributes(PyObject *self, PyObject *args)
static PyObject *
gl_popmatrix(PyObject *self, PyObject *args)
{
- popmatrix( );
- Py_INCREF(Py_None);
- return Py_None;
+ popmatrix( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pushattributes */
@@ -1072,9 +1072,9 @@ gl_popmatrix(PyObject *self, PyObject *args)
static PyObject *
gl_pushattributes(PyObject *self, PyObject *args)
{
- pushattributes( );
- Py_INCREF(Py_None);
- return Py_None;
+ pushattributes( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pushmatrix */
@@ -1082,9 +1082,9 @@ gl_pushattributes(PyObject *self, PyObject *args)
static PyObject *
gl_pushmatrix(PyObject *self, PyObject *args)
{
- pushmatrix( );
- Py_INCREF(Py_None);
- return Py_None;
+ pushmatrix( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pushviewport */
@@ -1092,9 +1092,9 @@ gl_pushmatrix(PyObject *self, PyObject *args)
static PyObject *
gl_pushviewport(PyObject *self, PyObject *args)
{
- pushviewport( );
- Py_INCREF(Py_None);
- return Py_None;
+ pushviewport( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void qreset */
@@ -1102,9 +1102,9 @@ gl_pushviewport(PyObject *self, PyObject *args)
static PyObject *
gl_qreset(PyObject *self, PyObject *args)
{
- qreset( );
- Py_INCREF(Py_None);
- return Py_None;
+ qreset( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void RGBmode */
@@ -1112,9 +1112,9 @@ gl_qreset(PyObject *self, PyObject *args)
static PyObject *
gl_RGBmode(PyObject *self, PyObject *args)
{
- RGBmode( );
- Py_INCREF(Py_None);
- return Py_None;
+ RGBmode( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void singlebuffer */
@@ -1122,9 +1122,9 @@ gl_RGBmode(PyObject *self, PyObject *args)
static PyObject *
gl_singlebuffer(PyObject *self, PyObject *args)
{
- singlebuffer( );
- Py_INCREF(Py_None);
- return Py_None;
+ singlebuffer( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void swapbuffers */
@@ -1132,9 +1132,9 @@ gl_singlebuffer(PyObject *self, PyObject *args)
static PyObject *
gl_swapbuffers(PyObject *self, PyObject *args)
{
- swapbuffers( );
- Py_INCREF(Py_None);
- return Py_None;
+ swapbuffers( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gsync */
@@ -1142,9 +1142,9 @@ gl_swapbuffers(PyObject *self, PyObject *args)
static PyObject *
gl_gsync(PyObject *self, PyObject *args)
{
- gsync( );
- Py_INCREF(Py_None);
- return Py_None;
+ gsync( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gflush */
@@ -1152,9 +1152,9 @@ gl_gsync(PyObject *self, PyObject *args)
static PyObject *
gl_gflush(PyObject *self, PyObject *args)
{
- gflush( );
- Py_INCREF(Py_None);
- return Py_None;
+ gflush( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void tpon */
@@ -1162,9 +1162,9 @@ gl_gflush(PyObject *self, PyObject *args)
static PyObject *
gl_tpon(PyObject *self, PyObject *args)
{
- tpon( );
- Py_INCREF(Py_None);
- return Py_None;
+ tpon( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void tpoff */
@@ -1172,9 +1172,9 @@ gl_tpon(PyObject *self, PyObject *args)
static PyObject *
gl_tpoff(PyObject *self, PyObject *args)
{
- tpoff( );
- Py_INCREF(Py_None);
- return Py_None;
+ tpoff( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void clkon */
@@ -1182,9 +1182,9 @@ gl_tpoff(PyObject *self, PyObject *args)
static PyObject *
gl_clkon(PyObject *self, PyObject *args)
{
- clkon( );
- Py_INCREF(Py_None);
- return Py_None;
+ clkon( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void clkoff */
@@ -1192,9 +1192,9 @@ gl_clkon(PyObject *self, PyObject *args)
static PyObject *
gl_clkoff(PyObject *self, PyObject *args)
{
- clkoff( );
- Py_INCREF(Py_None);
- return Py_None;
+ clkoff( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void ringbell */
@@ -1202,9 +1202,9 @@ gl_clkoff(PyObject *self, PyObject *args)
static PyObject *
gl_ringbell(PyObject *self, PyObject *args)
{
- ringbell( );
- Py_INCREF(Py_None);
- return Py_None;
+ ringbell( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gbegin */
@@ -1212,9 +1212,9 @@ gl_ringbell(PyObject *self, PyObject *args)
static PyObject *
gl_gbegin(PyObject *self, PyObject *args)
{
- gbegin( );
- Py_INCREF(Py_None);
- return Py_None;
+ gbegin( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void textinit */
@@ -1222,9 +1222,9 @@ gl_gbegin(PyObject *self, PyObject *args)
static PyObject *
gl_textinit(PyObject *self, PyObject *args)
{
- textinit( );
- Py_INCREF(Py_None);
- return Py_None;
+ textinit( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void initnames */
@@ -1232,9 +1232,9 @@ gl_textinit(PyObject *self, PyObject *args)
static PyObject *
gl_initnames(PyObject *self, PyObject *args)
{
- initnames( );
- Py_INCREF(Py_None);
- return Py_None;
+ initnames( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pclos */
@@ -1242,9 +1242,9 @@ gl_initnames(PyObject *self, PyObject *args)
static PyObject *
gl_pclos(PyObject *self, PyObject *args)
{
- pclos( );
- Py_INCREF(Py_None);
- return Py_None;
+ pclos( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void popname */
@@ -1252,9 +1252,9 @@ gl_pclos(PyObject *self, PyObject *args)
static PyObject *
gl_popname(PyObject *self, PyObject *args)
{
- popname( );
- Py_INCREF(Py_None);
- return Py_None;
+ popname( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void spclos */
@@ -1262,9 +1262,9 @@ gl_popname(PyObject *self, PyObject *args)
static PyObject *
gl_spclos(PyObject *self, PyObject *args)
{
- spclos( );
- Py_INCREF(Py_None);
- return Py_None;
+ spclos( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void zclear */
@@ -1272,9 +1272,9 @@ gl_spclos(PyObject *self, PyObject *args)
static PyObject *
gl_zclear(PyObject *self, PyObject *args)
{
- zclear( );
- Py_INCREF(Py_None);
- return Py_None;
+ zclear( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void screenspace */
@@ -1282,9 +1282,9 @@ gl_zclear(PyObject *self, PyObject *args)
static PyObject *
gl_screenspace(PyObject *self, PyObject *args)
{
- screenspace( );
- Py_INCREF(Py_None);
- return Py_None;
+ screenspace( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void reshapeviewport */
@@ -1292,9 +1292,9 @@ gl_screenspace(PyObject *self, PyObject *args)
static PyObject *
gl_reshapeviewport(PyObject *self, PyObject *args)
{
- reshapeviewport( );
- Py_INCREF(Py_None);
- return Py_None;
+ reshapeviewport( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void winpush */
@@ -1302,9 +1302,9 @@ gl_reshapeviewport(PyObject *self, PyObject *args)
static PyObject *
gl_winpush(PyObject *self, PyObject *args)
{
- winpush( );
- Py_INCREF(Py_None);
- return Py_None;
+ winpush( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void winpop */
@@ -1312,9 +1312,9 @@ gl_winpush(PyObject *self, PyObject *args)
static PyObject *
gl_winpop(PyObject *self, PyObject *args)
{
- winpop( );
- Py_INCREF(Py_None);
- return Py_None;
+ winpop( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void foreground */
@@ -1322,9 +1322,9 @@ gl_winpop(PyObject *self, PyObject *args)
static PyObject *
gl_foreground(PyObject *self, PyObject *args)
{
- foreground( );
- Py_INCREF(Py_None);
- return Py_None;
+ foreground( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endfullscrn */
@@ -1332,9 +1332,9 @@ gl_foreground(PyObject *self, PyObject *args)
static PyObject *
gl_endfullscrn(PyObject *self, PyObject *args)
{
- endfullscrn( );
- Py_INCREF(Py_None);
- return Py_None;
+ endfullscrn( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endpupmode */
@@ -1342,9 +1342,9 @@ gl_endfullscrn(PyObject *self, PyObject *args)
static PyObject *
gl_endpupmode(PyObject *self, PyObject *args)
{
- endpupmode( );
- Py_INCREF(Py_None);
- return Py_None;
+ endpupmode( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void fullscrn */
@@ -1352,9 +1352,9 @@ gl_endpupmode(PyObject *self, PyObject *args)
static PyObject *
gl_fullscrn(PyObject *self, PyObject *args)
{
- fullscrn( );
- Py_INCREF(Py_None);
- return Py_None;
+ fullscrn( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pupmode */
@@ -1362,9 +1362,9 @@ gl_fullscrn(PyObject *self, PyObject *args)
static PyObject *
gl_pupmode(PyObject *self, PyObject *args)
{
- pupmode( );
- Py_INCREF(Py_None);
- return Py_None;
+ pupmode( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void winconstraints */
@@ -1372,9 +1372,9 @@ gl_pupmode(PyObject *self, PyObject *args)
static PyObject *
gl_winconstraints(PyObject *self, PyObject *args)
{
- winconstraints( );
- Py_INCREF(Py_None);
- return Py_None;
+ winconstraints( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pagecolor short s */
@@ -1382,12 +1382,12 @@ gl_winconstraints(PyObject *self, PyObject *args)
static PyObject *
gl_pagecolor(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- pagecolor( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ pagecolor( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void textcolor short s */
@@ -1395,12 +1395,12 @@ gl_pagecolor(PyObject *self, PyObject *args)
static PyObject *
gl_textcolor(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- textcolor( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ textcolor( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void color short s */
@@ -1408,12 +1408,12 @@ gl_textcolor(PyObject *self, PyObject *args)
static PyObject *
gl_color(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- color( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ color( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void curveit short s */
@@ -1421,12 +1421,12 @@ gl_color(PyObject *self, PyObject *args)
static PyObject *
gl_curveit(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- curveit( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ curveit( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void font short s */
@@ -1434,12 +1434,12 @@ gl_curveit(PyObject *self, PyObject *args)
static PyObject *
gl_font(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- font( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ font( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void linewidth short s */
@@ -1447,12 +1447,12 @@ gl_font(PyObject *self, PyObject *args)
static PyObject *
gl_linewidth(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- linewidth( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ linewidth( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setlinestyle short s */
@@ -1460,12 +1460,12 @@ gl_linewidth(PyObject *self, PyObject *args)
static PyObject *
gl_setlinestyle(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- setlinestyle( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ setlinestyle( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setmap short s */
@@ -1473,12 +1473,12 @@ gl_setlinestyle(PyObject *self, PyObject *args)
static PyObject *
gl_setmap(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- setmap( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ setmap( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void swapinterval short s */
@@ -1486,12 +1486,12 @@ gl_setmap(PyObject *self, PyObject *args)
static PyObject *
gl_swapinterval(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- swapinterval( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ swapinterval( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void writemask short s */
@@ -1499,12 +1499,12 @@ gl_swapinterval(PyObject *self, PyObject *args)
static PyObject *
gl_writemask(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- writemask( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ writemask( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void textwritemask short s */
@@ -1512,12 +1512,12 @@ gl_writemask(PyObject *self, PyObject *args)
static PyObject *
gl_textwritemask(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- textwritemask( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ textwritemask( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void qdevice short s */
@@ -1525,12 +1525,12 @@ gl_textwritemask(PyObject *self, PyObject *args)
static PyObject *
gl_qdevice(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- qdevice( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ qdevice( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void unqdevice short s */
@@ -1538,12 +1538,12 @@ gl_qdevice(PyObject *self, PyObject *args)
static PyObject *
gl_unqdevice(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- unqdevice( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ unqdevice( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void curvebasis short s */
@@ -1551,12 +1551,12 @@ gl_unqdevice(PyObject *self, PyObject *args)
static PyObject *
gl_curvebasis(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- curvebasis( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ curvebasis( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void curveprecision short s */
@@ -1564,12 +1564,12 @@ gl_curvebasis(PyObject *self, PyObject *args)
static PyObject *
gl_curveprecision(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- curveprecision( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ curveprecision( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void loadname short s */
@@ -1577,12 +1577,12 @@ gl_curveprecision(PyObject *self, PyObject *args)
static PyObject *
gl_loadname(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- loadname( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ loadname( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void passthrough short s */
@@ -1590,12 +1590,12 @@ gl_loadname(PyObject *self, PyObject *args)
static PyObject *
gl_passthrough(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- passthrough( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ passthrough( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pushname short s */
@@ -1603,12 +1603,12 @@ gl_passthrough(PyObject *self, PyObject *args)
static PyObject *
gl_pushname(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- pushname( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ pushname( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setmonitor short s */
@@ -1616,12 +1616,12 @@ gl_pushname(PyObject *self, PyObject *args)
static PyObject *
gl_setmonitor(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- setmonitor( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ setmonitor( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setshade short s */
@@ -1629,12 +1629,12 @@ gl_setmonitor(PyObject *self, PyObject *args)
static PyObject *
gl_setshade(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- setshade( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ setshade( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setpattern short s */
@@ -1642,12 +1642,12 @@ gl_setshade(PyObject *self, PyObject *args)
static PyObject *
gl_setpattern(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- setpattern( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ setpattern( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pagewritemask short s */
@@ -1655,12 +1655,12 @@ gl_setpattern(PyObject *self, PyObject *args)
static PyObject *
gl_pagewritemask(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- pagewritemask( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ pagewritemask( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void callobj long s */
@@ -1668,12 +1668,12 @@ gl_pagewritemask(PyObject *self, PyObject *args)
static PyObject *
gl_callobj(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- callobj( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ callobj( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void delobj long s */
@@ -1681,12 +1681,12 @@ gl_callobj(PyObject *self, PyObject *args)
static PyObject *
gl_delobj(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- delobj( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ delobj( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void editobj long s */
@@ -1694,12 +1694,12 @@ gl_delobj(PyObject *self, PyObject *args)
static PyObject *
gl_editobj(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- editobj( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ editobj( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void makeobj long s */
@@ -1707,12 +1707,12 @@ gl_editobj(PyObject *self, PyObject *args)
static PyObject *
gl_makeobj(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- makeobj( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ makeobj( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void maketag long s */
@@ -1720,12 +1720,12 @@ gl_makeobj(PyObject *self, PyObject *args)
static PyObject *
gl_maketag(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- maketag( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ maketag( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void chunksize long s */
@@ -1733,12 +1733,12 @@ gl_maketag(PyObject *self, PyObject *args)
static PyObject *
gl_chunksize(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- chunksize( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ chunksize( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void compactify long s */
@@ -1746,12 +1746,12 @@ gl_chunksize(PyObject *self, PyObject *args)
static PyObject *
gl_compactify(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- compactify( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ compactify( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void deltag long s */
@@ -1759,12 +1759,12 @@ gl_compactify(PyObject *self, PyObject *args)
static PyObject *
gl_deltag(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- deltag( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ deltag( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lsrepeat long s */
@@ -1772,12 +1772,12 @@ gl_deltag(PyObject *self, PyObject *args)
static PyObject *
gl_lsrepeat(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- lsrepeat( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ lsrepeat( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void objinsert long s */
@@ -1785,12 +1785,12 @@ gl_lsrepeat(PyObject *self, PyObject *args)
static PyObject *
gl_objinsert(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- objinsert( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ objinsert( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void objreplace long s */
@@ -1798,12 +1798,12 @@ gl_objinsert(PyObject *self, PyObject *args)
static PyObject *
gl_objreplace(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- objreplace( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ objreplace( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void winclose long s */
@@ -1811,12 +1811,12 @@ gl_objreplace(PyObject *self, PyObject *args)
static PyObject *
gl_winclose(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- winclose( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ winclose( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void blanktime long s */
@@ -1824,12 +1824,12 @@ gl_winclose(PyObject *self, PyObject *args)
static PyObject *
gl_blanktime(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- blanktime( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ blanktime( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void freepup long s */
@@ -1837,12 +1837,12 @@ gl_blanktime(PyObject *self, PyObject *args)
static PyObject *
gl_freepup(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- freepup( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ freepup( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void backbuffer long s */
@@ -1850,12 +1850,12 @@ gl_freepup(PyObject *self, PyObject *args)
static PyObject *
gl_backbuffer(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- backbuffer( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ backbuffer( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void frontbuffer long s */
@@ -1863,12 +1863,12 @@ gl_backbuffer(PyObject *self, PyObject *args)
static PyObject *
gl_frontbuffer(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- frontbuffer( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ frontbuffer( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lsbackup long s */
@@ -1876,12 +1876,12 @@ gl_frontbuffer(PyObject *self, PyObject *args)
static PyObject *
gl_lsbackup(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- lsbackup( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ lsbackup( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void resetls long s */
@@ -1889,12 +1889,12 @@ gl_lsbackup(PyObject *self, PyObject *args)
static PyObject *
gl_resetls(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- resetls( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ resetls( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lampon long s */
@@ -1902,12 +1902,12 @@ gl_resetls(PyObject *self, PyObject *args)
static PyObject *
gl_lampon(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- lampon( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ lampon( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lampoff long s */
@@ -1915,12 +1915,12 @@ gl_lampon(PyObject *self, PyObject *args)
static PyObject *
gl_lampoff(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- lampoff( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ lampoff( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setbell long s */
@@ -1928,12 +1928,12 @@ gl_lampoff(PyObject *self, PyObject *args)
static PyObject *
gl_setbell(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- setbell( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ setbell( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void blankscreen long s */
@@ -1941,12 +1941,12 @@ gl_setbell(PyObject *self, PyObject *args)
static PyObject *
gl_blankscreen(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- blankscreen( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ blankscreen( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void depthcue long s */
@@ -1954,12 +1954,12 @@ gl_blankscreen(PyObject *self, PyObject *args)
static PyObject *
gl_depthcue(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- depthcue( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ depthcue( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void zbuffer long s */
@@ -1967,12 +1967,12 @@ gl_depthcue(PyObject *self, PyObject *args)
static PyObject *
gl_zbuffer(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- zbuffer( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ zbuffer( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void backface long s */
@@ -1980,12 +1980,12 @@ gl_zbuffer(PyObject *self, PyObject *args)
static PyObject *
gl_backface(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- backface( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ backface( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cmov2i long s long s */
@@ -1993,15 +1993,15 @@ gl_backface(PyObject *self, PyObject *args)
static PyObject *
gl_cmov2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- cmov2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ cmov2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void draw2i long s long s */
@@ -2009,15 +2009,15 @@ gl_cmov2i(PyObject *self, PyObject *args)
static PyObject *
gl_draw2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- draw2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ draw2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void move2i long s long s */
@@ -2025,15 +2025,15 @@ gl_draw2i(PyObject *self, PyObject *args)
static PyObject *
gl_move2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- move2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ move2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pnt2i long s long s */
@@ -2041,15 +2041,15 @@ gl_move2i(PyObject *self, PyObject *args)
static PyObject *
gl_pnt2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- pnt2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ pnt2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void patchbasis long s long s */
@@ -2057,15 +2057,15 @@ gl_pnt2i(PyObject *self, PyObject *args)
static PyObject *
gl_patchbasis(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- patchbasis( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ patchbasis( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void patchprecision long s long s */
@@ -2073,15 +2073,15 @@ gl_patchbasis(PyObject *self, PyObject *args)
static PyObject *
gl_patchprecision(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- patchprecision( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ patchprecision( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pdr2i long s long s */
@@ -2089,15 +2089,15 @@ gl_patchprecision(PyObject *self, PyObject *args)
static PyObject *
gl_pdr2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- pdr2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ pdr2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pmv2i long s long s */
@@ -2105,15 +2105,15 @@ gl_pdr2i(PyObject *self, PyObject *args)
static PyObject *
gl_pmv2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- pmv2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ pmv2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpdr2i long s long s */
@@ -2121,15 +2121,15 @@ gl_pmv2i(PyObject *self, PyObject *args)
static PyObject *
gl_rpdr2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- rpdr2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ rpdr2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpmv2i long s long s */
@@ -2137,15 +2137,15 @@ gl_rpdr2i(PyObject *self, PyObject *args)
static PyObject *
gl_rpmv2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- rpmv2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ rpmv2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt2i long s long s */
@@ -2153,15 +2153,15 @@ gl_rpmv2i(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- xfpt2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ xfpt2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void objdelete long s long s */
@@ -2169,15 +2169,15 @@ gl_xfpt2i(PyObject *self, PyObject *args)
static PyObject *
gl_objdelete(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- objdelete( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ objdelete( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void patchcurves long s long s */
@@ -2185,15 +2185,15 @@ gl_objdelete(PyObject *self, PyObject *args)
static PyObject *
gl_patchcurves(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- patchcurves( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ patchcurves( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void minsize long s long s */
@@ -2201,15 +2201,15 @@ gl_patchcurves(PyObject *self, PyObject *args)
static PyObject *
gl_minsize(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- minsize( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ minsize( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void maxsize long s long s */
@@ -2217,15 +2217,15 @@ gl_minsize(PyObject *self, PyObject *args)
static PyObject *
gl_maxsize(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- maxsize( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ maxsize( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void keepaspect long s long s */
@@ -2233,15 +2233,15 @@ gl_maxsize(PyObject *self, PyObject *args)
static PyObject *
gl_keepaspect(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- keepaspect( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ keepaspect( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void prefsize long s long s */
@@ -2249,15 +2249,15 @@ gl_keepaspect(PyObject *self, PyObject *args)
static PyObject *
gl_prefsize(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- prefsize( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ prefsize( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void stepunit long s long s */
@@ -2265,15 +2265,15 @@ gl_prefsize(PyObject *self, PyObject *args)
static PyObject *
gl_stepunit(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- stepunit( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ stepunit( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void fudge long s long s */
@@ -2281,15 +2281,15 @@ gl_stepunit(PyObject *self, PyObject *args)
static PyObject *
gl_fudge(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- fudge( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ fudge( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void winmove long s long s */
@@ -2297,15 +2297,15 @@ gl_fudge(PyObject *self, PyObject *args)
static PyObject *
gl_winmove(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- winmove( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ winmove( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void attachcursor short s short s */
@@ -2313,15 +2313,15 @@ gl_winmove(PyObject *self, PyObject *args)
static PyObject *
gl_attachcursor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- attachcursor( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ attachcursor( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void deflinestyle short s short s */
@@ -2329,15 +2329,15 @@ gl_attachcursor(PyObject *self, PyObject *args)
static PyObject *
gl_deflinestyle(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- deflinestyle( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ deflinestyle( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void noise short s short s */
@@ -2345,15 +2345,15 @@ gl_deflinestyle(PyObject *self, PyObject *args)
static PyObject *
gl_noise(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- noise( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ noise( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void picksize short s short s */
@@ -2361,15 +2361,15 @@ gl_noise(PyObject *self, PyObject *args)
static PyObject *
gl_picksize(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- picksize( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ picksize( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void qenter short s short s */
@@ -2377,15 +2377,15 @@ gl_picksize(PyObject *self, PyObject *args)
static PyObject *
gl_qenter(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- qenter( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ qenter( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setdepth short s short s */
@@ -2393,15 +2393,15 @@ gl_qenter(PyObject *self, PyObject *args)
static PyObject *
gl_setdepth(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- setdepth( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ setdepth( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cmov2s short s short s */
@@ -2409,15 +2409,15 @@ gl_setdepth(PyObject *self, PyObject *args)
static PyObject *
gl_cmov2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- cmov2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ cmov2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void draw2s short s short s */
@@ -2425,15 +2425,15 @@ gl_cmov2s(PyObject *self, PyObject *args)
static PyObject *
gl_draw2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- draw2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ draw2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void move2s short s short s */
@@ -2441,15 +2441,15 @@ gl_draw2s(PyObject *self, PyObject *args)
static PyObject *
gl_move2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- move2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ move2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pdr2s short s short s */
@@ -2457,15 +2457,15 @@ gl_move2s(PyObject *self, PyObject *args)
static PyObject *
gl_pdr2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- pdr2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ pdr2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pmv2s short s short s */
@@ -2473,15 +2473,15 @@ gl_pdr2s(PyObject *self, PyObject *args)
static PyObject *
gl_pmv2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- pmv2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ pmv2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pnt2s short s short s */
@@ -2489,15 +2489,15 @@ gl_pmv2s(PyObject *self, PyObject *args)
static PyObject *
gl_pnt2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- pnt2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ pnt2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rdr2s short s short s */
@@ -2505,15 +2505,15 @@ gl_pnt2s(PyObject *self, PyObject *args)
static PyObject *
gl_rdr2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- rdr2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ rdr2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rmv2s short s short s */
@@ -2521,15 +2521,15 @@ gl_rdr2s(PyObject *self, PyObject *args)
static PyObject *
gl_rmv2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- rmv2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ rmv2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpdr2s short s short s */
@@ -2537,15 +2537,15 @@ gl_rmv2s(PyObject *self, PyObject *args)
static PyObject *
gl_rpdr2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- rpdr2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ rpdr2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpmv2s short s short s */
@@ -2553,15 +2553,15 @@ gl_rpdr2s(PyObject *self, PyObject *args)
static PyObject *
gl_rpmv2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- rpmv2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ rpmv2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt2s short s short s */
@@ -2569,15 +2569,15 @@ gl_rpmv2s(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- xfpt2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ xfpt2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cmov2 float s float s */
@@ -2585,15 +2585,15 @@ gl_xfpt2s(PyObject *self, PyObject *args)
static PyObject *
gl_cmov2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- cmov2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ cmov2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void draw2 float s float s */
@@ -2601,15 +2601,15 @@ gl_cmov2(PyObject *self, PyObject *args)
static PyObject *
gl_draw2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- draw2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ draw2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void move2 float s float s */
@@ -2617,15 +2617,15 @@ gl_draw2(PyObject *self, PyObject *args)
static PyObject *
gl_move2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- move2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ move2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pnt2 float s float s */
@@ -2633,15 +2633,15 @@ gl_move2(PyObject *self, PyObject *args)
static PyObject *
gl_pnt2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- pnt2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ pnt2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pdr2 float s float s */
@@ -2649,15 +2649,15 @@ gl_pnt2(PyObject *self, PyObject *args)
static PyObject *
gl_pdr2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- pdr2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ pdr2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pmv2 float s float s */
@@ -2665,15 +2665,15 @@ gl_pdr2(PyObject *self, PyObject *args)
static PyObject *
gl_pmv2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- pmv2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ pmv2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rdr2 float s float s */
@@ -2681,15 +2681,15 @@ gl_pmv2(PyObject *self, PyObject *args)
static PyObject *
gl_rdr2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- rdr2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ rdr2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rmv2 float s float s */
@@ -2697,15 +2697,15 @@ gl_rdr2(PyObject *self, PyObject *args)
static PyObject *
gl_rmv2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- rmv2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ rmv2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpdr2 float s float s */
@@ -2713,15 +2713,15 @@ gl_rmv2(PyObject *self, PyObject *args)
static PyObject *
gl_rpdr2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- rpdr2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ rpdr2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpmv2 float s float s */
@@ -2729,15 +2729,15 @@ gl_rpdr2(PyObject *self, PyObject *args)
static PyObject *
gl_rpmv2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- rpmv2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ rpmv2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt2 float s float s */
@@ -2745,15 +2745,15 @@ gl_rpmv2(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- xfpt2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ xfpt2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void loadmatrix float s[4*4] */
@@ -2761,12 +2761,12 @@ gl_xfpt2(PyObject *self, PyObject *args)
static PyObject *
gl_loadmatrix(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] [ 4 ] ;
- if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
- return NULL;
- loadmatrix( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] [ 4 ] ;
+ if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
+ return NULL;
+ loadmatrix( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void multmatrix float s[4*4] */
@@ -2774,12 +2774,12 @@ gl_loadmatrix(PyObject *self, PyObject *args)
static PyObject *
gl_multmatrix(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] [ 4 ] ;
- if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
- return NULL;
- multmatrix( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] [ 4 ] ;
+ if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
+ return NULL;
+ multmatrix( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void crv float s[3*4] */
@@ -2787,12 +2787,12 @@ gl_multmatrix(PyObject *self, PyObject *args)
static PyObject *
gl_crv(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] [ 3 ] ;
- if (!getifloatarray(args, 1, 0, 3 * 4 , (float *) arg1))
- return NULL;
- crv( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] [ 3 ] ;
+ if (!getifloatarray(args, 1, 0, 3 * 4 , (float *) arg1))
+ return NULL;
+ crv( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rcrv float s[4*4] */
@@ -2800,12 +2800,12 @@ gl_crv(PyObject *self, PyObject *args)
static PyObject *
gl_rcrv(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] [ 4 ] ;
- if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
- return NULL;
- rcrv( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] [ 4 ] ;
+ if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
+ return NULL;
+ rcrv( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void addtopup long s char *s long s */
@@ -2813,18 +2813,18 @@ gl_rcrv(PyObject *self, PyObject *args)
static PyObject *
gl_addtopup(PyObject *self, PyObject *args)
{
- long arg1 ;
- string arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getistringarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- addtopup( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ string arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getistringarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ addtopup( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void charstr char *s */
@@ -2832,12 +2832,12 @@ gl_addtopup(PyObject *self, PyObject *args)
static PyObject *
gl_charstr(PyObject *self, PyObject *args)
{
- string arg1 ;
- if (!getistringarg(args, 1, 0, &arg1))
- return NULL;
- charstr( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ string arg1 ;
+ if (!getistringarg(args, 1, 0, &arg1))
+ return NULL;
+ charstr( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void getport char *s */
@@ -2845,12 +2845,12 @@ gl_charstr(PyObject *self, PyObject *args)
static PyObject *
gl_getport(PyObject *self, PyObject *args)
{
- string arg1 ;
- if (!getistringarg(args, 1, 0, &arg1))
- return NULL;
- getport( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ string arg1 ;
+ if (!getistringarg(args, 1, 0, &arg1))
+ return NULL;
+ getport( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long strwidth char *s */
@@ -2858,12 +2858,12 @@ gl_getport(PyObject *self, PyObject *args)
static PyObject *
gl_strwidth(PyObject *self, PyObject *args)
{
- long retval;
- string arg1 ;
- if (!getistringarg(args, 1, 0, &arg1))
- return NULL;
- retval = strwidth( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ string arg1 ;
+ if (!getistringarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = strwidth( arg1 );
+ return mknewlongobject(retval);
}
/* long winopen char *s */
@@ -2871,12 +2871,12 @@ gl_strwidth(PyObject *self, PyObject *args)
static PyObject *
gl_winopen(PyObject *self, PyObject *args)
{
- long retval;
- string arg1 ;
- if (!getistringarg(args, 1, 0, &arg1))
- return NULL;
- retval = winopen( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ string arg1 ;
+ if (!getistringarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = winopen( arg1 );
+ return mknewlongobject(retval);
}
/* void wintitle char *s */
@@ -2884,12 +2884,12 @@ gl_winopen(PyObject *self, PyObject *args)
static PyObject *
gl_wintitle(PyObject *self, PyObject *args)
{
- string arg1 ;
- if (!getistringarg(args, 1, 0, &arg1))
- return NULL;
- wintitle( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ string arg1 ;
+ if (!getistringarg(args, 1, 0, &arg1))
+ return NULL;
+ wintitle( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polf long s float s[3*arg1] */
@@ -2897,19 +2897,19 @@ gl_wintitle(PyObject *self, PyObject *args)
static PyObject *
gl_polf(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
- return NULL;
- polf( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
+ return NULL;
+ polf( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polf2 long s float s[2*arg1] */
@@ -2917,19 +2917,19 @@ gl_polf(PyObject *self, PyObject *args)
static PyObject *
gl_polf2(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 2 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 1, 0, 2 * arg1 , (float *) arg2))
- return NULL;
- polf2( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 2 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 1, 0, 2 * arg1 , (float *) arg2))
+ return NULL;
+ polf2( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void poly long s float s[3*arg1] */
@@ -2937,19 +2937,19 @@ gl_polf2(PyObject *self, PyObject *args)
static PyObject *
gl_poly(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
- return NULL;
- poly( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
+ return NULL;
+ poly( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void poly2 long s float s[2*arg1] */
@@ -2957,19 +2957,19 @@ gl_poly(PyObject *self, PyObject *args)
static PyObject *
gl_poly2(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 2 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 1, 0, 2 * arg1 , (float *) arg2))
- return NULL;
- poly2( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 2 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 1, 0, 2 * arg1 , (float *) arg2))
+ return NULL;
+ poly2( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void crvn long s float s[3*arg1] */
@@ -2977,19 +2977,19 @@ gl_poly2(PyObject *self, PyObject *args)
static PyObject *
gl_crvn(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
- return NULL;
- crvn( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
+ return NULL;
+ crvn( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rcrvn long s float s[4*arg1] */
@@ -2997,19 +2997,19 @@ gl_crvn(PyObject *self, PyObject *args)
static PyObject *
gl_rcrvn(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 4 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 4;
- if ((arg2 = (float(*)[4]) PyMem_NEW(float , 4 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 1, 0, 4 * arg1 , (float *) arg2))
- return NULL;
- rcrvn( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 4 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 4;
+ if ((arg2 = (float(*)[4]) PyMem_NEW(float , 4 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 1, 0, 4 * arg1 , (float *) arg2))
+ return NULL;
+ rcrvn( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polf2i long s long s[2*arg1] */
@@ -3017,19 +3017,19 @@ gl_rcrvn(PyObject *self, PyObject *args)
static PyObject *
gl_polf2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long (* arg2) [ 2 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getilongarray(args, 1, 0, 2 * arg1 , (long *) arg2))
- return NULL;
- polf2i( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long (* arg2) [ 2 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getilongarray(args, 1, 0, 2 * arg1 , (long *) arg2))
+ return NULL;
+ polf2i( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polfi long s long s[3*arg1] */
@@ -3037,19 +3037,19 @@ gl_polf2i(PyObject *self, PyObject *args)
static PyObject *
gl_polfi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getilongarray(args, 1, 0, 3 * arg1 , (long *) arg2))
- return NULL;
- polfi( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getilongarray(args, 1, 0, 3 * arg1 , (long *) arg2))
+ return NULL;
+ polfi( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void poly2i long s long s[2*arg1] */
@@ -3057,19 +3057,19 @@ gl_polfi(PyObject *self, PyObject *args)
static PyObject *
gl_poly2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long (* arg2) [ 2 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getilongarray(args, 1, 0, 2 * arg1 , (long *) arg2))
- return NULL;
- poly2i( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long (* arg2) [ 2 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getilongarray(args, 1, 0, 2 * arg1 , (long *) arg2))
+ return NULL;
+ poly2i( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polyi long s long s[3*arg1] */
@@ -3077,19 +3077,19 @@ gl_poly2i(PyObject *self, PyObject *args)
static PyObject *
gl_polyi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getilongarray(args, 1, 0, 3 * arg1 , (long *) arg2))
- return NULL;
- polyi( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getilongarray(args, 1, 0, 3 * arg1 , (long *) arg2))
+ return NULL;
+ polyi( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polf2s long s short s[2*arg1] */
@@ -3097,19 +3097,19 @@ gl_polyi(PyObject *self, PyObject *args)
static PyObject *
gl_polf2s(PyObject *self, PyObject *args)
{
- long arg1 ;
- short (* arg2) [ 2 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 1, 0, 2 * arg1 , (short *) arg2))
- return NULL;
- polf2s( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ short (* arg2) [ 2 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 1, 0, 2 * arg1 , (short *) arg2))
+ return NULL;
+ polf2s( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polfs long s short s[3*arg1] */
@@ -3117,19 +3117,19 @@ gl_polf2s(PyObject *self, PyObject *args)
static PyObject *
gl_polfs(PyObject *self, PyObject *args)
{
- long arg1 ;
- short (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 1, 0, 3 * arg1 , (short *) arg2))
- return NULL;
- polfs( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ short (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 1, 0, 3 * arg1 , (short *) arg2))
+ return NULL;
+ polfs( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polys long s short s[3*arg1] */
@@ -3137,19 +3137,19 @@ gl_polfs(PyObject *self, PyObject *args)
static PyObject *
gl_polys(PyObject *self, PyObject *args)
{
- long arg1 ;
- short (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 1, 0, 3 * arg1 , (short *) arg2))
- return NULL;
- polys( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ short (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 1, 0, 3 * arg1 , (short *) arg2))
+ return NULL;
+ polys( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void poly2s long s short s[2*arg1] */
@@ -3157,19 +3157,19 @@ gl_polys(PyObject *self, PyObject *args)
static PyObject *
gl_poly2s(PyObject *self, PyObject *args)
{
- long arg1 ;
- short (* arg2) [ 2 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 1, 0, 2 * arg1 , (short *) arg2))
- return NULL;
- poly2s( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ short (* arg2) [ 2 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 1, 0, 2 * arg1 , (short *) arg2))
+ return NULL;
+ poly2s( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void defcursor short s u_short s[128] */
@@ -3177,15 +3177,15 @@ gl_poly2s(PyObject *self, PyObject *args)
static PyObject *
gl_defcursor(PyObject *self, PyObject *args)
{
- short arg1 ;
- unsigned short arg2 [ 128 ] ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarray(args, 2, 1, 128 , (short *) arg2))
- return NULL;
- defcursor( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ unsigned short arg2 [ 128 ] ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarray(args, 2, 1, 128 , (short *) arg2))
+ return NULL;
+ defcursor( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void writepixels short s u_short s[arg1] */
@@ -3193,18 +3193,18 @@ gl_defcursor(PyObject *self, PyObject *args)
static PyObject *
gl_writepixels(PyObject *self, PyObject *args)
{
- short arg1 ;
- unsigned short * arg2 ;
- if (!getishortarraysize(args, 1, 0, &arg1))
- return NULL;
- if ((arg2 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 1, 0, arg1 , (short *) arg2))
- return NULL;
- writepixels( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ unsigned short * arg2 ;
+ if (!getishortarraysize(args, 1, 0, &arg1))
+ return NULL;
+ if ((arg2 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 1, 0, arg1 , (short *) arg2))
+ return NULL;
+ writepixels( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void defbasis long s float s[4*4] */
@@ -3212,15 +3212,15 @@ gl_writepixels(PyObject *self, PyObject *args)
static PyObject *
gl_defbasis(PyObject *self, PyObject *args)
{
- long arg1 ;
- float arg2 [ 4 ] [ 4 ] ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarray(args, 2, 1, 4 * 4 , (float *) arg2))
- return NULL;
- defbasis( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float arg2 [ 4 ] [ 4 ] ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarray(args, 2, 1, 4 * 4 , (float *) arg2))
+ return NULL;
+ defbasis( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gewrite short s short s[arg1] */
@@ -3228,18 +3228,18 @@ gl_defbasis(PyObject *self, PyObject *args)
static PyObject *
gl_gewrite(PyObject *self, PyObject *args)
{
- short arg1 ;
- short * arg2 ;
- if (!getishortarraysize(args, 1, 0, &arg1))
- return NULL;
- if ((arg2 = PyMem_NEW(short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 1, 0, arg1 , arg2))
- return NULL;
- gewrite( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short * arg2 ;
+ if (!getishortarraysize(args, 1, 0, &arg1))
+ return NULL;
+ if ((arg2 = PyMem_NEW(short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 1, 0, arg1 , arg2))
+ return NULL;
+ gewrite( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rotate short s char s */
@@ -3247,15 +3247,15 @@ gl_gewrite(PyObject *self, PyObject *args)
static PyObject *
gl_rotate(PyObject *self, PyObject *args)
{
- short arg1 ;
- char arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getichararg(args, 2, 1, &arg2))
- return NULL;
- rotate( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ char arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getichararg(args, 2, 1, &arg2))
+ return NULL;
+ rotate( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rot float s char s */
@@ -3263,15 +3263,15 @@ gl_rotate(PyObject *self, PyObject *args)
static PyObject *
gl_rot(PyObject *self, PyObject *args)
{
- float arg1 ;
- char arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getichararg(args, 2, 1, &arg2))
- return NULL;
- rot( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ char arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getichararg(args, 2, 1, &arg2))
+ return NULL;
+ rot( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void circfi long s long s long s */
@@ -3279,18 +3279,18 @@ gl_rot(PyObject *self, PyObject *args)
static PyObject *
gl_circfi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- circfi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ circfi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void circi long s long s long s */
@@ -3298,18 +3298,18 @@ gl_circfi(PyObject *self, PyObject *args)
static PyObject *
gl_circi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- circi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ circi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cmovi long s long s long s */
@@ -3317,18 +3317,18 @@ gl_circi(PyObject *self, PyObject *args)
static PyObject *
gl_cmovi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- cmovi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ cmovi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void drawi long s long s long s */
@@ -3336,18 +3336,18 @@ gl_cmovi(PyObject *self, PyObject *args)
static PyObject *
gl_drawi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- drawi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ drawi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void movei long s long s long s */
@@ -3355,18 +3355,18 @@ gl_drawi(PyObject *self, PyObject *args)
static PyObject *
gl_movei(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- movei( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ movei( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pnti long s long s long s */
@@ -3374,18 +3374,18 @@ gl_movei(PyObject *self, PyObject *args)
static PyObject *
gl_pnti(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- pnti( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ pnti( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void newtag long s long s long s */
@@ -3393,18 +3393,18 @@ gl_pnti(PyObject *self, PyObject *args)
static PyObject *
gl_newtag(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- newtag( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ newtag( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pdri long s long s long s */
@@ -3412,18 +3412,18 @@ gl_newtag(PyObject *self, PyObject *args)
static PyObject *
gl_pdri(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- pdri( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ pdri( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pmvi long s long s long s */
@@ -3431,18 +3431,18 @@ gl_pdri(PyObject *self, PyObject *args)
static PyObject *
gl_pmvi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- pmvi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ pmvi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rdri long s long s long s */
@@ -3450,18 +3450,18 @@ gl_pmvi(PyObject *self, PyObject *args)
static PyObject *
gl_rdri(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- rdri( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ rdri( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rmvi long s long s long s */
@@ -3469,18 +3469,18 @@ gl_rdri(PyObject *self, PyObject *args)
static PyObject *
gl_rmvi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- rmvi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ rmvi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpdri long s long s long s */
@@ -3488,18 +3488,18 @@ gl_rmvi(PyObject *self, PyObject *args)
static PyObject *
gl_rpdri(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- rpdri( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ rpdri( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpmvi long s long s long s */
@@ -3507,18 +3507,18 @@ gl_rpdri(PyObject *self, PyObject *args)
static PyObject *
gl_rpmvi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- rpmvi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ rpmvi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpti long s long s long s */
@@ -3526,18 +3526,18 @@ gl_rpmvi(PyObject *self, PyObject *args)
static PyObject *
gl_xfpti(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- xfpti( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ xfpti( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void circ float s float s float s */
@@ -3545,18 +3545,18 @@ gl_xfpti(PyObject *self, PyObject *args)
static PyObject *
gl_circ(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- circ( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ circ( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void circf float s float s float s */
@@ -3564,18 +3564,18 @@ gl_circ(PyObject *self, PyObject *args)
static PyObject *
gl_circf(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- circf( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ circf( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cmov float s float s float s */
@@ -3583,18 +3583,18 @@ gl_circf(PyObject *self, PyObject *args)
static PyObject *
gl_cmov(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- cmov( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ cmov( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void draw float s float s float s */
@@ -3602,18 +3602,18 @@ gl_cmov(PyObject *self, PyObject *args)
static PyObject *
gl_draw(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- draw( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ draw( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void move float s float s float s */
@@ -3621,18 +3621,18 @@ gl_draw(PyObject *self, PyObject *args)
static PyObject *
gl_move(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- move( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ move( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pnt float s float s float s */
@@ -3640,18 +3640,18 @@ gl_move(PyObject *self, PyObject *args)
static PyObject *
gl_pnt(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- pnt( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ pnt( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void scale float s float s float s */
@@ -3659,18 +3659,18 @@ gl_pnt(PyObject *self, PyObject *args)
static PyObject *
gl_scale(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- scale( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ scale( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void translate float s float s float s */
@@ -3678,18 +3678,18 @@ gl_scale(PyObject *self, PyObject *args)
static PyObject *
gl_translate(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- translate( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ translate( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pdr float s float s float s */
@@ -3697,18 +3697,18 @@ gl_translate(PyObject *self, PyObject *args)
static PyObject *
gl_pdr(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- pdr( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ pdr( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pmv float s float s float s */
@@ -3716,18 +3716,18 @@ gl_pdr(PyObject *self, PyObject *args)
static PyObject *
gl_pmv(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- pmv( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ pmv( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rdr float s float s float s */
@@ -3735,18 +3735,18 @@ gl_pmv(PyObject *self, PyObject *args)
static PyObject *
gl_rdr(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- rdr( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ rdr( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rmv float s float s float s */
@@ -3754,18 +3754,18 @@ gl_rdr(PyObject *self, PyObject *args)
static PyObject *
gl_rmv(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- rmv( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ rmv( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpdr float s float s float s */
@@ -3773,18 +3773,18 @@ gl_rmv(PyObject *self, PyObject *args)
static PyObject *
gl_rpdr(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- rpdr( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ rpdr( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpmv float s float s float s */
@@ -3792,18 +3792,18 @@ gl_rpdr(PyObject *self, PyObject *args)
static PyObject *
gl_rpmv(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- rpmv( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ rpmv( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt float s float s float s */
@@ -3811,18 +3811,18 @@ gl_rpmv(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- xfpt( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ xfpt( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void RGBcolor short s short s short s */
@@ -3830,18 +3830,18 @@ gl_xfpt(PyObject *self, PyObject *args)
static PyObject *
gl_RGBcolor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- RGBcolor( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ RGBcolor( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void RGBwritemask short s short s short s */
@@ -3849,18 +3849,18 @@ gl_RGBcolor(PyObject *self, PyObject *args)
static PyObject *
gl_RGBwritemask(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- RGBwritemask( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ RGBwritemask( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setcursor short s short s short s */
@@ -3868,18 +3868,18 @@ gl_RGBwritemask(PyObject *self, PyObject *args)
static PyObject *
gl_setcursor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- setcursor( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ setcursor( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void tie short s short s short s */
@@ -3887,18 +3887,18 @@ gl_setcursor(PyObject *self, PyObject *args)
static PyObject *
gl_tie(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- tie( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ tie( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void circfs short s short s short s */
@@ -3906,18 +3906,18 @@ gl_tie(PyObject *self, PyObject *args)
static PyObject *
gl_circfs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- circfs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ circfs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void circs short s short s short s */
@@ -3925,18 +3925,18 @@ gl_circfs(PyObject *self, PyObject *args)
static PyObject *
gl_circs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- circs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ circs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cmovs short s short s short s */
@@ -3944,18 +3944,18 @@ gl_circs(PyObject *self, PyObject *args)
static PyObject *
gl_cmovs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- cmovs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ cmovs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void draws short s short s short s */
@@ -3963,18 +3963,18 @@ gl_cmovs(PyObject *self, PyObject *args)
static PyObject *
gl_draws(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- draws( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ draws( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void moves short s short s short s */
@@ -3982,18 +3982,18 @@ gl_draws(PyObject *self, PyObject *args)
static PyObject *
gl_moves(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- moves( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ moves( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pdrs short s short s short s */
@@ -4001,18 +4001,18 @@ gl_moves(PyObject *self, PyObject *args)
static PyObject *
gl_pdrs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- pdrs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ pdrs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pmvs short s short s short s */
@@ -4020,18 +4020,18 @@ gl_pdrs(PyObject *self, PyObject *args)
static PyObject *
gl_pmvs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- pmvs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ pmvs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pnts short s short s short s */
@@ -4039,18 +4039,18 @@ gl_pmvs(PyObject *self, PyObject *args)
static PyObject *
gl_pnts(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- pnts( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ pnts( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rdrs short s short s short s */
@@ -4058,18 +4058,18 @@ gl_pnts(PyObject *self, PyObject *args)
static PyObject *
gl_rdrs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- rdrs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ rdrs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rmvs short s short s short s */
@@ -4077,18 +4077,18 @@ gl_rdrs(PyObject *self, PyObject *args)
static PyObject *
gl_rmvs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- rmvs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ rmvs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpdrs short s short s short s */
@@ -4096,18 +4096,18 @@ gl_rmvs(PyObject *self, PyObject *args)
static PyObject *
gl_rpdrs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- rpdrs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ rpdrs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpmvs short s short s short s */
@@ -4115,18 +4115,18 @@ gl_rpdrs(PyObject *self, PyObject *args)
static PyObject *
gl_rpmvs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- rpmvs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ rpmvs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpts short s short s short s */
@@ -4134,18 +4134,18 @@ gl_rpmvs(PyObject *self, PyObject *args)
static PyObject *
gl_xfpts(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- xfpts( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ xfpts( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void curorigin short s short s short s */
@@ -4153,18 +4153,18 @@ gl_xfpts(PyObject *self, PyObject *args)
static PyObject *
gl_curorigin(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- curorigin( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ curorigin( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cyclemap short s short s short s */
@@ -4172,18 +4172,18 @@ gl_curorigin(PyObject *self, PyObject *args)
static PyObject *
gl_cyclemap(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- cyclemap( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ cyclemap( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void patch float s[4*4] float s[4*4] float s[4*4] */
@@ -4191,18 +4191,18 @@ gl_cyclemap(PyObject *self, PyObject *args)
static PyObject *
gl_patch(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] [ 4 ] ;
- float arg2 [ 4 ] [ 4 ] ;
- float arg3 [ 4 ] [ 4 ] ;
- if (!getifloatarray(args, 3, 0, 4 * 4 , (float *) arg1))
- return NULL;
- if (!getifloatarray(args, 3, 1, 4 * 4 , (float *) arg2))
- return NULL;
- if (!getifloatarray(args, 3, 2, 4 * 4 , (float *) arg3))
- return NULL;
- patch( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] [ 4 ] ;
+ float arg2 [ 4 ] [ 4 ] ;
+ float arg3 [ 4 ] [ 4 ] ;
+ if (!getifloatarray(args, 3, 0, 4 * 4 , (float *) arg1))
+ return NULL;
+ if (!getifloatarray(args, 3, 1, 4 * 4 , (float *) arg2))
+ return NULL;
+ if (!getifloatarray(args, 3, 2, 4 * 4 , (float *) arg3))
+ return NULL;
+ patch( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void splf long s float s[3*arg1] u_short s[arg1] */
@@ -4210,25 +4210,25 @@ gl_patch(PyObject *self, PyObject *args)
static PyObject *
gl_splf(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 3 ] ;
- unsigned short * arg3 ;
- if (!getilongarraysize(args, 2, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 2, 0, 3 * arg1 , (float *) arg2))
- return NULL;
- if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
- return NULL;
- splf( arg1 , arg2 , arg3 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 3 ] ;
+ unsigned short * arg3 ;
+ if (!getilongarraysize(args, 2, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 2, 0, 3 * arg1 , (float *) arg2))
+ return NULL;
+ if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
+ return NULL;
+ splf( arg1 , arg2 , arg3 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void splf2 long s float s[2*arg1] u_short s[arg1] */
@@ -4236,25 +4236,25 @@ gl_splf(PyObject *self, PyObject *args)
static PyObject *
gl_splf2(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 2 ] ;
- unsigned short * arg3 ;
- if (!getilongarraysize(args, 2, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 2, 0, 2 * arg1 , (float *) arg2))
- return NULL;
- if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
- return NULL;
- splf2( arg1 , arg2 , arg3 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 2 ] ;
+ unsigned short * arg3 ;
+ if (!getilongarraysize(args, 2, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 2, 0, 2 * arg1 , (float *) arg2))
+ return NULL;
+ if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
+ return NULL;
+ splf2( arg1 , arg2 , arg3 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void splfi long s long s[3*arg1] u_short s[arg1] */
@@ -4262,25 +4262,25 @@ gl_splf2(PyObject *self, PyObject *args)
static PyObject *
gl_splfi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long (* arg2) [ 3 ] ;
- unsigned short * arg3 ;
- if (!getilongarraysize(args, 2, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getilongarray(args, 2, 0, 3 * arg1 , (long *) arg2))
- return NULL;
- if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
- return NULL;
- splfi( arg1 , arg2 , arg3 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long (* arg2) [ 3 ] ;
+ unsigned short * arg3 ;
+ if (!getilongarraysize(args, 2, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getilongarray(args, 2, 0, 3 * arg1 , (long *) arg2))
+ return NULL;
+ if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
+ return NULL;
+ splfi( arg1 , arg2 , arg3 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void splf2i long s long s[2*arg1] u_short s[arg1] */
@@ -4288,25 +4288,25 @@ gl_splfi(PyObject *self, PyObject *args)
static PyObject *
gl_splf2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long (* arg2) [ 2 ] ;
- unsigned short * arg3 ;
- if (!getilongarraysize(args, 2, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getilongarray(args, 2, 0, 2 * arg1 , (long *) arg2))
- return NULL;
- if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
- return NULL;
- splf2i( arg1 , arg2 , arg3 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long (* arg2) [ 2 ] ;
+ unsigned short * arg3 ;
+ if (!getilongarraysize(args, 2, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getilongarray(args, 2, 0, 2 * arg1 , (long *) arg2))
+ return NULL;
+ if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
+ return NULL;
+ splf2i( arg1 , arg2 , arg3 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void splfs long s short s[3*arg1] u_short s[arg1] */
@@ -4314,25 +4314,25 @@ gl_splf2i(PyObject *self, PyObject *args)
static PyObject *
gl_splfs(PyObject *self, PyObject *args)
{
- long arg1 ;
- short (* arg2) [ 3 ] ;
- unsigned short * arg3 ;
- if (!getilongarraysize(args, 2, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 0, 3 * arg1 , (short *) arg2))
- return NULL;
- if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
- return NULL;
- splfs( arg1 , arg2 , arg3 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ short (* arg2) [ 3 ] ;
+ unsigned short * arg3 ;
+ if (!getilongarraysize(args, 2, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 0, 3 * arg1 , (short *) arg2))
+ return NULL;
+ if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
+ return NULL;
+ splfs( arg1 , arg2 , arg3 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void splf2s long s short s[2*arg1] u_short s[arg1] */
@@ -4340,25 +4340,25 @@ gl_splfs(PyObject *self, PyObject *args)
static PyObject *
gl_splf2s(PyObject *self, PyObject *args)
{
- long arg1 ;
- short (* arg2) [ 2 ] ;
- unsigned short * arg3 ;
- if (!getilongarraysize(args, 2, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 0, 2 * arg1 , (short *) arg2))
- return NULL;
- if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
- return NULL;
- splf2s( arg1 , arg2 , arg3 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ short (* arg2) [ 2 ] ;
+ unsigned short * arg3 ;
+ if (!getilongarraysize(args, 2, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 0, 2 * arg1 , (short *) arg2))
+ return NULL;
+ if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
+ return NULL;
+ splf2s( arg1 , arg2 , arg3 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpatch float s[4*4] float s[4*4] float s[4*4] float s[4*4] */
@@ -4366,21 +4366,21 @@ gl_splf2s(PyObject *self, PyObject *args)
static PyObject *
gl_rpatch(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] [ 4 ] ;
- float arg2 [ 4 ] [ 4 ] ;
- float arg3 [ 4 ] [ 4 ] ;
- float arg4 [ 4 ] [ 4 ] ;
- if (!getifloatarray(args, 4, 0, 4 * 4 , (float *) arg1))
- return NULL;
- if (!getifloatarray(args, 4, 1, 4 * 4 , (float *) arg2))
- return NULL;
- if (!getifloatarray(args, 4, 2, 4 * 4 , (float *) arg3))
- return NULL;
- if (!getifloatarray(args, 4, 3, 4 * 4 , (float *) arg4))
- return NULL;
- rpatch( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] [ 4 ] ;
+ float arg2 [ 4 ] [ 4 ] ;
+ float arg3 [ 4 ] [ 4 ] ;
+ float arg4 [ 4 ] [ 4 ] ;
+ if (!getifloatarray(args, 4, 0, 4 * 4 , (float *) arg1))
+ return NULL;
+ if (!getifloatarray(args, 4, 1, 4 * 4 , (float *) arg2))
+ return NULL;
+ if (!getifloatarray(args, 4, 2, 4 * 4 , (float *) arg3))
+ return NULL;
+ if (!getifloatarray(args, 4, 3, 4 * 4 , (float *) arg4))
+ return NULL;
+ rpatch( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void ortho2 float s float s float s float s */
@@ -4388,21 +4388,21 @@ gl_rpatch(PyObject *self, PyObject *args)
static PyObject *
gl_ortho2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- ortho2( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ ortho2( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rect float s float s float s float s */
@@ -4410,21 +4410,21 @@ gl_ortho2(PyObject *self, PyObject *args)
static PyObject *
gl_rect(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- rect( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ rect( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rectf float s float s float s float s */
@@ -4432,21 +4432,21 @@ gl_rect(PyObject *self, PyObject *args)
static PyObject *
gl_rectf(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- rectf( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ rectf( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt4 float s float s float s float s */
@@ -4454,21 +4454,21 @@ gl_rectf(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt4(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- xfpt4( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ xfpt4( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void textport short s short s short s short s */
@@ -4476,21 +4476,21 @@ gl_xfpt4(PyObject *self, PyObject *args)
static PyObject *
gl_textport(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- textport( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ textport( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void mapcolor short s short s short s short s */
@@ -4498,21 +4498,21 @@ gl_textport(PyObject *self, PyObject *args)
static PyObject *
gl_mapcolor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- mapcolor( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ mapcolor( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void scrmask short s short s short s short s */
@@ -4520,21 +4520,21 @@ gl_mapcolor(PyObject *self, PyObject *args)
static PyObject *
gl_scrmask(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- scrmask( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ scrmask( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setvaluator short s short s short s short s */
@@ -4542,21 +4542,21 @@ gl_scrmask(PyObject *self, PyObject *args)
static PyObject *
gl_setvaluator(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- setvaluator( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ setvaluator( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void viewport short s short s short s short s */
@@ -4564,21 +4564,21 @@ gl_setvaluator(PyObject *self, PyObject *args)
static PyObject *
gl_viewport(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- viewport( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ viewport( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void shaderange short s short s short s short s */
@@ -4586,21 +4586,21 @@ gl_viewport(PyObject *self, PyObject *args)
static PyObject *
gl_shaderange(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- shaderange( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ shaderange( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt4s short s short s short s short s */
@@ -4608,21 +4608,21 @@ gl_shaderange(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt4s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- xfpt4s( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ xfpt4s( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rectfi long s long s long s long s */
@@ -4630,21 +4630,21 @@ gl_xfpt4s(PyObject *self, PyObject *args)
static PyObject *
gl_rectfi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- rectfi( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ rectfi( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void recti long s long s long s long s */
@@ -4652,21 +4652,21 @@ gl_rectfi(PyObject *self, PyObject *args)
static PyObject *
gl_recti(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- recti( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ recti( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt4i long s long s long s long s */
@@ -4674,21 +4674,21 @@ gl_recti(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt4i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- xfpt4i( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ xfpt4i( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void prefposition long s long s long s long s */
@@ -4696,21 +4696,21 @@ gl_xfpt4i(PyObject *self, PyObject *args)
static PyObject *
gl_prefposition(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- prefposition( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ prefposition( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void arc float s float s float s short s short s */
@@ -4718,24 +4718,24 @@ gl_prefposition(PyObject *self, PyObject *args)
static PyObject *
gl_arc(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getifloatarg(args, 5, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 5, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- arc( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getifloatarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ arc( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void arcf float s float s float s short s short s */
@@ -4743,24 +4743,24 @@ gl_arc(PyObject *self, PyObject *args)
static PyObject *
gl_arcf(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getifloatarg(args, 5, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 5, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- arcf( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getifloatarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ arcf( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void arcfi long s long s long s short s short s */
@@ -4768,24 +4768,24 @@ gl_arcf(PyObject *self, PyObject *args)
static PyObject *
gl_arcfi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getilongarg(args, 5, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 5, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- arcfi( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getilongarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ arcfi( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void arci long s long s long s short s short s */
@@ -4793,24 +4793,24 @@ gl_arcfi(PyObject *self, PyObject *args)
static PyObject *
gl_arci(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getilongarg(args, 5, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 5, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- arci( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getilongarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ arci( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bbox2 short s short s float s float s float s float s */
@@ -4818,27 +4818,27 @@ gl_arci(PyObject *self, PyObject *args)
static PyObject *
gl_bbox2(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- float arg3 ;
- float arg4 ;
- float arg5 ;
- float arg6 ;
- if (!getishortarg(args, 6, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 6, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 6, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 6, 3, &arg4))
- return NULL;
- if (!getifloatarg(args, 6, 4, &arg5))
- return NULL;
- if (!getifloatarg(args, 6, 5, &arg6))
- return NULL;
- bbox2( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ float arg3 ;
+ float arg4 ;
+ float arg5 ;
+ float arg6 ;
+ if (!getishortarg(args, 6, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 6, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 6, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 6, 3, &arg4))
+ return NULL;
+ if (!getifloatarg(args, 6, 4, &arg5))
+ return NULL;
+ if (!getifloatarg(args, 6, 5, &arg6))
+ return NULL;
+ bbox2( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bbox2i short s short s long s long s long s long s */
@@ -4846,27 +4846,27 @@ gl_bbox2(PyObject *self, PyObject *args)
static PyObject *
gl_bbox2i(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- long arg3 ;
- long arg4 ;
- long arg5 ;
- long arg6 ;
- if (!getishortarg(args, 6, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 6, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 6, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 6, 3, &arg4))
- return NULL;
- if (!getilongarg(args, 6, 4, &arg5))
- return NULL;
- if (!getilongarg(args, 6, 5, &arg6))
- return NULL;
- bbox2i( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ long arg3 ;
+ long arg4 ;
+ long arg5 ;
+ long arg6 ;
+ if (!getishortarg(args, 6, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 6, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 6, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 6, 3, &arg4))
+ return NULL;
+ if (!getilongarg(args, 6, 4, &arg5))
+ return NULL;
+ if (!getilongarg(args, 6, 5, &arg6))
+ return NULL;
+ bbox2i( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bbox2s short s short s short s short s short s short s */
@@ -4874,27 +4874,27 @@ gl_bbox2i(PyObject *self, PyObject *args)
static PyObject *
gl_bbox2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- short arg6 ;
- if (!getishortarg(args, 6, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 6, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 6, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 6, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 6, 4, &arg5))
- return NULL;
- if (!getishortarg(args, 6, 5, &arg6))
- return NULL;
- bbox2s( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ short arg6 ;
+ if (!getishortarg(args, 6, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 6, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 6, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 6, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 6, 4, &arg5))
+ return NULL;
+ if (!getishortarg(args, 6, 5, &arg6))
+ return NULL;
+ bbox2s( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void blink short s short s short s short s short s */
@@ -4902,24 +4902,24 @@ gl_bbox2s(PyObject *self, PyObject *args)
static PyObject *
gl_blink(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getishortarg(args, 5, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 5, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- blink( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getishortarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ blink( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void ortho float s float s float s float s float s float s */
@@ -4927,27 +4927,27 @@ gl_blink(PyObject *self, PyObject *args)
static PyObject *
gl_ortho(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- float arg5 ;
- float arg6 ;
- if (!getifloatarg(args, 6, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 6, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 6, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 6, 3, &arg4))
- return NULL;
- if (!getifloatarg(args, 6, 4, &arg5))
- return NULL;
- if (!getifloatarg(args, 6, 5, &arg6))
- return NULL;
- ortho( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ float arg5 ;
+ float arg6 ;
+ if (!getifloatarg(args, 6, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 6, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 6, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 6, 3, &arg4))
+ return NULL;
+ if (!getifloatarg(args, 6, 4, &arg5))
+ return NULL;
+ if (!getifloatarg(args, 6, 5, &arg6))
+ return NULL;
+ ortho( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void window float s float s float s float s float s float s */
@@ -4955,27 +4955,27 @@ gl_ortho(PyObject *self, PyObject *args)
static PyObject *
gl_window(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- float arg5 ;
- float arg6 ;
- if (!getifloatarg(args, 6, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 6, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 6, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 6, 3, &arg4))
- return NULL;
- if (!getifloatarg(args, 6, 4, &arg5))
- return NULL;
- if (!getifloatarg(args, 6, 5, &arg6))
- return NULL;
- window( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ float arg5 ;
+ float arg6 ;
+ if (!getifloatarg(args, 6, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 6, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 6, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 6, 3, &arg4))
+ return NULL;
+ if (!getifloatarg(args, 6, 4, &arg5))
+ return NULL;
+ if (!getifloatarg(args, 6, 5, &arg6))
+ return NULL;
+ window( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lookat float s float s float s float s float s float s short s */
@@ -4983,30 +4983,30 @@ gl_window(PyObject *self, PyObject *args)
static PyObject *
gl_lookat(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- float arg5 ;
- float arg6 ;
- short arg7 ;
- if (!getifloatarg(args, 7, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 7, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 7, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 7, 3, &arg4))
- return NULL;
- if (!getifloatarg(args, 7, 4, &arg5))
- return NULL;
- if (!getifloatarg(args, 7, 5, &arg6))
- return NULL;
- if (!getishortarg(args, 7, 6, &arg7))
- return NULL;
- lookat( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ float arg5 ;
+ float arg6 ;
+ short arg7 ;
+ if (!getifloatarg(args, 7, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 7, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 7, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 7, 3, &arg4))
+ return NULL;
+ if (!getifloatarg(args, 7, 4, &arg5))
+ return NULL;
+ if (!getifloatarg(args, 7, 5, &arg6))
+ return NULL;
+ if (!getishortarg(args, 7, 6, &arg7))
+ return NULL;
+ lookat( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void perspective short s float s float s float s */
@@ -5014,21 +5014,21 @@ gl_lookat(PyObject *self, PyObject *args)
static PyObject *
gl_perspective(PyObject *self, PyObject *args)
{
- short arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- perspective( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ perspective( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polarview float s short s short s short s */
@@ -5036,21 +5036,21 @@ gl_perspective(PyObject *self, PyObject *args)
static PyObject *
gl_polarview(PyObject *self, PyObject *args)
{
- float arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- polarview( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ polarview( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void arcfs short s short s short s short s short s */
@@ -5058,24 +5058,24 @@ gl_polarview(PyObject *self, PyObject *args)
static PyObject *
gl_arcfs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getishortarg(args, 5, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 5, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- arcfs( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getishortarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ arcfs( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void arcs short s short s short s short s short s */
@@ -5083,24 +5083,24 @@ gl_arcfs(PyObject *self, PyObject *args)
static PyObject *
gl_arcs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getishortarg(args, 5, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 5, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- arcs( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getishortarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ arcs( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rectcopy short s short s short s short s short s short s */
@@ -5108,27 +5108,27 @@ gl_arcs(PyObject *self, PyObject *args)
static PyObject *
gl_rectcopy(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- short arg6 ;
- if (!getishortarg(args, 6, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 6, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 6, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 6, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 6, 4, &arg5))
- return NULL;
- if (!getishortarg(args, 6, 5, &arg6))
- return NULL;
- rectcopy( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ short arg6 ;
+ if (!getishortarg(args, 6, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 6, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 6, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 6, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 6, 4, &arg5))
+ return NULL;
+ if (!getishortarg(args, 6, 5, &arg6))
+ return NULL;
+ rectcopy( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void RGBcursor short s short s short s short s short s short s short s */
@@ -5136,30 +5136,30 @@ gl_rectcopy(PyObject *self, PyObject *args)
static PyObject *
gl_RGBcursor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- short arg6 ;
- short arg7 ;
- if (!getishortarg(args, 7, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 7, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 7, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 7, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 7, 4, &arg5))
- return NULL;
- if (!getishortarg(args, 7, 5, &arg6))
- return NULL;
- if (!getishortarg(args, 7, 6, &arg7))
- return NULL;
- RGBcursor( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ short arg6 ;
+ short arg7 ;
+ if (!getishortarg(args, 7, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 7, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 7, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 7, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 7, 4, &arg5))
+ return NULL;
+ if (!getishortarg(args, 7, 5, &arg6))
+ return NULL;
+ if (!getishortarg(args, 7, 6, &arg7))
+ return NULL;
+ RGBcursor( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long getbutton short s */
@@ -5167,12 +5167,12 @@ gl_RGBcursor(PyObject *self, PyObject *args)
static PyObject *
gl_getbutton(PyObject *self, PyObject *args)
{
- long retval;
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- retval = getbutton( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = getbutton( arg1 );
+ return mknewlongobject(retval);
}
/* long getcmmode */
@@ -5180,9 +5180,9 @@ gl_getbutton(PyObject *self, PyObject *args)
static PyObject *
gl_getcmmode(PyObject *self, PyObject *args)
{
- long retval;
- retval = getcmmode( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getcmmode( );
+ return mknewlongobject(retval);
}
/* long getlsbackup */
@@ -5190,9 +5190,9 @@ gl_getcmmode(PyObject *self, PyObject *args)
static PyObject *
gl_getlsbackup(PyObject *self, PyObject *args)
{
- long retval;
- retval = getlsbackup( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getlsbackup( );
+ return mknewlongobject(retval);
}
/* long getresetls */
@@ -5200,9 +5200,9 @@ gl_getlsbackup(PyObject *self, PyObject *args)
static PyObject *
gl_getresetls(PyObject *self, PyObject *args)
{
- long retval;
- retval = getresetls( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getresetls( );
+ return mknewlongobject(retval);
}
/* long getdcm */
@@ -5210,9 +5210,9 @@ gl_getresetls(PyObject *self, PyObject *args)
static PyObject *
gl_getdcm(PyObject *self, PyObject *args)
{
- long retval;
- retval = getdcm( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getdcm( );
+ return mknewlongobject(retval);
}
/* long getzbuffer */
@@ -5220,9 +5220,9 @@ gl_getdcm(PyObject *self, PyObject *args)
static PyObject *
gl_getzbuffer(PyObject *self, PyObject *args)
{
- long retval;
- retval = getzbuffer( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getzbuffer( );
+ return mknewlongobject(retval);
}
/* long ismex */
@@ -5230,9 +5230,9 @@ gl_getzbuffer(PyObject *self, PyObject *args)
static PyObject *
gl_ismex(PyObject *self, PyObject *args)
{
- long retval;
- retval = ismex( );
- return mknewlongobject(retval);
+ long retval;
+ retval = ismex( );
+ return mknewlongobject(retval);
}
/* long isobj long s */
@@ -5240,12 +5240,12 @@ gl_ismex(PyObject *self, PyObject *args)
static PyObject *
gl_isobj(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = isobj( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = isobj( arg1 );
+ return mknewlongobject(retval);
}
/* long isqueued short s */
@@ -5253,12 +5253,12 @@ gl_isobj(PyObject *self, PyObject *args)
static PyObject *
gl_isqueued(PyObject *self, PyObject *args)
{
- long retval;
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- retval = isqueued( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = isqueued( arg1 );
+ return mknewlongobject(retval);
}
/* long istag long s */
@@ -5266,12 +5266,12 @@ gl_isqueued(PyObject *self, PyObject *args)
static PyObject *
gl_istag(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = istag( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = istag( arg1 );
+ return mknewlongobject(retval);
}
/* long genobj */
@@ -5279,9 +5279,9 @@ gl_istag(PyObject *self, PyObject *args)
static PyObject *
gl_genobj(PyObject *self, PyObject *args)
{
- long retval;
- retval = genobj( );
- return mknewlongobject(retval);
+ long retval;
+ retval = genobj( );
+ return mknewlongobject(retval);
}
/* long gentag */
@@ -5289,9 +5289,9 @@ gl_genobj(PyObject *self, PyObject *args)
static PyObject *
gl_gentag(PyObject *self, PyObject *args)
{
- long retval;
- retval = gentag( );
- return mknewlongobject(retval);
+ long retval;
+ retval = gentag( );
+ return mknewlongobject(retval);
}
/* long getbuffer */
@@ -5299,9 +5299,9 @@ gl_gentag(PyObject *self, PyObject *args)
static PyObject *
gl_getbuffer(PyObject *self, PyObject *args)
{
- long retval;
- retval = getbuffer( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getbuffer( );
+ return mknewlongobject(retval);
}
/* long getcolor */
@@ -5309,9 +5309,9 @@ gl_getbuffer(PyObject *self, PyObject *args)
static PyObject *
gl_getcolor(PyObject *self, PyObject *args)
{
- long retval;
- retval = getcolor( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getcolor( );
+ return mknewlongobject(retval);
}
/* long getdisplaymode */
@@ -5319,9 +5319,9 @@ gl_getcolor(PyObject *self, PyObject *args)
static PyObject *
gl_getdisplaymode(PyObject *self, PyObject *args)
{
- long retval;
- retval = getdisplaymode( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getdisplaymode( );
+ return mknewlongobject(retval);
}
/* long getfont */
@@ -5329,9 +5329,9 @@ gl_getdisplaymode(PyObject *self, PyObject *args)
static PyObject *
gl_getfont(PyObject *self, PyObject *args)
{
- long retval;
- retval = getfont( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getfont( );
+ return mknewlongobject(retval);
}
/* long getheight */
@@ -5339,9 +5339,9 @@ gl_getfont(PyObject *self, PyObject *args)
static PyObject *
gl_getheight(PyObject *self, PyObject *args)
{
- long retval;
- retval = getheight( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getheight( );
+ return mknewlongobject(retval);
}
/* long gethitcode */
@@ -5349,9 +5349,9 @@ gl_getheight(PyObject *self, PyObject *args)
static PyObject *
gl_gethitcode(PyObject *self, PyObject *args)
{
- long retval;
- retval = gethitcode( );
- return mknewlongobject(retval);
+ long retval;
+ retval = gethitcode( );
+ return mknewlongobject(retval);
}
/* long getlstyle */
@@ -5359,9 +5359,9 @@ gl_gethitcode(PyObject *self, PyObject *args)
static PyObject *
gl_getlstyle(PyObject *self, PyObject *args)
{
- long retval;
- retval = getlstyle( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getlstyle( );
+ return mknewlongobject(retval);
}
/* long getlwidth */
@@ -5369,9 +5369,9 @@ gl_getlstyle(PyObject *self, PyObject *args)
static PyObject *
gl_getlwidth(PyObject *self, PyObject *args)
{
- long retval;
- retval = getlwidth( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getlwidth( );
+ return mknewlongobject(retval);
}
/* long getmap */
@@ -5379,9 +5379,9 @@ gl_getlwidth(PyObject *self, PyObject *args)
static PyObject *
gl_getmap(PyObject *self, PyObject *args)
{
- long retval;
- retval = getmap( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getmap( );
+ return mknewlongobject(retval);
}
/* long getplanes */
@@ -5389,9 +5389,9 @@ gl_getmap(PyObject *self, PyObject *args)
static PyObject *
gl_getplanes(PyObject *self, PyObject *args)
{
- long retval;
- retval = getplanes( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getplanes( );
+ return mknewlongobject(retval);
}
/* long getwritemask */
@@ -5399,9 +5399,9 @@ gl_getplanes(PyObject *self, PyObject *args)
static PyObject *
gl_getwritemask(PyObject *self, PyObject *args)
{
- long retval;
- retval = getwritemask( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getwritemask( );
+ return mknewlongobject(retval);
}
/* long qtest */
@@ -5409,9 +5409,9 @@ gl_getwritemask(PyObject *self, PyObject *args)
static PyObject *
gl_qtest(PyObject *self, PyObject *args)
{
- long retval;
- retval = qtest( );
- return mknewlongobject(retval);
+ long retval;
+ retval = qtest( );
+ return mknewlongobject(retval);
}
/* long getlsrepeat */
@@ -5419,9 +5419,9 @@ gl_qtest(PyObject *self, PyObject *args)
static PyObject *
gl_getlsrepeat(PyObject *self, PyObject *args)
{
- long retval;
- retval = getlsrepeat( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getlsrepeat( );
+ return mknewlongobject(retval);
}
/* long getmonitor */
@@ -5429,9 +5429,9 @@ gl_getlsrepeat(PyObject *self, PyObject *args)
static PyObject *
gl_getmonitor(PyObject *self, PyObject *args)
{
- long retval;
- retval = getmonitor( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getmonitor( );
+ return mknewlongobject(retval);
}
/* long getopenobj */
@@ -5439,9 +5439,9 @@ gl_getmonitor(PyObject *self, PyObject *args)
static PyObject *
gl_getopenobj(PyObject *self, PyObject *args)
{
- long retval;
- retval = getopenobj( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getopenobj( );
+ return mknewlongobject(retval);
}
/* long getpattern */
@@ -5449,9 +5449,9 @@ gl_getopenobj(PyObject *self, PyObject *args)
static PyObject *
gl_getpattern(PyObject *self, PyObject *args)
{
- long retval;
- retval = getpattern( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getpattern( );
+ return mknewlongobject(retval);
}
/* long winget */
@@ -5459,9 +5459,9 @@ gl_getpattern(PyObject *self, PyObject *args)
static PyObject *
gl_winget(PyObject *self, PyObject *args)
{
- long retval;
- retval = winget( );
- return mknewlongobject(retval);
+ long retval;
+ retval = winget( );
+ return mknewlongobject(retval);
}
/* long winattach */
@@ -5469,9 +5469,9 @@ gl_winget(PyObject *self, PyObject *args)
static PyObject *
gl_winattach(PyObject *self, PyObject *args)
{
- long retval;
- retval = winattach( );
- return mknewlongobject(retval);
+ long retval;
+ retval = winattach( );
+ return mknewlongobject(retval);
}
/* long getothermonitor */
@@ -5479,9 +5479,9 @@ gl_winattach(PyObject *self, PyObject *args)
static PyObject *
gl_getothermonitor(PyObject *self, PyObject *args)
{
- long retval;
- retval = getothermonitor( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getothermonitor( );
+ return mknewlongobject(retval);
}
/* long newpup */
@@ -5489,9 +5489,9 @@ gl_getothermonitor(PyObject *self, PyObject *args)
static PyObject *
gl_newpup(PyObject *self, PyObject *args)
{
- long retval;
- retval = newpup( );
- return mknewlongobject(retval);
+ long retval;
+ retval = newpup( );
+ return mknewlongobject(retval);
}
/* long getvaluator short s */
@@ -5499,12 +5499,12 @@ gl_newpup(PyObject *self, PyObject *args)
static PyObject *
gl_getvaluator(PyObject *self, PyObject *args)
{
- long retval;
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- retval = getvaluator( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = getvaluator( arg1 );
+ return mknewlongobject(retval);
}
/* void winset long s */
@@ -5512,12 +5512,12 @@ gl_getvaluator(PyObject *self, PyObject *args)
static PyObject *
gl_winset(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- winset( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ winset( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long dopup long s */
@@ -5525,12 +5525,12 @@ gl_winset(PyObject *self, PyObject *args)
static PyObject *
gl_dopup(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = dopup( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = dopup( arg1 );
+ return mknewlongobject(retval);
}
/* void getdepth short r short r */
@@ -5538,15 +5538,15 @@ gl_dopup(PyObject *self, PyObject *args)
static PyObject *
gl_getdepth(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- getdepth( & arg1 , & arg2 );
- { PyObject *v = PyTuple_New( 2 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ getdepth( & arg1 , & arg2 );
+ { PyObject *v = PyTuple_New( 2 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ return v;
+ }
}
/* void getcpos short r short r */
@@ -5554,15 +5554,15 @@ gl_getdepth(PyObject *self, PyObject *args)
static PyObject *
gl_getcpos(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- getcpos( & arg1 , & arg2 );
- { PyObject *v = PyTuple_New( 2 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ getcpos( & arg1 , & arg2 );
+ { PyObject *v = PyTuple_New( 2 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ return v;
+ }
}
/* void getsize long r long r */
@@ -5570,15 +5570,15 @@ gl_getcpos(PyObject *self, PyObject *args)
static PyObject *
gl_getsize(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- getsize( & arg1 , & arg2 );
- { PyObject *v = PyTuple_New( 2 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewlongobject(arg1));
- PyTuple_SetItem(v, 1, mknewlongobject(arg2));
- return v;
- }
+ long arg1 ;
+ long arg2 ;
+ getsize( & arg1 , & arg2 );
+ { PyObject *v = PyTuple_New( 2 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewlongobject(arg1));
+ PyTuple_SetItem(v, 1, mknewlongobject(arg2));
+ return v;
+ }
}
/* void getorigin long r long r */
@@ -5586,15 +5586,15 @@ gl_getsize(PyObject *self, PyObject *args)
static PyObject *
gl_getorigin(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- getorigin( & arg1 , & arg2 );
- { PyObject *v = PyTuple_New( 2 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewlongobject(arg1));
- PyTuple_SetItem(v, 1, mknewlongobject(arg2));
- return v;
- }
+ long arg1 ;
+ long arg2 ;
+ getorigin( & arg1 , & arg2 );
+ { PyObject *v = PyTuple_New( 2 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewlongobject(arg1));
+ PyTuple_SetItem(v, 1, mknewlongobject(arg2));
+ return v;
+ }
}
/* void getviewport short r short r short r short r */
@@ -5602,19 +5602,19 @@ gl_getorigin(PyObject *self, PyObject *args)
static PyObject *
gl_getviewport(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- getviewport( & arg1 , & arg2 , & arg3 , & arg4 );
- { PyObject *v = PyTuple_New( 4 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- PyTuple_SetItem(v, 2, mknewshortobject(arg3));
- PyTuple_SetItem(v, 3, mknewshortobject(arg4));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ getviewport( & arg1 , & arg2 , & arg3 , & arg4 );
+ { PyObject *v = PyTuple_New( 4 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ PyTuple_SetItem(v, 2, mknewshortobject(arg3));
+ PyTuple_SetItem(v, 3, mknewshortobject(arg4));
+ return v;
+ }
}
/* void gettp short r short r short r short r */
@@ -5622,19 +5622,19 @@ gl_getviewport(PyObject *self, PyObject *args)
static PyObject *
gl_gettp(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- gettp( & arg1 , & arg2 , & arg3 , & arg4 );
- { PyObject *v = PyTuple_New( 4 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- PyTuple_SetItem(v, 2, mknewshortobject(arg3));
- PyTuple_SetItem(v, 3, mknewshortobject(arg4));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ gettp( & arg1 , & arg2 , & arg3 , & arg4 );
+ { PyObject *v = PyTuple_New( 4 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ PyTuple_SetItem(v, 2, mknewshortobject(arg3));
+ PyTuple_SetItem(v, 3, mknewshortobject(arg4));
+ return v;
+ }
}
/* void getgpos float r float r float r float r */
@@ -5642,19 +5642,19 @@ gl_gettp(PyObject *self, PyObject *args)
static PyObject *
gl_getgpos(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- getgpos( & arg1 , & arg2 , & arg3 , & arg4 );
- { PyObject *v = PyTuple_New( 4 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewfloatobject(arg1));
- PyTuple_SetItem(v, 1, mknewfloatobject(arg2));
- PyTuple_SetItem(v, 2, mknewfloatobject(arg3));
- PyTuple_SetItem(v, 3, mknewfloatobject(arg4));
- return v;
- }
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ getgpos( & arg1 , & arg2 , & arg3 , & arg4 );
+ { PyObject *v = PyTuple_New( 4 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewfloatobject(arg1));
+ PyTuple_SetItem(v, 1, mknewfloatobject(arg2));
+ PyTuple_SetItem(v, 2, mknewfloatobject(arg3));
+ PyTuple_SetItem(v, 3, mknewfloatobject(arg4));
+ return v;
+ }
}
/* void winposition long s long s long s long s */
@@ -5662,21 +5662,21 @@ gl_getgpos(PyObject *self, PyObject *args)
static PyObject *
gl_winposition(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- winposition( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ winposition( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gRGBcolor short r short r short r */
@@ -5684,17 +5684,17 @@ gl_winposition(PyObject *self, PyObject *args)
static PyObject *
gl_gRGBcolor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- gRGBcolor( & arg1 , & arg2 , & arg3 );
- { PyObject *v = PyTuple_New( 3 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- PyTuple_SetItem(v, 2, mknewshortobject(arg3));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ gRGBcolor( & arg1 , & arg2 , & arg3 );
+ { PyObject *v = PyTuple_New( 3 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ PyTuple_SetItem(v, 2, mknewshortobject(arg3));
+ return v;
+ }
}
/* void gRGBmask short r short r short r */
@@ -5702,17 +5702,17 @@ gl_gRGBcolor(PyObject *self, PyObject *args)
static PyObject *
gl_gRGBmask(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- gRGBmask( & arg1 , & arg2 , & arg3 );
- { PyObject *v = PyTuple_New( 3 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- PyTuple_SetItem(v, 2, mknewshortobject(arg3));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ gRGBmask( & arg1 , & arg2 , & arg3 );
+ { PyObject *v = PyTuple_New( 3 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ PyTuple_SetItem(v, 2, mknewshortobject(arg3));
+ return v;
+ }
}
/* void getscrmask short r short r short r short r */
@@ -5720,19 +5720,19 @@ gl_gRGBmask(PyObject *self, PyObject *args)
static PyObject *
gl_getscrmask(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- getscrmask( & arg1 , & arg2 , & arg3 , & arg4 );
- { PyObject *v = PyTuple_New( 4 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- PyTuple_SetItem(v, 2, mknewshortobject(arg3));
- PyTuple_SetItem(v, 3, mknewshortobject(arg4));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ getscrmask( & arg1 , & arg2 , & arg3 , & arg4 );
+ { PyObject *v = PyTuple_New( 4 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ PyTuple_SetItem(v, 2, mknewshortobject(arg3));
+ PyTuple_SetItem(v, 3, mknewshortobject(arg4));
+ return v;
+ }
}
/* void getmcolor short s short r short r short r */
@@ -5740,20 +5740,20 @@ gl_getscrmask(PyObject *self, PyObject *args)
static PyObject *
gl_getmcolor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- getmcolor( arg1 , & arg2 , & arg3 , & arg4 );
- { PyObject *v = PyTuple_New( 3 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg2));
- PyTuple_SetItem(v, 1, mknewshortobject(arg3));
- PyTuple_SetItem(v, 2, mknewshortobject(arg4));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ getmcolor( arg1 , & arg2 , & arg3 , & arg4 );
+ { PyObject *v = PyTuple_New( 3 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg2));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg3));
+ PyTuple_SetItem(v, 2, mknewshortobject(arg4));
+ return v;
+ }
}
/* void mapw long s short s short s float r float r float r float r float r float r */
@@ -5761,32 +5761,32 @@ gl_getmcolor(PyObject *self, PyObject *args)
static PyObject *
gl_mapw(PyObject *self, PyObject *args)
{
- long arg1 ;
- short arg2 ;
- short arg3 ;
- float arg4 ;
- float arg5 ;
- float arg6 ;
- float arg7 ;
- float arg8 ;
- float arg9 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- mapw( arg1 , arg2 , arg3 , & arg4 , & arg5 , & arg6 , & arg7 , & arg8 , & arg9 );
- { PyObject *v = PyTuple_New( 6 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewfloatobject(arg4));
- PyTuple_SetItem(v, 1, mknewfloatobject(arg5));
- PyTuple_SetItem(v, 2, mknewfloatobject(arg6));
- PyTuple_SetItem(v, 3, mknewfloatobject(arg7));
- PyTuple_SetItem(v, 4, mknewfloatobject(arg8));
- PyTuple_SetItem(v, 5, mknewfloatobject(arg9));
- return v;
- }
+ long arg1 ;
+ short arg2 ;
+ short arg3 ;
+ float arg4 ;
+ float arg5 ;
+ float arg6 ;
+ float arg7 ;
+ float arg8 ;
+ float arg9 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ mapw( arg1 , arg2 , arg3 , & arg4 , & arg5 , & arg6 , & arg7 , & arg8 , & arg9 );
+ { PyObject *v = PyTuple_New( 6 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewfloatobject(arg4));
+ PyTuple_SetItem(v, 1, mknewfloatobject(arg5));
+ PyTuple_SetItem(v, 2, mknewfloatobject(arg6));
+ PyTuple_SetItem(v, 3, mknewfloatobject(arg7));
+ PyTuple_SetItem(v, 4, mknewfloatobject(arg8));
+ PyTuple_SetItem(v, 5, mknewfloatobject(arg9));
+ return v;
+ }
}
/* void mapw2 long s short s short s float r float r */
@@ -5794,24 +5794,24 @@ gl_mapw(PyObject *self, PyObject *args)
static PyObject *
gl_mapw2(PyObject *self, PyObject *args)
{
- long arg1 ;
- short arg2 ;
- short arg3 ;
- float arg4 ;
- float arg5 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- mapw2( arg1 , arg2 , arg3 , & arg4 , & arg5 );
- { PyObject *v = PyTuple_New( 2 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewfloatobject(arg4));
- PyTuple_SetItem(v, 1, mknewfloatobject(arg5));
- return v;
- }
+ long arg1 ;
+ short arg2 ;
+ short arg3 ;
+ float arg4 ;
+ float arg5 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ mapw2( arg1 , arg2 , arg3 , & arg4 , & arg5 );
+ { PyObject *v = PyTuple_New( 2 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewfloatobject(arg4));
+ PyTuple_SetItem(v, 1, mknewfloatobject(arg5));
+ return v;
+ }
}
/* void getcursor short r u_short r u_short r long r */
@@ -5819,19 +5819,19 @@ gl_mapw2(PyObject *self, PyObject *args)
static PyObject *
gl_getcursor(PyObject *self, PyObject *args)
{
- short arg1 ;
- unsigned short arg2 ;
- unsigned short arg3 ;
- long arg4 ;
- getcursor( & arg1 , & arg2 , & arg3 , & arg4 );
- { PyObject *v = PyTuple_New( 4 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject((short) arg2));
- PyTuple_SetItem(v, 2, mknewshortobject((short) arg3));
- PyTuple_SetItem(v, 3, mknewlongobject(arg4));
- return v;
- }
+ short arg1 ;
+ unsigned short arg2 ;
+ unsigned short arg3 ;
+ long arg4 ;
+ getcursor( & arg1 , & arg2 , & arg3 , & arg4 );
+ { PyObject *v = PyTuple_New( 4 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject((short) arg2));
+ PyTuple_SetItem(v, 2, mknewshortobject((short) arg3));
+ PyTuple_SetItem(v, 3, mknewlongobject(arg4));
+ return v;
+ }
}
/* void cmode */
@@ -5839,9 +5839,9 @@ gl_getcursor(PyObject *self, PyObject *args)
static PyObject *
gl_cmode(PyObject *self, PyObject *args)
{
- cmode( );
- Py_INCREF(Py_None);
- return Py_None;
+ cmode( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void concave long s */
@@ -5849,12 +5849,12 @@ gl_cmode(PyObject *self, PyObject *args)
static PyObject *
gl_concave(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- concave( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ concave( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void curstype long s */
@@ -5862,12 +5862,12 @@ gl_concave(PyObject *self, PyObject *args)
static PyObject *
gl_curstype(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- curstype( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ curstype( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void drawmode long s */
@@ -5875,12 +5875,12 @@ gl_curstype(PyObject *self, PyObject *args)
static PyObject *
gl_drawmode(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- drawmode( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ drawmode( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gammaramp short s[256] short s[256] short s[256] */
@@ -5888,18 +5888,18 @@ gl_drawmode(PyObject *self, PyObject *args)
static PyObject *
gl_gammaramp(PyObject *self, PyObject *args)
{
- short arg1 [ 256 ] ;
- short arg2 [ 256 ] ;
- short arg3 [ 256 ] ;
- if (!getishortarray(args, 3, 0, 256 , arg1))
- return NULL;
- if (!getishortarray(args, 3, 1, 256 , arg2))
- return NULL;
- if (!getishortarray(args, 3, 2, 256 , arg3))
- return NULL;
- gammaramp( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 [ 256 ] ;
+ short arg2 [ 256 ] ;
+ short arg3 [ 256 ] ;
+ if (!getishortarray(args, 3, 0, 256 , arg1))
+ return NULL;
+ if (!getishortarray(args, 3, 1, 256 , arg2))
+ return NULL;
+ if (!getishortarray(args, 3, 2, 256 , arg3))
+ return NULL;
+ gammaramp( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long getbackface */
@@ -5907,9 +5907,9 @@ gl_gammaramp(PyObject *self, PyObject *args)
static PyObject *
gl_getbackface(PyObject *self, PyObject *args)
{
- long retval;
- retval = getbackface( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getbackface( );
+ return mknewlongobject(retval);
}
/* long getdescender */
@@ -5917,9 +5917,9 @@ gl_getbackface(PyObject *self, PyObject *args)
static PyObject *
gl_getdescender(PyObject *self, PyObject *args)
{
- long retval;
- retval = getdescender( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getdescender( );
+ return mknewlongobject(retval);
}
/* long getdrawmode */
@@ -5927,9 +5927,9 @@ gl_getdescender(PyObject *self, PyObject *args)
static PyObject *
gl_getdrawmode(PyObject *self, PyObject *args)
{
- long retval;
- retval = getdrawmode( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getdrawmode( );
+ return mknewlongobject(retval);
}
/* long getmmode */
@@ -5937,9 +5937,9 @@ gl_getdrawmode(PyObject *self, PyObject *args)
static PyObject *
gl_getmmode(PyObject *self, PyObject *args)
{
- long retval;
- retval = getmmode( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getmmode( );
+ return mknewlongobject(retval);
}
/* long getsm */
@@ -5947,9 +5947,9 @@ gl_getmmode(PyObject *self, PyObject *args)
static PyObject *
gl_getsm(PyObject *self, PyObject *args)
{
- long retval;
- retval = getsm( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getsm( );
+ return mknewlongobject(retval);
}
/* long getvideo long s */
@@ -5957,12 +5957,12 @@ gl_getsm(PyObject *self, PyObject *args)
static PyObject *
gl_getvideo(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = getvideo( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = getvideo( arg1 );
+ return mknewlongobject(retval);
}
/* void imakebackground */
@@ -5970,9 +5970,9 @@ gl_getvideo(PyObject *self, PyObject *args)
static PyObject *
gl_imakebackground(PyObject *self, PyObject *args)
{
- imakebackground( );
- Py_INCREF(Py_None);
- return Py_None;
+ imakebackground( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lmbind short s short s */
@@ -5980,15 +5980,15 @@ gl_imakebackground(PyObject *self, PyObject *args)
static PyObject *
gl_lmbind(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- lmbind( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ lmbind( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lmdef long s long s long s float s[arg3] */
@@ -5996,24 +5996,24 @@ gl_lmbind(PyObject *self, PyObject *args)
static PyObject *
gl_lmdef(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- float * arg4 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarraysize(args, 3, 2, &arg3))
- return NULL;
- if ((arg4 = PyMem_NEW(float , arg3 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 3, 2, arg3 , arg4))
- return NULL;
- lmdef( arg1 , arg2 , arg3 , arg4 );
- PyMem_DEL(arg4);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ float * arg4 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarraysize(args, 3, 2, &arg3))
+ return NULL;
+ if ((arg4 = PyMem_NEW(float , arg3 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 3, 2, arg3 , arg4))
+ return NULL;
+ lmdef( arg1 , arg2 , arg3 , arg4 );
+ PyMem_DEL(arg4);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void mmode long s */
@@ -6021,12 +6021,12 @@ gl_lmdef(PyObject *self, PyObject *args)
static PyObject *
gl_mmode(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- mmode( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ mmode( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void normal float s[3] */
@@ -6034,12 +6034,12 @@ gl_mmode(PyObject *self, PyObject *args)
static PyObject *
gl_normal(PyObject *self, PyObject *args)
{
- float arg1 [ 3 ] ;
- if (!getifloatarray(args, 1, 0, 3 , arg1))
- return NULL;
- normal( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 3 ] ;
+ if (!getifloatarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ normal( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void overlay long s */
@@ -6047,12 +6047,12 @@ gl_normal(PyObject *self, PyObject *args)
static PyObject *
gl_overlay(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- overlay( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ overlay( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void RGBrange short s short s short s short s short s short s short s short s */
@@ -6060,33 +6060,33 @@ gl_overlay(PyObject *self, PyObject *args)
static PyObject *
gl_RGBrange(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- short arg6 ;
- short arg7 ;
- short arg8 ;
- if (!getishortarg(args, 8, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 8, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 8, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 8, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 8, 4, &arg5))
- return NULL;
- if (!getishortarg(args, 8, 5, &arg6))
- return NULL;
- if (!getishortarg(args, 8, 6, &arg7))
- return NULL;
- if (!getishortarg(args, 8, 7, &arg8))
- return NULL;
- RGBrange( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ short arg6 ;
+ short arg7 ;
+ short arg8 ;
+ if (!getishortarg(args, 8, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 8, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 8, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 8, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 8, 4, &arg5))
+ return NULL;
+ if (!getishortarg(args, 8, 5, &arg6))
+ return NULL;
+ if (!getishortarg(args, 8, 6, &arg7))
+ return NULL;
+ if (!getishortarg(args, 8, 7, &arg8))
+ return NULL;
+ RGBrange( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setvideo long s long s */
@@ -6094,15 +6094,15 @@ gl_RGBrange(PyObject *self, PyObject *args)
static PyObject *
gl_setvideo(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- setvideo( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ setvideo( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void shademodel long s */
@@ -6110,12 +6110,12 @@ gl_setvideo(PyObject *self, PyObject *args)
static PyObject *
gl_shademodel(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- shademodel( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ shademodel( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void underlay long s */
@@ -6123,12 +6123,12 @@ gl_shademodel(PyObject *self, PyObject *args)
static PyObject *
gl_underlay(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- underlay( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ underlay( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgnclosedline */
@@ -6136,9 +6136,9 @@ gl_underlay(PyObject *self, PyObject *args)
static PyObject *
gl_bgnclosedline(PyObject *self, PyObject *args)
{
- bgnclosedline( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgnclosedline( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgnline */
@@ -6146,9 +6146,9 @@ gl_bgnclosedline(PyObject *self, PyObject *args)
static PyObject *
gl_bgnline(PyObject *self, PyObject *args)
{
- bgnline( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgnline( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgnpoint */
@@ -6156,9 +6156,9 @@ gl_bgnline(PyObject *self, PyObject *args)
static PyObject *
gl_bgnpoint(PyObject *self, PyObject *args)
{
- bgnpoint( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgnpoint( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgnpolygon */
@@ -6166,9 +6166,9 @@ gl_bgnpoint(PyObject *self, PyObject *args)
static PyObject *
gl_bgnpolygon(PyObject *self, PyObject *args)
{
- bgnpolygon( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgnpolygon( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgnsurface */
@@ -6176,9 +6176,9 @@ gl_bgnpolygon(PyObject *self, PyObject *args)
static PyObject *
gl_bgnsurface(PyObject *self, PyObject *args)
{
- bgnsurface( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgnsurface( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgntmesh */
@@ -6186,9 +6186,9 @@ gl_bgnsurface(PyObject *self, PyObject *args)
static PyObject *
gl_bgntmesh(PyObject *self, PyObject *args)
{
- bgntmesh( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgntmesh( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgntrim */
@@ -6196,9 +6196,9 @@ gl_bgntmesh(PyObject *self, PyObject *args)
static PyObject *
gl_bgntrim(PyObject *self, PyObject *args)
{
- bgntrim( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgntrim( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endclosedline */
@@ -6206,9 +6206,9 @@ gl_bgntrim(PyObject *self, PyObject *args)
static PyObject *
gl_endclosedline(PyObject *self, PyObject *args)
{
- endclosedline( );
- Py_INCREF(Py_None);
- return Py_None;
+ endclosedline( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endline */
@@ -6216,9 +6216,9 @@ gl_endclosedline(PyObject *self, PyObject *args)
static PyObject *
gl_endline(PyObject *self, PyObject *args)
{
- endline( );
- Py_INCREF(Py_None);
- return Py_None;
+ endline( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endpoint */
@@ -6226,9 +6226,9 @@ gl_endline(PyObject *self, PyObject *args)
static PyObject *
gl_endpoint(PyObject *self, PyObject *args)
{
- endpoint( );
- Py_INCREF(Py_None);
- return Py_None;
+ endpoint( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endpolygon */
@@ -6236,9 +6236,9 @@ gl_endpoint(PyObject *self, PyObject *args)
static PyObject *
gl_endpolygon(PyObject *self, PyObject *args)
{
- endpolygon( );
- Py_INCREF(Py_None);
- return Py_None;
+ endpolygon( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endsurface */
@@ -6246,9 +6246,9 @@ gl_endpolygon(PyObject *self, PyObject *args)
static PyObject *
gl_endsurface(PyObject *self, PyObject *args)
{
- endsurface( );
- Py_INCREF(Py_None);
- return Py_None;
+ endsurface( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endtmesh */
@@ -6256,9 +6256,9 @@ gl_endsurface(PyObject *self, PyObject *args)
static PyObject *
gl_endtmesh(PyObject *self, PyObject *args)
{
- endtmesh( );
- Py_INCREF(Py_None);
- return Py_None;
+ endtmesh( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endtrim */
@@ -6266,9 +6266,9 @@ gl_endtmesh(PyObject *self, PyObject *args)
static PyObject *
gl_endtrim(PyObject *self, PyObject *args)
{
- endtrim( );
- Py_INCREF(Py_None);
- return Py_None;
+ endtrim( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void blendfunction long s long s */
@@ -6276,15 +6276,15 @@ gl_endtrim(PyObject *self, PyObject *args)
static PyObject *
gl_blendfunction(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- blendfunction( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ blendfunction( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void c3f float s[3] */
@@ -6292,12 +6292,12 @@ gl_blendfunction(PyObject *self, PyObject *args)
static PyObject *
gl_c3f(PyObject *self, PyObject *args)
{
- float arg1 [ 3 ] ;
- if (!getifloatarray(args, 1, 0, 3 , arg1))
- return NULL;
- c3f( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 3 ] ;
+ if (!getifloatarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ c3f( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void c3i long s[3] */
@@ -6305,12 +6305,12 @@ gl_c3f(PyObject *self, PyObject *args)
static PyObject *
gl_c3i(PyObject *self, PyObject *args)
{
- long arg1 [ 3 ] ;
- if (!getilongarray(args, 1, 0, 3 , arg1))
- return NULL;
- c3i( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 [ 3 ] ;
+ if (!getilongarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ c3i( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void c3s short s[3] */
@@ -6318,12 +6318,12 @@ gl_c3i(PyObject *self, PyObject *args)
static PyObject *
gl_c3s(PyObject *self, PyObject *args)
{
- short arg1 [ 3 ] ;
- if (!getishortarray(args, 1, 0, 3 , arg1))
- return NULL;
- c3s( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 [ 3 ] ;
+ if (!getishortarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ c3s( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void c4f float s[4] */
@@ -6331,12 +6331,12 @@ gl_c3s(PyObject *self, PyObject *args)
static PyObject *
gl_c4f(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] ;
- if (!getifloatarray(args, 1, 0, 4 , arg1))
- return NULL;
- c4f( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] ;
+ if (!getifloatarray(args, 1, 0, 4 , arg1))
+ return NULL;
+ c4f( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void c4i long s[4] */
@@ -6344,12 +6344,12 @@ gl_c4f(PyObject *self, PyObject *args)
static PyObject *
gl_c4i(PyObject *self, PyObject *args)
{
- long arg1 [ 4 ] ;
- if (!getilongarray(args, 1, 0, 4 , arg1))
- return NULL;
- c4i( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 [ 4 ] ;
+ if (!getilongarray(args, 1, 0, 4 , arg1))
+ return NULL;
+ c4i( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void c4s short s[4] */
@@ -6357,12 +6357,12 @@ gl_c4i(PyObject *self, PyObject *args)
static PyObject *
gl_c4s(PyObject *self, PyObject *args)
{
- short arg1 [ 4 ] ;
- if (!getishortarray(args, 1, 0, 4 , arg1))
- return NULL;
- c4s( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 [ 4 ] ;
+ if (!getishortarray(args, 1, 0, 4 , arg1))
+ return NULL;
+ c4s( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void colorf float s */
@@ -6370,12 +6370,12 @@ gl_c4s(PyObject *self, PyObject *args)
static PyObject *
gl_colorf(PyObject *self, PyObject *args)
{
- float arg1 ;
- if (!getifloatarg(args, 1, 0, &arg1))
- return NULL;
- colorf( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ if (!getifloatarg(args, 1, 0, &arg1))
+ return NULL;
+ colorf( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cpack long s */
@@ -6383,12 +6383,12 @@ gl_colorf(PyObject *self, PyObject *args)
static PyObject *
gl_cpack(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- cpack( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ cpack( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void czclear long s long s */
@@ -6396,15 +6396,15 @@ gl_cpack(PyObject *self, PyObject *args)
static PyObject *
gl_czclear(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- czclear( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ czclear( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void dglclose long s */
@@ -6412,12 +6412,12 @@ gl_czclear(PyObject *self, PyObject *args)
static PyObject *
gl_dglclose(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- dglclose( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ dglclose( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long dglopen char *s long s */
@@ -6425,15 +6425,15 @@ gl_dglclose(PyObject *self, PyObject *args)
static PyObject *
gl_dglopen(PyObject *self, PyObject *args)
{
- long retval;
- string arg1 ;
- long arg2 ;
- if (!getistringarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- retval = dglopen( arg1 , arg2 );
- return mknewlongobject(retval);
+ long retval;
+ string arg1 ;
+ long arg2 ;
+ if (!getistringarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ retval = dglopen( arg1 , arg2 );
+ return mknewlongobject(retval);
}
/* long getgdesc long s */
@@ -6441,12 +6441,12 @@ gl_dglopen(PyObject *self, PyObject *args)
static PyObject *
gl_getgdesc(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = getgdesc( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = getgdesc( arg1 );
+ return mknewlongobject(retval);
}
/* void getnurbsproperty long s float r */
@@ -6454,12 +6454,12 @@ gl_getgdesc(PyObject *self, PyObject *args)
static PyObject *
gl_getnurbsproperty(PyObject *self, PyObject *args)
{
- long arg1 ;
- float arg2 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- getnurbsproperty( arg1 , & arg2 );
- return mknewfloatobject(arg2);
+ long arg1 ;
+ float arg2 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ getnurbsproperty( arg1 , & arg2 );
+ return mknewfloatobject(arg2);
}
/* void glcompat long s long s */
@@ -6467,15 +6467,15 @@ gl_getnurbsproperty(PyObject *self, PyObject *args)
static PyObject *
gl_glcompat(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- glcompat( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ glcompat( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void iconsize long s long s */
@@ -6483,15 +6483,15 @@ gl_glcompat(PyObject *self, PyObject *args)
static PyObject *
gl_iconsize(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- iconsize( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ iconsize( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void icontitle char *s */
@@ -6499,12 +6499,12 @@ gl_iconsize(PyObject *self, PyObject *args)
static PyObject *
gl_icontitle(PyObject *self, PyObject *args)
{
- string arg1 ;
- if (!getistringarg(args, 1, 0, &arg1))
- return NULL;
- icontitle( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ string arg1 ;
+ if (!getistringarg(args, 1, 0, &arg1))
+ return NULL;
+ icontitle( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lRGBrange short s short s short s short s short s short s long s long s */
@@ -6512,33 +6512,33 @@ gl_icontitle(PyObject *self, PyObject *args)
static PyObject *
gl_lRGBrange(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- short arg6 ;
- long arg7 ;
- long arg8 ;
- if (!getishortarg(args, 8, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 8, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 8, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 8, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 8, 4, &arg5))
- return NULL;
- if (!getishortarg(args, 8, 5, &arg6))
- return NULL;
- if (!getilongarg(args, 8, 6, &arg7))
- return NULL;
- if (!getilongarg(args, 8, 7, &arg8))
- return NULL;
- lRGBrange( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ short arg6 ;
+ long arg7 ;
+ long arg8 ;
+ if (!getishortarg(args, 8, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 8, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 8, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 8, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 8, 4, &arg5))
+ return NULL;
+ if (!getishortarg(args, 8, 5, &arg6))
+ return NULL;
+ if (!getilongarg(args, 8, 6, &arg7))
+ return NULL;
+ if (!getilongarg(args, 8, 7, &arg8))
+ return NULL;
+ lRGBrange( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void linesmooth long s */
@@ -6546,12 +6546,12 @@ gl_lRGBrange(PyObject *self, PyObject *args)
static PyObject *
gl_linesmooth(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- linesmooth( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ linesmooth( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lmcolor long s */
@@ -6559,12 +6559,12 @@ gl_linesmooth(PyObject *self, PyObject *args)
static PyObject *
gl_lmcolor(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- lmcolor( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ lmcolor( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void logicop long s */
@@ -6572,12 +6572,12 @@ gl_lmcolor(PyObject *self, PyObject *args)
static PyObject *
gl_logicop(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- logicop( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ logicop( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lsetdepth long s long s */
@@ -6585,15 +6585,15 @@ gl_logicop(PyObject *self, PyObject *args)
static PyObject *
gl_lsetdepth(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- lsetdepth( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ lsetdepth( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lshaderange short s short s long s long s */
@@ -6601,21 +6601,21 @@ gl_lsetdepth(PyObject *self, PyObject *args)
static PyObject *
gl_lshaderange(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- lshaderange( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ lshaderange( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void n3f float s[3] */
@@ -6623,12 +6623,12 @@ gl_lshaderange(PyObject *self, PyObject *args)
static PyObject *
gl_n3f(PyObject *self, PyObject *args)
{
- float arg1 [ 3 ] ;
- if (!getifloatarray(args, 1, 0, 3 , arg1))
- return NULL;
- n3f( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 3 ] ;
+ if (!getifloatarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ n3f( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void noborder */
@@ -6636,9 +6636,9 @@ gl_n3f(PyObject *self, PyObject *args)
static PyObject *
gl_noborder(PyObject *self, PyObject *args)
{
- noborder( );
- Py_INCREF(Py_None);
- return Py_None;
+ noborder( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pntsmooth long s */
@@ -6646,12 +6646,12 @@ gl_noborder(PyObject *self, PyObject *args)
static PyObject *
gl_pntsmooth(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- pntsmooth( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ pntsmooth( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void readsource long s */
@@ -6659,12 +6659,12 @@ gl_pntsmooth(PyObject *self, PyObject *args)
static PyObject *
gl_readsource(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- readsource( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ readsource( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rectzoom float s float s */
@@ -6672,15 +6672,15 @@ gl_readsource(PyObject *self, PyObject *args)
static PyObject *
gl_rectzoom(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- rectzoom( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ rectzoom( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void sbox float s float s float s float s */
@@ -6688,21 +6688,21 @@ gl_rectzoom(PyObject *self, PyObject *args)
static PyObject *
gl_sbox(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- sbox( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ sbox( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void sboxi long s long s long s long s */
@@ -6710,21 +6710,21 @@ gl_sbox(PyObject *self, PyObject *args)
static PyObject *
gl_sboxi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- sboxi( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ sboxi( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void sboxs short s short s short s short s */
@@ -6732,21 +6732,21 @@ gl_sboxi(PyObject *self, PyObject *args)
static PyObject *
gl_sboxs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- sboxs( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ sboxs( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void sboxf float s float s float s float s */
@@ -6754,21 +6754,21 @@ gl_sboxs(PyObject *self, PyObject *args)
static PyObject *
gl_sboxf(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- sboxf( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ sboxf( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void sboxfi long s long s long s long s */
@@ -6776,21 +6776,21 @@ gl_sboxf(PyObject *self, PyObject *args)
static PyObject *
gl_sboxfi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- sboxfi( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ sboxfi( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void sboxfs short s short s short s short s */
@@ -6798,21 +6798,21 @@ gl_sboxfi(PyObject *self, PyObject *args)
static PyObject *
gl_sboxfs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- sboxfs( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ sboxfs( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setnurbsproperty long s float s */
@@ -6820,15 +6820,15 @@ gl_sboxfs(PyObject *self, PyObject *args)
static PyObject *
gl_setnurbsproperty(PyObject *self, PyObject *args)
{
- long arg1 ;
- float arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- setnurbsproperty( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ setnurbsproperty( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setpup long s long s long s */
@@ -6836,18 +6836,18 @@ gl_setnurbsproperty(PyObject *self, PyObject *args)
static PyObject *
gl_setpup(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- setpup( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ setpup( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void smoothline long s */
@@ -6855,12 +6855,12 @@ gl_setpup(PyObject *self, PyObject *args)
static PyObject *
gl_smoothline(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- smoothline( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ smoothline( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void subpixel long s */
@@ -6868,12 +6868,12 @@ gl_smoothline(PyObject *self, PyObject *args)
static PyObject *
gl_subpixel(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- subpixel( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ subpixel( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void swaptmesh */
@@ -6881,9 +6881,9 @@ gl_subpixel(PyObject *self, PyObject *args)
static PyObject *
gl_swaptmesh(PyObject *self, PyObject *args)
{
- swaptmesh( );
- Py_INCREF(Py_None);
- return Py_None;
+ swaptmesh( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long swinopen long s */
@@ -6891,12 +6891,12 @@ gl_swaptmesh(PyObject *self, PyObject *args)
static PyObject *
gl_swinopen(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = swinopen( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = swinopen( arg1 );
+ return mknewlongobject(retval);
}
/* void v2f float s[2] */
@@ -6904,12 +6904,12 @@ gl_swinopen(PyObject *self, PyObject *args)
static PyObject *
gl_v2f(PyObject *self, PyObject *args)
{
- float arg1 [ 2 ] ;
- if (!getifloatarray(args, 1, 0, 2 , arg1))
- return NULL;
- v2f( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 2 ] ;
+ if (!getifloatarray(args, 1, 0, 2 , arg1))
+ return NULL;
+ v2f( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v2i long s[2] */
@@ -6917,12 +6917,12 @@ gl_v2f(PyObject *self, PyObject *args)
static PyObject *
gl_v2i(PyObject *self, PyObject *args)
{
- long arg1 [ 2 ] ;
- if (!getilongarray(args, 1, 0, 2 , arg1))
- return NULL;
- v2i( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 [ 2 ] ;
+ if (!getilongarray(args, 1, 0, 2 , arg1))
+ return NULL;
+ v2i( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v2s short s[2] */
@@ -6930,12 +6930,12 @@ gl_v2i(PyObject *self, PyObject *args)
static PyObject *
gl_v2s(PyObject *self, PyObject *args)
{
- short arg1 [ 2 ] ;
- if (!getishortarray(args, 1, 0, 2 , arg1))
- return NULL;
- v2s( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 [ 2 ] ;
+ if (!getishortarray(args, 1, 0, 2 , arg1))
+ return NULL;
+ v2s( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v3f float s[3] */
@@ -6943,12 +6943,12 @@ gl_v2s(PyObject *self, PyObject *args)
static PyObject *
gl_v3f(PyObject *self, PyObject *args)
{
- float arg1 [ 3 ] ;
- if (!getifloatarray(args, 1, 0, 3 , arg1))
- return NULL;
- v3f( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 3 ] ;
+ if (!getifloatarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ v3f( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v3i long s[3] */
@@ -6956,12 +6956,12 @@ gl_v3f(PyObject *self, PyObject *args)
static PyObject *
gl_v3i(PyObject *self, PyObject *args)
{
- long arg1 [ 3 ] ;
- if (!getilongarray(args, 1, 0, 3 , arg1))
- return NULL;
- v3i( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 [ 3 ] ;
+ if (!getilongarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ v3i( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v3s short s[3] */
@@ -6969,12 +6969,12 @@ gl_v3i(PyObject *self, PyObject *args)
static PyObject *
gl_v3s(PyObject *self, PyObject *args)
{
- short arg1 [ 3 ] ;
- if (!getishortarray(args, 1, 0, 3 , arg1))
- return NULL;
- v3s( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 [ 3 ] ;
+ if (!getishortarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ v3s( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v4f float s[4] */
@@ -6982,12 +6982,12 @@ gl_v3s(PyObject *self, PyObject *args)
static PyObject *
gl_v4f(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] ;
- if (!getifloatarray(args, 1, 0, 4 , arg1))
- return NULL;
- v4f( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] ;
+ if (!getifloatarray(args, 1, 0, 4 , arg1))
+ return NULL;
+ v4f( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v4i long s[4] */
@@ -6995,12 +6995,12 @@ gl_v4f(PyObject *self, PyObject *args)
static PyObject *
gl_v4i(PyObject *self, PyObject *args)
{
- long arg1 [ 4 ] ;
- if (!getilongarray(args, 1, 0, 4 , arg1))
- return NULL;
- v4i( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 [ 4 ] ;
+ if (!getilongarray(args, 1, 0, 4 , arg1))
+ return NULL;
+ v4i( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v4s short s[4] */
@@ -7008,12 +7008,12 @@ gl_v4i(PyObject *self, PyObject *args)
static PyObject *
gl_v4s(PyObject *self, PyObject *args)
{
- short arg1 [ 4 ] ;
- if (!getishortarray(args, 1, 0, 4 , arg1))
- return NULL;
- v4s( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 [ 4 ] ;
+ if (!getishortarray(args, 1, 0, 4 , arg1))
+ return NULL;
+ v4s( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void videocmd long s */
@@ -7021,12 +7021,12 @@ gl_v4s(PyObject *self, PyObject *args)
static PyObject *
gl_videocmd(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- videocmd( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ videocmd( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long windepth long s */
@@ -7034,12 +7034,12 @@ gl_videocmd(PyObject *self, PyObject *args)
static PyObject *
gl_windepth(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = windepth( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = windepth( arg1 );
+ return mknewlongobject(retval);
}
/* void wmpack long s */
@@ -7047,12 +7047,12 @@ gl_windepth(PyObject *self, PyObject *args)
static PyObject *
gl_wmpack(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- wmpack( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ wmpack( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void zdraw long s */
@@ -7060,12 +7060,12 @@ gl_wmpack(PyObject *self, PyObject *args)
static PyObject *
gl_zdraw(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- zdraw( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ zdraw( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void zfunction long s */
@@ -7073,12 +7073,12 @@ gl_zdraw(PyObject *self, PyObject *args)
static PyObject *
gl_zfunction(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- zfunction( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ zfunction( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void zsource long s */
@@ -7086,12 +7086,12 @@ gl_zfunction(PyObject *self, PyObject *args)
static PyObject *
gl_zsource(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- zsource( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ zsource( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void zwritemask long s */
@@ -7099,12 +7099,12 @@ gl_zsource(PyObject *self, PyObject *args)
static PyObject *
gl_zwritemask(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- zwritemask( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ zwritemask( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v2d double s[2] */
@@ -7112,12 +7112,12 @@ gl_zwritemask(PyObject *self, PyObject *args)
static PyObject *
gl_v2d(PyObject *self, PyObject *args)
{
- double arg1 [ 2 ] ;
- if (!getidoublearray(args, 1, 0, 2 , arg1))
- return NULL;
- v2d( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ double arg1 [ 2 ] ;
+ if (!getidoublearray(args, 1, 0, 2 , arg1))
+ return NULL;
+ v2d( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v3d double s[3] */
@@ -7125,12 +7125,12 @@ gl_v2d(PyObject *self, PyObject *args)
static PyObject *
gl_v3d(PyObject *self, PyObject *args)
{
- double arg1 [ 3 ] ;
- if (!getidoublearray(args, 1, 0, 3 , arg1))
- return NULL;
- v3d( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ double arg1 [ 3 ] ;
+ if (!getidoublearray(args, 1, 0, 3 , arg1))
+ return NULL;
+ v3d( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v4d double s[4] */
@@ -7138,12 +7138,12 @@ gl_v3d(PyObject *self, PyObject *args)
static PyObject *
gl_v4d(PyObject *self, PyObject *args)
{
- double arg1 [ 4 ] ;
- if (!getidoublearray(args, 1, 0, 4 , arg1))
- return NULL;
- v4d( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ double arg1 [ 4 ] ;
+ if (!getidoublearray(args, 1, 0, 4 , arg1))
+ return NULL;
+ v4d( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pixmode long s long s */
@@ -7151,15 +7151,15 @@ gl_v4d(PyObject *self, PyObject *args)
static PyObject *
gl_pixmode(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- pixmode( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ pixmode( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long qgetfd */
@@ -7167,9 +7167,9 @@ gl_pixmode(PyObject *self, PyObject *args)
static PyObject *
gl_qgetfd(PyObject *self, PyObject *args)
{
- long retval;
- retval = qgetfd( );
- return mknewlongobject(retval);
+ long retval;
+ retval = qgetfd( );
+ return mknewlongobject(retval);
}
/* void dither long s */
@@ -7177,457 +7177,457 @@ gl_qgetfd(PyObject *self, PyObject *args)
static PyObject *
gl_dither(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- dither( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ dither( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
static struct PyMethodDef gl_methods[] = {
- {"qread", gl_qread, METH_OLDARGS},
- {"varray", gl_varray, METH_OLDARGS},
- {"nvarray", gl_nvarray, METH_OLDARGS},
- {"vnarray", gl_vnarray, METH_OLDARGS},
- {"nurbssurface", gl_nurbssurface, METH_OLDARGS},
- {"nurbscurve", gl_nurbscurve, METH_OLDARGS},
- {"pwlcurve", gl_pwlcurve, METH_OLDARGS},
- {"pick", gl_pick, METH_OLDARGS},
- {"endpick", gl_endpick, METH_NOARGS},
- {"gselect", gl_gselect, METH_OLDARGS},
- {"endselect", gl_endselect, METH_NOARGS},
- {"getmatrix", gl_getmatrix, METH_OLDARGS},
- {"altgetmatrix", gl_altgetmatrix, METH_OLDARGS},
- {"lrectwrite", gl_lrectwrite, METH_OLDARGS},
- {"lrectread", gl_lrectread, METH_OLDARGS},
- {"readdisplay", gl_readdisplay, METH_OLDARGS},
- {"packrect", gl_packrect, METH_OLDARGS},
- {"unpackrect", gl_unpackrect, METH_OLDARGS},
- {"gversion", gl_gversion, METH_OLDARGS},
- {"clear", gl_clear, METH_OLDARGS},
- {"getshade", gl_getshade, METH_OLDARGS},
- {"devport", gl_devport, METH_OLDARGS},
- {"rdr2i", gl_rdr2i, METH_OLDARGS},
- {"rectfs", gl_rectfs, METH_OLDARGS},
- {"rects", gl_rects, METH_OLDARGS},
- {"rmv2i", gl_rmv2i, METH_OLDARGS},
- {"noport", gl_noport, METH_OLDARGS},
- {"popviewport", gl_popviewport, METH_OLDARGS},
- {"clearhitcode", gl_clearhitcode, METH_OLDARGS},
- {"closeobj", gl_closeobj, METH_OLDARGS},
- {"cursoff", gl_cursoff, METH_OLDARGS},
- {"curson", gl_curson, METH_OLDARGS},
- {"doublebuffer", gl_doublebuffer, METH_OLDARGS},
- {"finish", gl_finish, METH_OLDARGS},
- {"gconfig", gl_gconfig, METH_OLDARGS},
- {"ginit", gl_ginit, METH_OLDARGS},
- {"greset", gl_greset, METH_OLDARGS},
- {"multimap", gl_multimap, METH_OLDARGS},
- {"onemap", gl_onemap, METH_OLDARGS},
- {"popattributes", gl_popattributes, METH_OLDARGS},
- {"popmatrix", gl_popmatrix, METH_OLDARGS},
- {"pushattributes", gl_pushattributes,METH_OLDARGS},
- {"pushmatrix", gl_pushmatrix, METH_OLDARGS},
- {"pushviewport", gl_pushviewport, METH_OLDARGS},
- {"qreset", gl_qreset, METH_OLDARGS},
- {"RGBmode", gl_RGBmode, METH_OLDARGS},
- {"singlebuffer", gl_singlebuffer, METH_OLDARGS},
- {"swapbuffers", gl_swapbuffers, METH_OLDARGS},
- {"gsync", gl_gsync, METH_OLDARGS},
- {"gflush", gl_gflush, METH_OLDARGS},
- {"tpon", gl_tpon, METH_OLDARGS},
- {"tpoff", gl_tpoff, METH_OLDARGS},
- {"clkon", gl_clkon, METH_OLDARGS},
- {"clkoff", gl_clkoff, METH_OLDARGS},
- {"ringbell", gl_ringbell, METH_OLDARGS},
- {"gbegin", gl_gbegin, METH_OLDARGS},
- {"textinit", gl_textinit, METH_OLDARGS},
- {"initnames", gl_initnames, METH_OLDARGS},
- {"pclos", gl_pclos, METH_OLDARGS},
- {"popname", gl_popname, METH_OLDARGS},
- {"spclos", gl_spclos, METH_OLDARGS},
- {"zclear", gl_zclear, METH_OLDARGS},
- {"screenspace", gl_screenspace, METH_OLDARGS},
- {"reshapeviewport", gl_reshapeviewport, METH_OLDARGS},
- {"winpush", gl_winpush, METH_OLDARGS},
- {"winpop", gl_winpop, METH_OLDARGS},
- {"foreground", gl_foreground, METH_OLDARGS},
- {"endfullscrn", gl_endfullscrn, METH_OLDARGS},
- {"endpupmode", gl_endpupmode, METH_OLDARGS},
- {"fullscrn", gl_fullscrn, METH_OLDARGS},
- {"pupmode", gl_pupmode, METH_OLDARGS},
- {"winconstraints", gl_winconstraints, METH_OLDARGS},
- {"pagecolor", gl_pagecolor, METH_OLDARGS},
- {"textcolor", gl_textcolor, METH_OLDARGS},
- {"color", gl_color, METH_OLDARGS},
- {"curveit", gl_curveit, METH_OLDARGS},
- {"font", gl_font, METH_OLDARGS},
- {"linewidth", gl_linewidth, METH_OLDARGS},
- {"setlinestyle", gl_setlinestyle, METH_OLDARGS},
- {"setmap", gl_setmap, METH_OLDARGS},
- {"swapinterval", gl_swapinterval, METH_OLDARGS},
- {"writemask", gl_writemask, METH_OLDARGS},
- {"textwritemask", gl_textwritemask, METH_OLDARGS},
- {"qdevice", gl_qdevice, METH_OLDARGS},
- {"unqdevice", gl_unqdevice, METH_OLDARGS},
- {"curvebasis", gl_curvebasis, METH_OLDARGS},
- {"curveprecision", gl_curveprecision,METH_OLDARGS},
- {"loadname", gl_loadname, METH_OLDARGS},
- {"passthrough", gl_passthrough, METH_OLDARGS},
- {"pushname", gl_pushname, METH_OLDARGS},
- {"setmonitor", gl_setmonitor, METH_OLDARGS},
- {"setshade", gl_setshade, METH_OLDARGS},
- {"setpattern", gl_setpattern, METH_OLDARGS},
- {"pagewritemask", gl_pagewritemask, METH_OLDARGS},
- {"callobj", gl_callobj, METH_OLDARGS},
- {"delobj", gl_delobj, METH_OLDARGS},
- {"editobj", gl_editobj, METH_OLDARGS},
- {"makeobj", gl_makeobj, METH_OLDARGS},
- {"maketag", gl_maketag, METH_OLDARGS},
- {"chunksize", gl_chunksize, METH_OLDARGS},
- {"compactify", gl_compactify, METH_OLDARGS},
- {"deltag", gl_deltag, METH_OLDARGS},
- {"lsrepeat", gl_lsrepeat, METH_OLDARGS},
- {"objinsert", gl_objinsert, METH_OLDARGS},
- {"objreplace", gl_objreplace, METH_OLDARGS},
- {"winclose", gl_winclose, METH_OLDARGS},
- {"blanktime", gl_blanktime, METH_OLDARGS},
- {"freepup", gl_freepup, METH_OLDARGS},
- {"backbuffer", gl_backbuffer, METH_OLDARGS},
- {"frontbuffer", gl_frontbuffer, METH_OLDARGS},
- {"lsbackup", gl_lsbackup, METH_OLDARGS},
- {"resetls", gl_resetls, METH_OLDARGS},
- {"lampon", gl_lampon, METH_OLDARGS},
- {"lampoff", gl_lampoff, METH_OLDARGS},
- {"setbell", gl_setbell, METH_OLDARGS},
- {"blankscreen", gl_blankscreen, METH_OLDARGS},
- {"depthcue", gl_depthcue, METH_OLDARGS},
- {"zbuffer", gl_zbuffer, METH_OLDARGS},
- {"backface", gl_backface, METH_OLDARGS},
- {"cmov2i", gl_cmov2i, METH_OLDARGS},
- {"draw2i", gl_draw2i, METH_OLDARGS},
- {"move2i", gl_move2i, METH_OLDARGS},
- {"pnt2i", gl_pnt2i, METH_OLDARGS},
- {"patchbasis", gl_patchbasis, METH_OLDARGS},
- {"patchprecision", gl_patchprecision, METH_OLDARGS},
- {"pdr2i", gl_pdr2i, METH_OLDARGS},
- {"pmv2i", gl_pmv2i, METH_OLDARGS},
- {"rpdr2i", gl_rpdr2i, METH_OLDARGS},
- {"rpmv2i", gl_rpmv2i, METH_OLDARGS},
- {"xfpt2i", gl_xfpt2i, METH_OLDARGS},
- {"objdelete", gl_objdelete, METH_OLDARGS},
- {"patchcurves", gl_patchcurves, METH_OLDARGS},
- {"minsize", gl_minsize, METH_OLDARGS},
- {"maxsize", gl_maxsize, METH_OLDARGS},
- {"keepaspect", gl_keepaspect, METH_OLDARGS},
- {"prefsize", gl_prefsize, METH_OLDARGS},
- {"stepunit", gl_stepunit, METH_OLDARGS},
- {"fudge", gl_fudge, METH_OLDARGS},
- {"winmove", gl_winmove, METH_OLDARGS},
- {"attachcursor", gl_attachcursor, METH_OLDARGS},
- {"deflinestyle", gl_deflinestyle, METH_OLDARGS},
- {"noise", gl_noise, METH_OLDARGS},
- {"picksize", gl_picksize, METH_OLDARGS},
- {"qenter", gl_qenter, METH_OLDARGS},
- {"setdepth", gl_setdepth, METH_OLDARGS},
- {"cmov2s", gl_cmov2s, METH_OLDARGS},
- {"draw2s", gl_draw2s, METH_OLDARGS},
- {"move2s", gl_move2s, METH_OLDARGS},
- {"pdr2s", gl_pdr2s, METH_OLDARGS},
- {"pmv2s", gl_pmv2s, METH_OLDARGS},
- {"pnt2s", gl_pnt2s, METH_OLDARGS},
- {"rdr2s", gl_rdr2s, METH_OLDARGS},
- {"rmv2s", gl_rmv2s, METH_OLDARGS},
- {"rpdr2s", gl_rpdr2s, METH_OLDARGS},
- {"rpmv2s", gl_rpmv2s, METH_OLDARGS},
- {"xfpt2s", gl_xfpt2s, METH_OLDARGS},
- {"cmov2", gl_cmov2, METH_OLDARGS},
- {"draw2", gl_draw2, METH_OLDARGS},
- {"move2", gl_move2, METH_OLDARGS},
- {"pnt2", gl_pnt2, METH_OLDARGS},
- {"pdr2", gl_pdr2, METH_OLDARGS},
- {"pmv2", gl_pmv2, METH_OLDARGS},
- {"rdr2", gl_rdr2, METH_OLDARGS},
- {"rmv2", gl_rmv2, METH_OLDARGS},
- {"rpdr2", gl_rpdr2, METH_OLDARGS},
- {"rpmv2", gl_rpmv2, METH_OLDARGS},
- {"xfpt2", gl_xfpt2, METH_OLDARGS},
- {"loadmatrix", gl_loadmatrix, METH_OLDARGS},
- {"multmatrix", gl_multmatrix, METH_OLDARGS},
- {"crv", gl_crv, METH_OLDARGS},
- {"rcrv", gl_rcrv, METH_OLDARGS},
- {"addtopup", gl_addtopup, METH_OLDARGS},
- {"charstr", gl_charstr, METH_OLDARGS},
- {"getport", gl_getport, METH_OLDARGS},
- {"strwidth", gl_strwidth, METH_OLDARGS},
- {"winopen", gl_winopen, METH_OLDARGS},
- {"wintitle", gl_wintitle, METH_OLDARGS},
- {"polf", gl_polf, METH_OLDARGS},
- {"polf2", gl_polf2, METH_OLDARGS},
- {"poly", gl_poly, METH_OLDARGS},
- {"poly2", gl_poly2, METH_OLDARGS},
- {"crvn", gl_crvn, METH_OLDARGS},
- {"rcrvn", gl_rcrvn, METH_OLDARGS},
- {"polf2i", gl_polf2i, METH_OLDARGS},
- {"polfi", gl_polfi, METH_OLDARGS},
- {"poly2i", gl_poly2i, METH_OLDARGS},
- {"polyi", gl_polyi, METH_OLDARGS},
- {"polf2s", gl_polf2s, METH_OLDARGS},
- {"polfs", gl_polfs, METH_OLDARGS},
- {"polys", gl_polys, METH_OLDARGS},
- {"poly2s", gl_poly2s, METH_OLDARGS},
- {"defcursor", gl_defcursor, METH_OLDARGS},
- {"writepixels", gl_writepixels, METH_OLDARGS},
- {"defbasis", gl_defbasis, METH_OLDARGS},
- {"gewrite", gl_gewrite, METH_OLDARGS},
- {"rotate", gl_rotate, METH_OLDARGS},
- {"rot", gl_rot, METH_OLDARGS},
- {"circfi", gl_circfi, METH_OLDARGS},
- {"circi", gl_circi, METH_OLDARGS},
- {"cmovi", gl_cmovi, METH_OLDARGS},
- {"drawi", gl_drawi, METH_OLDARGS},
- {"movei", gl_movei, METH_OLDARGS},
- {"pnti", gl_pnti, METH_OLDARGS},
- {"newtag", gl_newtag, METH_OLDARGS},
- {"pdri", gl_pdri, METH_OLDARGS},
- {"pmvi", gl_pmvi, METH_OLDARGS},
- {"rdri", gl_rdri, METH_OLDARGS},
- {"rmvi", gl_rmvi, METH_OLDARGS},
- {"rpdri", gl_rpdri, METH_OLDARGS},
- {"rpmvi", gl_rpmvi, METH_OLDARGS},
- {"xfpti", gl_xfpti, METH_OLDARGS},
- {"circ", gl_circ, METH_OLDARGS},
- {"circf", gl_circf, METH_OLDARGS},
- {"cmov", gl_cmov, METH_OLDARGS},
- {"draw", gl_draw, METH_OLDARGS},
- {"move", gl_move, METH_OLDARGS},
- {"pnt", gl_pnt, METH_OLDARGS},
- {"scale", gl_scale, METH_OLDARGS},
- {"translate", gl_translate, METH_OLDARGS},
- {"pdr", gl_pdr, METH_OLDARGS},
- {"pmv", gl_pmv, METH_OLDARGS},
- {"rdr", gl_rdr, METH_OLDARGS},
- {"rmv", gl_rmv, METH_OLDARGS},
- {"rpdr", gl_rpdr, METH_OLDARGS},
- {"rpmv", gl_rpmv, METH_OLDARGS},
- {"xfpt", gl_xfpt, METH_OLDARGS},
- {"RGBcolor", gl_RGBcolor, METH_OLDARGS},
- {"RGBwritemask", gl_RGBwritemask, METH_OLDARGS},
- {"setcursor", gl_setcursor, METH_OLDARGS},
- {"tie", gl_tie, METH_OLDARGS},
- {"circfs", gl_circfs, METH_OLDARGS},
- {"circs", gl_circs, METH_OLDARGS},
- {"cmovs", gl_cmovs, METH_OLDARGS},
- {"draws", gl_draws, METH_OLDARGS},
- {"moves", gl_moves, METH_OLDARGS},
- {"pdrs", gl_pdrs, METH_OLDARGS},
- {"pmvs", gl_pmvs, METH_OLDARGS},
- {"pnts", gl_pnts, METH_OLDARGS},
- {"rdrs", gl_rdrs, METH_OLDARGS},
- {"rmvs", gl_rmvs, METH_OLDARGS},
- {"rpdrs", gl_rpdrs, METH_OLDARGS},
- {"rpmvs", gl_rpmvs, METH_OLDARGS},
- {"xfpts", gl_xfpts, METH_OLDARGS},
- {"curorigin", gl_curorigin, METH_OLDARGS},
- {"cyclemap", gl_cyclemap, METH_OLDARGS},
- {"patch", gl_patch, METH_OLDARGS},
- {"splf", gl_splf, METH_OLDARGS},
- {"splf2", gl_splf2, METH_OLDARGS},
- {"splfi", gl_splfi, METH_OLDARGS},
- {"splf2i", gl_splf2i, METH_OLDARGS},
- {"splfs", gl_splfs, METH_OLDARGS},
- {"splf2s", gl_splf2s, METH_OLDARGS},
- {"rpatch", gl_rpatch, METH_OLDARGS},
- {"ortho2", gl_ortho2, METH_OLDARGS},
- {"rect", gl_rect, METH_OLDARGS},
- {"rectf", gl_rectf, METH_OLDARGS},
- {"xfpt4", gl_xfpt4, METH_OLDARGS},
- {"textport", gl_textport, METH_OLDARGS},
- {"mapcolor", gl_mapcolor, METH_OLDARGS},
- {"scrmask", gl_scrmask, METH_OLDARGS},
- {"setvaluator", gl_setvaluator, METH_OLDARGS},
- {"viewport", gl_viewport, METH_OLDARGS},
- {"shaderange", gl_shaderange, METH_OLDARGS},
- {"xfpt4s", gl_xfpt4s, METH_OLDARGS},
- {"rectfi", gl_rectfi, METH_OLDARGS},
- {"recti", gl_recti, METH_OLDARGS},
- {"xfpt4i", gl_xfpt4i, METH_OLDARGS},
- {"prefposition", gl_prefposition, METH_OLDARGS},
- {"arc", gl_arc, METH_OLDARGS},
- {"arcf", gl_arcf, METH_OLDARGS},
- {"arcfi", gl_arcfi, METH_OLDARGS},
- {"arci", gl_arci, METH_OLDARGS},
- {"bbox2", gl_bbox2, METH_OLDARGS},
- {"bbox2i", gl_bbox2i, METH_OLDARGS},
- {"bbox2s", gl_bbox2s, METH_OLDARGS},
- {"blink", gl_blink, METH_OLDARGS},
- {"ortho", gl_ortho, METH_OLDARGS},
- {"window", gl_window, METH_OLDARGS},
- {"lookat", gl_lookat, METH_OLDARGS},
- {"perspective", gl_perspective, METH_OLDARGS},
- {"polarview", gl_polarview, METH_OLDARGS},
- {"arcfs", gl_arcfs, METH_OLDARGS},
- {"arcs", gl_arcs, METH_OLDARGS},
- {"rectcopy", gl_rectcopy, METH_OLDARGS},
- {"RGBcursor", gl_RGBcursor, METH_OLDARGS},
- {"getbutton", gl_getbutton, METH_OLDARGS},
- {"getcmmode", gl_getcmmode, METH_OLDARGS},
- {"getlsbackup", gl_getlsbackup, METH_OLDARGS},
- {"getresetls", gl_getresetls, METH_OLDARGS},
- {"getdcm", gl_getdcm, METH_OLDARGS},
- {"getzbuffer", gl_getzbuffer, METH_OLDARGS},
- {"ismex", gl_ismex, METH_OLDARGS},
- {"isobj", gl_isobj, METH_OLDARGS},
- {"isqueued", gl_isqueued, METH_OLDARGS},
- {"istag", gl_istag, METH_OLDARGS},
- {"genobj", gl_genobj, METH_OLDARGS},
- {"gentag", gl_gentag, METH_OLDARGS},
- {"getbuffer", gl_getbuffer, METH_OLDARGS},
- {"getcolor", gl_getcolor, METH_OLDARGS},
- {"getdisplaymode", gl_getdisplaymode, METH_OLDARGS},
- {"getfont", gl_getfont, METH_OLDARGS},
- {"getheight", gl_getheight, METH_OLDARGS},
- {"gethitcode", gl_gethitcode, METH_OLDARGS},
- {"getlstyle", gl_getlstyle, METH_OLDARGS},
- {"getlwidth", gl_getlwidth, METH_OLDARGS},
- {"getmap", gl_getmap, METH_OLDARGS},
- {"getplanes", gl_getplanes, METH_OLDARGS},
- {"getwritemask", gl_getwritemask, METH_OLDARGS},
- {"qtest", gl_qtest, METH_OLDARGS},
- {"getlsrepeat", gl_getlsrepeat, METH_OLDARGS},
- {"getmonitor", gl_getmonitor, METH_OLDARGS},
- {"getopenobj", gl_getopenobj, METH_OLDARGS},
- {"getpattern", gl_getpattern, METH_OLDARGS},
- {"winget", gl_winget, METH_OLDARGS},
- {"winattach", gl_winattach, METH_OLDARGS},
- {"getothermonitor", gl_getothermonitor, METH_OLDARGS},
- {"newpup", gl_newpup, METH_OLDARGS},
- {"getvaluator", gl_getvaluator, METH_OLDARGS},
- {"winset", gl_winset, METH_OLDARGS},
- {"dopup", gl_dopup, METH_OLDARGS},
- {"getdepth", gl_getdepth, METH_OLDARGS},
- {"getcpos", gl_getcpos, METH_OLDARGS},
- {"getsize", gl_getsize, METH_OLDARGS},
- {"getorigin", gl_getorigin, METH_OLDARGS},
- {"getviewport", gl_getviewport, METH_OLDARGS},
- {"gettp", gl_gettp, METH_OLDARGS},
- {"getgpos", gl_getgpos, METH_OLDARGS},
- {"winposition", gl_winposition, METH_OLDARGS},
- {"gRGBcolor", gl_gRGBcolor, METH_OLDARGS},
- {"gRGBmask", gl_gRGBmask, METH_OLDARGS},
- {"getscrmask", gl_getscrmask, METH_OLDARGS},
- {"getmcolor", gl_getmcolor, METH_OLDARGS},
- {"mapw", gl_mapw, METH_OLDARGS},
- {"mapw2", gl_mapw2, METH_OLDARGS},
- {"getcursor", gl_getcursor, METH_OLDARGS},
- {"cmode", gl_cmode, METH_OLDARGS},
- {"concave", gl_concave, METH_OLDARGS},
- {"curstype", gl_curstype, METH_OLDARGS},
- {"drawmode", gl_drawmode, METH_OLDARGS},
- {"gammaramp", gl_gammaramp, METH_OLDARGS},
- {"getbackface", gl_getbackface, METH_OLDARGS},
- {"getdescender", gl_getdescender, METH_OLDARGS},
- {"getdrawmode", gl_getdrawmode, METH_OLDARGS},
- {"getmmode", gl_getmmode, METH_OLDARGS},
- {"getsm", gl_getsm, METH_OLDARGS},
- {"getvideo", gl_getvideo, METH_OLDARGS},
- {"imakebackground", gl_imakebackground, METH_OLDARGS},
- {"lmbind", gl_lmbind, METH_OLDARGS},
- {"lmdef", gl_lmdef, METH_OLDARGS},
- {"mmode", gl_mmode, METH_OLDARGS},
- {"normal", gl_normal, METH_OLDARGS},
- {"overlay", gl_overlay, METH_OLDARGS},
- {"RGBrange", gl_RGBrange, METH_OLDARGS},
- {"setvideo", gl_setvideo, METH_OLDARGS},
- {"shademodel", gl_shademodel, METH_OLDARGS},
- {"underlay", gl_underlay, METH_OLDARGS},
- {"bgnclosedline", gl_bgnclosedline, METH_OLDARGS},
- {"bgnline", gl_bgnline, METH_OLDARGS},
- {"bgnpoint", gl_bgnpoint, METH_OLDARGS},
- {"bgnpolygon", gl_bgnpolygon, METH_OLDARGS},
- {"bgnsurface", gl_bgnsurface, METH_OLDARGS},
- {"bgntmesh", gl_bgntmesh, METH_OLDARGS},
- {"bgntrim", gl_bgntrim, METH_OLDARGS},
- {"endclosedline", gl_endclosedline, METH_OLDARGS},
- {"endline", gl_endline, METH_OLDARGS},
- {"endpoint", gl_endpoint, METH_OLDARGS},
- {"endpolygon", gl_endpolygon, METH_OLDARGS},
- {"endsurface", gl_endsurface, METH_OLDARGS},
- {"endtmesh", gl_endtmesh, METH_OLDARGS},
- {"endtrim", gl_endtrim, METH_OLDARGS},
- {"blendfunction", gl_blendfunction, METH_OLDARGS},
- {"c3f", gl_c3f, METH_OLDARGS},
- {"c3i", gl_c3i, METH_OLDARGS},
- {"c3s", gl_c3s, METH_OLDARGS},
- {"c4f", gl_c4f, METH_OLDARGS},
- {"c4i", gl_c4i, METH_OLDARGS},
- {"c4s", gl_c4s, METH_OLDARGS},
- {"colorf", gl_colorf, METH_OLDARGS},
- {"cpack", gl_cpack, METH_OLDARGS},
- {"czclear", gl_czclear, METH_OLDARGS},
- {"dglclose", gl_dglclose, METH_OLDARGS},
- {"dglopen", gl_dglopen, METH_OLDARGS},
- {"getgdesc", gl_getgdesc, METH_OLDARGS},
- {"getnurbsproperty", gl_getnurbsproperty, METH_OLDARGS},
- {"glcompat", gl_glcompat, METH_OLDARGS},
- {"iconsize", gl_iconsize, METH_OLDARGS},
- {"icontitle", gl_icontitle, METH_OLDARGS},
- {"lRGBrange", gl_lRGBrange, METH_OLDARGS},
- {"linesmooth", gl_linesmooth, METH_OLDARGS},
- {"lmcolor", gl_lmcolor, METH_OLDARGS},
- {"logicop", gl_logicop, METH_OLDARGS},
- {"lsetdepth", gl_lsetdepth, METH_OLDARGS},
- {"lshaderange", gl_lshaderange, METH_OLDARGS},
- {"n3f", gl_n3f, METH_OLDARGS},
- {"noborder", gl_noborder, METH_OLDARGS},
- {"pntsmooth", gl_pntsmooth, METH_OLDARGS},
- {"readsource", gl_readsource, METH_OLDARGS},
- {"rectzoom", gl_rectzoom, METH_OLDARGS},
- {"sbox", gl_sbox, METH_OLDARGS},
- {"sboxi", gl_sboxi, METH_OLDARGS},
- {"sboxs", gl_sboxs, METH_OLDARGS},
- {"sboxf", gl_sboxf, METH_OLDARGS},
- {"sboxfi", gl_sboxfi, METH_OLDARGS},
- {"sboxfs", gl_sboxfs, METH_OLDARGS},
- {"setnurbsproperty", gl_setnurbsproperty, METH_OLDARGS},
- {"setpup", gl_setpup, METH_OLDARGS},
- {"smoothline", gl_smoothline, METH_OLDARGS},
- {"subpixel", gl_subpixel, METH_OLDARGS},
- {"swaptmesh", gl_swaptmesh, METH_OLDARGS},
- {"swinopen", gl_swinopen, METH_OLDARGS},
- {"v2f", gl_v2f, METH_OLDARGS},
- {"v2i", gl_v2i, METH_OLDARGS},
- {"v2s", gl_v2s, METH_OLDARGS},
- {"v3f", gl_v3f, METH_OLDARGS},
- {"v3i", gl_v3i, METH_OLDARGS},
- {"v3s", gl_v3s, METH_OLDARGS},
- {"v4f", gl_v4f, METH_OLDARGS},
- {"v4i", gl_v4i, METH_OLDARGS},
- {"v4s", gl_v4s, METH_OLDARGS},
- {"videocmd", gl_videocmd, METH_OLDARGS},
- {"windepth", gl_windepth, METH_OLDARGS},
- {"wmpack", gl_wmpack, METH_OLDARGS},
- {"zdraw", gl_zdraw, METH_OLDARGS},
- {"zfunction", gl_zfunction, METH_OLDARGS},
- {"zsource", gl_zsource, METH_OLDARGS},
- {"zwritemask", gl_zwritemask, METH_OLDARGS},
- {"v2d", gl_v2d, METH_OLDARGS},
- {"v3d", gl_v3d, METH_OLDARGS},
- {"v4d", gl_v4d, METH_OLDARGS},
- {"pixmode", gl_pixmode, METH_OLDARGS},
- {"qgetfd", gl_qgetfd, METH_OLDARGS},
- {"dither", gl_dither, METH_OLDARGS},
- {NULL, NULL} /* Sentinel */
+ {"qread", gl_qread, METH_OLDARGS},
+ {"varray", gl_varray, METH_OLDARGS},
+ {"nvarray", gl_nvarray, METH_OLDARGS},
+ {"vnarray", gl_vnarray, METH_OLDARGS},
+ {"nurbssurface", gl_nurbssurface, METH_OLDARGS},
+ {"nurbscurve", gl_nurbscurve, METH_OLDARGS},
+ {"pwlcurve", gl_pwlcurve, METH_OLDARGS},
+ {"pick", gl_pick, METH_OLDARGS},
+ {"endpick", gl_endpick, METH_NOARGS},
+ {"gselect", gl_gselect, METH_OLDARGS},
+ {"endselect", gl_endselect, METH_NOARGS},
+ {"getmatrix", gl_getmatrix, METH_OLDARGS},
+ {"altgetmatrix", gl_altgetmatrix, METH_OLDARGS},
+ {"lrectwrite", gl_lrectwrite, METH_OLDARGS},
+ {"lrectread", gl_lrectread, METH_OLDARGS},
+ {"readdisplay", gl_readdisplay, METH_OLDARGS},
+ {"packrect", gl_packrect, METH_OLDARGS},
+ {"unpackrect", gl_unpackrect, METH_OLDARGS},
+ {"gversion", gl_gversion, METH_OLDARGS},
+ {"clear", gl_clear, METH_OLDARGS},
+ {"getshade", gl_getshade, METH_OLDARGS},
+ {"devport", gl_devport, METH_OLDARGS},
+ {"rdr2i", gl_rdr2i, METH_OLDARGS},
+ {"rectfs", gl_rectfs, METH_OLDARGS},
+ {"rects", gl_rects, METH_OLDARGS},
+ {"rmv2i", gl_rmv2i, METH_OLDARGS},
+ {"noport", gl_noport, METH_OLDARGS},
+ {"popviewport", gl_popviewport, METH_OLDARGS},
+ {"clearhitcode", gl_clearhitcode, METH_OLDARGS},
+ {"closeobj", gl_closeobj, METH_OLDARGS},
+ {"cursoff", gl_cursoff, METH_OLDARGS},
+ {"curson", gl_curson, METH_OLDARGS},
+ {"doublebuffer", gl_doublebuffer, METH_OLDARGS},
+ {"finish", gl_finish, METH_OLDARGS},
+ {"gconfig", gl_gconfig, METH_OLDARGS},
+ {"ginit", gl_ginit, METH_OLDARGS},
+ {"greset", gl_greset, METH_OLDARGS},
+ {"multimap", gl_multimap, METH_OLDARGS},
+ {"onemap", gl_onemap, METH_OLDARGS},
+ {"popattributes", gl_popattributes, METH_OLDARGS},
+ {"popmatrix", gl_popmatrix, METH_OLDARGS},
+ {"pushattributes", gl_pushattributes,METH_OLDARGS},
+ {"pushmatrix", gl_pushmatrix, METH_OLDARGS},
+ {"pushviewport", gl_pushviewport, METH_OLDARGS},
+ {"qreset", gl_qreset, METH_OLDARGS},
+ {"RGBmode", gl_RGBmode, METH_OLDARGS},
+ {"singlebuffer", gl_singlebuffer, METH_OLDARGS},
+ {"swapbuffers", gl_swapbuffers, METH_OLDARGS},
+ {"gsync", gl_gsync, METH_OLDARGS},
+ {"gflush", gl_gflush, METH_OLDARGS},
+ {"tpon", gl_tpon, METH_OLDARGS},
+ {"tpoff", gl_tpoff, METH_OLDARGS},
+ {"clkon", gl_clkon, METH_OLDARGS},
+ {"clkoff", gl_clkoff, METH_OLDARGS},
+ {"ringbell", gl_ringbell, METH_OLDARGS},
+ {"gbegin", gl_gbegin, METH_OLDARGS},
+ {"textinit", gl_textinit, METH_OLDARGS},
+ {"initnames", gl_initnames, METH_OLDARGS},
+ {"pclos", gl_pclos, METH_OLDARGS},
+ {"popname", gl_popname, METH_OLDARGS},
+ {"spclos", gl_spclos, METH_OLDARGS},
+ {"zclear", gl_zclear, METH_OLDARGS},
+ {"screenspace", gl_screenspace, METH_OLDARGS},
+ {"reshapeviewport", gl_reshapeviewport, METH_OLDARGS},
+ {"winpush", gl_winpush, METH_OLDARGS},
+ {"winpop", gl_winpop, METH_OLDARGS},
+ {"foreground", gl_foreground, METH_OLDARGS},
+ {"endfullscrn", gl_endfullscrn, METH_OLDARGS},
+ {"endpupmode", gl_endpupmode, METH_OLDARGS},
+ {"fullscrn", gl_fullscrn, METH_OLDARGS},
+ {"pupmode", gl_pupmode, METH_OLDARGS},
+ {"winconstraints", gl_winconstraints, METH_OLDARGS},
+ {"pagecolor", gl_pagecolor, METH_OLDARGS},
+ {"textcolor", gl_textcolor, METH_OLDARGS},
+ {"color", gl_color, METH_OLDARGS},
+ {"curveit", gl_curveit, METH_OLDARGS},
+ {"font", gl_font, METH_OLDARGS},
+ {"linewidth", gl_linewidth, METH_OLDARGS},
+ {"setlinestyle", gl_setlinestyle, METH_OLDARGS},
+ {"setmap", gl_setmap, METH_OLDARGS},
+ {"swapinterval", gl_swapinterval, METH_OLDARGS},
+ {"writemask", gl_writemask, METH_OLDARGS},
+ {"textwritemask", gl_textwritemask, METH_OLDARGS},
+ {"qdevice", gl_qdevice, METH_OLDARGS},
+ {"unqdevice", gl_unqdevice, METH_OLDARGS},
+ {"curvebasis", gl_curvebasis, METH_OLDARGS},
+ {"curveprecision", gl_curveprecision,METH_OLDARGS},
+ {"loadname", gl_loadname, METH_OLDARGS},
+ {"passthrough", gl_passthrough, METH_OLDARGS},
+ {"pushname", gl_pushname, METH_OLDARGS},
+ {"setmonitor", gl_setmonitor, METH_OLDARGS},
+ {"setshade", gl_setshade, METH_OLDARGS},
+ {"setpattern", gl_setpattern, METH_OLDARGS},
+ {"pagewritemask", gl_pagewritemask, METH_OLDARGS},
+ {"callobj", gl_callobj, METH_OLDARGS},
+ {"delobj", gl_delobj, METH_OLDARGS},
+ {"editobj", gl_editobj, METH_OLDARGS},
+ {"makeobj", gl_makeobj, METH_OLDARGS},
+ {"maketag", gl_maketag, METH_OLDARGS},
+ {"chunksize", gl_chunksize, METH_OLDARGS},
+ {"compactify", gl_compactify, METH_OLDARGS},
+ {"deltag", gl_deltag, METH_OLDARGS},
+ {"lsrepeat", gl_lsrepeat, METH_OLDARGS},
+ {"objinsert", gl_objinsert, METH_OLDARGS},
+ {"objreplace", gl_objreplace, METH_OLDARGS},
+ {"winclose", gl_winclose, METH_OLDARGS},
+ {"blanktime", gl_blanktime, METH_OLDARGS},
+ {"freepup", gl_freepup, METH_OLDARGS},
+ {"backbuffer", gl_backbuffer, METH_OLDARGS},
+ {"frontbuffer", gl_frontbuffer, METH_OLDARGS},
+ {"lsbackup", gl_lsbackup, METH_OLDARGS},
+ {"resetls", gl_resetls, METH_OLDARGS},
+ {"lampon", gl_lampon, METH_OLDARGS},
+ {"lampoff", gl_lampoff, METH_OLDARGS},
+ {"setbell", gl_setbell, METH_OLDARGS},
+ {"blankscreen", gl_blankscreen, METH_OLDARGS},
+ {"depthcue", gl_depthcue, METH_OLDARGS},
+ {"zbuffer", gl_zbuffer, METH_OLDARGS},
+ {"backface", gl_backface, METH_OLDARGS},
+ {"cmov2i", gl_cmov2i, METH_OLDARGS},
+ {"draw2i", gl_draw2i, METH_OLDARGS},
+ {"move2i", gl_move2i, METH_OLDARGS},
+ {"pnt2i", gl_pnt2i, METH_OLDARGS},
+ {"patchbasis", gl_patchbasis, METH_OLDARGS},
+ {"patchprecision", gl_patchprecision, METH_OLDARGS},
+ {"pdr2i", gl_pdr2i, METH_OLDARGS},
+ {"pmv2i", gl_pmv2i, METH_OLDARGS},
+ {"rpdr2i", gl_rpdr2i, METH_OLDARGS},
+ {"rpmv2i", gl_rpmv2i, METH_OLDARGS},
+ {"xfpt2i", gl_xfpt2i, METH_OLDARGS},
+ {"objdelete", gl_objdelete, METH_OLDARGS},
+ {"patchcurves", gl_patchcurves, METH_OLDARGS},
+ {"minsize", gl_minsize, METH_OLDARGS},
+ {"maxsize", gl_maxsize, METH_OLDARGS},
+ {"keepaspect", gl_keepaspect, METH_OLDARGS},
+ {"prefsize", gl_prefsize, METH_OLDARGS},
+ {"stepunit", gl_stepunit, METH_OLDARGS},
+ {"fudge", gl_fudge, METH_OLDARGS},
+ {"winmove", gl_winmove, METH_OLDARGS},
+ {"attachcursor", gl_attachcursor, METH_OLDARGS},
+ {"deflinestyle", gl_deflinestyle, METH_OLDARGS},
+ {"noise", gl_noise, METH_OLDARGS},
+ {"picksize", gl_picksize, METH_OLDARGS},
+ {"qenter", gl_qenter, METH_OLDARGS},
+ {"setdepth", gl_setdepth, METH_OLDARGS},
+ {"cmov2s", gl_cmov2s, METH_OLDARGS},
+ {"draw2s", gl_draw2s, METH_OLDARGS},
+ {"move2s", gl_move2s, METH_OLDARGS},
+ {"pdr2s", gl_pdr2s, METH_OLDARGS},
+ {"pmv2s", gl_pmv2s, METH_OLDARGS},
+ {"pnt2s", gl_pnt2s, METH_OLDARGS},
+ {"rdr2s", gl_rdr2s, METH_OLDARGS},
+ {"rmv2s", gl_rmv2s, METH_OLDARGS},
+ {"rpdr2s", gl_rpdr2s, METH_OLDARGS},
+ {"rpmv2s", gl_rpmv2s, METH_OLDARGS},
+ {"xfpt2s", gl_xfpt2s, METH_OLDARGS},
+ {"cmov2", gl_cmov2, METH_OLDARGS},
+ {"draw2", gl_draw2, METH_OLDARGS},
+ {"move2", gl_move2, METH_OLDARGS},
+ {"pnt2", gl_pnt2, METH_OLDARGS},
+ {"pdr2", gl_pdr2, METH_OLDARGS},
+ {"pmv2", gl_pmv2, METH_OLDARGS},
+ {"rdr2", gl_rdr2, METH_OLDARGS},
+ {"rmv2", gl_rmv2, METH_OLDARGS},
+ {"rpdr2", gl_rpdr2, METH_OLDARGS},
+ {"rpmv2", gl_rpmv2, METH_OLDARGS},
+ {"xfpt2", gl_xfpt2, METH_OLDARGS},
+ {"loadmatrix", gl_loadmatrix, METH_OLDARGS},
+ {"multmatrix", gl_multmatrix, METH_OLDARGS},
+ {"crv", gl_crv, METH_OLDARGS},
+ {"rcrv", gl_rcrv, METH_OLDARGS},
+ {"addtopup", gl_addtopup, METH_OLDARGS},
+ {"charstr", gl_charstr, METH_OLDARGS},
+ {"getport", gl_getport, METH_OLDARGS},
+ {"strwidth", gl_strwidth, METH_OLDARGS},
+ {"winopen", gl_winopen, METH_OLDARGS},
+ {"wintitle", gl_wintitle, METH_OLDARGS},
+ {"polf", gl_polf, METH_OLDARGS},
+ {"polf2", gl_polf2, METH_OLDARGS},
+ {"poly", gl_poly, METH_OLDARGS},
+ {"poly2", gl_poly2, METH_OLDARGS},
+ {"crvn", gl_crvn, METH_OLDARGS},
+ {"rcrvn", gl_rcrvn, METH_OLDARGS},
+ {"polf2i", gl_polf2i, METH_OLDARGS},
+ {"polfi", gl_polfi, METH_OLDARGS},
+ {"poly2i", gl_poly2i, METH_OLDARGS},
+ {"polyi", gl_polyi, METH_OLDARGS},
+ {"polf2s", gl_polf2s, METH_OLDARGS},
+ {"polfs", gl_polfs, METH_OLDARGS},
+ {"polys", gl_polys, METH_OLDARGS},
+ {"poly2s", gl_poly2s, METH_OLDARGS},
+ {"defcursor", gl_defcursor, METH_OLDARGS},
+ {"writepixels", gl_writepixels, METH_OLDARGS},
+ {"defbasis", gl_defbasis, METH_OLDARGS},
+ {"gewrite", gl_gewrite, METH_OLDARGS},
+ {"rotate", gl_rotate, METH_OLDARGS},
+ {"rot", gl_rot, METH_OLDARGS},
+ {"circfi", gl_circfi, METH_OLDARGS},
+ {"circi", gl_circi, METH_OLDARGS},
+ {"cmovi", gl_cmovi, METH_OLDARGS},
+ {"drawi", gl_drawi, METH_OLDARGS},
+ {"movei", gl_movei, METH_OLDARGS},
+ {"pnti", gl_pnti, METH_OLDARGS},
+ {"newtag", gl_newtag, METH_OLDARGS},
+ {"pdri", gl_pdri, METH_OLDARGS},
+ {"pmvi", gl_pmvi, METH_OLDARGS},
+ {"rdri", gl_rdri, METH_OLDARGS},
+ {"rmvi", gl_rmvi, METH_OLDARGS},
+ {"rpdri", gl_rpdri, METH_OLDARGS},
+ {"rpmvi", gl_rpmvi, METH_OLDARGS},
+ {"xfpti", gl_xfpti, METH_OLDARGS},
+ {"circ", gl_circ, METH_OLDARGS},
+ {"circf", gl_circf, METH_OLDARGS},
+ {"cmov", gl_cmov, METH_OLDARGS},
+ {"draw", gl_draw, METH_OLDARGS},
+ {"move", gl_move, METH_OLDARGS},
+ {"pnt", gl_pnt, METH_OLDARGS},
+ {"scale", gl_scale, METH_OLDARGS},
+ {"translate", gl_translate, METH_OLDARGS},
+ {"pdr", gl_pdr, METH_OLDARGS},
+ {"pmv", gl_pmv, METH_OLDARGS},
+ {"rdr", gl_rdr, METH_OLDARGS},
+ {"rmv", gl_rmv, METH_OLDARGS},
+ {"rpdr", gl_rpdr, METH_OLDARGS},
+ {"rpmv", gl_rpmv, METH_OLDARGS},
+ {"xfpt", gl_xfpt, METH_OLDARGS},
+ {"RGBcolor", gl_RGBcolor, METH_OLDARGS},
+ {"RGBwritemask", gl_RGBwritemask, METH_OLDARGS},
+ {"setcursor", gl_setcursor, METH_OLDARGS},
+ {"tie", gl_tie, METH_OLDARGS},
+ {"circfs", gl_circfs, METH_OLDARGS},
+ {"circs", gl_circs, METH_OLDARGS},
+ {"cmovs", gl_cmovs, METH_OLDARGS},
+ {"draws", gl_draws, METH_OLDARGS},
+ {"moves", gl_moves, METH_OLDARGS},
+ {"pdrs", gl_pdrs, METH_OLDARGS},
+ {"pmvs", gl_pmvs, METH_OLDARGS},
+ {"pnts", gl_pnts, METH_OLDARGS},
+ {"rdrs", gl_rdrs, METH_OLDARGS},
+ {"rmvs", gl_rmvs, METH_OLDARGS},
+ {"rpdrs", gl_rpdrs, METH_OLDARGS},
+ {"rpmvs", gl_rpmvs, METH_OLDARGS},
+ {"xfpts", gl_xfpts, METH_OLDARGS},
+ {"curorigin", gl_curorigin, METH_OLDARGS},
+ {"cyclemap", gl_cyclemap, METH_OLDARGS},
+ {"patch", gl_patch, METH_OLDARGS},
+ {"splf", gl_splf, METH_OLDARGS},
+ {"splf2", gl_splf2, METH_OLDARGS},
+ {"splfi", gl_splfi, METH_OLDARGS},
+ {"splf2i", gl_splf2i, METH_OLDARGS},
+ {"splfs", gl_splfs, METH_OLDARGS},
+ {"splf2s", gl_splf2s, METH_OLDARGS},
+ {"rpatch", gl_rpatch, METH_OLDARGS},
+ {"ortho2", gl_ortho2, METH_OLDARGS},
+ {"rect", gl_rect, METH_OLDARGS},
+ {"rectf", gl_rectf, METH_OLDARGS},
+ {"xfpt4", gl_xfpt4, METH_OLDARGS},
+ {"textport", gl_textport, METH_OLDARGS},
+ {"mapcolor", gl_mapcolor, METH_OLDARGS},
+ {"scrmask", gl_scrmask, METH_OLDARGS},
+ {"setvaluator", gl_setvaluator, METH_OLDARGS},
+ {"viewport", gl_viewport, METH_OLDARGS},
+ {"shaderange", gl_shaderange, METH_OLDARGS},
+ {"xfpt4s", gl_xfpt4s, METH_OLDARGS},
+ {"rectfi", gl_rectfi, METH_OLDARGS},
+ {"recti", gl_recti, METH_OLDARGS},
+ {"xfpt4i", gl_xfpt4i, METH_OLDARGS},
+ {"prefposition", gl_prefposition, METH_OLDARGS},
+ {"arc", gl_arc, METH_OLDARGS},
+ {"arcf", gl_arcf, METH_OLDARGS},
+ {"arcfi", gl_arcfi, METH_OLDARGS},
+ {"arci", gl_arci, METH_OLDARGS},
+ {"bbox2", gl_bbox2, METH_OLDARGS},
+ {"bbox2i", gl_bbox2i, METH_OLDARGS},
+ {"bbox2s", gl_bbox2s, METH_OLDARGS},
+ {"blink", gl_blink, METH_OLDARGS},
+ {"ortho", gl_ortho, METH_OLDARGS},
+ {"window", gl_window, METH_OLDARGS},
+ {"lookat", gl_lookat, METH_OLDARGS},
+ {"perspective", gl_perspective, METH_OLDARGS},
+ {"polarview", gl_polarview, METH_OLDARGS},
+ {"arcfs", gl_arcfs, METH_OLDARGS},
+ {"arcs", gl_arcs, METH_OLDARGS},
+ {"rectcopy", gl_rectcopy, METH_OLDARGS},
+ {"RGBcursor", gl_RGBcursor, METH_OLDARGS},
+ {"getbutton", gl_getbutton, METH_OLDARGS},
+ {"getcmmode", gl_getcmmode, METH_OLDARGS},
+ {"getlsbackup", gl_getlsbackup, METH_OLDARGS},
+ {"getresetls", gl_getresetls, METH_OLDARGS},
+ {"getdcm", gl_getdcm, METH_OLDARGS},
+ {"getzbuffer", gl_getzbuffer, METH_OLDARGS},
+ {"ismex", gl_ismex, METH_OLDARGS},
+ {"isobj", gl_isobj, METH_OLDARGS},
+ {"isqueued", gl_isqueued, METH_OLDARGS},
+ {"istag", gl_istag, METH_OLDARGS},
+ {"genobj", gl_genobj, METH_OLDARGS},
+ {"gentag", gl_gentag, METH_OLDARGS},
+ {"getbuffer", gl_getbuffer, METH_OLDARGS},
+ {"getcolor", gl_getcolor, METH_OLDARGS},
+ {"getdisplaymode", gl_getdisplaymode, METH_OLDARGS},
+ {"getfont", gl_getfont, METH_OLDARGS},
+ {"getheight", gl_getheight, METH_OLDARGS},
+ {"gethitcode", gl_gethitcode, METH_OLDARGS},
+ {"getlstyle", gl_getlstyle, METH_OLDARGS},
+ {"getlwidth", gl_getlwidth, METH_OLDARGS},
+ {"getmap", gl_getmap, METH_OLDARGS},
+ {"getplanes", gl_getplanes, METH_OLDARGS},
+ {"getwritemask", gl_getwritemask, METH_OLDARGS},
+ {"qtest", gl_qtest, METH_OLDARGS},
+ {"getlsrepeat", gl_getlsrepeat, METH_OLDARGS},
+ {"getmonitor", gl_getmonitor, METH_OLDARGS},
+ {"getopenobj", gl_getopenobj, METH_OLDARGS},
+ {"getpattern", gl_getpattern, METH_OLDARGS},
+ {"winget", gl_winget, METH_OLDARGS},
+ {"winattach", gl_winattach, METH_OLDARGS},
+ {"getothermonitor", gl_getothermonitor, METH_OLDARGS},
+ {"newpup", gl_newpup, METH_OLDARGS},
+ {"getvaluator", gl_getvaluator, METH_OLDARGS},
+ {"winset", gl_winset, METH_OLDARGS},
+ {"dopup", gl_dopup, METH_OLDARGS},
+ {"getdepth", gl_getdepth, METH_OLDARGS},
+ {"getcpos", gl_getcpos, METH_OLDARGS},
+ {"getsize", gl_getsize, METH_OLDARGS},
+ {"getorigin", gl_getorigin, METH_OLDARGS},
+ {"getviewport", gl_getviewport, METH_OLDARGS},
+ {"gettp", gl_gettp, METH_OLDARGS},
+ {"getgpos", gl_getgpos, METH_OLDARGS},
+ {"winposition", gl_winposition, METH_OLDARGS},
+ {"gRGBcolor", gl_gRGBcolor, METH_OLDARGS},
+ {"gRGBmask", gl_gRGBmask, METH_OLDARGS},
+ {"getscrmask", gl_getscrmask, METH_OLDARGS},
+ {"getmcolor", gl_getmcolor, METH_OLDARGS},
+ {"mapw", gl_mapw, METH_OLDARGS},
+ {"mapw2", gl_mapw2, METH_OLDARGS},
+ {"getcursor", gl_getcursor, METH_OLDARGS},
+ {"cmode", gl_cmode, METH_OLDARGS},
+ {"concave", gl_concave, METH_OLDARGS},
+ {"curstype", gl_curstype, METH_OLDARGS},
+ {"drawmode", gl_drawmode, METH_OLDARGS},
+ {"gammaramp", gl_gammaramp, METH_OLDARGS},
+ {"getbackface", gl_getbackface, METH_OLDARGS},
+ {"getdescender", gl_getdescender, METH_OLDARGS},
+ {"getdrawmode", gl_getdrawmode, METH_OLDARGS},
+ {"getmmode", gl_getmmode, METH_OLDARGS},
+ {"getsm", gl_getsm, METH_OLDARGS},
+ {"getvideo", gl_getvideo, METH_OLDARGS},
+ {"imakebackground", gl_imakebackground, METH_OLDARGS},
+ {"lmbind", gl_lmbind, METH_OLDARGS},
+ {"lmdef", gl_lmdef, METH_OLDARGS},
+ {"mmode", gl_mmode, METH_OLDARGS},
+ {"normal", gl_normal, METH_OLDARGS},
+ {"overlay", gl_overlay, METH_OLDARGS},
+ {"RGBrange", gl_RGBrange, METH_OLDARGS},
+ {"setvideo", gl_setvideo, METH_OLDARGS},
+ {"shademodel", gl_shademodel, METH_OLDARGS},
+ {"underlay", gl_underlay, METH_OLDARGS},
+ {"bgnclosedline", gl_bgnclosedline, METH_OLDARGS},
+ {"bgnline", gl_bgnline, METH_OLDARGS},
+ {"bgnpoint", gl_bgnpoint, METH_OLDARGS},
+ {"bgnpolygon", gl_bgnpolygon, METH_OLDARGS},
+ {"bgnsurface", gl_bgnsurface, METH_OLDARGS},
+ {"bgntmesh", gl_bgntmesh, METH_OLDARGS},
+ {"bgntrim", gl_bgntrim, METH_OLDARGS},
+ {"endclosedline", gl_endclosedline, METH_OLDARGS},
+ {"endline", gl_endline, METH_OLDARGS},
+ {"endpoint", gl_endpoint, METH_OLDARGS},
+ {"endpolygon", gl_endpolygon, METH_OLDARGS},
+ {"endsurface", gl_endsurface, METH_OLDARGS},
+ {"endtmesh", gl_endtmesh, METH_OLDARGS},
+ {"endtrim", gl_endtrim, METH_OLDARGS},
+ {"blendfunction", gl_blendfunction, METH_OLDARGS},
+ {"c3f", gl_c3f, METH_OLDARGS},
+ {"c3i", gl_c3i, METH_OLDARGS},
+ {"c3s", gl_c3s, METH_OLDARGS},
+ {"c4f", gl_c4f, METH_OLDARGS},
+ {"c4i", gl_c4i, METH_OLDARGS},
+ {"c4s", gl_c4s, METH_OLDARGS},
+ {"colorf", gl_colorf, METH_OLDARGS},
+ {"cpack", gl_cpack, METH_OLDARGS},
+ {"czclear", gl_czclear, METH_OLDARGS},
+ {"dglclose", gl_dglclose, METH_OLDARGS},
+ {"dglopen", gl_dglopen, METH_OLDARGS},
+ {"getgdesc", gl_getgdesc, METH_OLDARGS},
+ {"getnurbsproperty", gl_getnurbsproperty, METH_OLDARGS},
+ {"glcompat", gl_glcompat, METH_OLDARGS},
+ {"iconsize", gl_iconsize, METH_OLDARGS},
+ {"icontitle", gl_icontitle, METH_OLDARGS},
+ {"lRGBrange", gl_lRGBrange, METH_OLDARGS},
+ {"linesmooth", gl_linesmooth, METH_OLDARGS},
+ {"lmcolor", gl_lmcolor, METH_OLDARGS},
+ {"logicop", gl_logicop, METH_OLDARGS},
+ {"lsetdepth", gl_lsetdepth, METH_OLDARGS},
+ {"lshaderange", gl_lshaderange, METH_OLDARGS},
+ {"n3f", gl_n3f, METH_OLDARGS},
+ {"noborder", gl_noborder, METH_OLDARGS},
+ {"pntsmooth", gl_pntsmooth, METH_OLDARGS},
+ {"readsource", gl_readsource, METH_OLDARGS},
+ {"rectzoom", gl_rectzoom, METH_OLDARGS},
+ {"sbox", gl_sbox, METH_OLDARGS},
+ {"sboxi", gl_sboxi, METH_OLDARGS},
+ {"sboxs", gl_sboxs, METH_OLDARGS},
+ {"sboxf", gl_sboxf, METH_OLDARGS},
+ {"sboxfi", gl_sboxfi, METH_OLDARGS},
+ {"sboxfs", gl_sboxfs, METH_OLDARGS},
+ {"setnurbsproperty", gl_setnurbsproperty, METH_OLDARGS},
+ {"setpup", gl_setpup, METH_OLDARGS},
+ {"smoothline", gl_smoothline, METH_OLDARGS},
+ {"subpixel", gl_subpixel, METH_OLDARGS},
+ {"swaptmesh", gl_swaptmesh, METH_OLDARGS},
+ {"swinopen", gl_swinopen, METH_OLDARGS},
+ {"v2f", gl_v2f, METH_OLDARGS},
+ {"v2i", gl_v2i, METH_OLDARGS},
+ {"v2s", gl_v2s, METH_OLDARGS},
+ {"v3f", gl_v3f, METH_OLDARGS},
+ {"v3i", gl_v3i, METH_OLDARGS},
+ {"v3s", gl_v3s, METH_OLDARGS},
+ {"v4f", gl_v4f, METH_OLDARGS},
+ {"v4i", gl_v4i, METH_OLDARGS},
+ {"v4s", gl_v4s, METH_OLDARGS},
+ {"videocmd", gl_videocmd, METH_OLDARGS},
+ {"windepth", gl_windepth, METH_OLDARGS},
+ {"wmpack", gl_wmpack, METH_OLDARGS},
+ {"zdraw", gl_zdraw, METH_OLDARGS},
+ {"zfunction", gl_zfunction, METH_OLDARGS},
+ {"zsource", gl_zsource, METH_OLDARGS},
+ {"zwritemask", gl_zwritemask, METH_OLDARGS},
+ {"v2d", gl_v2d, METH_OLDARGS},
+ {"v3d", gl_v3d, METH_OLDARGS},
+ {"v4d", gl_v4d, METH_OLDARGS},
+ {"pixmode", gl_pixmode, METH_OLDARGS},
+ {"qgetfd", gl_qgetfd, METH_OLDARGS},
+ {"dither", gl_dither, METH_OLDARGS},
+ {NULL, NULL} /* Sentinel */
};
void
initgl(void)
{
-
+
if (PyErr_WarnPy3k("the gl module has been removed in "
"Python 3.0", 2) < 0)
- return;
-
- (void) Py_InitModule("gl", gl_methods);
+ return;
+
+ (void) Py_InitModule("gl", gl_methods);
}
diff --git a/Modules/imageop.c b/Modules/imageop.c
index 8d0d68f..8bd11b2 100644
--- a/Modules/imageop.c
+++ b/Modules/imageop.c
@@ -33,10 +33,10 @@ static PyObject *ImageopDict;
static int
check_coordonnate(int value, const char* name)
{
- if ( 0 < value)
- return 1;
- PyErr_Format(PyExc_ValueError, "%s value is negative or nul", name);
- return 0;
+ if ( 0 < value)
+ return 1;
+ PyErr_Format(PyExc_ValueError, "%s value is negative or nul", name);
+ return 0;
}
/**
@@ -46,14 +46,14 @@ check_coordonnate(int value, const char* name)
static int
check_multiply_size(int product, int x, const char* xname, int y, const char* yname, int size)
{
- if ( !check_coordonnate(x, xname) )
- return 0;
- if ( !check_coordonnate(y, yname) )
- return 0;
- if ( size == (product / y) / x )
- return 1;
- PyErr_SetString(ImageopError, "String has incorrect length");
- return 0;
+ if ( !check_coordonnate(x, xname) )
+ return 0;
+ if ( !check_coordonnate(y, yname) )
+ return 0;
+ if ( size == (product / y) / x )
+ return 1;
+ PyErr_SetString(ImageopError, "String has incorrect length");
+ return 0;
}
/**
@@ -63,7 +63,7 @@ check_multiply_size(int product, int x, const char* xname, int y, const char* yn
static int
check_multiply(int product, int x, int y)
{
- return check_multiply_size(product, x, "x", y, "y", 1);
+ return check_multiply_size(product, x, "x", y, "y", 1);
}
/* If this function returns true (the default if anything goes wrong), we're
@@ -86,131 +86,131 @@ check_multiply(int product, int x, int y)
static int
imageop_backward_compatible(void)
{
- static PyObject *bcos;
- PyObject *bco;
- long rc;
-
- if (ImageopDict == NULL) /* "cannot happen" */
- return 1;
- if (bcos == NULL) {
- /* cache string object for future use */
- bcos = PyString_FromString("backward_compatible");
- if (bcos == NULL)
- return 1;
- }
- bco = PyDict_GetItem(ImageopDict, bcos);
- if (bco == NULL)
- return 1;
- if (!PyInt_Check(bco))
- return 1;
- rc = PyInt_AsLong(bco);
- if (PyErr_Occurred()) {
- /* not an integer, or too large, or something */
- PyErr_Clear();
- rc = 1;
- }
- return rc != 0; /* convert to values 0, 1 */
+ static PyObject *bcos;
+ PyObject *bco;
+ long rc;
+
+ if (ImageopDict == NULL) /* "cannot happen" */
+ return 1;
+ if (bcos == NULL) {
+ /* cache string object for future use */
+ bcos = PyString_FromString("backward_compatible");
+ if (bcos == NULL)
+ return 1;
+ }
+ bco = PyDict_GetItem(ImageopDict, bcos);
+ if (bco == NULL)
+ return 1;
+ if (!PyInt_Check(bco))
+ return 1;
+ rc = PyInt_AsLong(bco);
+ if (PyErr_Occurred()) {
+ /* not an integer, or too large, or something */
+ PyErr_Clear();
+ rc = 1;
+ }
+ return rc != 0; /* convert to values 0, 1 */
}
static PyObject *
imageop_crop(PyObject *self, PyObject *args)
{
- char *cp, *ncp;
- short *nsp;
- Py_Int32 *nlp;
- int len, size, x, y, newx1, newx2, newy1, newy2, nlen;
- int ix, iy, xstep, ystep;
- PyObject *rv;
-
- if ( !PyArg_ParseTuple(args, "s#iiiiiii", &cp, &len, &size, &x, &y,
- &newx1, &newy1, &newx2, &newy2) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(ImageopError, "Size should be 1, 2 or 4");
- return 0;
- }
- if ( !check_multiply_size(len, x, "x", y, "y", size) )
- return 0;
-
- xstep = (newx1 < newx2)? 1 : -1;
- ystep = (newy1 < newy2)? 1 : -1;
-
- nlen = (abs(newx2-newx1)+1)*(abs(newy2-newy1)+1)*size;
- if ( !check_multiply_size(nlen, abs(newx2-newx1)+1, "abs(newx2-newx1)+1", abs(newy2-newy1)+1, "abs(newy2-newy1)+1", size) )
- return 0;
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (char *)PyString_AsString(rv);
- nsp = (short *)ncp;
- nlp = (Py_Int32 *)ncp;
- newy2 += ystep;
- newx2 += xstep;
- for( iy = newy1; iy != newy2; iy+=ystep ) {
- for ( ix = newx1; ix != newx2; ix+=xstep ) {
- if ( iy < 0 || iy >= y || ix < 0 || ix >= x ) {
- if ( size == 1 )
- *ncp++ = 0;
- else
- *nlp++ = 0;
- } else {
- if ( size == 1 )
- *ncp++ = *CHARP(cp, x, ix, iy);
- else if ( size == 2 )
- *nsp++ = *SHORTP(cp, x, ix, iy);
- else
- *nlp++ = *LONGP(cp, x, ix, iy);
- }
- }
- }
- return rv;
+ char *cp, *ncp;
+ short *nsp;
+ Py_Int32 *nlp;
+ int len, size, x, y, newx1, newx2, newy1, newy2, nlen;
+ int ix, iy, xstep, ystep;
+ PyObject *rv;
+
+ if ( !PyArg_ParseTuple(args, "s#iiiiiii", &cp, &len, &size, &x, &y,
+ &newx1, &newy1, &newx2, &newy2) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(ImageopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ if ( !check_multiply_size(len, x, "x", y, "y", size) )
+ return 0;
+
+ xstep = (newx1 < newx2)? 1 : -1;
+ ystep = (newy1 < newy2)? 1 : -1;
+
+ nlen = (abs(newx2-newx1)+1)*(abs(newy2-newy1)+1)*size;
+ if ( !check_multiply_size(nlen, abs(newx2-newx1)+1, "abs(newx2-newx1)+1", abs(newy2-newy1)+1, "abs(newy2-newy1)+1", size) )
+ return 0;
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (char *)PyString_AsString(rv);
+ nsp = (short *)ncp;
+ nlp = (Py_Int32 *)ncp;
+ newy2 += ystep;
+ newx2 += xstep;
+ for( iy = newy1; iy != newy2; iy+=ystep ) {
+ for ( ix = newx1; ix != newx2; ix+=xstep ) {
+ if ( iy < 0 || iy >= y || ix < 0 || ix >= x ) {
+ if ( size == 1 )
+ *ncp++ = 0;
+ else
+ *nlp++ = 0;
+ } else {
+ if ( size == 1 )
+ *ncp++ = *CHARP(cp, x, ix, iy);
+ else if ( size == 2 )
+ *nsp++ = *SHORTP(cp, x, ix, iy);
+ else
+ *nlp++ = *LONGP(cp, x, ix, iy);
+ }
+ }
+ }
+ return rv;
}
static PyObject *
imageop_scale(PyObject *self, PyObject *args)
{
- char *cp, *ncp;
- short *nsp;
- Py_Int32 *nlp;
- int len, size, x, y, newx, newy, nlen;
- int ix, iy;
- int oix, oiy;
- PyObject *rv;
-
- if ( !PyArg_ParseTuple(args, "s#iiiii",
- &cp, &len, &size, &x, &y, &newx, &newy) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(ImageopError, "Size should be 1, 2 or 4");
- return 0;
- }
- if ( !check_multiply_size(len, x, "x", y, "y", size) )
- return 0;
- nlen = newx*newy*size;
- if ( !check_multiply_size(nlen, newx, "newx", newy, "newy", size) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (char *)PyString_AsString(rv);
- nsp = (short *)ncp;
- nlp = (Py_Int32 *)ncp;
- for( iy = 0; iy < newy; iy++ ) {
- for ( ix = 0; ix < newx; ix++ ) {
- oix = ix * x / newx;
- oiy = iy * y / newy;
- if ( size == 1 )
- *ncp++ = *CHARP(cp, x, oix, oiy);
- else if ( size == 2 )
- *nsp++ = *SHORTP(cp, x, oix, oiy);
- else
- *nlp++ = *LONGP(cp, x, oix, oiy);
- }
- }
- return rv;
+ char *cp, *ncp;
+ short *nsp;
+ Py_Int32 *nlp;
+ int len, size, x, y, newx, newy, nlen;
+ int ix, iy;
+ int oix, oiy;
+ PyObject *rv;
+
+ if ( !PyArg_ParseTuple(args, "s#iiiii",
+ &cp, &len, &size, &x, &y, &newx, &newy) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(ImageopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ if ( !check_multiply_size(len, x, "x", y, "y", size) )
+ return 0;
+ nlen = newx*newy*size;
+ if ( !check_multiply_size(nlen, newx, "newx", newy, "newy", size) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (char *)PyString_AsString(rv);
+ nsp = (short *)ncp;
+ nlp = (Py_Int32 *)ncp;
+ for( iy = 0; iy < newy; iy++ ) {
+ for ( ix = 0; ix < newx; ix++ ) {
+ oix = ix * x / newx;
+ oiy = iy * y / newy;
+ if ( size == 1 )
+ *ncp++ = *CHARP(cp, x, oix, oiy);
+ else if ( size == 2 )
+ *nsp++ = *SHORTP(cp, x, oix, oiy);
+ else
+ *nlp++ = *LONGP(cp, x, oix, oiy);
+ }
+ }
+ return rv;
}
/* Note: this routine can use a bit of optimizing */
@@ -218,577 +218,577 @@ imageop_scale(PyObject *self, PyObject *args)
static PyObject *
imageop_tovideo(PyObject *self, PyObject *args)
{
- int maxx, maxy, x, y, len;
- int i;
- unsigned char *cp, *ncp;
- int width;
- PyObject *rv;
-
-
- if ( !PyArg_ParseTuple(args, "s#iii", &cp, &len, &width, &maxx, &maxy) )
- return 0;
-
- if ( width != 1 && width != 4 ) {
- PyErr_SetString(ImageopError, "Size should be 1 or 4");
- return 0;
- }
- if ( !check_multiply_size(len, maxx, "max", maxy, "maxy", width) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, len);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- if ( width == 1 ) {
- memcpy(ncp, cp, maxx); /* Copy first line */
- ncp += maxx;
- for (y=1; y<maxy; y++) { /* Interpolate other lines */
- for(x=0; x<maxx; x++) {
- i = y*maxx + x;
- *ncp++ = ((int)cp[i] + (int)cp[i-maxx]) >> 1;
- }
- }
- } else {
- memcpy(ncp, cp, maxx*4); /* Copy first line */
- ncp += maxx*4;
- for (y=1; y<maxy; y++) { /* Interpolate other lines */
- for(x=0; x<maxx; x++) {
- i = (y*maxx + x)*4 + 1;
- *ncp++ = 0; /* Skip alfa comp */
- *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
- i++;
- *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
- i++;
- *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
- }
- }
- }
- return rv;
+ int maxx, maxy, x, y, len;
+ int i;
+ unsigned char *cp, *ncp;
+ int width;
+ PyObject *rv;
+
+
+ if ( !PyArg_ParseTuple(args, "s#iii", &cp, &len, &width, &maxx, &maxy) )
+ return 0;
+
+ if ( width != 1 && width != 4 ) {
+ PyErr_SetString(ImageopError, "Size should be 1 or 4");
+ return 0;
+ }
+ if ( !check_multiply_size(len, maxx, "max", maxy, "maxy", width) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ if ( width == 1 ) {
+ memcpy(ncp, cp, maxx); /* Copy first line */
+ ncp += maxx;
+ for (y=1; y<maxy; y++) { /* Interpolate other lines */
+ for(x=0; x<maxx; x++) {
+ i = y*maxx + x;
+ *ncp++ = ((int)cp[i] + (int)cp[i-maxx]) >> 1;
+ }
+ }
+ } else {
+ memcpy(ncp, cp, maxx*4); /* Copy first line */
+ ncp += maxx*4;
+ for (y=1; y<maxy; y++) { /* Interpolate other lines */
+ for(x=0; x<maxx; x++) {
+ i = (y*maxx + x)*4 + 1;
+ *ncp++ = 0; /* Skip alfa comp */
+ *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
+ i++;
+ *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
+ i++;
+ *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
+ }
+ }
+ }
+ return rv;
}
static PyObject *
imageop_grey2mono(PyObject *self, PyObject *args)
{
- int tres, x, y, len;
- unsigned char *cp, *ncp;
- unsigned char ovalue;
- PyObject *rv;
- int i, bit;
-
-
- if ( !PyArg_ParseTuple(args, "s#iii", &cp, &len, &x, &y, &tres) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, (len+7)/8);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- bit = 0x80;
- ovalue = 0;
- for ( i=0; i < len; i++ ) {
- if ( (int)cp[i] > tres )
- ovalue |= bit;
- bit >>= 1;
- if ( bit == 0 ) {
- *ncp++ = ovalue;
- bit = 0x80;
- ovalue = 0;
- }
- }
- if ( bit != 0x80 )
- *ncp++ = ovalue;
- return rv;
+ int tres, x, y, len;
+ unsigned char *cp, *ncp;
+ unsigned char ovalue;
+ PyObject *rv;
+ int i, bit;
+
+
+ if ( !PyArg_ParseTuple(args, "s#iii", &cp, &len, &x, &y, &tres) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, (len+7)/8);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ bit = 0x80;
+ ovalue = 0;
+ for ( i=0; i < len; i++ ) {
+ if ( (int)cp[i] > tres )
+ ovalue |= bit;
+ bit >>= 1;
+ if ( bit == 0 ) {
+ *ncp++ = ovalue;
+ bit = 0x80;
+ ovalue = 0;
+ }
+ }
+ if ( bit != 0x80 )
+ *ncp++ = ovalue;
+ return rv;
}
static PyObject *
imageop_grey2grey4(PyObject *self, PyObject *args)
{
- int x, y, len;
- unsigned char *cp, *ncp;
- unsigned char ovalue;
- PyObject *rv;
- int i;
- int pos;
-
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, (len+1)/2);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
- pos = 0;
- ovalue = 0;
- for ( i=0; i < len; i++ ) {
- ovalue |= ((int)cp[i] & 0xf0) >> pos;
- pos += 4;
- if ( pos == 8 ) {
- *ncp++ = ovalue;
- ovalue = 0;
- pos = 0;
- }
- }
- if ( pos != 0 )
- *ncp++ = ovalue;
- return rv;
+ int x, y, len;
+ unsigned char *cp, *ncp;
+ unsigned char ovalue;
+ PyObject *rv;
+ int i;
+ int pos;
+
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, (len+1)/2);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+ pos = 0;
+ ovalue = 0;
+ for ( i=0; i < len; i++ ) {
+ ovalue |= ((int)cp[i] & 0xf0) >> pos;
+ pos += 4;
+ if ( pos == 8 ) {
+ *ncp++ = ovalue;
+ ovalue = 0;
+ pos = 0;
+ }
+ }
+ if ( pos != 0 )
+ *ncp++ = ovalue;
+ return rv;
}
static PyObject *
imageop_grey2grey2(PyObject *self, PyObject *args)
{
- int x, y, len;
- unsigned char *cp, *ncp;
- unsigned char ovalue;
- PyObject *rv;
- int i;
- int pos;
-
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, (len+3)/4);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
- pos = 0;
- ovalue = 0;
- for ( i=0; i < len; i++ ) {
- ovalue |= ((int)cp[i] & 0xc0) >> pos;
- pos += 2;
- if ( pos == 8 ) {
- *ncp++ = ovalue;
- ovalue = 0;
- pos = 0;
- }
- }
- if ( pos != 0 )
- *ncp++ = ovalue;
- return rv;
+ int x, y, len;
+ unsigned char *cp, *ncp;
+ unsigned char ovalue;
+ PyObject *rv;
+ int i;
+ int pos;
+
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, (len+3)/4);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+ pos = 0;
+ ovalue = 0;
+ for ( i=0; i < len; i++ ) {
+ ovalue |= ((int)cp[i] & 0xc0) >> pos;
+ pos += 2;
+ if ( pos == 8 ) {
+ *ncp++ = ovalue;
+ ovalue = 0;
+ pos = 0;
+ }
+ }
+ if ( pos != 0 )
+ *ncp++ = ovalue;
+ return rv;
}
static PyObject *
imageop_dither2mono(PyObject *self, PyObject *args)
{
- int sum, x, y, len;
- unsigned char *cp, *ncp;
- unsigned char ovalue;
- PyObject *rv;
- int i, bit;
-
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, (len+7)/8);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- bit = 0x80;
- ovalue = 0;
- sum = 0;
- for ( i=0; i < len; i++ ) {
- sum += cp[i];
- if ( sum >= 256 ) {
- sum -= 256;
- ovalue |= bit;
- }
- bit >>= 1;
- if ( bit == 0 ) {
- *ncp++ = ovalue;
- bit = 0x80;
- ovalue = 0;
- }
- }
- if ( bit != 0x80 )
- *ncp++ = ovalue;
- return rv;
+ int sum, x, y, len;
+ unsigned char *cp, *ncp;
+ unsigned char ovalue;
+ PyObject *rv;
+ int i, bit;
+
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, (len+7)/8);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ bit = 0x80;
+ ovalue = 0;
+ sum = 0;
+ for ( i=0; i < len; i++ ) {
+ sum += cp[i];
+ if ( sum >= 256 ) {
+ sum -= 256;
+ ovalue |= bit;
+ }
+ bit >>= 1;
+ if ( bit == 0 ) {
+ *ncp++ = ovalue;
+ bit = 0x80;
+ ovalue = 0;
+ }
+ }
+ if ( bit != 0x80 )
+ *ncp++ = ovalue;
+ return rv;
}
static PyObject *
imageop_dither2grey2(PyObject *self, PyObject *args)
{
- int x, y, len;
- unsigned char *cp, *ncp;
- unsigned char ovalue;
- PyObject *rv;
- int i;
- int pos;
- int sum = 0, nvalue;
-
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, (len+3)/4);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
- pos = 1;
- ovalue = 0;
- for ( i=0; i < len; i++ ) {
- sum += cp[i];
- nvalue = sum & 0x180;
- sum -= nvalue;
- ovalue |= nvalue >> pos;
- pos += 2;
- if ( pos == 9 ) {
- *ncp++ = ovalue;
- ovalue = 0;
- pos = 1;
- }
- }
- if ( pos != 0 )
- *ncp++ = ovalue;
- return rv;
+ int x, y, len;
+ unsigned char *cp, *ncp;
+ unsigned char ovalue;
+ PyObject *rv;
+ int i;
+ int pos;
+ int sum = 0, nvalue;
+
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, (len+3)/4);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+ pos = 1;
+ ovalue = 0;
+ for ( i=0; i < len; i++ ) {
+ sum += cp[i];
+ nvalue = sum & 0x180;
+ sum -= nvalue;
+ ovalue |= nvalue >> pos;
+ pos += 2;
+ if ( pos == 9 ) {
+ *ncp++ = ovalue;
+ ovalue = 0;
+ pos = 1;
+ }
+ }
+ if ( pos != 0 )
+ *ncp++ = ovalue;
+ return rv;
}
static PyObject *
imageop_mono2grey(PyObject *self, PyObject *args)
{
- int v0, v1, x, y, len, nlen;
- unsigned char *cp, *ncp;
- PyObject *rv;
- int i, bit;
-
- if ( !PyArg_ParseTuple(args, "s#iiii", &cp, &len, &x, &y, &v0, &v1) )
- return 0;
-
- nlen = x*y;
- if ( !check_multiply(nlen, x, y) )
- return 0;
- if ( (nlen+7)/8 != len ) {
- PyErr_SetString(ImageopError, "String has incorrect length");
- return 0;
- }
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- bit = 0x80;
- for ( i=0; i < nlen; i++ ) {
- if ( *cp & bit )
- *ncp++ = v1;
- else
- *ncp++ = v0;
- bit >>= 1;
- if ( bit == 0 ) {
- bit = 0x80;
- cp++;
- }
- }
- return rv;
+ int v0, v1, x, y, len, nlen;
+ unsigned char *cp, *ncp;
+ PyObject *rv;
+ int i, bit;
+
+ if ( !PyArg_ParseTuple(args, "s#iiii", &cp, &len, &x, &y, &v0, &v1) )
+ return 0;
+
+ nlen = x*y;
+ if ( !check_multiply(nlen, x, y) )
+ return 0;
+ if ( (nlen+7)/8 != len ) {
+ PyErr_SetString(ImageopError, "String has incorrect length");
+ return 0;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ bit = 0x80;
+ for ( i=0; i < nlen; i++ ) {
+ if ( *cp & bit )
+ *ncp++ = v1;
+ else
+ *ncp++ = v0;
+ bit >>= 1;
+ if ( bit == 0 ) {
+ bit = 0x80;
+ cp++;
+ }
+ }
+ return rv;
}
static PyObject *
imageop_grey22grey(PyObject *self, PyObject *args)
{
- int x, y, len, nlen;
- unsigned char *cp, *ncp;
- PyObject *rv;
- int i, pos, value = 0, nvalue;
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- nlen = x*y;
- if ( !check_multiply(nlen, x, y) ) {
- return 0;
- }
- if ( (nlen+3)/4 != len ) {
- PyErr_SetString(ImageopError, "String has incorrect length");
- return 0;
- }
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- pos = 0;
- for ( i=0; i < nlen; i++ ) {
- if ( pos == 0 ) {
- value = *cp++;
- pos = 8;
- }
- pos -= 2;
- nvalue = (value >> pos) & 0x03;
- *ncp++ = nvalue | (nvalue << 2) |
- (nvalue << 4) | (nvalue << 6);
- }
- return rv;
+ int x, y, len, nlen;
+ unsigned char *cp, *ncp;
+ PyObject *rv;
+ int i, pos, value = 0, nvalue;
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ nlen = x*y;
+ if ( !check_multiply(nlen, x, y) ) {
+ return 0;
+ }
+ if ( (nlen+3)/4 != len ) {
+ PyErr_SetString(ImageopError, "String has incorrect length");
+ return 0;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ pos = 0;
+ for ( i=0; i < nlen; i++ ) {
+ if ( pos == 0 ) {
+ value = *cp++;
+ pos = 8;
+ }
+ pos -= 2;
+ nvalue = (value >> pos) & 0x03;
+ *ncp++ = nvalue | (nvalue << 2) |
+ (nvalue << 4) | (nvalue << 6);
+ }
+ return rv;
}
static PyObject *
imageop_grey42grey(PyObject *self, PyObject *args)
{
- int x, y, len, nlen;
- unsigned char *cp, *ncp;
- PyObject *rv;
- int i, pos, value = 0, nvalue;
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- nlen = x*y;
- if ( !check_multiply(nlen, x, y) )
- return 0;
- if ( (nlen+1)/2 != len ) {
- PyErr_SetString(ImageopError, "String has incorrect length");
- return 0;
- }
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- pos = 0;
- for ( i=0; i < nlen; i++ ) {
- if ( pos == 0 ) {
- value = *cp++;
- pos = 8;
- }
- pos -= 4;
- nvalue = (value >> pos) & 0x0f;
- *ncp++ = nvalue | (nvalue << 4);
- }
- return rv;
+ int x, y, len, nlen;
+ unsigned char *cp, *ncp;
+ PyObject *rv;
+ int i, pos, value = 0, nvalue;
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ nlen = x*y;
+ if ( !check_multiply(nlen, x, y) )
+ return 0;
+ if ( (nlen+1)/2 != len ) {
+ PyErr_SetString(ImageopError, "String has incorrect length");
+ return 0;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ pos = 0;
+ for ( i=0; i < nlen; i++ ) {
+ if ( pos == 0 ) {
+ value = *cp++;
+ pos = 8;
+ }
+ pos -= 4;
+ nvalue = (value >> pos) & 0x0f;
+ *ncp++ = nvalue | (nvalue << 4);
+ }
+ return rv;
}
static PyObject *
imageop_rgb2rgb8(PyObject *self, PyObject *args)
{
- int x, y, len, nlen;
- unsigned char *cp;
- unsigned char *ncp;
- PyObject *rv;
- int i, r, g, b;
- int backward_compatible = imageop_backward_compatible();
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply_size(len, x, "x", y, "y", 4) )
- return 0;
- nlen = x*y;
- if ( !check_multiply(nlen, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- for ( i=0; i < nlen; i++ ) {
- /* Bits in source: aaaaaaaa BBbbbbbb GGGggggg RRRrrrrr */
- if (backward_compatible) {
- Py_UInt32 value = * (Py_UInt32 *) cp;
- cp += 4;
- r = (int) ((value & 0xff) / 255. * 7. + .5);
- g = (int) (((value >> 8) & 0xff) / 255. * 7. + .5);
- b = (int) (((value >> 16) & 0xff) / 255. * 3. + .5);
- } else {
- cp++; /* skip alpha channel */
- b = (int) (*cp++ / 255. * 3. + .5);
- g = (int) (*cp++ / 255. * 7. + .5);
- r = (int) (*cp++ / 255. * 7. + .5);
- }
- *ncp++ = (unsigned char)((r<<5) | (b<<3) | g);
- }
- return rv;
+ int x, y, len, nlen;
+ unsigned char *cp;
+ unsigned char *ncp;
+ PyObject *rv;
+ int i, r, g, b;
+ int backward_compatible = imageop_backward_compatible();
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply_size(len, x, "x", y, "y", 4) )
+ return 0;
+ nlen = x*y;
+ if ( !check_multiply(nlen, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ for ( i=0; i < nlen; i++ ) {
+ /* Bits in source: aaaaaaaa BBbbbbbb GGGggggg RRRrrrrr */
+ if (backward_compatible) {
+ Py_UInt32 value = * (Py_UInt32 *) cp;
+ cp += 4;
+ r = (int) ((value & 0xff) / 255. * 7. + .5);
+ g = (int) (((value >> 8) & 0xff) / 255. * 7. + .5);
+ b = (int) (((value >> 16) & 0xff) / 255. * 3. + .5);
+ } else {
+ cp++; /* skip alpha channel */
+ b = (int) (*cp++ / 255. * 3. + .5);
+ g = (int) (*cp++ / 255. * 7. + .5);
+ r = (int) (*cp++ / 255. * 7. + .5);
+ }
+ *ncp++ = (unsigned char)((r<<5) | (b<<3) | g);
+ }
+ return rv;
}
static PyObject *
imageop_rgb82rgb(PyObject *self, PyObject *args)
{
- int x, y, len, nlen;
- unsigned char *cp;
- unsigned char *ncp;
- PyObject *rv;
- int i, r, g, b;
- unsigned char value;
- int backward_compatible = imageop_backward_compatible();
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
- nlen = x*y*4;
- if ( !check_multiply_size(nlen, x, "x", y, "y", 4) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- for ( i=0; i < len; i++ ) {
- /* Bits in source: RRRBBGGG
- ** Red and Green are multiplied by 36.5, Blue by 85
- */
- value = *cp++;
- r = (value >> 5) & 7;
- g = (value ) & 7;
- b = (value >> 3) & 3;
- r = (r<<5) | (r<<3) | (r>>1);
- g = (g<<5) | (g<<3) | (g>>1);
- b = (b<<6) | (b<<4) | (b<<2) | b;
- if (backward_compatible) {
- Py_UInt32 nvalue = r | (g<<8) | (b<<16);
- * (Py_UInt32 *) ncp = nvalue;
- ncp += 4;
- } else {
- *ncp++ = 0;
- *ncp++ = b;
- *ncp++ = g;
- *ncp++ = r;
- }
- }
- return rv;
+ int x, y, len, nlen;
+ unsigned char *cp;
+ unsigned char *ncp;
+ PyObject *rv;
+ int i, r, g, b;
+ unsigned char value;
+ int backward_compatible = imageop_backward_compatible();
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+ nlen = x*y*4;
+ if ( !check_multiply_size(nlen, x, "x", y, "y", 4) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ for ( i=0; i < len; i++ ) {
+ /* Bits in source: RRRBBGGG
+ ** Red and Green are multiplied by 36.5, Blue by 85
+ */
+ value = *cp++;
+ r = (value >> 5) & 7;
+ g = (value ) & 7;
+ b = (value >> 3) & 3;
+ r = (r<<5) | (r<<3) | (r>>1);
+ g = (g<<5) | (g<<3) | (g>>1);
+ b = (b<<6) | (b<<4) | (b<<2) | b;
+ if (backward_compatible) {
+ Py_UInt32 nvalue = r | (g<<8) | (b<<16);
+ * (Py_UInt32 *) ncp = nvalue;
+ ncp += 4;
+ } else {
+ *ncp++ = 0;
+ *ncp++ = b;
+ *ncp++ = g;
+ *ncp++ = r;
+ }
+ }
+ return rv;
}
static PyObject *
imageop_rgb2grey(PyObject *self, PyObject *args)
{
- int x, y, len, nlen;
- unsigned char *cp;
- unsigned char *ncp;
- PyObject *rv;
- int i, r, g, b;
- int nvalue;
- int backward_compatible = imageop_backward_compatible();
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply_size(len, x, "x", y, "y", 4) )
- return 0;
- nlen = x*y;
- if ( !check_multiply(nlen, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- for ( i=0; i < nlen; i++ ) {
- if (backward_compatible) {
- Py_UInt32 value = * (Py_UInt32 *) cp;
- cp += 4;
- r = (int) ((value & 0xff) / 255. * 7. + .5);
- g = (int) (((value >> 8) & 0xff) / 255. * 7. + .5);
- b = (int) (((value >> 16) & 0xff) / 255. * 3. + .5);
- } else {
- cp++; /* skip alpha channel */
- b = *cp++;
- g = *cp++;
- r = *cp++;
- }
- nvalue = (int)(0.30*r + 0.59*g + 0.11*b);
- if ( nvalue > 255 ) nvalue = 255;
- *ncp++ = (unsigned char)nvalue;
- }
- return rv;
+ int x, y, len, nlen;
+ unsigned char *cp;
+ unsigned char *ncp;
+ PyObject *rv;
+ int i, r, g, b;
+ int nvalue;
+ int backward_compatible = imageop_backward_compatible();
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply_size(len, x, "x", y, "y", 4) )
+ return 0;
+ nlen = x*y;
+ if ( !check_multiply(nlen, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ for ( i=0; i < nlen; i++ ) {
+ if (backward_compatible) {
+ Py_UInt32 value = * (Py_UInt32 *) cp;
+ cp += 4;
+ r = (int) ((value & 0xff) / 255. * 7. + .5);
+ g = (int) (((value >> 8) & 0xff) / 255. * 7. + .5);
+ b = (int) (((value >> 16) & 0xff) / 255. * 3. + .5);
+ } else {
+ cp++; /* skip alpha channel */
+ b = *cp++;
+ g = *cp++;
+ r = *cp++;
+ }
+ nvalue = (int)(0.30*r + 0.59*g + 0.11*b);
+ if ( nvalue > 255 ) nvalue = 255;
+ *ncp++ = (unsigned char)nvalue;
+ }
+ return rv;
}
static PyObject *
imageop_grey2rgb(PyObject *self, PyObject *args)
{
- int x, y, len, nlen;
- unsigned char *cp;
- unsigned char *ncp;
- PyObject *rv;
- int i;
- unsigned char value;
- int backward_compatible = imageop_backward_compatible();
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
- nlen = x*y*4;
- if ( !check_multiply_size(nlen, x, "x", y, "y", 4) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- for ( i=0; i < len; i++ ) {
- value = *cp++;
- if (backward_compatible) {
- * (Py_UInt32 *) ncp = (Py_UInt32) value | ((Py_UInt32) value << 8 ) | ((Py_UInt32) value << 16);
- ncp += 4;
- } else {
- *ncp++ = 0;
- *ncp++ = value;
- *ncp++ = value;
- *ncp++ = value;
- }
- }
- return rv;
+ int x, y, len, nlen;
+ unsigned char *cp;
+ unsigned char *ncp;
+ PyObject *rv;
+ int i;
+ unsigned char value;
+ int backward_compatible = imageop_backward_compatible();
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+ nlen = x*y*4;
+ if ( !check_multiply_size(nlen, x, "x", y, "y", 4) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ for ( i=0; i < len; i++ ) {
+ value = *cp++;
+ if (backward_compatible) {
+ * (Py_UInt32 *) ncp = (Py_UInt32) value | ((Py_UInt32) value << 8 ) | ((Py_UInt32) value << 16);
+ ncp += 4;
+ } else {
+ *ncp++ = 0;
+ *ncp++ = value;
+ *ncp++ = value;
+ *ncp++ = value;
+ }
+ }
+ return rv;
}
static PyMethodDef imageop_methods[] = {
- { "crop", imageop_crop, METH_VARARGS },
- { "scale", imageop_scale, METH_VARARGS },
- { "grey2mono", imageop_grey2mono, METH_VARARGS },
- { "grey2grey2", imageop_grey2grey2, METH_VARARGS },
- { "grey2grey4", imageop_grey2grey4, METH_VARARGS },
- { "dither2mono", imageop_dither2mono, METH_VARARGS },
- { "dither2grey2", imageop_dither2grey2, METH_VARARGS },
- { "mono2grey", imageop_mono2grey, METH_VARARGS },
- { "grey22grey", imageop_grey22grey, METH_VARARGS },
- { "grey42grey", imageop_grey42grey, METH_VARARGS },
- { "tovideo", imageop_tovideo, METH_VARARGS },
- { "rgb2rgb8", imageop_rgb2rgb8, METH_VARARGS },
- { "rgb82rgb", imageop_rgb82rgb, METH_VARARGS },
- { "rgb2grey", imageop_rgb2grey, METH_VARARGS },
- { "grey2rgb", imageop_grey2rgb, METH_VARARGS },
- { 0, 0 }
+ { "crop", imageop_crop, METH_VARARGS },
+ { "scale", imageop_scale, METH_VARARGS },
+ { "grey2mono", imageop_grey2mono, METH_VARARGS },
+ { "grey2grey2", imageop_grey2grey2, METH_VARARGS },
+ { "grey2grey4", imageop_grey2grey4, METH_VARARGS },
+ { "dither2mono", imageop_dither2mono, METH_VARARGS },
+ { "dither2grey2", imageop_dither2grey2, METH_VARARGS },
+ { "mono2grey", imageop_mono2grey, METH_VARARGS },
+ { "grey22grey", imageop_grey22grey, METH_VARARGS },
+ { "grey42grey", imageop_grey42grey, METH_VARARGS },
+ { "tovideo", imageop_tovideo, METH_VARARGS },
+ { "rgb2rgb8", imageop_rgb2rgb8, METH_VARARGS },
+ { "rgb82rgb", imageop_rgb82rgb, METH_VARARGS },
+ { "rgb2grey", imageop_rgb2grey, METH_VARARGS },
+ { "grey2rgb", imageop_grey2rgb, METH_VARARGS },
+ { 0, 0 }
};
PyMODINIT_FUNC
initimageop(void)
{
- PyObject *m;
-
- if (PyErr_WarnPy3k("the imageop module has been removed in "
- "Python 3.0", 2) < 0)
- return;
-
- m = Py_InitModule("imageop", imageop_methods);
- if (m == NULL)
- return;
- ImageopDict = PyModule_GetDict(m);
- ImageopError = PyErr_NewException("imageop.error", NULL, NULL);
- if (ImageopError != NULL)
- PyDict_SetItemString(ImageopDict, "error", ImageopError);
+ PyObject *m;
+
+ if (PyErr_WarnPy3k("the imageop module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
+
+ m = Py_InitModule("imageop", imageop_methods);
+ if (m == NULL)
+ return;
+ ImageopDict = PyModule_GetDict(m);
+ ImageopError = PyErr_NewException("imageop.error", NULL, NULL);
+ if (ImageopError != NULL)
+ PyDict_SetItemString(ImageopDict, "error", ImageopError);
}
diff --git a/Modules/imgfile.c b/Modules/imgfile.c
index baa6ead..70d307b 100644
--- a/Modules/imgfile.c
+++ b/Modules/imgfile.c
@@ -25,7 +25,7 @@ extern void getrow();
static PyObject * ImgfileError; /* Exception we raise for various trouble */
-static int top_to_bottom; /* True if we want top-to-bottom images */
+static int top_to_bottom; /* True if we want top-to-bottom images */
/* The image library does not always call the error hander :-(,
therefore we have a global variable indicating that it was called.
@@ -39,9 +39,9 @@ static int error_called;
static void
imgfile_error(char *str)
{
- PyErr_SetString(ImgfileError, str);
- error_called = 1;
- return; /* To imglib, which will return a failure indicator */
+ PyErr_SetString(ImgfileError, str);
+ error_called = 1;
+ return; /* To imglib, which will return a failure indicator */
}
@@ -51,123 +51,123 @@ imgfile_error(char *str)
static IMAGE *
imgfile_open(char *fname)
{
- IMAGE *image;
- i_seterror(imgfile_error);
- error_called = 0;
- errno = 0;
- if ( (image = iopen(fname, "r")) == NULL ) {
- /* Error may already be set by imgfile_error */
- if ( !error_called ) {
- if (errno)
- PyErr_SetFromErrno(ImgfileError);
- else
- PyErr_SetString(ImgfileError,
- "Can't open image file");
- }
- return NULL;
- }
- return image;
+ IMAGE *image;
+ i_seterror(imgfile_error);
+ error_called = 0;
+ errno = 0;
+ if ( (image = iopen(fname, "r")) == NULL ) {
+ /* Error may already be set by imgfile_error */
+ if ( !error_called ) {
+ if (errno)
+ PyErr_SetFromErrno(ImgfileError);
+ else
+ PyErr_SetString(ImgfileError,
+ "Can't open image file");
+ }
+ return NULL;
+ }
+ return image;
}
static PyObject *
imgfile_ttob(PyObject *self, PyObject *args)
{
- int newval;
- PyObject *rv;
-
- if (!PyArg_ParseTuple(args, "i:ttob", &newval))
- return NULL;
- rv = PyInt_FromLong(top_to_bottom);
- top_to_bottom = newval;
- return rv;
+ int newval;
+ PyObject *rv;
+
+ if (!PyArg_ParseTuple(args, "i:ttob", &newval))
+ return NULL;
+ rv = PyInt_FromLong(top_to_bottom);
+ top_to_bottom = newval;
+ return rv;
}
static PyObject *
imgfile_read(PyObject *self, PyObject *args)
{
- char *fname;
- PyObject *rv;
- int xsize, ysize, zsize;
- char *cdatap;
- long *idatap;
- static short rs[8192], gs[8192], bs[8192];
- int x, y;
- IMAGE *image;
- int yfirst, ylast, ystep;
-
- if ( !PyArg_ParseTuple(args, "s:read", &fname) )
- return NULL;
-
- if ( (image = imgfile_open(fname)) == NULL )
- return NULL;
-
- if ( image->colormap != CM_NORMAL ) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can only handle CM_NORMAL images");
- return NULL;
- }
- if ( BPP(image->type) != 1 ) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can't handle imgfiles with bpp!=1");
- return NULL;
- }
- xsize = image->xsize;
- ysize = image->ysize;
- zsize = image->zsize;
- if ( zsize != 1 && zsize != 3) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can only handle 1 or 3 byte pixels");
- return NULL;
- }
- if ( xsize > 8192 ) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can't handle image with > 8192 columns");
- return NULL;
- }
-
- if ( zsize == 3 ) zsize = 4;
- rv = PyString_FromStringAndSize((char *)NULL, xsize*ysize*zsize);
- if ( rv == NULL ) {
- iclose(image);
- return NULL;
- }
- cdatap = PyString_AsString(rv);
- idatap = (long *)cdatap;
-
- if (top_to_bottom) {
- yfirst = ysize-1;
- ylast = -1;
- ystep = -1;
- } else {
- yfirst = 0;
- ylast = ysize;
- ystep = 1;
- }
- for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
- if ( zsize == 1 ) {
- getrow(image, rs, y, 0);
- for(x=0; x<xsize; x++ )
- *cdatap++ = rs[x];
- } else {
- getrow(image, rs, y, 0);
- getrow(image, gs, y, 1);
- getrow(image, bs, y, 2);
- for(x=0; x<xsize; x++ )
- *idatap++ = (rs[x] & 0xff) |
- ((gs[x] & 0xff)<<8) |
- ((bs[x] & 0xff)<<16);
- }
- }
- iclose(image);
- if ( error_called ) {
- Py_DECREF(rv);
- return NULL;
- }
- return rv;
+ char *fname;
+ PyObject *rv;
+ int xsize, ysize, zsize;
+ char *cdatap;
+ long *idatap;
+ static short rs[8192], gs[8192], bs[8192];
+ int x, y;
+ IMAGE *image;
+ int yfirst, ylast, ystep;
+
+ if ( !PyArg_ParseTuple(args, "s:read", &fname) )
+ return NULL;
+
+ if ( (image = imgfile_open(fname)) == NULL )
+ return NULL;
+
+ if ( image->colormap != CM_NORMAL ) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can only handle CM_NORMAL images");
+ return NULL;
+ }
+ if ( BPP(image->type) != 1 ) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can't handle imgfiles with bpp!=1");
+ return NULL;
+ }
+ xsize = image->xsize;
+ ysize = image->ysize;
+ zsize = image->zsize;
+ if ( zsize != 1 && zsize != 3) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can only handle 1 or 3 byte pixels");
+ return NULL;
+ }
+ if ( xsize > 8192 ) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can't handle image with > 8192 columns");
+ return NULL;
+ }
+
+ if ( zsize == 3 ) zsize = 4;
+ rv = PyString_FromStringAndSize((char *)NULL, xsize*ysize*zsize);
+ if ( rv == NULL ) {
+ iclose(image);
+ return NULL;
+ }
+ cdatap = PyString_AsString(rv);
+ idatap = (long *)cdatap;
+
+ if (top_to_bottom) {
+ yfirst = ysize-1;
+ ylast = -1;
+ ystep = -1;
+ } else {
+ yfirst = 0;
+ ylast = ysize;
+ ystep = 1;
+ }
+ for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
+ if ( zsize == 1 ) {
+ getrow(image, rs, y, 0);
+ for(x=0; x<xsize; x++ )
+ *cdatap++ = rs[x];
+ } else {
+ getrow(image, rs, y, 0);
+ getrow(image, gs, y, 1);
+ getrow(image, bs, y, 2);
+ for(x=0; x<xsize; x++ )
+ *idatap++ = (rs[x] & 0xff) |
+ ((gs[x] & 0xff)<<8) |
+ ((bs[x] & 0xff)<<16);
+ }
+ }
+ iclose(image);
+ if ( error_called ) {
+ Py_DECREF(rv);
+ return NULL;
+ }
+ return rv;
}
static IMAGE *glob_image;
@@ -177,332 +177,332 @@ static int glob_width, glob_z, glob_ysize;
static void
xs_get(short *buf, int y)
{
- if (top_to_bottom)
- getrow(glob_image, buf, (glob_ysize-1-y), glob_z);
- else
- getrow(glob_image, buf, y, glob_z);
+ if (top_to_bottom)
+ getrow(glob_image, buf, (glob_ysize-1-y), glob_z);
+ else
+ getrow(glob_image, buf, y, glob_z);
}
static void
xs_put_c(short *buf, int y)
{
- char *datap = (char *)glob_datap + y*glob_width;
- int width = glob_width;
+ char *datap = (char *)glob_datap + y*glob_width;
+ int width = glob_width;
- while ( width-- )
- *datap++ = (*buf++) & 0xff;
+ while ( width-- )
+ *datap++ = (*buf++) & 0xff;
}
static void
xs_put_0(short *buf, int y)
{
- long *datap = glob_datap + y*glob_width;
- int width = glob_width;
+ long *datap = glob_datap + y*glob_width;
+ int width = glob_width;
- while ( width-- )
- *datap++ = (*buf++) & 0xff;
+ while ( width-- )
+ *datap++ = (*buf++) & 0xff;
}
static void
xs_put_12(short *buf, int y)
{
- long *datap = glob_datap + y*glob_width;
- int width = glob_width;
+ long *datap = glob_datap + y*glob_width;
+ int width = glob_width;
- while ( width-- )
- *datap++ |= ((*buf++) & 0xff) << (glob_z*8);
+ while ( width-- )
+ *datap++ |= ((*buf++) & 0xff) << (glob_z*8);
}
static void
xscale(IMAGE *image, int xsize, int ysize, int zsize,
long *datap, int xnew, int ynew, int fmode, double blur)
{
- glob_image = image;
- glob_datap = datap;
- glob_width = xnew;
- glob_ysize = ysize;
- if ( zsize == 1 ) {
- glob_z = 0;
- filterzoom(xs_get, xs_put_c, xsize, ysize,
- xnew, ynew, fmode, blur);
- } else {
- glob_z = 0;
- filterzoom(xs_get, xs_put_0, xsize, ysize,
- xnew, ynew, fmode, blur);
- glob_z = 1;
- filterzoom(xs_get, xs_put_12, xsize, ysize,
- xnew, ynew, fmode, blur);
- glob_z = 2;
- filterzoom(xs_get, xs_put_12, xsize, ysize,
- xnew, ynew, fmode, blur);
- }
+ glob_image = image;
+ glob_datap = datap;
+ glob_width = xnew;
+ glob_ysize = ysize;
+ if ( zsize == 1 ) {
+ glob_z = 0;
+ filterzoom(xs_get, xs_put_c, xsize, ysize,
+ xnew, ynew, fmode, blur);
+ } else {
+ glob_z = 0;
+ filterzoom(xs_get, xs_put_0, xsize, ysize,
+ xnew, ynew, fmode, blur);
+ glob_z = 1;
+ filterzoom(xs_get, xs_put_12, xsize, ysize,
+ xnew, ynew, fmode, blur);
+ glob_z = 2;
+ filterzoom(xs_get, xs_put_12, xsize, ysize,
+ xnew, ynew, fmode, blur);
+ }
}
static PyObject *
imgfile_readscaled(PyObject *self, PyObject *args)
{
- char *fname;
- PyObject *rv;
- int xsize, ysize, zsize;
- char *cdatap;
- long *idatap;
- static short rs[8192], gs[8192], bs[8192];
- int x, y;
- int xwtd, ywtd, xorig, yorig;
- float xfac, yfac;
- IMAGE *image;
- char *filter;
- double blur = 1.0;
- int extended;
- int fmode = 0;
- int yfirst, ylast, ystep;
-
- /*
- ** Parse args. Funny, since arg 4 and 5 are optional
- ** (filter name and blur factor). Also, 4 or 5 arguments indicates
- ** extended scale algorithm in stead of simple-minded pixel drop/dup.
- */
- extended = PyTuple_Size(args) >= 4;
- if ( !PyArg_ParseTuple(args, "sii|sd",
- &fname, &xwtd, &ywtd, &filter, &blur) )
- return NULL;
-
- /*
- ** Check parameters, open file and check type, rows, etc.
- */
- if ( extended ) {
- if ( strcmp(filter, "impulse") == 0 )
- fmode = IMPULSE;
- else if ( strcmp( filter, "box") == 0 )
- fmode = BOX;
- else if ( strcmp( filter, "triangle") == 0 )
- fmode = TRIANGLE;
- else if ( strcmp( filter, "quadratic") == 0 )
- fmode = QUADRATIC;
- else if ( strcmp( filter, "gaussian") == 0 )
- fmode = GAUSSIAN;
- else {
- PyErr_SetString(ImgfileError, "Unknown filter type");
- return NULL;
- }
- }
-
- if ( (image = imgfile_open(fname)) == NULL )
- return NULL;
-
- if ( image->colormap != CM_NORMAL ) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can only handle CM_NORMAL images");
- return NULL;
- }
- if ( BPP(image->type) != 1 ) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can't handle imgfiles with bpp!=1");
- return NULL;
- }
- xsize = image->xsize;
- ysize = image->ysize;
- zsize = image->zsize;
- if ( zsize != 1 && zsize != 3) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can only handle 1 or 3 byte pixels");
- return NULL;
- }
- if ( xsize > 8192 ) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can't handle image with > 8192 columns");
- return NULL;
- }
-
- if ( zsize == 3 ) zsize = 4;
- rv = PyString_FromStringAndSize(NULL, xwtd*ywtd*zsize);
- if ( rv == NULL ) {
- iclose(image);
- return NULL;
- }
- PyFPE_START_PROTECT("readscaled", return 0)
- xfac = (float)xsize/(float)xwtd;
- yfac = (float)ysize/(float)ywtd;
- PyFPE_END_PROTECT(yfac)
- cdatap = PyString_AsString(rv);
- idatap = (long *)cdatap;
-
- if ( extended ) {
- xscale(image, xsize, ysize, zsize,
- idatap, xwtd, ywtd, fmode, blur);
- } else {
- if (top_to_bottom) {
- yfirst = ywtd-1;
- ylast = -1;
- ystep = -1;
- } else {
- yfirst = 0;
- ylast = ywtd;
- ystep = 1;
- }
- for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
- yorig = (int)(y*yfac);
- if ( zsize == 1 ) {
- getrow(image, rs, yorig, 0);
- for(x=0; x<xwtd; x++ ) {
- *cdatap++ = rs[(int)(x*xfac)];
- }
- } else {
- getrow(image, rs, yorig, 0);
- getrow(image, gs, yorig, 1);
- getrow(image, bs, yorig, 2);
- for(x=0; x<xwtd; x++ ) {
- xorig = (int)(x*xfac);
- *idatap++ = (rs[xorig] & 0xff) |
- ((gs[xorig] & 0xff)<<8) |
- ((bs[xorig] & 0xff)<<16);
- }
- }
- }
- }
- iclose(image);
- if ( error_called ) {
- Py_DECREF(rv);
- return NULL;
- }
- return rv;
+ char *fname;
+ PyObject *rv;
+ int xsize, ysize, zsize;
+ char *cdatap;
+ long *idatap;
+ static short rs[8192], gs[8192], bs[8192];
+ int x, y;
+ int xwtd, ywtd, xorig, yorig;
+ float xfac, yfac;
+ IMAGE *image;
+ char *filter;
+ double blur = 1.0;
+ int extended;
+ int fmode = 0;
+ int yfirst, ylast, ystep;
+
+ /*
+ ** Parse args. Funny, since arg 4 and 5 are optional
+ ** (filter name and blur factor). Also, 4 or 5 arguments indicates
+ ** extended scale algorithm in stead of simple-minded pixel drop/dup.
+ */
+ extended = PyTuple_Size(args) >= 4;
+ if ( !PyArg_ParseTuple(args, "sii|sd",
+ &fname, &xwtd, &ywtd, &filter, &blur) )
+ return NULL;
+
+ /*
+ ** Check parameters, open file and check type, rows, etc.
+ */
+ if ( extended ) {
+ if ( strcmp(filter, "impulse") == 0 )
+ fmode = IMPULSE;
+ else if ( strcmp( filter, "box") == 0 )
+ fmode = BOX;
+ else if ( strcmp( filter, "triangle") == 0 )
+ fmode = TRIANGLE;
+ else if ( strcmp( filter, "quadratic") == 0 )
+ fmode = QUADRATIC;
+ else if ( strcmp( filter, "gaussian") == 0 )
+ fmode = GAUSSIAN;
+ else {
+ PyErr_SetString(ImgfileError, "Unknown filter type");
+ return NULL;
+ }
+ }
+
+ if ( (image = imgfile_open(fname)) == NULL )
+ return NULL;
+
+ if ( image->colormap != CM_NORMAL ) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can only handle CM_NORMAL images");
+ return NULL;
+ }
+ if ( BPP(image->type) != 1 ) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can't handle imgfiles with bpp!=1");
+ return NULL;
+ }
+ xsize = image->xsize;
+ ysize = image->ysize;
+ zsize = image->zsize;
+ if ( zsize != 1 && zsize != 3) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can only handle 1 or 3 byte pixels");
+ return NULL;
+ }
+ if ( xsize > 8192 ) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can't handle image with > 8192 columns");
+ return NULL;
+ }
+
+ if ( zsize == 3 ) zsize = 4;
+ rv = PyString_FromStringAndSize(NULL, xwtd*ywtd*zsize);
+ if ( rv == NULL ) {
+ iclose(image);
+ return NULL;
+ }
+ PyFPE_START_PROTECT("readscaled", return 0)
+ xfac = (float)xsize/(float)xwtd;
+ yfac = (float)ysize/(float)ywtd;
+ PyFPE_END_PROTECT(yfac)
+ cdatap = PyString_AsString(rv);
+ idatap = (long *)cdatap;
+
+ if ( extended ) {
+ xscale(image, xsize, ysize, zsize,
+ idatap, xwtd, ywtd, fmode, blur);
+ } else {
+ if (top_to_bottom) {
+ yfirst = ywtd-1;
+ ylast = -1;
+ ystep = -1;
+ } else {
+ yfirst = 0;
+ ylast = ywtd;
+ ystep = 1;
+ }
+ for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
+ yorig = (int)(y*yfac);
+ if ( zsize == 1 ) {
+ getrow(image, rs, yorig, 0);
+ for(x=0; x<xwtd; x++ ) {
+ *cdatap++ = rs[(int)(x*xfac)];
+ }
+ } else {
+ getrow(image, rs, yorig, 0);
+ getrow(image, gs, yorig, 1);
+ getrow(image, bs, yorig, 2);
+ for(x=0; x<xwtd; x++ ) {
+ xorig = (int)(x*xfac);
+ *idatap++ = (rs[xorig] & 0xff) |
+ ((gs[xorig] & 0xff)<<8) |
+ ((bs[xorig] & 0xff)<<16);
+ }
+ }
+ }
+ }
+ iclose(image);
+ if ( error_called ) {
+ Py_DECREF(rv);
+ return NULL;
+ }
+ return rv;
}
static PyObject *
imgfile_getsizes(PyObject *self, PyObject *args)
{
- char *fname;
- PyObject *rv;
- IMAGE *image;
-
- if ( !PyArg_ParseTuple(args, "s:getsizes", &fname) )
- return NULL;
-
- if ( (image = imgfile_open(fname)) == NULL )
- return NULL;
- rv = Py_BuildValue("(iii)", image->xsize, image->ysize, image->zsize);
- iclose(image);
- return rv;
+ char *fname;
+ PyObject *rv;
+ IMAGE *image;
+
+ if ( !PyArg_ParseTuple(args, "s:getsizes", &fname) )
+ return NULL;
+
+ if ( (image = imgfile_open(fname)) == NULL )
+ return NULL;
+ rv = Py_BuildValue("(iii)", image->xsize, image->ysize, image->zsize);
+ iclose(image);
+ return rv;
}
static PyObject *
imgfile_write(PyObject *self, PyObject *args)
{
- IMAGE *image;
- char *fname;
- int xsize, ysize, zsize, len;
- char *cdatap;
- long *idatap;
- short rs[8192], gs[8192], bs[8192];
- short r, g, b;
- long rgb;
- int x, y;
- int yfirst, ylast, ystep;
-
-
- if ( !PyArg_ParseTuple(args, "ss#iii:write",
- &fname, &cdatap, &len, &xsize, &ysize, &zsize) )
- return NULL;
-
- if ( zsize != 1 && zsize != 3 ) {
- PyErr_SetString(ImgfileError,
- "Can only handle 1 or 3 byte pixels");
- return NULL;
- }
- if ( len != xsize * ysize * (zsize == 1 ? 1 : 4) ) {
- PyErr_SetString(ImgfileError, "Data does not match sizes");
- return NULL;
- }
- if ( xsize > 8192 ) {
- PyErr_SetString(ImgfileError,
- "Can't handle image with > 8192 columns");
- return NULL;
- }
-
- error_called = 0;
- errno = 0;
- image =iopen(fname, "w", RLE(1), 3, xsize, ysize, zsize);
- if ( image == 0 ) {
- if ( ! error_called ) {
- if (errno)
- PyErr_SetFromErrno(ImgfileError);
- else
- PyErr_SetString(ImgfileError,
- "Can't create image file");
- }
- return NULL;
- }
-
- idatap = (long *)cdatap;
-
- if (top_to_bottom) {
- yfirst = ysize-1;
- ylast = -1;
- ystep = -1;
- } else {
- yfirst = 0;
- ylast = ysize;
- ystep = 1;
- }
- for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
- if ( zsize == 1 ) {
- for( x=0; x<xsize; x++ )
- rs[x] = *cdatap++;
- putrow(image, rs, y, 0);
- } else {
- for( x=0; x<xsize; x++ ) {
- rgb = *idatap++;
- r = rgb & 0xff;
- g = (rgb >> 8 ) & 0xff;
- b = (rgb >> 16 ) & 0xff;
- rs[x] = r;
- gs[x] = g;
- bs[x] = b;
- }
- putrow(image, rs, y, 0);
- putrow(image, gs, y, 1);
- putrow(image, bs, y, 2);
- }
- }
- iclose(image);
- if ( error_called )
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
-
+ IMAGE *image;
+ char *fname;
+ int xsize, ysize, zsize, len;
+ char *cdatap;
+ long *idatap;
+ short rs[8192], gs[8192], bs[8192];
+ short r, g, b;
+ long rgb;
+ int x, y;
+ int yfirst, ylast, ystep;
+
+
+ if ( !PyArg_ParseTuple(args, "ss#iii:write",
+ &fname, &cdatap, &len, &xsize, &ysize, &zsize) )
+ return NULL;
+
+ if ( zsize != 1 && zsize != 3 ) {
+ PyErr_SetString(ImgfileError,
+ "Can only handle 1 or 3 byte pixels");
+ return NULL;
+ }
+ if ( len != xsize * ysize * (zsize == 1 ? 1 : 4) ) {
+ PyErr_SetString(ImgfileError, "Data does not match sizes");
+ return NULL;
+ }
+ if ( xsize > 8192 ) {
+ PyErr_SetString(ImgfileError,
+ "Can't handle image with > 8192 columns");
+ return NULL;
+ }
+
+ error_called = 0;
+ errno = 0;
+ image =iopen(fname, "w", RLE(1), 3, xsize, ysize, zsize);
+ if ( image == 0 ) {
+ if ( ! error_called ) {
+ if (errno)
+ PyErr_SetFromErrno(ImgfileError);
+ else
+ PyErr_SetString(ImgfileError,
+ "Can't create image file");
+ }
+ return NULL;
+ }
+
+ idatap = (long *)cdatap;
+
+ if (top_to_bottom) {
+ yfirst = ysize-1;
+ ylast = -1;
+ ystep = -1;
+ } else {
+ yfirst = 0;
+ ylast = ysize;
+ ystep = 1;
+ }
+ for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
+ if ( zsize == 1 ) {
+ for( x=0; x<xsize; x++ )
+ rs[x] = *cdatap++;
+ putrow(image, rs, y, 0);
+ } else {
+ for( x=0; x<xsize; x++ ) {
+ rgb = *idatap++;
+ r = rgb & 0xff;
+ g = (rgb >> 8 ) & 0xff;
+ b = (rgb >> 16 ) & 0xff;
+ rs[x] = r;
+ gs[x] = g;
+ bs[x] = b;
+ }
+ putrow(image, rs, y, 0);
+ putrow(image, gs, y, 1);
+ putrow(image, bs, y, 2);
+ }
+ }
+ iclose(image);
+ if ( error_called )
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
+
}
static PyMethodDef imgfile_methods[] = {
- { "getsizes", imgfile_getsizes, METH_VARARGS },
- { "read", imgfile_read, METH_VARARGS },
- { "readscaled", imgfile_readscaled, METH_VARARGS},
- { "write", imgfile_write, METH_VARARGS },
- { "ttob", imgfile_ttob, METH_VARARGS },
- { NULL, NULL } /* Sentinel */
+ { "getsizes", imgfile_getsizes, METH_VARARGS },
+ { "read", imgfile_read, METH_VARARGS },
+ { "readscaled", imgfile_readscaled, METH_VARARGS},
+ { "write", imgfile_write, METH_VARARGS },
+ { "ttob", imgfile_ttob, METH_VARARGS },
+ { NULL, NULL } /* Sentinel */
};
void
initimgfile(void)
{
- PyObject *m, *d;
-
- if (PyErr_WarnPy3k("the imgfile module has been removed in "
- "Python 3.0", 2) < 0)
- return;
-
- m = Py_InitModule("imgfile", imgfile_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- ImgfileError = PyErr_NewException("imgfile.error", NULL, NULL);
- if (ImgfileError != NULL)
- PyDict_SetItemString(d, "error", ImgfileError);
+ PyObject *m, *d;
+
+ if (PyErr_WarnPy3k("the imgfile module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
+
+ m = Py_InitModule("imgfile", imgfile_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ ImgfileError = PyErr_NewException("imgfile.error", NULL, NULL);
+ if (ImgfileError != NULL)
+ PyDict_SetItemString(d, "error", ImgfileError);
}
diff --git a/Modules/itertoolsmodule.c b/Modules/itertoolsmodule.c
index 5f1b167..91b482d 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_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 */
- 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_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 */
+ 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_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 */
- 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_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 */
+ 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_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 */
- 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_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 */
+ 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_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_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_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_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,89 +682,89 @@ 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);
- 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);
+ 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,
@@ -774,57 +774,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_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 */
- 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_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 */
+ 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;
@@ -832,82 +832,82 @@ 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 *);
-
- assert(PyIter_Check(it));
- 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 *);
+
+ assert(PyIter_Check(it));
+ 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,
@@ -917,57 +917,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_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 */
- 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_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 */
+ 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;
@@ -975,79 +975,79 @@ 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;
- assert(PyIter_Check(it));
- item = (*Py_TYPE(it)->tp_iternext)(it);
- if (item == NULL)
- return NULL;
+ assert(PyIter_Check(it));
+ 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_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 */
- 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_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 */
+ 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,128 +1117,128 @@ 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 = PyInt_AsSsize_t(a1);
- if (stop == -1) {
- if (PyErr_Occurred())
- PyErr_Clear();
- PyErr_SetString(PyExc_ValueError,
- "Stop argument for islice() must be a non-negative integer or None.");
- return NULL;
- }
- }
- } else {
- if (a1 != Py_None)
- start = PyInt_AsSsize_t(a1);
- if (start == -1 && PyErr_Occurred())
- PyErr_Clear();
- if (a2 != Py_None) {
- stop = PyInt_AsSsize_t(a2);
- if (stop == -1) {
- if (PyErr_Occurred())
- PyErr_Clear();
- PyErr_SetString(PyExc_ValueError,
- "Stop argument for islice() must be a non-negative integer or None.");
- return NULL;
- }
- }
- }
- if (start<0 || stop<-1) {
- PyErr_SetString(PyExc_ValueError,
- "Indices for islice() must be non-negative integers or None.");
- return NULL;
- }
-
- if (a3 != NULL) {
- if (a3 != Py_None)
- step = PyInt_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 = PyInt_AsSsize_t(a1);
+ if (stop == -1) {
+ if (PyErr_Occurred())
+ PyErr_Clear();
+ PyErr_SetString(PyExc_ValueError,
+ "Stop argument for islice() must be a non-negative integer or None.");
+ return NULL;
+ }
+ }
+ } else {
+ if (a1 != Py_None)
+ start = PyInt_AsSsize_t(a1);
+ if (start == -1 && PyErr_Occurred())
+ PyErr_Clear();
+ if (a2 != Py_None) {
+ stop = PyInt_AsSsize_t(a2);
+ if (stop == -1) {
+ if (PyErr_Occurred())
+ PyErr_Clear();
+ PyErr_SetString(PyExc_ValueError,
+ "Stop argument for islice() must be a non-negative integer or None.");
+ return NULL;
+ }
+ }
+ }
+ if (start<0 || stop<-1) {
+ PyErr_SetString(PyExc_ValueError,
+ "Indices for islice() must be non-negative integers or None.");
+ return NULL;
+ }
+
+ if (a3 != NULL) {
+ if (a3 != Py_None)
+ step = PyInt_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 *);
-
- assert(PyIter_Check(it));
- 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;
- assert(PyIter_Check(it));
- 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 *);
+
+ assert(PyIter_Check(it));
+ 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;
+ assert(PyIter_Check(it));
+ 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,
@@ -1252,56 +1252,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_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 */
- 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_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 */
+ 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;
@@ -1309,72 +1309,72 @@ 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;
-
- assert(PyIter_Check(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;
+
+ assert(PyIter_Check(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,
@@ -1384,56 +1384,56 @@ 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_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 */
- 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_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 */
+ 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 */
};
/* imap object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *iters;
- PyObject *func;
+ PyObject_HEAD
+ PyObject *iters;
+ PyObject *func;
} imapobject;
static PyTypeObject imap_type;
@@ -1441,66 +1441,66 @@ static PyTypeObject imap_type;
static PyObject *
imap_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *it, *iters, *func;
- imapobject *lz;
- Py_ssize_t numargs, i;
-
- if (type == &imap_type && !_PyArg_NoKeywords("imap()", kwds))
- return NULL;
-
- numargs = PyTuple_Size(args);
- if (numargs < 2) {
- PyErr_SetString(PyExc_TypeError,
- "imap() must have at least two arguments.");
- return NULL;
- }
-
- iters = PyTuple_New(numargs-1);
- if (iters == NULL)
- return NULL;
-
- for (i=1 ; i<numargs ; i++) {
- /* Get iterator. */
- it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
- if (it == NULL) {
- Py_DECREF(iters);
- return NULL;
- }
- PyTuple_SET_ITEM(iters, i-1, it);
- }
-
- /* create imapobject structure */
- lz = (imapobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(iters);
- return NULL;
- }
- lz->iters = iters;
- func = PyTuple_GET_ITEM(args, 0);
- Py_INCREF(func);
- lz->func = func;
-
- return (PyObject *)lz;
+ PyObject *it, *iters, *func;
+ imapobject *lz;
+ Py_ssize_t numargs, i;
+
+ if (type == &imap_type && !_PyArg_NoKeywords("imap()", kwds))
+ return NULL;
+
+ numargs = PyTuple_Size(args);
+ if (numargs < 2) {
+ PyErr_SetString(PyExc_TypeError,
+ "imap() must have at least two arguments.");
+ return NULL;
+ }
+
+ iters = PyTuple_New(numargs-1);
+ if (iters == NULL)
+ return NULL;
+
+ for (i=1 ; i<numargs ; i++) {
+ /* Get iterator. */
+ it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
+ if (it == NULL) {
+ Py_DECREF(iters);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(iters, i-1, it);
+ }
+
+ /* create imapobject structure */
+ lz = (imapobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(iters);
+ return NULL;
+ }
+ lz->iters = iters;
+ func = PyTuple_GET_ITEM(args, 0);
+ Py_INCREF(func);
+ lz->func = func;
+
+ return (PyObject *)lz;
}
static void
imap_dealloc(imapobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->iters);
- Py_XDECREF(lz->func);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->iters);
+ Py_XDECREF(lz->func);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
imap_traverse(imapobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->iters);
- Py_VISIT(lz->func);
- return 0;
+ Py_VISIT(lz->iters);
+ Py_VISIT(lz->func);
+ return 0;
}
-/*
+/*
imap() is an iterator version of __builtins__.map() except that it does
not have the None fill-in feature. That was intentionally left out for
the following reasons:
@@ -1511,15 +1511,15 @@ the following reasons:
infinite iterators like count() and repeat() (for supplying sequential
or constant arguments to a function).
- 2) In typical use cases for combining itertools, having one finite data
+ 2) In typical use cases for combining itertools, having one finite data
supplier run out before another is likely to be an error condition which
should not pass silently by automatically supplying None.
3) The use cases for automatic None fill-in are rare -- not many functions
do something useful when a parameter suddenly switches type and becomes
- None.
+ None.
- 4) If a need does arise, it can be met by __builtins__.map() or by
+ 4) If a need does arise, it can be met by __builtins__.map() or by
writing: chain(iterable, repeat(None)).
5) Similar toolsets in Haskell and SML do not have automatic None fill-in.
@@ -1528,187 +1528,187 @@ the following reasons:
static PyObject *
imap_next(imapobject *lz)
{
- PyObject *val;
- PyObject *argtuple;
- PyObject *result;
- Py_ssize_t numargs, i;
-
- numargs = PyTuple_Size(lz->iters);
- argtuple = PyTuple_New(numargs);
- if (argtuple == NULL)
- return NULL;
-
- for (i=0 ; i<numargs ; i++) {
- val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
- if (val == NULL) {
- Py_DECREF(argtuple);
- return NULL;
- }
- PyTuple_SET_ITEM(argtuple, i, val);
- }
- if (lz->func == Py_None)
- return argtuple;
- result = PyObject_Call(lz->func, argtuple, NULL);
- Py_DECREF(argtuple);
- return result;
+ PyObject *val;
+ PyObject *argtuple;
+ PyObject *result;
+ Py_ssize_t numargs, i;
+
+ numargs = PyTuple_Size(lz->iters);
+ argtuple = PyTuple_New(numargs);
+ if (argtuple == NULL)
+ return NULL;
+
+ for (i=0 ; i<numargs ; i++) {
+ val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
+ if (val == NULL) {
+ Py_DECREF(argtuple);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(argtuple, i, val);
+ }
+ if (lz->func == Py_None)
+ return argtuple;
+ result = PyObject_Call(lz->func, argtuple, NULL);
+ Py_DECREF(argtuple);
+ return result;
}
PyDoc_STRVAR(imap_doc,
"imap(func, *iterables) --> imap object\n\
\n\
Make an iterator that computes the function using arguments from\n\
-each of the iterables. Like map() except that it returns\n\
+each of the iterables. Like map() except that it returns\n\
an iterator instead of a list and that it stops when the shortest\n\
iterable is exhausted instead of filling in None for shorter\n\
iterables.");
static PyTypeObject imap_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.imap", /* tp_name */
- sizeof(imapobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)imap_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- imap_doc, /* tp_doc */
- (traverseproc)imap_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)imap_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 */
- imap_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.imap", /* tp_name */
+ sizeof(imapobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)imap_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ imap_doc, /* tp_doc */
+ (traverseproc)imap_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)imap_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 */
+ imap_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 = (chainobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(source);
- return NULL;
- }
-
- lz->source = source;
- lz->active = NULL;
- return (PyObject *)lz;
+ 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;
-
- source = PyObject_GetIter(args);
- if (source == NULL)
- return NULL;
+ if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds))
+ return NULL;
- return chain_new_internal(type, source);
+ source = PyObject_GetIter(args);
+ if (source == NULL)
+ return NULL;
+
+ 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,
@@ -1725,64 +1725,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_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 */
- 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_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 */
+ 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;
@@ -1790,180 +1790,180 @@ 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);
- PyMem_Free(lz->indices);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->pools);
+ Py_XDECREF(lz->result);
+ 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,
@@ -1978,59 +1978,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_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 */
- 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_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 */
+ 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;
@@ -2038,159 +2038,159 @@ 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);
- PyMem_Free(co->indices);
- Py_TYPE(co)->tp_free(co);
+ PyObject_GC_UnTrack(co);
+ Py_XDECREF(co->pool);
+ Py_XDECREF(co->result);
+ 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,
@@ -2200,52 +2200,52 @@ 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_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 */
- 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_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 */
+ 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 */
};
/* 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)
@@ -2255,28 +2255,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;
@@ -2284,180 +2284,180 @@ 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) {
- r = PyInt_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) {
+ r = PyInt_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,
@@ -2467,56 +2467,56 @@ 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_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 */
- 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_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 */
+ 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 */
};
/* ifilter object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *func;
- PyObject *it;
+ PyObject_HEAD
+ PyObject *func;
+ PyObject *it;
} ifilterobject;
static PyTypeObject ifilter_type;
@@ -2524,83 +2524,83 @@ static PyTypeObject ifilter_type;
static PyObject *
ifilter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *func, *seq;
- PyObject *it;
- ifilterobject *lz;
+ PyObject *func, *seq;
+ PyObject *it;
+ ifilterobject *lz;
- if (type == &ifilter_type && !_PyArg_NoKeywords("ifilter()", kwds))
- return NULL;
+ if (type == &ifilter_type && !_PyArg_NoKeywords("ifilter()", kwds))
+ return NULL;
- if (!PyArg_UnpackTuple(args, "ifilter", 2, 2, &func, &seq))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "ifilter", 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 ifilterobject structure */
- lz = (ifilterobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- return NULL;
- }
- Py_INCREF(func);
- lz->func = func;
- lz->it = it;
+ /* create ifilterobject structure */
+ lz = (ifilterobject *)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
ifilter_dealloc(ifilterobject *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
ifilter_traverse(ifilterobject *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 *
ifilter_next(ifilterobject *lz)
{
- PyObject *item;
- PyObject *it = lz->it;
- long ok;
- PyObject *(*iternext)(PyObject *);
-
- assert(PyIter_Check(it));
- 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 *);
+
+ assert(PyIter_Check(it));
+ 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(ifilter_doc,
@@ -2610,56 +2610,56 @@ Return those items of sequence for which function(item) is true.\n\
If function is None, return the items that are true.");
static PyTypeObject ifilter_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.ifilter", /* tp_name */
- sizeof(ifilterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)ifilter_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- ifilter_doc, /* tp_doc */
- (traverseproc)ifilter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)ifilter_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 */
- ifilter_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.ifilter", /* tp_name */
+ sizeof(ifilterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)ifilter_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ ifilter_doc, /* tp_doc */
+ (traverseproc)ifilter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)ifilter_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 */
+ ifilter_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* ifilterfalse object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *func;
- PyObject *it;
+ PyObject_HEAD
+ PyObject *func;
+ PyObject *it;
} ifilterfalseobject;
static PyTypeObject ifilterfalse_type;
@@ -2667,84 +2667,84 @@ static PyTypeObject ifilterfalse_type;
static PyObject *
ifilterfalse_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *func, *seq;
- PyObject *it;
- ifilterfalseobject *lz;
+ PyObject *func, *seq;
+ PyObject *it;
+ ifilterfalseobject *lz;
- if (type == &ifilterfalse_type &&
- !_PyArg_NoKeywords("ifilterfalse()", kwds))
- return NULL;
+ if (type == &ifilterfalse_type &&
+ !_PyArg_NoKeywords("ifilterfalse()", kwds))
+ return NULL;
- if (!PyArg_UnpackTuple(args, "ifilterfalse", 2, 2, &func, &seq))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "ifilterfalse", 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 ifilterfalseobject structure */
- lz = (ifilterfalseobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- return NULL;
- }
- Py_INCREF(func);
- lz->func = func;
- lz->it = it;
+ /* create ifilterfalseobject structure */
+ lz = (ifilterfalseobject *)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
ifilterfalse_dealloc(ifilterfalseobject *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
ifilterfalse_traverse(ifilterfalseobject *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 *
ifilterfalse_next(ifilterfalseobject *lz)
{
- PyObject *item;
- PyObject *it = lz->it;
- long ok;
- PyObject *(*iternext)(PyObject *);
-
- assert(PyIter_Check(it));
- 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 *);
+
+ assert(PyIter_Check(it));
+ 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(ifilterfalse_doc,
@@ -2754,56 +2754,56 @@ Return those items of sequence for which function(item) is false.\n\
If function is None, return the items that are false.");
static PyTypeObject ifilterfalse_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.ifilterfalse", /* tp_name */
- sizeof(ifilterfalseobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)ifilterfalse_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- ifilterfalse_doc, /* tp_doc */
- (traverseproc)ifilterfalse_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)ifilterfalse_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 */
- ifilterfalse_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.ifilterfalse", /* tp_name */
+ sizeof(ifilterfalseobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)ifilterfalse_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ ifilterfalse_doc, /* tp_doc */
+ (traverseproc)ifilterfalse_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)ifilterfalse_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 */
+ ifilterfalse_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* count object ************************************************************/
typedef struct {
- PyObject_HEAD
- Py_ssize_t cnt;
- PyObject *long_cnt; /* Arbitrarily large count when cnt >= PY_SSIZE_T_MAX */
+ PyObject_HEAD
+ Py_ssize_t cnt;
+ PyObject *long_cnt; /* Arbitrarily large count when cnt >= PY_SSIZE_T_MAX */
} countobject;
static PyTypeObject count_type;
@@ -2811,115 +2811,115 @@ static PyTypeObject count_type;
static PyObject *
count_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- countobject *lz;
- Py_ssize_t cnt = 0;
- PyObject *cnt_arg = NULL;
- PyObject *long_cnt = NULL;
-
- if (type == &count_type && !_PyArg_NoKeywords("count()", kwds))
- return NULL;
-
- if (!PyArg_UnpackTuple(args, "count", 0, 1, &cnt_arg))
- return NULL;
-
- if (cnt_arg != NULL) {
- cnt = PyInt_AsSsize_t(cnt_arg);
- if (cnt == -1 && PyErr_Occurred()) {
- PyErr_Clear();
- if (!PyLong_Check(cnt_arg)) {
- PyErr_SetString(PyExc_TypeError, "an integer is required");
- return NULL;
- }
- long_cnt = cnt_arg;
- Py_INCREF(long_cnt);
- cnt = PY_SSIZE_T_MAX;
- }
- }
-
- /* create countobject structure */
- lz = (countobject *)PyObject_New(countobject, &count_type);
- if (lz == NULL) {
- Py_XDECREF(long_cnt);
- return NULL;
- }
- lz->cnt = cnt;
- lz->long_cnt = long_cnt;
-
- return (PyObject *)lz;
+ countobject *lz;
+ Py_ssize_t cnt = 0;
+ PyObject *cnt_arg = NULL;
+ PyObject *long_cnt = NULL;
+
+ if (type == &count_type && !_PyArg_NoKeywords("count()", kwds))
+ return NULL;
+
+ if (!PyArg_UnpackTuple(args, "count", 0, 1, &cnt_arg))
+ return NULL;
+
+ if (cnt_arg != NULL) {
+ cnt = PyInt_AsSsize_t(cnt_arg);
+ if (cnt == -1 && PyErr_Occurred()) {
+ PyErr_Clear();
+ if (!PyLong_Check(cnt_arg)) {
+ PyErr_SetString(PyExc_TypeError, "an integer is required");
+ return NULL;
+ }
+ long_cnt = cnt_arg;
+ Py_INCREF(long_cnt);
+ cnt = PY_SSIZE_T_MAX;
+ }
+ }
+
+ /* create countobject structure */
+ lz = (countobject *)PyObject_New(countobject, &count_type);
+ if (lz == NULL) {
+ Py_XDECREF(long_cnt);
+ return NULL;
+ }
+ lz->cnt = cnt;
+ lz->long_cnt = long_cnt;
+
+ return (PyObject *)lz;
}
static void
count_dealloc(countobject *lz)
{
- Py_XDECREF(lz->long_cnt);
- PyObject_Del(lz);
+ Py_XDECREF(lz->long_cnt);
+ PyObject_Del(lz);
}
static PyObject *
count_nextlong(countobject *lz)
{
- static PyObject *one = NULL;
- PyObject *cnt;
- PyObject *stepped_up;
-
- if (lz->long_cnt == NULL) {
- lz->long_cnt = PyInt_FromSsize_t(PY_SSIZE_T_MAX);
- if (lz->long_cnt == NULL)
- return NULL;
- }
- if (one == NULL) {
- one = PyInt_FromLong(1);
- if (one == NULL)
- return NULL;
- }
- cnt = lz->long_cnt;
- assert(cnt != NULL);
- stepped_up = PyNumber_Add(cnt, one);
- if (stepped_up == NULL)
- return NULL;
- lz->long_cnt = stepped_up;
- return cnt;
+ static PyObject *one = NULL;
+ PyObject *cnt;
+ PyObject *stepped_up;
+
+ if (lz->long_cnt == NULL) {
+ lz->long_cnt = PyInt_FromSsize_t(PY_SSIZE_T_MAX);
+ if (lz->long_cnt == NULL)
+ return NULL;
+ }
+ if (one == NULL) {
+ one = PyInt_FromLong(1);
+ if (one == NULL)
+ return NULL;
+ }
+ cnt = lz->long_cnt;
+ assert(cnt != NULL);
+ stepped_up = PyNumber_Add(cnt, one);
+ if (stepped_up == NULL)
+ return NULL;
+ lz->long_cnt = stepped_up;
+ return cnt;
}
static PyObject *
count_next(countobject *lz)
{
- if (lz->cnt == PY_SSIZE_T_MAX)
- return count_nextlong(lz);
- return PyInt_FromSsize_t(lz->cnt++);
+ if (lz->cnt == PY_SSIZE_T_MAX)
+ return count_nextlong(lz);
+ return PyInt_FromSsize_t(lz->cnt++);
}
static PyObject *
count_repr(countobject *lz)
{
- PyObject *cnt_repr;
- PyObject *result;
+ PyObject *cnt_repr;
+ PyObject *result;
- if (lz->cnt != PY_SSIZE_T_MAX)
- return PyString_FromFormat("count(%zd)", lz->cnt);
+ if (lz->cnt != PY_SSIZE_T_MAX)
+ return PyString_FromFormat("count(%zd)", lz->cnt);
- cnt_repr = PyObject_Repr(lz->long_cnt);
- if (cnt_repr == NULL)
- return NULL;
- result = PyString_FromFormat("count(%s)", PyString_AS_STRING(cnt_repr));
- Py_DECREF(cnt_repr);
- return result;
+ cnt_repr = PyObject_Repr(lz->long_cnt);
+ if (cnt_repr == NULL)
+ return NULL;
+ result = PyString_FromFormat("count(%s)", PyString_AS_STRING(cnt_repr));
+ Py_DECREF(cnt_repr);
+ return result;
}
static PyObject *
count_reduce(countobject *lz)
{
- if (lz->cnt == PY_SSIZE_T_MAX)
- return Py_BuildValue("O(O)", Py_TYPE(lz), lz->long_cnt);
- return Py_BuildValue("O(n)", Py_TYPE(lz), lz->cnt);
+ if (lz->cnt == PY_SSIZE_T_MAX)
+ return Py_BuildValue("O(O)", Py_TYPE(lz), lz->long_cnt);
+ 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,
@@ -2929,45 +2929,45 @@ Return a count object whose .next() method returns consecutive\n\
integers starting from zero or, if specified, from firstval.");
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_compare */
- (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, /* tp_flags */
- count_doc, /* tp_doc */
- 0, /* 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 */
+ 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_compare */
+ (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, /* tp_flags */
+ count_doc, /* tp_doc */
+ 0, /* 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 */
};
@@ -2976,10 +2976,10 @@ static PyTypeObject count_type = {
#include "Python.h"
typedef struct {
- PyObject_HEAD
- Py_ssize_t tuplesize;
- PyObject *ittuple; /* tuple of iterators */
- PyObject *result;
+ PyObject_HEAD
+ Py_ssize_t tuplesize;
+ PyObject *ittuple; /* tuple of iterators */
+ PyObject *result;
} izipobject;
static PyTypeObject izip_type;
@@ -2987,120 +2987,120 @@ static PyTypeObject izip_type;
static PyObject *
izip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- izipobject *lz;
- Py_ssize_t i;
- PyObject *ittuple; /* tuple of iterators */
- PyObject *result;
- Py_ssize_t tuplesize = PySequence_Length(args);
-
- if (type == &izip_type && !_PyArg_NoKeywords("izip()", kwds))
- 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,
- "izip 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 izipobject structure */
- lz = (izipobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(ittuple);
- Py_DECREF(result);
- return NULL;
- }
- lz->ittuple = ittuple;
- lz->tuplesize = tuplesize;
- lz->result = result;
-
- return (PyObject *)lz;
+ izipobject *lz;
+ Py_ssize_t i;
+ PyObject *ittuple; /* tuple of iterators */
+ PyObject *result;
+ Py_ssize_t tuplesize = PySequence_Length(args);
+
+ if (type == &izip_type && !_PyArg_NoKeywords("izip()", kwds))
+ 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,
+ "izip 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 izipobject structure */
+ lz = (izipobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(ittuple);
+ Py_DECREF(result);
+ return NULL;
+ }
+ lz->ittuple = ittuple;
+ lz->tuplesize = tuplesize;
+ lz->result = result;
+
+ return (PyObject *)lz;
}
static void
izip_dealloc(izipobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->ittuple);
- Py_XDECREF(lz->result);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->ittuple);
+ Py_XDECREF(lz->result);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
izip_traverse(izipobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->ittuple);
- Py_VISIT(lz->result);
- return 0;
+ Py_VISIT(lz->ittuple);
+ Py_VISIT(lz->result);
+ return 0;
}
static PyObject *
izip_next(izipobject *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 (Py_REFCNT(result) == 1) {
- Py_INCREF(result);
- for (i=0 ; i < tuplesize ; i++) {
- it = PyTuple_GET_ITEM(lz->ittuple, i);
- assert(PyIter_Check(it));
- item = (*Py_TYPE(it)->tp_iternext)(it);
- if (item == NULL) {
- Py_DECREF(result);
- return 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);
- assert(PyIter_Check(it));
- item = (*Py_TYPE(it)->tp_iternext)(it);
- if (item == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- PyTuple_SET_ITEM(result, i, item);
- }
- }
- return result;
+ 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 (Py_REFCNT(result) == 1) {
+ Py_INCREF(result);
+ for (i=0 ; i < tuplesize ; i++) {
+ it = PyTuple_GET_ITEM(lz->ittuple, i);
+ assert(PyIter_Check(it));
+ item = (*Py_TYPE(it)->tp_iternext)(it);
+ if (item == NULL) {
+ Py_DECREF(result);
+ return 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);
+ assert(PyIter_Check(it));
+ item = (*Py_TYPE(it)->tp_iternext)(it);
+ if (item == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(result, i, item);
+ }
+ }
+ return result;
}
PyDoc_STRVAR(izip_doc,
@@ -3114,56 +3114,56 @@ function but consumes less memory by returning an iterator instead of\n\
a list.");
static PyTypeObject izip_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.izip", /* tp_name */
- sizeof(izipobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)izip_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- izip_doc, /* tp_doc */
- (traverseproc)izip_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)izip_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 */
- izip_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.izip", /* tp_name */
+ sizeof(izipobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)izip_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ izip_doc, /* tp_doc */
+ (traverseproc)izip_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)izip_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 */
+ izip_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;
@@ -3171,88 +3171,88 @@ static PyTypeObject repeat_type;
static PyObject *
repeat_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- repeatobject *ro;
- PyObject *element;
- Py_ssize_t cnt = -1;
+ repeatobject *ro;
+ PyObject *element;
+ Py_ssize_t cnt = -1;
- if (type == &repeat_type && !_PyArg_NoKeywords("repeat()", kwds))
- return NULL;
+ if (type == &repeat_type && !_PyArg_NoKeywords("repeat()", kwds))
+ return NULL;
- if (!PyArg_ParseTuple(args, "O|n:repeat", &element, &cnt))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O|n:repeat", &element, &cnt))
+ return NULL;
- if (PyTuple_Size(args) == 2 && cnt < 0)
- cnt = 0;
+ 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;
+ 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)
{
- PyObject *result, *objrepr;
+ PyObject *result, *objrepr;
- objrepr = PyObject_Repr(ro->element);
- if (objrepr == NULL)
- return NULL;
+ objrepr = PyObject_Repr(ro->element);
+ if (objrepr == NULL)
+ return NULL;
- if (ro->cnt == -1)
- result = PyString_FromFormat("repeat(%s)",
- PyString_AS_STRING(objrepr));
- else
- result = PyString_FromFormat("repeat(%s, %zd)",
- PyString_AS_STRING(objrepr), ro->cnt);
- Py_DECREF(objrepr);
- return result;
-}
+ if (ro->cnt == -1)
+ result = PyString_FromFormat("repeat(%s)",
+ PyString_AS_STRING(objrepr));
+ else
+ result = PyString_FromFormat("repeat(%s, %zd)",
+ PyString_AS_STRING(objrepr), ro->cnt);
+ Py_DECREF(objrepr);
+ return result;
+}
static PyObject *
repeat_len(repeatobject *ro)
{
- if (ro->cnt == -1) {
- PyErr_SetString(PyExc_TypeError, "len() of unsized object");
- return NULL;
- }
- return PyInt_FromSize_t(ro->cnt);
+ if (ro->cnt == -1) {
+ PyErr_SetString(PyExc_TypeError, "len() of unsized object");
+ return NULL;
+ }
+ return PyInt_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,
@@ -3261,47 +3261,47 @@ for the specified number of times. If not specified, returns the element\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_compare */
- (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_compare */
+ (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 */
};
/* iziplongest object ************************************************************/
@@ -3309,12 +3309,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;
} iziplongestobject;
static PyTypeObject iziplongest_type;
@@ -3322,161 +3322,161 @@ static PyTypeObject iziplongest_type;
static PyObject *
izip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- iziplongestobject *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,
- "izip_longest() got an unexpected keyword argument");
- return NULL;
- }
+ iziplongestobject *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,
+ "izip_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,
- "izip_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 iziplongestobject structure */
- lz = (iziplongestobject *)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,
+ "izip_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 iziplongestobject structure */
+ lz = (iziplongestobject *)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
izip_longest_dealloc(iziplongestobject *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
izip_longest_traverse(iziplongestobject *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 *
izip_longest_next(iziplongestobject *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 {
- assert(PyIter_Check(it));
- 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 {
+ assert(PyIter_Check(it));
+ 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 {
+ assert(PyIter_Check(it));
+ 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 {
- assert(PyIter_Check(it));
- 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(izip_longest_doc,
@@ -3491,47 +3491,47 @@ defaults to None or can be specified by a keyword argument.\n\
");
static PyTypeObject iziplongest_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.izip_longest", /* tp_name */
- sizeof(iziplongestobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)izip_longest_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- izip_longest_doc, /* tp_doc */
- (traverseproc)izip_longest_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)izip_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 */
- izip_longest_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.izip_longest", /* tp_name */
+ sizeof(iziplongestobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)izip_longest_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ izip_longest_doc, /* tp_doc */
+ (traverseproc)izip_longest_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)izip_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 */
+ izip_longest_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* module level code ********************************************************/
@@ -3567,55 +3567,55 @@ combinations(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 */
};
PyMODINIT_FUNC
inititertools(void)
{
- int i;
- PyObject *m;
- char *name;
- PyTypeObject *typelist[] = {
- &combinations_type,
- &cycle_type,
- &dropwhile_type,
- &takewhile_type,
- &islice_type,
- &starmap_type,
- &imap_type,
- &chain_type,
- &ifilter_type,
- &ifilterfalse_type,
- &count_type,
- &izip_type,
- &iziplongest_type,
- &permutations_type,
- &product_type,
- &repeat_type,
- &groupby_type,
- NULL
- };
-
- Py_TYPE(&teedataobject_type) = &PyType_Type;
- m = Py_InitModule3("itertools", module_methods, module_doc);
- if (m == NULL)
- return;
-
- for (i=0 ; typelist[i] != NULL ; i++) {
- if (PyType_Ready(typelist[i]) < 0)
- return;
- 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;
- if (PyType_Ready(&tee_type) < 0)
- return;
- if (PyType_Ready(&_grouper_type) < 0)
- return;
+ int i;
+ PyObject *m;
+ char *name;
+ PyTypeObject *typelist[] = {
+ &combinations_type,
+ &cycle_type,
+ &dropwhile_type,
+ &takewhile_type,
+ &islice_type,
+ &starmap_type,
+ &imap_type,
+ &chain_type,
+ &ifilter_type,
+ &ifilterfalse_type,
+ &count_type,
+ &izip_type,
+ &iziplongest_type,
+ &permutations_type,
+ &product_type,
+ &repeat_type,
+ &groupby_type,
+ NULL
+ };
+
+ Py_TYPE(&teedataobject_type) = &PyType_Type;
+ m = Py_InitModule3("itertools", module_methods, module_doc);
+ if (m == NULL)
+ return;
+
+ for (i=0 ; typelist[i] != NULL ; i++) {
+ if (PyType_Ready(typelist[i]) < 0)
+ return;
+ 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;
+ if (PyType_Ready(&tee_type) < 0)
+ return;
+ if (PyType_Ready(&_grouper_type) < 0)
+ return;
}
diff --git a/Modules/linuxaudiodev.c b/Modules/linuxaudiodev.c
index 80077c6..7fe20ae 100644
--- a/Modules/linuxaudiodev.c
+++ b/Modules/linuxaudiodev.c
@@ -1,14 +1,14 @@
-/* Hey Emacs, this is -*-C-*-
+/* Hey Emacs, this is -*-C-*-
******************************************************************************
* linuxaudiodev.c -- Linux audio device for python.
- *
+ *
* Author : Peter Bosch
* Created On : Thu Mar 2 21:10:33 2000
* Status : Unknown, Use with caution!
- *
+ *
* Unless other notices are present in any part of this file
- * explicitly claiming copyrights for other people and/or
- * organizations, the contents of this file is fully copyright
+ * explicitly claiming copyrights for other people and/or
+ * organizations, the contents of this file is fully copyright
* (C) 2000 Peter Bosch, all rights reserved.
******************************************************************************
*/
@@ -43,11 +43,11 @@ typedef unsigned long uint32_t;
typedef struct {
PyObject_HEAD
- int x_fd; /* The open file */
+ int x_fd; /* The open file */
int x_mode; /* file mode */
- int x_icount; /* Input count */
- int x_ocount; /* Output count */
- uint32_t x_afmts; /* Audio formats supported by hardware*/
+ int x_icount; /* Input count */
+ int x_ocount; /* Output count */
+ uint32_t x_afmts; /* Audio formats supported by hardware*/
} lad_t;
/* XXX several format defined in soundcard.h are not supported,
@@ -55,19 +55,19 @@ typedef struct {
*/
static struct {
- int a_bps;
- uint32_t a_fmt;
+ int a_bps;
+ uint32_t a_fmt;
char *a_name;
} audio_types[] = {
- { 8, AFMT_MU_LAW, "logarithmic mu-law 8-bit audio" },
- { 8, AFMT_A_LAW, "logarithmic A-law 8-bit audio" },
- { 8, AFMT_U8, "linear unsigned 8-bit audio" },
- { 8, AFMT_S8, "linear signed 8-bit audio" },
- { 16, AFMT_U16_BE, "linear unsigned 16-bit big-endian audio" },
- { 16, AFMT_U16_LE, "linear unsigned 16-bit little-endian audio" },
- { 16, AFMT_S16_BE, "linear signed 16-bit big-endian audio" },
- { 16, AFMT_S16_LE, "linear signed 16-bit little-endian audio" },
- { 16, AFMT_S16_NE, "linear signed 16-bit native-endian audio" },
+ { 8, AFMT_MU_LAW, "logarithmic mu-law 8-bit audio" },
+ { 8, AFMT_A_LAW, "logarithmic A-law 8-bit audio" },
+ { 8, AFMT_U8, "linear unsigned 8-bit audio" },
+ { 8, AFMT_S8, "linear signed 8-bit audio" },
+ { 16, AFMT_U16_BE, "linear unsigned 16-bit big-endian audio" },
+ { 16, AFMT_U16_LE, "linear unsigned 16-bit little-endian audio" },
+ { 16, AFMT_S16_BE, "linear signed 16-bit big-endian audio" },
+ { 16, AFMT_S16_LE, "linear signed 16-bit little-endian audio" },
+ { 16, AFMT_S16_NE, "linear signed 16-bit native-endian audio" },
};
static int n_audio_types = sizeof(audio_types) / sizeof(audio_types[0]);
@@ -108,7 +108,7 @@ newladobject(PyObject *arg)
/* Open the correct device. The base device name comes from the
* AUDIODEV environment variable first, then /dev/dsp. The
* control device tacks "ctl" onto the base device name.
- *
+ *
* Note that the only difference between /dev/audio and /dev/dsp
* is that the former uses logarithmic mu-law encoding and the
* latter uses 8-bit unsigned encoding.
@@ -149,7 +149,7 @@ lad_dealloc(lad_t *xp)
{
/* if already closed, don't reclose it */
if (xp->x_fd != -1)
- close(xp->x_fd);
+ close(xp->x_fd);
PyObject_Del(xp);
}
@@ -159,7 +159,7 @@ lad_read(lad_t *self, PyObject *args)
int size, count;
char *cp;
PyObject *rv;
-
+
if (!PyArg_ParseTuple(args, "i:read", &size))
return NULL;
rv = PyString_FromStringAndSize(NULL, size);
@@ -184,36 +184,36 @@ lad_write(lad_t *self, PyObject *args)
fd_set write_set_fds;
struct timeval tv;
int select_retval;
-
- if (!PyArg_ParseTuple(args, "s#:write", &cp, &size))
- return NULL;
+
+ if (!PyArg_ParseTuple(args, "s#:write", &cp, &size))
+ return NULL;
/* use select to wait for audio device to be available */
FD_ZERO(&write_set_fds);
FD_SET(self->x_fd, &write_set_fds);
tv.tv_sec = 4; /* timeout values */
- tv.tv_usec = 0;
+ tv.tv_usec = 0;
while (size > 0) {
select_retval = select(self->x_fd+1, NULL, &write_set_fds, NULL, &tv);
tv.tv_sec = 1; tv.tv_usec = 0; /* willing to wait this long next time*/
if (select_retval) {
if ((rv = write(self->x_fd, cp, size)) == -1) {
- if (errno != EAGAIN) {
- PyErr_SetFromErrno(LinuxAudioError);
- return NULL;
- } else {
- errno = 0; /* EAGAIN: buffer is full, try again */
- }
+ if (errno != EAGAIN) {
+ PyErr_SetFromErrno(LinuxAudioError);
+ return NULL;
+ } else {
+ errno = 0; /* EAGAIN: buffer is full, try again */
+ }
} else {
- self->x_ocount += rv;
- size -= rv;
- cp += rv;
- }
+ self->x_ocount += rv;
+ size -= rv;
+ cp += rv;
+ }
} else {
- /* printf("Not able to write to linux audio device within %ld seconds\n", tv.tv_sec); */
- PyErr_SetFromErrno(LinuxAudioError);
- return NULL;
+ /* printf("Not able to write to linux audio device within %ld seconds\n", tv.tv_sec); */
+ PyErr_SetFromErrno(LinuxAudioError);
+ return NULL;
}
}
Py_INCREF(Py_None);
@@ -244,47 +244,47 @@ lad_setparameters(lad_t *self, PyObject *args)
if (!PyArg_ParseTuple(args, "iiii|i:setparameters",
&rate, &ssize, &nchannels, &fmt, &emulate))
return NULL;
-
+
if (rate < 0) {
- PyErr_Format(PyExc_ValueError, "expected rate >= 0, not %d",
- rate);
- return NULL;
+ PyErr_Format(PyExc_ValueError, "expected rate >= 0, not %d",
+ rate);
+ return NULL;
}
if (ssize < 0) {
- PyErr_Format(PyExc_ValueError, "expected sample size >= 0, not %d",
- ssize);
- return NULL;
+ PyErr_Format(PyExc_ValueError, "expected sample size >= 0, not %d",
+ ssize);
+ return NULL;
}
if (nchannels != 1 && nchannels != 2) {
- PyErr_Format(PyExc_ValueError, "nchannels must be 1 or 2, not %d",
- nchannels);
- return NULL;
+ PyErr_Format(PyExc_ValueError, "nchannels must be 1 or 2, not %d",
+ nchannels);
+ return NULL;
}
for (n = 0; n < n_audio_types; n++)
if (fmt == audio_types[n].a_fmt)
break;
if (n == n_audio_types) {
- PyErr_Format(PyExc_ValueError, "unknown audio encoding: %d", fmt);
- return NULL;
+ PyErr_Format(PyExc_ValueError, "unknown audio encoding: %d", fmt);
+ return NULL;
}
if (audio_types[n].a_bps != ssize) {
- PyErr_Format(PyExc_ValueError,
- "for %s, expected sample size %d, not %d",
- audio_types[n].a_name, audio_types[n].a_bps, ssize);
- return NULL;
+ PyErr_Format(PyExc_ValueError,
+ "for %s, expected sample size %d, not %d",
+ audio_types[n].a_name, audio_types[n].a_bps, ssize);
+ return NULL;
}
if (emulate == 0) {
- if ((self->x_afmts & audio_types[n].a_fmt) == 0) {
- PyErr_Format(PyExc_ValueError,
- "%s format not supported by device",
- audio_types[n].a_name);
- return NULL;
- }
+ if ((self->x_afmts & audio_types[n].a_fmt) == 0) {
+ PyErr_Format(PyExc_ValueError,
+ "%s format not supported by device",
+ audio_types[n].a_name);
+ return NULL;
+ }
}
- if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT,
- &audio_types[n].a_fmt) == -1) {
+ if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT,
+ &audio_types[n].a_fmt) == -1) {
PyErr_SetFromErrno(LinuxAudioError);
return NULL;
}
@@ -307,7 +307,7 @@ _ssize(lad_t *self, int *nchannels, int *ssize)
int fmt;
fmt = 0;
- if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT, &fmt) < 0)
+ if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT, &fmt) < 0)
return -errno;
switch (fmt) {
@@ -334,7 +334,7 @@ _ssize(lad_t *self, int *nchannels, int *ssize)
}
-/* bufsize returns the size of the hardware audio buffer in number
+/* bufsize returns the size of the hardware audio buffer in number
of samples */
static PyObject *
lad_bufsize(lad_t *self, PyObject *unused)
@@ -353,7 +353,7 @@ lad_bufsize(lad_t *self, PyObject *unused)
return PyInt_FromLong((ai.fragstotal * ai.fragsize) / (nchannels * ssize));
}
-/* obufcount returns the number of samples that are available in the
+/* obufcount returns the number of samples that are available in the
hardware for playing */
static PyObject *
lad_obufcount(lad_t *self, PyObject *unused)
@@ -369,7 +369,7 @@ lad_obufcount(lad_t *self, PyObject *unused)
PyErr_SetFromErrno(LinuxAudioError);
return NULL;
}
- return PyInt_FromLong((ai.fragstotal * ai.fragsize - ai.bytes) /
+ return PyInt_FromLong((ai.fragstotal * ai.fragsize - ai.bytes) /
(ssize * nchannels));
}
@@ -410,9 +410,9 @@ lad_getptr(lad_t *self, PyObject *unused)
int req;
if (self->x_mode == O_RDONLY)
- req = SNDCTL_DSP_GETIPTR;
+ req = SNDCTL_DSP_GETIPTR;
else
- req = SNDCTL_DSP_GETOPTR;
+ req = SNDCTL_DSP_GETOPTR;
if (ioctl(self->x_fd, req, &info) == -1) {
PyErr_SetFromErrno(LinuxAudioError);
return NULL;
@@ -421,17 +421,17 @@ lad_getptr(lad_t *self, PyObject *unused)
}
static PyMethodDef lad_methods[] = {
- { "read", (PyCFunction)lad_read, METH_VARARGS },
- { "write", (PyCFunction)lad_write, METH_VARARGS },
- { "setparameters", (PyCFunction)lad_setparameters, METH_VARARGS },
- { "bufsize", (PyCFunction)lad_bufsize, METH_VARARGS },
- { "obufcount", (PyCFunction)lad_obufcount, METH_NOARGS },
- { "obuffree", (PyCFunction)lad_obuffree, METH_NOARGS },
- { "flush", (PyCFunction)lad_flush, METH_NOARGS },
- { "close", (PyCFunction)lad_close, METH_NOARGS },
- { "fileno", (PyCFunction)lad_fileno, METH_NOARGS },
+ { "read", (PyCFunction)lad_read, METH_VARARGS },
+ { "write", (PyCFunction)lad_write, METH_VARARGS },
+ { "setparameters", (PyCFunction)lad_setparameters, METH_VARARGS },
+ { "bufsize", (PyCFunction)lad_bufsize, METH_VARARGS },
+ { "obufcount", (PyCFunction)lad_obufcount, METH_NOARGS },
+ { "obuffree", (PyCFunction)lad_obuffree, METH_NOARGS },
+ { "flush", (PyCFunction)lad_flush, METH_NOARGS },
+ { "close", (PyCFunction)lad_close, METH_NOARGS },
+ { "fileno", (PyCFunction)lad_fileno, METH_NOARGS },
{ "getptr", (PyCFunction)lad_getptr, METH_NOARGS },
- { NULL, NULL} /* sentinel */
+ { NULL, NULL} /* sentinel */
};
static PyObject *
@@ -443,15 +443,15 @@ lad_getattr(lad_t *xp, char *name)
static PyTypeObject Ladtype = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"linuxaudiodev.linux_audio_device", /*tp_name*/
- sizeof(lad_t), /*tp_size*/
- 0, /*tp_itemsize*/
+ sizeof(lad_t), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- (destructor)lad_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)lad_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ (destructor)lad_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)lad_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
static PyObject *
@@ -469,37 +469,37 @@ void
initlinuxaudiodev(void)
{
PyObject *m;
-
+
if (PyErr_WarnPy3k("the linuxaudiodev module has been removed in "
"Python 3.0; use the ossaudiodev module instead", 2) < 0)
return;
-
+
m = Py_InitModule("linuxaudiodev", linuxaudiodev_methods);
if (m == NULL)
- return;
+ return;
LinuxAudioError = PyErr_NewException("linuxaudiodev.error", NULL, NULL);
if (LinuxAudioError)
- PyModule_AddObject(m, "error", LinuxAudioError);
+ PyModule_AddObject(m, "error", LinuxAudioError);
if (PyModule_AddIntConstant(m, "AFMT_MU_LAW", (long)AFMT_MU_LAW) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_A_LAW", (long)AFMT_A_LAW) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_U8", (long)AFMT_U8) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_S8", (long)AFMT_S8) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_U16_BE", (long)AFMT_U16_BE) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_U16_LE", (long)AFMT_U16_LE) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_S16_BE", (long)AFMT_S16_BE) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_S16_LE", (long)AFMT_S16_LE) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_S16_NE", (long)AFMT_S16_NE) == -1)
- return;
+ return;
return;
}
diff --git a/Modules/main.c b/Modules/main.c
index a1159b7..dd196ef 100644
--- a/Modules/main.c
+++ b/Modules/main.c
@@ -106,119 +106,119 @@ PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n\
static int
usage(int exitcode, char* 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(char *module, int set_argv0)
{
- PyObject *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;
- }
- runargs = Py_BuildValue("(si)", 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);
- return -1;
- }
- result = PyObject_Call(runmodule, runargs, NULL);
- if (result == NULL) {
- PyErr_Print();
- }
- Py_DECREF(runpy);
- Py_DECREF(runmodule);
- Py_DECREF(runargs);
- if (result == NULL) {
- return -1;
- }
- Py_DECREF(result);
- return 0;
+ PyObject *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;
+ }
+ runargs = Py_BuildValue("(si)", 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);
+ return -1;
+ }
+ result = PyObject_Call(runmodule, runargs, NULL);
+ if (result == NULL) {
+ PyErr_Print();
+ }
+ Py_DECREF(runpy);
+ Py_DECREF(runmodule);
+ Py_DECREF(runargs);
+ if (result == NULL) {
+ return -1;
+ }
+ Py_DECREF(result);
+ return 0;
}
static int RunMainFromImporter(char *filename)
{
- PyObject *argv0 = NULL, *importer = NULL;
-
- if ((argv0 = PyString_FromString(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("__main__", 0) != 0;
- }
- }
- Py_XDECREF(argv0);
- Py_XDECREF(importer);
- if (PyErr_Occurred()) {
- PyErr_Print();
- return 1;
- }
- return -1;
+ PyObject *argv0 = NULL, *importer = NULL;
+
+ if ((argv0 = PyString_FromString(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("__main__", 0) != 0;
+ }
+ }
+ Py_XDECREF(argv0);
+ Py_XDECREF(importer);
+ if (PyErr_Occurred()) {
+ PyErr_Print();
+ return 1;
+ }
+ return -1;
}
@@ -227,398 +227,398 @@ static int RunMainFromImporter(char *filename)
int
Py_Main(int argc, char **argv)
{
- int c;
- int sts;
- char *command = NULL;
- char *filename = NULL;
- char *module = NULL;
- FILE *fp = stdin;
- char *p;
- int unbuffered = 0;
- 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;
+ int c;
+ int sts;
+ char *command = NULL;
+ char *filename = NULL;
+ char *module = NULL;
+ FILE *fp = stdin;
+ char *p;
+ int unbuffered = 0;
+ 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;
#ifdef RISCOS
- Py_RISCOSWimpFlag = 0;
+ Py_RISCOSWimpFlag = 0;
#endif
- PySys_ResetWarnOptions();
-
- while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
- if (c == 'c') {
- /* -c is the last option; following arguments
- that look like options are left for the
- command to interpret. */
- command = (char *)malloc(strlen(_PyOS_optarg) + 2);
- if (command == NULL)
- Py_FatalError(
- "not enough memory to copy -c argument");
- strcpy(command, _PyOS_optarg);
- strcat(command, "\n");
- break;
- }
-
- if (c == 'm') {
- /* -m is the last option; following arguments
- that look like options are left for the
- module to interpret. */
- module = (char *)malloc(strlen(_PyOS_optarg) + 2);
- if (module == NULL)
- Py_FatalError(
- "not enough memory to copy -m argument");
- strcpy(module, _PyOS_optarg);
- break;
- }
-
- switch (c) {
- case 'b':
- Py_BytesWarningFlag++;
- break;
-
- case 'd':
- Py_DebugFlag++;
- break;
-
- case '3':
- Py_Py3kWarningFlag++;
- if (!Py_DivisionWarningFlag)
- Py_DivisionWarningFlag = 1;
- break;
-
- case 'Q':
- if (strcmp(_PyOS_optarg, "old") == 0) {
- Py_DivisionWarningFlag = 0;
- break;
- }
- if (strcmp(_PyOS_optarg, "warn") == 0) {
- Py_DivisionWarningFlag = 1;
- break;
- }
- if (strcmp(_PyOS_optarg, "warnall") == 0) {
- Py_DivisionWarningFlag = 2;
- break;
- }
- if (strcmp(_PyOS_optarg, "new") == 0) {
- /* This only affects __main__ */
- cf.cf_flags |= CO_FUTURE_DIVISION;
- /* And this tells the eval loop to treat
- BINARY_DIVIDE as BINARY_TRUE_DIVIDE */
- _Py_QnewFlag = 1;
- break;
- }
- fprintf(stderr,
- "-Q option should be `-Qold', "
- "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
- return usage(2, argv[0]);
- /* NOTREACHED */
-
- 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':
- Py_TabcheckFlag++;
- break;
-
- case 'u':
- unbuffered++;
- saw_unbuffered_flag = 1;
- break;
-
- case 'v':
- Py_VerboseFlag++;
- break;
+ PySys_ResetWarnOptions();
+
+ while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
+ if (c == 'c') {
+ /* -c is the last option; following arguments
+ that look like options are left for the
+ command to interpret. */
+ command = (char *)malloc(strlen(_PyOS_optarg) + 2);
+ if (command == NULL)
+ Py_FatalError(
+ "not enough memory to copy -c argument");
+ strcpy(command, _PyOS_optarg);
+ strcat(command, "\n");
+ break;
+ }
+
+ if (c == 'm') {
+ /* -m is the last option; following arguments
+ that look like options are left for the
+ module to interpret. */
+ module = (char *)malloc(strlen(_PyOS_optarg) + 2);
+ if (module == NULL)
+ Py_FatalError(
+ "not enough memory to copy -m argument");
+ strcpy(module, _PyOS_optarg);
+ break;
+ }
+
+ switch (c) {
+ case 'b':
+ Py_BytesWarningFlag++;
+ break;
+
+ case 'd':
+ Py_DebugFlag++;
+ break;
+
+ case '3':
+ Py_Py3kWarningFlag++;
+ if (!Py_DivisionWarningFlag)
+ Py_DivisionWarningFlag = 1;
+ break;
+
+ case 'Q':
+ if (strcmp(_PyOS_optarg, "old") == 0) {
+ Py_DivisionWarningFlag = 0;
+ break;
+ }
+ if (strcmp(_PyOS_optarg, "warn") == 0) {
+ Py_DivisionWarningFlag = 1;
+ break;
+ }
+ if (strcmp(_PyOS_optarg, "warnall") == 0) {
+ Py_DivisionWarningFlag = 2;
+ break;
+ }
+ if (strcmp(_PyOS_optarg, "new") == 0) {
+ /* This only affects __main__ */
+ cf.cf_flags |= CO_FUTURE_DIVISION;
+ /* And this tells the eval loop to treat
+ BINARY_DIVIDE as BINARY_TRUE_DIVIDE */
+ _Py_QnewFlag = 1;
+ break;
+ }
+ fprintf(stderr,
+ "-Q option should be `-Qold', "
+ "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
+ return usage(2, argv[0]);
+ /* NOTREACHED */
+
+ 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':
+ Py_TabcheckFlag++;
+ break;
+
+ case 'u':
+ unbuffered++;
+ saw_unbuffered_flag = 1;
+ break;
+
+ case 'v':
+ Py_VerboseFlag++;
+ break;
#ifdef RISCOS
- case 'w':
- Py_RISCOSWimpFlag = 1;
- break;
+ case 'w':
+ Py_RISCOSWimpFlag = 1;
+ break;
#endif
- case 'x':
- skipfirstline = 1;
- break;
-
- /* case 'X': reserved for implementation-specific arguments */
-
- case 'U':
- Py_UnicodeFlag++;
- break;
- 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')
- unbuffered = 1;
-
- if (!Py_NoUserSiteDirectory &&
- (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0')
- Py_NoUserSiteDirectory = 1;
-
- if (command == NULL && module == NULL && _PyOS_optind < argc &&
- strcmp(argv[_PyOS_optind], "-") != 0)
- {
+ case 'x':
+ skipfirstline = 1;
+ break;
+
+ /* case 'X': reserved for implementation-specific arguments */
+
+ case 'U':
+ Py_UnicodeFlag++;
+ break;
+ 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')
+ unbuffered = 1;
+
+ if (!Py_NoUserSiteDirectory &&
+ (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0')
+ Py_NoUserSiteDirectory = 1;
+
+ if (command == NULL && module == NULL && _PyOS_optind < argc &&
+ strcmp(argv[_PyOS_optind], "-") != 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 (unbuffered) {
+ if (unbuffered) {
#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')
- Py_SetProgramName(p);
- 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')
+ Py_SetProgramName(p);
+ 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] = "-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] = "-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) {
- sts = PyRun_SimpleStringFlags(command, &cf) != 0;
- free(command);
- } else if (module) {
- sts = RunModule(module, 1);
- free(module);
- }
- 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 = fopen(filename, "r")) == NULL) {
- fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n",
- argv[0], filename, 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, "%s: '%s' is a directory, cannot continue\n", argv[0], filename);
- fclose(fp);
- return 1;
- }
- }
- }
-
- if (sts==-1) {
- /* call pending calls like signal handlers (SIGINT) */
- if (Py_MakePendingCalls() == -1) {
- PyErr_Print();
- sts = 1;
- } else {
- sts = PyRun_AnyFileExFlags(
- fp,
- filename == NULL ? "<stdin>" : filename,
- filename != NULL, &cf) != 0;
- }
- }
-
- }
-
- /* 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] = "-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] = "-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) {
+ sts = PyRun_SimpleStringFlags(command, &cf) != 0;
+ free(command);
+ } else if (module) {
+ sts = RunModule(module, 1);
+ free(module);
+ }
+ 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 = fopen(filename, "r")) == NULL) {
+ fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n",
+ argv[0], filename, 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, "%s: '%s' is a directory, cannot continue\n", argv[0], filename);
+ fclose(fp);
+ return 1;
+ }
+ }
+ }
+
+ if (sts==-1) {
+ /* call pending calls like signal handlers (SIGINT) */
+ if (Py_MakePendingCalls() == -1) {
+ PyErr_Print();
+ sts = 1;
+ } else {
+ sts = PyRun_AnyFileExFlags(
+ fp,
+ filename == NULL ? "<stdin>" : filename,
+ filename != NULL, &cf) != 0;
+ }
+ }
+
+ }
+
+ /* 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 RISCOS
- if (Py_RISCOSWimpFlag)
- fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */
+ if (Py_RISCOSWimpFlag)
+ fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */
#endif
#ifdef __INSURE__
- /* Insure++ is a memory analysis tool that aids in discovering
- * memory leaks and other memory problems. On Python exit, the
- * interned string dictionary is 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();
+ /* Insure++ is a memory analysis tool that aids in discovering
+ * memory leaks and other memory problems. On Python exit, the
+ * interned string dictionary is 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();
#endif /* __INSURE__ */
- return sts;
+ return sts;
}
/* this is gonna seem *real weird*, but if you put some other code between
@@ -631,8 +631,8 @@ Py_Main(int argc, char **argv)
void
Py_GetArgcArgv(int *argc, char ***argv)
{
- *argc = orig_argc;
- *argv = orig_argv;
+ *argc = orig_argc;
+ *argv = orig_argv;
}
#ifdef __cplusplus
diff --git a/Modules/mathmodule.c b/Modules/mathmodule.c
index 20d66e0..13d6e62 100644
--- a/Modules/mathmodule.c
+++ b/Modules/mathmodule.c
@@ -67,37 +67,37 @@ extern double copysign(double, double);
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;
}
/*
@@ -111,29 +111,29 @@ is_error(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);
}
/*
@@ -146,45 +146,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 */
+ }
}
@@ -221,30 +221,30 @@ m_log10(double x)
static PyObject *
math_1(PyObject *arg, 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)) {
- if (!Py_IS_NAN(x))
- errno = EDOM;
- else
- errno = 0;
- }
- else if (Py_IS_INFINITY(r)) {
- if (Py_IS_FINITE(x))
- errno = can_overflow ? ERANGE : EDOM;
- else
- errno = 0;
- }
- if (errno && is_error(r))
- return NULL;
- else
- 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_1", return 0);
+ r = (*func)(x);
+ PyFPE_END_PROTECT(r);
+ if (Py_IS_NAN(r)) {
+ if (!Py_IS_NAN(x))
+ errno = EDOM;
+ else
+ errno = 0;
+ }
+ else if (Py_IS_INFINITY(r)) {
+ if (Py_IS_FINITE(x))
+ errno = can_overflow ? ERANGE : EDOM;
+ else
+ errno = 0;
+ }
+ if (errno && is_error(r))
+ return NULL;
+ else
+ return PyFloat_FromDouble(r);
}
/*
@@ -277,47 +277,47 @@ math_1(PyObject *arg, double (*func) (double), int 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 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.")
@@ -384,7 +384,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,
@@ -407,27 +407,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.
@@ -435,17 +435,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
@@ -463,119 +463,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
@@ -588,46 +588,46 @@ 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)) {
- double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
- if (dx != floor(dx)) {
- PyErr_SetString(PyExc_ValueError,
- "factorial() only accepts integral values");
- return NULL;
- }
- }
-
- x = PyInt_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 *)PyInt_FromLong(1);
- if (result == NULL)
- return NULL;
- for (i=1 ; i<=x ; i++) {
- iobj = (PyObject *)PyInt_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)) {
+ double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
+ if (dx != floor(dx)) {
+ PyErr_SetString(PyExc_ValueError,
+ "factorial() only accepts integral values");
+ return NULL;
+ }
+ }
+
+ x = PyInt_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 *)PyInt_FromLong(1);
+ if (result == NULL)
+ return NULL;
+ for (i=1 ; i<=x ; i++) {
+ iobj = (PyObject *)PyInt_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,
@@ -638,7 +638,7 @@ PyDoc_STRVAR(math_factorial_doc,
static PyObject *
math_trunc(PyObject *self, PyObject *number)
{
- return PyObject_CallMethod(number, "__trunc__", NULL);
+ return PyObject_CallMethod(number, "__trunc__", NULL);
}
PyDoc_STRVAR(math_trunc_doc,
@@ -649,21 +649,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,
@@ -676,66 +676,66 @@ PyDoc_STRVAR(math_frexp_doc,
static PyObject *
math_ldexp(PyObject *self, PyObject *args)
{
- double x, r;
- PyObject *oexp;
- long exp;
- 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_AsLong(oexp);
- if (exp == -1 && PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
- if (Py_SIZE(oexp) < 0) {
- exp = LONG_MIN;
- }
- else {
- exp = LONG_MAX;
- }
- PyErr_Clear();
- }
- else {
- /* propagate any unexpected exception */
- return NULL;
- }
- }
- }
- else if (PyInt_Check(oexp)) {
- exp = PyInt_AS_LONG(oexp);
- }
- 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;
+ 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_AsLong(oexp);
+ if (exp == -1 && PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
+ if (Py_SIZE(oexp) < 0) {
+ exp = LONG_MIN;
+ }
+ else {
+ exp = LONG_MAX;
+ }
+ PyErr_Clear();
+ }
+ else {
+ /* propagate any unexpected exception */
+ return NULL;
+ }
+ }
+ }
+ else if (PyInt_Check(oexp)) {
+ exp = PyInt_AS_LONG(oexp);
+ }
+ 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,
@@ -745,23 +745,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,
@@ -781,53 +781,53 @@ 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;
- int e;
- x = _PyLong_AsScaledDouble(arg, &e);
- if (x <= 0.0) {
- PyErr_SetString(PyExc_ValueError,
- "math domain error");
- return NULL;
- }
- /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
- log(x) + log(2) * e * PyLong_SHIFT.
- CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
- so force use of double. */
- x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
- 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;
+ int e;
+ x = _PyLong_AsScaledDouble(arg, &e);
+ if (x <= 0.0) {
+ PyErr_SetString(PyExc_ValueError,
+ "math domain error");
+ return NULL;
+ }
+ /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
+ log(x) + log(2) * e * PyLong_SHIFT.
+ CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
+ so force use of double. */
+ x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
+ 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_Divide(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_Divide(num, den);
+ Py_DECREF(num);
+ Py_DECREF(den);
+ return ans;
}
PyDoc_STRVAR(math_log_doc,
@@ -838,7 +838,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,
@@ -847,31 +847,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,
@@ -881,39 +881,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,
@@ -928,79 +928,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,
@@ -1012,10 +1012,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,
@@ -1025,10 +1025,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,
@@ -1038,10 +1038,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,
@@ -1051,10 +1051,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,
@@ -1062,42 +1062,42 @@ 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},
- {"exp", math_exp, METH_O, math_exp_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},
- {"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},
- {"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},
+ {"exp", math_exp, METH_O, math_exp_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},
+ {"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},
+ {"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 */
};
@@ -1108,15 +1108,15 @@ PyDoc_STRVAR(module_doc,
PyMODINIT_FUNC
initmath(void)
{
- PyObject *m;
+ PyObject *m;
- m = Py_InitModule3("math", math_methods, module_doc);
- if (m == NULL)
- goto finally;
+ m = Py_InitModule3("math", math_methods, module_doc);
+ 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;
+ return;
}
diff --git a/Modules/md5.c b/Modules/md5.c
index 0e1058f..982fd7f 100644
--- a/Modules/md5.c
+++ b/Modules/md5.c
@@ -27,7 +27,7 @@
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
- http://www.ietf.org/rfc/rfc1321.txt
+ http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
@@ -38,14 +38,14 @@
that follows (in reverse chronological order):
2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order
- either statically or dynamically; added missing #include <string.h>
- in library.
+ either statically or dynamically; added missing #include <string.h>
+ in library.
2002-03-11 lpd Corrected argument list for main(), and added int return
- type, in test program and T value program.
+ type, in test program and T value program.
2002-02-21 lpd Added missing #include <stdio.h> in test program.
2000-07-03 lpd Patched to eliminate warnings about "constant is
- unsigned in ANSI C, signed in traditional"; made test program
- self-checking.
+ unsigned in ANSI C, signed in traditional"; made test program
+ self-checking.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
1999-05-03 lpd Original version.
@@ -55,7 +55,7 @@
#include <string.h>
#include <limits.h>
-#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
+#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
#ifdef ARCH_IS_BIG_ENDIAN
# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
#else
@@ -133,8 +133,8 @@ static void
md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
{
md5_word_t
- a = pms->abcd[0], b = pms->abcd[1],
- c = pms->abcd[2], d = pms->abcd[3];
+ a = pms->abcd[0], b = pms->abcd[1],
+ c = pms->abcd[2], d = pms->abcd[3];
md5_word_t t;
#if BYTE_ORDER > 0
/* Define storage only for big-endian CPUs. */
@@ -147,51 +147,51 @@ md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
{
#if BYTE_ORDER == 0
- /*
- * Determine dynamically whether this is a big-endian or
- * little-endian machine, since we can use a more efficient
- * algorithm on the latter.
- */
- static const int w = 1;
-
- if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
+ /*
+ * Determine dynamically whether this is a big-endian or
+ * little-endian machine, since we can use a more efficient
+ * algorithm on the latter.
+ */
+ static const int w = 1;
+
+ if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
#endif
-#if BYTE_ORDER <= 0 /* little-endian */
- {
- /*
- * On little-endian machines, we can process properly aligned
- * data without copying it.
- */
- if (!((data - (const md5_byte_t *)0) & 3)) {
- /* data are properly aligned */
- X = (const md5_word_t *)data;
- } else {
- /* not aligned */
- memcpy(xbuf, data, 64);
- X = xbuf;
- }
- }
+#if BYTE_ORDER <= 0 /* little-endian */
+ {
+ /*
+ * On little-endian machines, we can process properly aligned
+ * data without copying it.
+ */
+ if (!((data - (const md5_byte_t *)0) & 3)) {
+ /* data are properly aligned */
+ X = (const md5_word_t *)data;
+ } else {
+ /* not aligned */
+ memcpy(xbuf, data, 64);
+ X = xbuf;
+ }
+ }
#endif
#if BYTE_ORDER == 0
- else /* dynamic big-endian */
+ else /* dynamic big-endian */
#endif
-#if BYTE_ORDER >= 0 /* big-endian */
- {
- /*
- * On big-endian machines, we must arrange the bytes in the
- * right order.
- */
- const md5_byte_t *xp = data;
- int i;
+#if BYTE_ORDER >= 0 /* big-endian */
+ {
+ /*
+ * On big-endian machines, we must arrange the bytes in the
+ * right order.
+ */
+ const md5_byte_t *xp = data;
+ int i;
# if BYTE_ORDER == 0
- X = xbuf; /* (dynamic only) */
+ X = xbuf; /* (dynamic only) */
# else
-# define xbuf X /* (static only) */
+# define xbuf X /* (static only) */
# endif
- for (i = 0; i < 16; ++i, xp += 4)
- xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
- }
+ for (i = 0; i < 16; ++i, xp += 4)
+ xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
+ }
#endif
}
@@ -329,7 +329,7 @@ md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes)
md5_word_t nbits = (md5_word_t)(nbytes << 3);
if (nbytes <= 0)
- return;
+ return;
/* this special case is handled recursively */
if (nbytes > INT_MAX - offset) {
@@ -339,7 +339,7 @@ md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes)
overlap = 64 - offset;
md5_append(pms, data, overlap);
- md5_append(pms, data + overlap, nbytes - overlap);
+ md5_append(pms, data + overlap, nbytes - overlap);
return;
}
@@ -347,48 +347,48 @@ md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes)
pms->count[1] += nbytes >> 29;
pms->count[0] += nbits;
if (pms->count[0] < nbits)
- pms->count[1]++;
+ pms->count[1]++;
/* Process an initial partial block. */
if (offset) {
- int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
-
- memcpy(pms->buf + offset, p, copy);
- if (offset + copy < 64)
- return;
- p += copy;
- left -= copy;
- md5_process(pms, pms->buf);
+ int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
+
+ memcpy(pms->buf + offset, p, copy);
+ if (offset + copy < 64)
+ return;
+ p += copy;
+ left -= copy;
+ md5_process(pms, pms->buf);
}
/* Process full blocks. */
for (; left >= 64; p += 64, left -= 64)
- md5_process(pms, p);
+ md5_process(pms, p);
/* Process a final partial block. */
if (left)
- memcpy(pms->buf, p, left);
+ memcpy(pms->buf, p, left);
}
void
md5_finish(md5_state_t *pms, md5_byte_t digest[16])
{
static const md5_byte_t pad[64] = {
- 0x80, 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, 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
+ 0x80, 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, 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
};
md5_byte_t data[8];
int i;
/* Save the length before padding. */
for (i = 0; i < 8; ++i)
- data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
+ data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
/* Pad to 56 bytes mod 64. */
md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
/* Append the length. */
md5_append(pms, data, 8);
for (i = 0; i < 16; ++i)
- digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
+ digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
}
diff --git a/Modules/md5module.c b/Modules/md5module.c
index 1e2e6e3..ce94fb5 100644
--- a/Modules/md5module.c
+++ b/Modules/md5module.c
@@ -14,25 +14,25 @@
#include "md5.h"
typedef struct {
- PyObject_HEAD
- md5_state_t md5; /* the context holder */
+ PyObject_HEAD
+ md5_state_t md5; /* the context holder */
} md5object;
static PyTypeObject MD5type;
-#define is_md5object(v) ((v)->ob_type == &MD5type)
+#define is_md5object(v) ((v)->ob_type == &MD5type)
static md5object *
newmd5object(void)
{
- md5object *md5p;
+ md5object *md5p;
- md5p = PyObject_New(md5object, &MD5type);
- if (md5p == NULL)
- return NULL;
+ md5p = PyObject_New(md5object, &MD5type);
+ if (md5p == NULL)
+ return NULL;
- md5_init(&md5p->md5); /* actual initialisation */
- return md5p;
+ md5_init(&md5p->md5); /* actual initialisation */
+ return md5p;
}
@@ -41,7 +41,7 @@ newmd5object(void)
static void
md5_dealloc(md5object *md5p)
{
- PyObject_Del(md5p);
+ PyObject_Del(md5p);
}
@@ -50,16 +50,16 @@ md5_dealloc(md5object *md5p)
static PyObject *
md5_update(md5object *self, PyObject *args)
{
- unsigned char *cp;
- int len;
+ unsigned char *cp;
+ int len;
- if (!PyArg_ParseTuple(args, "s#:update", &cp, &len))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s#:update", &cp, &len))
+ return NULL;
- md5_append(&self->md5, cp, len);
+ md5_append(&self->md5, cp, len);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(update_doc,
@@ -73,14 +73,14 @@ arguments.");
static PyObject *
md5_digest(md5object *self)
{
- md5_state_t mdContext;
- unsigned char aDigest[16];
+ md5_state_t mdContext;
+ unsigned char aDigest[16];
- /* make a temporary copy, and perform the final */
- mdContext = self->md5;
- md5_finish(&mdContext, aDigest);
+ /* make a temporary copy, and perform the final */
+ mdContext = self->md5;
+ md5_finish(&mdContext, aDigest);
- return PyString_FromStringAndSize((char *)aDigest, 16);
+ return PyString_FromStringAndSize((char *)aDigest, 16);
}
PyDoc_STRVAR(digest_doc,
@@ -94,26 +94,26 @@ including null bytes.");
static PyObject *
md5_hexdigest(md5object *self)
{
- md5_state_t mdContext;
- unsigned char digest[16];
- unsigned char hexdigest[32];
- int i, j;
-
- /* make a temporary copy, and perform the final */
- mdContext = self->md5;
- md5_finish(&mdContext, digest);
-
- /* Make hex version of the digest */
- for(i=j=0; i<16; i++) {
- char c;
- c = (digest[i] >> 4) & 0xf;
- c = (c>9) ? c+'a'-10 : c + '0';
- hexdigest[j++] = c;
- c = (digest[i] & 0xf);
- c = (c>9) ? c+'a'-10 : c + '0';
- hexdigest[j++] = c;
- }
- return PyString_FromStringAndSize((char*)hexdigest, 32);
+ md5_state_t mdContext;
+ unsigned char digest[16];
+ unsigned char hexdigest[32];
+ int i, j;
+
+ /* make a temporary copy, and perform the final */
+ mdContext = self->md5;
+ md5_finish(&mdContext, digest);
+
+ /* Make hex version of the digest */
+ for(i=j=0; i<16; i++) {
+ char c;
+ c = (digest[i] >> 4) & 0xf;
+ c = (c>9) ? c+'a'-10 : c + '0';
+ hexdigest[j++] = c;
+ c = (digest[i] & 0xf);
+ c = (c>9) ? c+'a'-10 : c + '0';
+ hexdigest[j++] = c;
+ }
+ return PyString_FromStringAndSize((char*)hexdigest, 32);
}
@@ -126,14 +126,14 @@ Like digest(), but returns the digest as a string of hexadecimal digits.");
static PyObject *
md5_copy(md5object *self)
{
- md5object *md5p;
+ md5object *md5p;
- if ((md5p = newmd5object()) == NULL)
- return NULL;
+ if ((md5p = newmd5object()) == NULL)
+ return NULL;
- md5p->md5 = self->md5;
+ md5p->md5 = self->md5;
- return (PyObject *)md5p;
+ return (PyObject *)md5p;
}
PyDoc_STRVAR(copy_doc,
@@ -143,11 +143,11 @@ Return a copy (``clone'') of the md5 object.");
static PyMethodDef md5_methods[] = {
- {"update", (PyCFunction)md5_update, METH_VARARGS, update_doc},
- {"digest", (PyCFunction)md5_digest, METH_NOARGS, digest_doc},
- {"hexdigest", (PyCFunction)md5_hexdigest, METH_NOARGS, hexdigest_doc},
- {"copy", (PyCFunction)md5_copy, METH_NOARGS, copy_doc},
- {NULL, NULL} /* sentinel */
+ {"update", (PyCFunction)md5_update, METH_VARARGS, update_doc},
+ {"digest", (PyCFunction)md5_digest, METH_NOARGS, digest_doc},
+ {"hexdigest", (PyCFunction)md5_hexdigest, METH_NOARGS, hexdigest_doc},
+ {"copy", (PyCFunction)md5_copy, METH_NOARGS, copy_doc},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
@@ -221,37 +221,37 @@ hexdigest() -- return the current digest as a string of hexadecimal digits\n\
copy() -- return a copy of the current md5 object");
static PyTypeObject MD5type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_md5.md5", /*tp_name*/
- sizeof(md5object), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)md5_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- md5type_doc, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- md5_methods, /*tp_methods*/
- 0, /*tp_members*/
- md5_getseters, /*tp_getset*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_md5.md5", /*tp_name*/
+ sizeof(md5object), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)md5_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ md5type_doc, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ md5_methods, /*tp_methods*/
+ 0, /*tp_members*/
+ md5_getseters, /*tp_getset*/
};
@@ -260,20 +260,20 @@ static PyTypeObject MD5type = {
static PyObject *
MD5_new(PyObject *self, PyObject *args)
{
- md5object *md5p;
- unsigned char *cp = NULL;
- int len = 0;
+ md5object *md5p;
+ unsigned char *cp = NULL;
+ int len = 0;
- if (!PyArg_ParseTuple(args, "|s#:new", &cp, &len))
- return NULL;
+ if (!PyArg_ParseTuple(args, "|s#:new", &cp, &len))
+ return NULL;
- if ((md5p = newmd5object()) == NULL)
- return NULL;
+ if ((md5p = newmd5object()) == NULL)
+ return NULL;
- if (cp)
- md5_append(&md5p->md5, cp, len);
+ if (cp)
+ md5_append(&md5p->md5, cp, len);
- return (PyObject *)md5p;
+ return (PyObject *)md5p;
}
PyDoc_STRVAR(new_doc,
@@ -286,8 +286,8 @@ is made.");
/* List of functions exported by this module */
static PyMethodDef md5_functions[] = {
- {"new", (PyCFunction)MD5_new, METH_VARARGS, new_doc},
- {NULL, NULL} /* Sentinel */
+ {"new", (PyCFunction)MD5_new, METH_VARARGS, new_doc},
+ {NULL, NULL} /* Sentinel */
};
@@ -296,16 +296,16 @@ static PyMethodDef md5_functions[] = {
PyMODINIT_FUNC
init_md5(void)
{
- PyObject *m, *d;
-
- Py_TYPE(&MD5type) = &PyType_Type;
- if (PyType_Ready(&MD5type) < 0)
- return;
- m = Py_InitModule3("_md5", md5_functions, module_doc);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- PyDict_SetItemString(d, "MD5Type", (PyObject *)&MD5type);
- PyModule_AddIntConstant(m, "digest_size", 16);
- /* No need to check the error here, the caller will do that */
+ PyObject *m, *d;
+
+ Py_TYPE(&MD5type) = &PyType_Type;
+ if (PyType_Ready(&MD5type) < 0)
+ return;
+ m = Py_InitModule3("_md5", md5_functions, module_doc);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ PyDict_SetItemString(d, "MD5Type", (PyObject *)&MD5type);
+ PyModule_AddIntConstant(m, "digest_size", 16);
+ /* No need to check the error here, the caller will do that */
}
diff --git a/Modules/mmapmodule.c b/Modules/mmapmodule.c
index ac572d2..24f7851 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,30 +79,30 @@ 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;
+ PyObject_HEAD
+ char * data;
+ size_t size;
+ size_t pos; /* relative to offset */
+ size_t offset;
#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;
@@ -110,321 +110,321 @@ 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)
{
#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("c", 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("c", 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 = PyString_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 = PyString_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 = Py_BuildValue("s#", 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 = Py_BuildValue("s#", 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 ? "s#|nn:rfind" : "s#|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 PyInt_FromSsize_t(p - self->data);
- }
- }
- return PyInt_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 ? "s#|nn:rfind" : "s#|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 PyInt_FromSsize_t(p - self->data);
+ }
+ }
+ return PyInt_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_writeable(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->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->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, "s#:write", &data, &length))
- return(NULL);
-
- if (!is_writeable(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, "s#:write", &data, &length))
+ return(NULL);
+
+ if (!is_writeable(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, "c:write_byte", &value))
- return(NULL);
-
- if (!is_writeable(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, "c:write_byte", &value))
+ return(NULL);
+
+ if (!is_writeable(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 PyInt_FromLong((long)low);
- size = (((PY_LONG_LONG)high)<<32) + low;
- return PyLong_FromLongLong(size);
- } else {
- return PyInt_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 PyInt_FromLong((long)low);
+ size = (((PY_LONG_LONG)high)<<32) + low;
+ return PyLong_FromLongLong(size);
+ } else {
+ return PyInt_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 PyInt_FromSsize_t(buf.st_size);
- }
+ {
+ struct stat buf;
+ if (-1 == fstat(self->fd, &buf)) {
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
+ return PyInt_FromSsize_t(buf.st_size);
+ }
#endif /* UNIX */
}
@@ -439,223 +439,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 PyInt_FromSize_t(self->pos);
+ CHECK_VALID(NULL);
+ return PyInt_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 PyInt_FromLong((long) FlushViewOfFile(self->data+offset, size));
+ return PyInt_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 PyInt_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 PyInt_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, count;
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &count) ||
- !is_writeable(self)) {
- return NULL;
- } else {
- /* bounds check the values */
- unsigned long pos = src > dest ? src : dest;
- if (self->size < pos || count > self->size - pos) {
- PyErr_SetString(PyExc_ValueError,
- "source or destination out of range");
- return NULL;
- } else {
- memmove(self->data+dest, self->data+src, count);
- Py_INCREF(Py_None);
- return Py_None;
- }
- }
+ unsigned long dest, src, count;
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &count) ||
+ !is_writeable(self)) {
+ return NULL;
+ } else {
+ /* bounds check the values */
+ unsigned long pos = src > dest ? src : dest;
+ if (self->size < pos || count > self->size - pos) {
+ PyErr_SetString(PyExc_ValueError,
+ "source or destination out of range");
+ return NULL;
+ } else {
+ memmove(self->data+dest, self->data+src, count);
+ 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 */
@@ -663,337 +663,337 @@ static struct PyMethodDef mmap_object_methods[] = {
static Py_ssize_t
mmap_buffer_getreadbuf(mmap_object *self, Py_ssize_t index, const void **ptr)
{
- CHECK_VALID(-1);
- if (index != 0) {
- PyErr_SetString(PyExc_SystemError,
- "Accessing non-existent mmap segment");
- return -1;
- }
- *ptr = self->data;
- return self->size;
+ CHECK_VALID(-1);
+ if (index != 0) {
+ PyErr_SetString(PyExc_SystemError,
+ "Accessing non-existent mmap segment");
+ return -1;
+ }
+ *ptr = self->data;
+ return self->size;
}
static Py_ssize_t
mmap_buffer_getwritebuf(mmap_object *self, Py_ssize_t index, const void **ptr)
{
- CHECK_VALID(-1);
- if (index != 0) {
- PyErr_SetString(PyExc_SystemError,
- "Accessing non-existent mmap segment");
- return -1;
- }
- if (!is_writeable(self))
- return -1;
- *ptr = self->data;
- return self->size;
+ CHECK_VALID(-1);
+ if (index != 0) {
+ PyErr_SetString(PyExc_SystemError,
+ "Accessing non-existent mmap segment");
+ return -1;
+ }
+ if (!is_writeable(self))
+ return -1;
+ *ptr = self->data;
+ return self->size;
}
static Py_ssize_t
mmap_buffer_getsegcount(mmap_object *self, Py_ssize_t *lenp)
{
- CHECK_VALID(-1);
- if (lenp)
- *lenp = self->size;
- return 1;
+ CHECK_VALID(-1);
+ if (lenp)
+ *lenp = self->size;
+ return 1;
}
static Py_ssize_t
mmap_buffer_getcharbuffer(mmap_object *self, Py_ssize_t index, const void **ptr)
{
- if (index != 0) {
- PyErr_SetString(PyExc_SystemError,
- "accessing non-existent buffer segment");
- return -1;
- }
- *ptr = (const char *)self->data;
- return self->size;
+ if (index != 0) {
+ PyErr_SetString(PyExc_SystemError,
+ "accessing non-existent buffer segment");
+ return -1;
+ }
+ *ptr = (const char *)self->data;
+ return self->size;
}
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 PyString_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 PyString_FromStringAndSize(self->data + i, 1);
}
static PyObject *
mmap_slice(mmap_object *self, Py_ssize_t ilow, Py_ssize_t ihigh)
{
- CHECK_VALID(NULL);
- if (ilow < 0)
- ilow = 0;
- else if ((size_t)ilow > self->size)
- ilow = self->size;
- if (ihigh < 0)
- ihigh = 0;
- if (ihigh < ilow)
- ihigh = ilow;
- else if ((size_t)ihigh > self->size)
- ihigh = self->size;
-
- return PyString_FromStringAndSize(self->data + ilow, ihigh-ilow);
+ CHECK_VALID(NULL);
+ if (ilow < 0)
+ ilow = 0;
+ else if ((size_t)ilow > self->size)
+ ilow = self->size;
+ if (ihigh < 0)
+ ihigh = 0;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if ((size_t)ihigh > self->size)
+ ihigh = self->size;
+
+ return PyString_FromStringAndSize(self->data + ilow, ihigh-ilow);
}
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 PyString_FromStringAndSize(self->data + i, 1);
- }
- 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 PyString_FromStringAndSize("", 0);
- else if (step == 1)
- return PyString_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 = PyString_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 PyString_FromStringAndSize(self->data + i, 1);
+ }
+ 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 PyString_FromStringAndSize("", 0);
+ else if (step == 1)
+ return PyString_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 = PyString_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_slice(mmap_object *self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
{
- const char *buf;
-
- CHECK_VALID(-1);
- if (ilow < 0)
- ilow = 0;
- else if ((size_t)ilow > self->size)
- ilow = self->size;
- if (ihigh < 0)
- ihigh = 0;
- if (ihigh < ilow)
- ihigh = ilow;
- else if ((size_t)ihigh > self->size)
- ihigh = self->size;
-
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "mmap object doesn't support slice deletion");
- return -1;
- }
- if (! (PyString_Check(v)) ) {
- PyErr_SetString(PyExc_IndexError,
- "mmap slice assignment must be a string");
- return -1;
- }
- if (PyString_Size(v) != (ihigh - ilow)) {
- PyErr_SetString(PyExc_IndexError,
- "mmap slice assignment is wrong size");
- return -1;
- }
- if (!is_writeable(self))
- return -1;
- buf = PyString_AsString(v);
- memcpy(self->data + ilow, buf, ihigh-ilow);
- return 0;
+ const char *buf;
+
+ CHECK_VALID(-1);
+ if (ilow < 0)
+ ilow = 0;
+ else if ((size_t)ilow > self->size)
+ ilow = self->size;
+ if (ihigh < 0)
+ ihigh = 0;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if ((size_t)ihigh > self->size)
+ ihigh = self->size;
+
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap object doesn't support slice deletion");
+ return -1;
+ }
+ if (! (PyString_Check(v)) ) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap slice assignment must be a string");
+ return -1;
+ }
+ if (PyString_Size(v) != (ihigh - ilow)) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap slice assignment is wrong size");
+ return -1;
+ }
+ if (!is_writeable(self))
+ return -1;
+ buf = PyString_AsString(v);
+ memcpy(self->data + ilow, buf, ihigh-ilow);
+ return 0;
}
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 (! (PyString_Check(v) && PyString_Size(v)==1) ) {
- PyErr_SetString(PyExc_IndexError,
- "mmap assignment must be single-character string");
- return -1;
- }
- if (!is_writeable(self))
- return -1;
- buf = PyString_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 (! (PyString_Check(v) && PyString_Size(v)==1) ) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap assignment must be single-character string");
+ return -1;
+ }
+ if (!is_writeable(self))
+ return -1;
+ buf = PyString_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 (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- const char *buf;
-
- 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 object doesn't support item deletion");
- return -1;
- }
- if (!PyString_Check(value) || PyString_Size(value) != 1) {
- PyErr_SetString(PyExc_IndexError,
- "mmap assignment must be single-character string");
- return -1;
- }
- if (!is_writeable(self))
- return -1;
- buf = PyString_AsString(value);
- self->data[i] = buf[0];
- return 0;
- }
- 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 -1;
- }
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "mmap object doesn't support slice deletion");
- return -1;
- }
- if (!PyString_Check(value)) {
- PyErr_SetString(PyExc_IndexError,
- "mmap slice assignment must be a string");
- return -1;
- }
- if (PyString_Size(value) != slicelen) {
- PyErr_SetString(PyExc_IndexError,
- "mmap slice assignment is wrong size");
- return -1;
- }
- if (!is_writeable(self))
- return -1;
-
- if (slicelen == 0)
- return 0;
- else if (step == 1) {
- const char *buf = PyString_AsString(value);
-
- if (buf == NULL)
- return -1;
- memcpy(self->data + start, buf, slicelen);
- return 0;
- }
- else {
- Py_ssize_t cur, i;
- const char *buf = PyString_AsString(value);
-
- if (buf == NULL)
- return -1;
- for (cur = start, i = 0; i < slicelen;
- cur += step, i++) {
- self->data[cur] = buf[i];
- }
- return 0;
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "mmap indices must be integer");
- return -1;
- }
+ CHECK_VALID(-1);
+
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ const char *buf;
+
+ 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 object doesn't support item deletion");
+ return -1;
+ }
+ if (!PyString_Check(value) || PyString_Size(value) != 1) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap assignment must be single-character string");
+ return -1;
+ }
+ if (!is_writeable(self))
+ return -1;
+ buf = PyString_AsString(value);
+ self->data[i] = buf[0];
+ return 0;
+ }
+ 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 -1;
+ }
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap object doesn't support slice deletion");
+ return -1;
+ }
+ if (!PyString_Check(value)) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap slice assignment must be a string");
+ return -1;
+ }
+ if (PyString_Size(value) != slicelen) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap slice assignment is wrong size");
+ return -1;
+ }
+ if (!is_writeable(self))
+ return -1;
+
+ if (slicelen == 0)
+ return 0;
+ else if (step == 1) {
+ const char *buf = PyString_AsString(value);
+
+ if (buf == NULL)
+ return -1;
+ memcpy(self->data + start, buf, slicelen);
+ return 0;
+ }
+ else {
+ Py_ssize_t cur, i;
+ const char *buf = PyString_AsString(value);
+
+ if (buf == NULL)
+ return -1;
+ for (cur = start, i = 0; i < slicelen;
+ cur += step, i++) {
+ self->data[cur] = buf[i];
+ }
+ 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*/
- (ssizessizeargfunc)mmap_slice, /*sq_slice*/
- (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/
- (ssizessizeobjargproc)mmap_ass_slice, /*sq_ass_slice*/
+ (lenfunc)mmap_length, /*sq_length*/
+ (binaryfunc)mmap_concat, /*sq_concat*/
+ (ssizeargfunc)mmap_repeat, /*sq_repeat*/
+ (ssizeargfunc)mmap_item, /*sq_item*/
+ (ssizessizeargfunc)mmap_slice, /*sq_slice*/
+ (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/
+ (ssizessizeobjargproc)mmap_ass_slice, /*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 = {
- (readbufferproc)mmap_buffer_getreadbuf,
- (writebufferproc)mmap_buffer_getwritebuf,
- (segcountproc)mmap_buffer_getsegcount,
- (charbufferproc)mmap_buffer_getcharbuffer,
+ (readbufferproc)mmap_buffer_getreadbuf,
+ (writebufferproc)mmap_buffer_getwritebuf,
+ (segcountproc)mmap_buffer_getsegcount,
+ (charbufferproc)mmap_buffer_getcharbuffer,
};
static PyObject *
@@ -1024,46 +1024,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_compare */
- 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 | Py_TPFLAGS_HAVE_GETCHARBUFFER, /*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_compare */
+ 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 | Py_TPFLAGS_HAVE_GETCHARBUFFER, /*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 */
};
@@ -1074,23 +1074,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
@@ -1098,124 +1098,124 @@ 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->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->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 */
@@ -1223,250 +1223,250 @@ 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_Warn(PyExc_DeprecationWarning,
- "don't use 0 for anonymous memory");
- */
- 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_Warn(PyExc_DeprecationWarning,
+ "don't use 0 for anonymous memory");
+ */
+ 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;
-
- /* 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;
+
+ /* 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 = PyInt_FromLong(value);
- if (o && PyDict_SetItemString(d, name, o) == 0) {
- Py_DECREF(o);
- }
+ PyObject *o = PyInt_FromLong(value);
+ if (o && PyDict_SetItemString(d, name, o) == 0) {
+ Py_DECREF(o);
+ }
}
PyMODINIT_FUNC
initmmap(void)
{
- PyObject *dict, *module;
-
- if (PyType_Ready(&mmap_object_type) < 0)
- return;
-
- module = Py_InitModule("mmap", NULL);
- if (module == NULL)
- return;
- dict = PyModule_GetDict(module);
- if (!dict)
- return;
- mmap_module_error = PyErr_NewException("mmap.error",
- PyExc_EnvironmentError , NULL);
- if (mmap_module_error == NULL)
- return;
- 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;
+
+ module = Py_InitModule("mmap", NULL);
+ if (module == NULL)
+ return;
+ dict = PyModule_GetDict(module);
+ if (!dict)
+ return;
+ mmap_module_error = PyErr_NewException("mmap.error",
+ PyExc_EnvironmentError , NULL);
+ if (mmap_module_error == NULL)
+ return;
+ 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);
+ setint(dict, "ACCESS_READ", ACCESS_READ);
+ setint(dict, "ACCESS_WRITE", ACCESS_WRITE);
+ setint(dict, "ACCESS_COPY", ACCESS_COPY);
}
diff --git a/Modules/nismodule.c b/Modules/nismodule.c
index 9fbab5a..04d8570 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 = PyString_FromStringAndSize(inkey, inkeylen);
- val = PyString_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 = PyString_FromStringAndSize(inkey, inkeylen);
+ val = PyString_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 = PyString_FromStringAndSize (domain, strlen(domain));
- return res;
+ res = PyString_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,
- "t#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 = PyString_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,
+ "t#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 = PyString_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,105 +329,105 @@ 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 = PyString_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 = PyString_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__,
@@ -436,12 +436,12 @@ PyDoc_STRVAR(nis__doc__,
void
initnis (void)
{
- PyObject *m, *d;
- m = Py_InitModule3("nis", nis_methods, nis__doc__);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- NisError = PyErr_NewException("nis.error", NULL, NULL);
- if (NisError != NULL)
- PyDict_SetItemString(d, "error", NisError);
+ PyObject *m, *d;
+ m = Py_InitModule3("nis", nis_methods, nis__doc__);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ NisError = PyErr_NewException("nis.error", NULL, NULL);
+ if (NisError != NULL)
+ PyDict_SetItemString(d, "error", NisError);
}
diff --git a/Modules/operator.c b/Modules/operator.c
index 3ed4bc5..591b5ea 100644
--- a/Modules/operator.c
+++ b/Modules/operator.c
@@ -121,88 +121,88 @@ 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;
}
static PyObject*
op_getslice(PyObject *s, PyObject *a)
{
- PyObject *a1;
- Py_ssize_t a2, a3;
+ PyObject *a1;
+ Py_ssize_t a2, a3;
- if (!PyArg_ParseTuple(a, "Onn:getslice", &a1, &a2, &a3))
- return NULL;
- return PySequence_GetSlice(a1, a2, a3);
+ if (!PyArg_ParseTuple(a, "Onn:getslice", &a1, &a2, &a3))
+ return NULL;
+ return PySequence_GetSlice(a1, a2, a3);
}
static PyObject*
op_setslice(PyObject *s, PyObject *a)
{
- PyObject *a1, *a4;
- Py_ssize_t a2, a3;
+ PyObject *a1, *a4;
+ Py_ssize_t a2, a3;
- if (!PyArg_ParseTuple(a, "OnnO:setslice", &a1, &a2, &a3, &a4))
- return NULL;
+ if (!PyArg_ParseTuple(a, "OnnO:setslice", &a1, &a2, &a3, &a4))
+ return NULL;
- if (-1 == PySequence_SetSlice(a1, a2, a3, a4))
- return NULL;
+ if (-1 == PySequence_SetSlice(a1, a2, a3, a4))
+ return NULL;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static PyObject*
op_delslice(PyObject *s, PyObject *a)
{
- PyObject *a1;
- Py_ssize_t a2, a3;
+ PyObject *a1;
+ Py_ssize_t a2, a3;
- if (!PyArg_ParseTuple(a, "Onn:delslice", &a1, &a2, &a3))
- return NULL;
+ if (!PyArg_ParseTuple(a, "Onn:delslice", &a1, &a2, &a3))
+ return NULL;
- if (-1 == PySequence_DelSlice(a1, a2, a3))
- return NULL;
+ if (-1 == PySequence_DelSlice(a1, a2, a3))
+ return NULL;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
#undef spam1
@@ -211,10 +211,10 @@ op_delslice(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[] = {
@@ -299,16 +299,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;
@@ -316,77 +316,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,
@@ -397,55 +397,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_compare */
- 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_compare */
+ 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;
@@ -453,120 +453,120 @@ 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;
+ char *s, *p;
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(attr)) {
- attr = _PyUnicode_AsDefaultEncodedString(attr, NULL);
- if (attr == NULL)
- return NULL;
- }
+ if (PyUnicode_Check(attr)) {
+ attr = _PyUnicode_AsDefaultEncodedString(attr, NULL);
+ if (attr == NULL)
+ return NULL;
+ }
#endif
-
- if (!PyString_Check(attr)) {
- PyErr_SetString(PyExc_TypeError,
- "attribute name must be a string");
- return NULL;
- }
-
- s = PyString_AS_STRING(attr);
- Py_INCREF(obj);
- for (;;) {
- PyObject *newobj, *str;
- p = strchr(s, '.');
- str = p ? PyString_FromStringAndSize(s, (p-s)) :
- PyString_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;
+
+ if (!PyString_Check(attr)) {
+ PyErr_SetString(PyExc_TypeError,
+ "attribute name must be a string");
+ return NULL;
+ }
+
+ s = PyString_AS_STRING(attr);
+ Py_INCREF(obj);
+ for (;;) {
+ PyObject *newobj, *str;
+ p = strchr(s, '.');
+ str = p ? PyString_FromStringAndSize(s, (p-s)) :
+ PyString_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,
@@ -579,56 +579,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_compare */
- 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_compare */
+ 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;
@@ -636,69 +636,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,
@@ -710,46 +710,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_compare */
- 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_compare */
+ 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 */
};
@@ -758,26 +758,26 @@ static PyTypeObject methodcaller_type = {
PyMODINIT_FUNC
initoperator(void)
{
- PyObject *m;
-
- /* Create the module and add the functions */
- m = Py_InitModule4("operator", operator_methods, operator_doc,
- (PyObject*)NULL, PYTHON_API_VERSION);
- if (m == NULL)
- return;
-
- if (PyType_Ready(&itemgetter_type) < 0)
- return;
- Py_INCREF(&itemgetter_type);
- PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type);
-
- if (PyType_Ready(&attrgetter_type) < 0)
- return;
- Py_INCREF(&attrgetter_type);
- PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type);
-
- if (PyType_Ready(&methodcaller_type) < 0)
- return;
- Py_INCREF(&methodcaller_type);
- PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type);
+ PyObject *m;
+
+ /* Create the module and add the functions */
+ m = Py_InitModule4("operator", operator_methods, operator_doc,
+ (PyObject*)NULL, PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
+
+ if (PyType_Ready(&itemgetter_type) < 0)
+ return;
+ Py_INCREF(&itemgetter_type);
+ PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type);
+
+ if (PyType_Ready(&attrgetter_type) < 0)
+ return;
+ Py_INCREF(&attrgetter_type);
+ PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type);
+
+ if (PyType_Ready(&methodcaller_type) < 0)
+ return;
+ Py_INCREF(&methodcaller_type);
+ PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type);
}
diff --git a/Modules/parsermodule.c b/Modules/parsermodule.c
index 12b7fc3..0dd69cd 100644
--- a/Modules/parsermodule.c
+++ b/Modules/parsermodule.c
@@ -555,8 +555,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;
}
@@ -767,7 +767,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);
return 0;
@@ -940,9 +940,9 @@ VALIDATER(arglist); VALIDATER(argument);
VALIDATER(listmaker); VALIDATER(yield_stmt);
VALIDATER(testlist1); VALIDATER(gen_for);
VALIDATER(gen_iter); VALIDATER(gen_if);
-VALIDATER(testlist_gexp); VALIDATER(yield_expr);
-VALIDATER(yield_or_testlist); VALIDATER(or_test);
-VALIDATER(old_test); VALIDATER(old_lambdef);
+VALIDATER(testlist_gexp); VALIDATER(yield_expr);
+VALIDATER(yield_or_testlist); VALIDATER(or_test);
+VALIDATER(old_test); VALIDATER(old_lambdef);
#undef VALIDATER
@@ -1031,7 +1031,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")
@@ -1042,17 +1042,17 @@ validate_class(node *tree)
else {
(void) validate_numnodes(tree, 4, "class");
}
-
+
if (res) {
- if (nch == 7) {
- res = ((validate_lparen(CHILD(tree, 2)) &&
- validate_testlist(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_testlist(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);
}
@@ -1433,7 +1433,7 @@ validate_gen_if(node *tree)
res = validate_gen_iter(CHILD(tree, 2));
else
res = validate_numnodes(tree, 2, "gen_if");
-
+
if (res)
res = (validate_name(CHILD(tree, 0), "if")
&& validate_old_test(CHILD(tree, 1)));
@@ -1593,10 +1593,10 @@ validate_compound_stmt(node *tree)
static int
validate_yield_or_testlist(node *tree)
{
- if (TYPE(tree) == yield_expr)
- return validate_yield_expr(tree);
- else
- return validate_testlist(tree);
+ if (TYPE(tree) == yield_expr)
+ return validate_yield_expr(tree);
+ else
+ return validate_testlist(tree);
}
static int
@@ -1611,7 +1611,7 @@ validate_expr_stmt(node *tree)
if (res && nch == 3
&& TYPE(CHILD(tree, 1)) == augassign) {
res = validate_numnodes(CHILD(tree, 1), 1, "augassign")
- && validate_yield_or_testlist(CHILD(tree, 2));
+ && validate_yield_or_testlist(CHILD(tree, 2));
if (res) {
char *s = STR(CHILD(CHILD(tree, 1), 0));
@@ -1837,14 +1837,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);
}
@@ -1857,8 +1857,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);
}
@@ -1867,13 +1867,13 @@ 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
+/* Helper function to count the number of leading dots in
* 'from ...module import name'
*/
static int
@@ -1881,8 +1881,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;
}
@@ -1892,24 +1892,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);
}
@@ -1921,9 +1921,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;
@@ -2456,11 +2456,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_gexp(CHILD(tree, 1));
- }
+ if (TYPE(CHILD(tree, 1))==yield_expr)
+ res = validate_yield_expr(CHILD(tree, 1));
+ else
+ res = validate_testlist_gexp(CHILD(tree, 1));
+ }
break;
case LSQB:
if (nch == 2)
@@ -2586,17 +2586,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;
@@ -2608,12 +2608,12 @@ validate_decorator(node *tree)
static int
validate_decorators(node *tree)
{
- int i, nch, ok;
+ int i, nch, ok;
nch = NCH(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;
}
@@ -2644,14 +2644,14 @@ validate_with_stmt(node *tree)
&& ((nch == 4) || (nch == 5))
&& validate_name(CHILD(tree, 0), "with")
&& validate_test(CHILD(tree, 1))
- && (nch == 4 || validate_with_var(CHILD(tree, 2)))
+ && (nch == 4 || validate_with_var(CHILD(tree, 2)))
&& validate_colon(RCHILD(tree, -2))
&& validate_suite(RCHILD(tree, -1)));
return ok;
}
/* funcdef:
- *
+ *
* -5 -4 -3 -2 -1
* 'def' NAME parameters ':' suite
*/
@@ -2660,12 +2660,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;
}
@@ -2678,11 +2678,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;
}
@@ -3032,9 +3032,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?)
@@ -3106,12 +3106,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;
@@ -3347,7 +3347,7 @@ initparser(void)
Py_TYPE(&PyST_Type) = &PyType_Type;
module = Py_InitModule("parser", parser_functions);
if (module == NULL)
- return;
+ return;
if (parser_error == 0)
parser_error = PyErr_NewException("parser.ParserError", NULL, NULL);
diff --git a/Modules/puremodule.c b/Modules/puremodule.c
index ede63ab..b89f172 100644
--- a/Modules/puremodule.c
+++ b/Modules/puremodule.c
@@ -58,107 +58,107 @@ typedef int (*PrintfishFunc)(const char*, ...);
typedef int (*StringIntArgFunc)(const char*, int);
-
+
static PyObject*
call_voidarg_function(VoidArgFunc func, PyObject *self, PyObject *args)
{
- int status;
+ int status;
- if (!PyArg_ParseTuple(args, ""))
- return NULL;
+ if (!PyArg_ParseTuple(args, ""))
+ return NULL;
- status = func();
- return Py_BuildValue("i", status);
+ status = func();
+ return Py_BuildValue("i", status);
}
static PyObject*
call_stringarg_function(StringArgFunc func, PyObject *self, PyObject *args)
{
- int status;
- char* stringarg;
+ int status;
+ char* stringarg;
- if (!PyArg_ParseTuple(args, "s", &stringarg))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s", &stringarg))
+ return NULL;
- status = func(stringarg);
- return Py_BuildValue("i", status);
+ status = func(stringarg);
+ return Py_BuildValue("i", status);
}
static PyObject*
call_stringorint_function(StringArgFunc func, PyObject *self, PyObject *args)
{
- int status;
- int intarg;
- char* stringarg;
+ int status;
+ int intarg;
+ char* stringarg;
- /* according to the quantify.h file, the argument to
- * quantify_*_recording_system_call can be an integer or a string,
- * but the functions are prototyped as taking a single char*
- * argument. Yikes!
+ /* according to the quantify.h file, the argument to
+ * quantify_*_recording_system_call can be an integer or a string,
+ * but the functions are prototyped as taking a single char*
+ * argument. Yikes!
+ */
+ if (PyArg_ParseTuple(args, "i", &intarg))
+ /* func is prototyped as int(*)(char*)
+ * better shut up the compiler
*/
- if (PyArg_ParseTuple(args, "i", &intarg))
- /* func is prototyped as int(*)(char*)
- * better shut up the compiler
- */
- status = func((char*)intarg);
+ status = func((char*)intarg);
- else {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "s", &stringarg))
- return NULL;
- else
- status = func(stringarg);
- }
- return Py_BuildValue("i", status);
+ else {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "s", &stringarg))
+ return NULL;
+ else
+ status = func(stringarg);
+ }
+ return Py_BuildValue("i", status);
}
static PyObject*
call_printfish_function(PrintfishFunc func, PyObject *self, PyObject *args)
{
- /* we support the printf() style vararg functions by requiring the
- * formatting be done in Python. At the C level we pass just a string
- * to the printf() style function.
- */
- int status;
- char* argstring;
+ /* we support the printf() style vararg functions by requiring the
+ * formatting be done in Python. At the C level we pass just a string
+ * to the printf() style function.
+ */
+ int status;
+ char* argstring;
- if (!PyArg_ParseTuple(args, "s", &argstring))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s", &argstring))
+ return NULL;
- status = func("%s", argstring);
- return Py_BuildValue("i", status);
+ status = func("%s", argstring);
+ return Py_BuildValue("i", status);
}
static PyObject*
call_intasaddr_function(StringArgFunc func, PyObject *self, PyObject *args)
{
- long memrep;
- int id;
+ long memrep;
+ int id;
- if (!PyArg_ParseTuple(args, "l", &memrep))
- return NULL;
+ if (!PyArg_ParseTuple(args, "l", &memrep))
+ return NULL;
- id = func((char*)memrep);
- return Py_BuildValue("i", id);
+ id = func((char*)memrep);
+ return Py_BuildValue("i", id);
}
static PyObject*
call_stringandint_function(StringIntArgFunc func, PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- long srcrep;
- int size;
- int status;
+ long srcrep;
+ int size;
+ int status;
- if (!PyArg_ParseTuple(args, "li", &srcrep, &size))
- return NULL;
+ if (!PyArg_ParseTuple(args, "li", &srcrep, &size))
+ return NULL;
- status = func((char*)srcrep, size);
- return Py_BuildValue("i", status);
+ status = func((char*)srcrep, size);
+ return Py_BuildValue("i", status);
}
-
+
/* functions common to all products
*
* N.B. These printf() style functions are a bit of a kludge. Since the
@@ -174,26 +174,26 @@ call_stringandint_function(StringIntArgFunc func, PyObject *self,
static PyObject*
pure_pure_logfile_printf(PyObject* self, PyObject* args)
{
- return call_printfish_function(pure_logfile_printf, self, args);
+ return call_printfish_function(pure_logfile_printf, self, args);
}
static PyObject*
pure_pure_printf(PyObject* self, PyObject* args)
{
- return call_printfish_function(pure_printf, self, args);
+ return call_printfish_function(pure_printf, self, args);
}
static PyObject*
pure_pure_printf_with_banner(PyObject* self, PyObject* args)
{
- return call_printfish_function(pure_printf_with_banner, self, args);
+ return call_printfish_function(pure_printf_with_banner, self, args);
}
#endif /* COMMON_PURE_FUNCTIONS */
-
+
/* Purify functions
*
* N.B. There are some interfaces described in the purify.h file that are
@@ -235,97 +235,97 @@ pure_pure_printf_with_banner(PyObject* self, PyObject* args)
static PyObject*
pure_purify_all_inuse(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_all_inuse, self, args);
+ return call_voidarg_function(purify_all_inuse, self, args);
}
static PyObject*
pure_purify_all_leaks(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_all_leaks, self, args);
+ return call_voidarg_function(purify_all_leaks, self, args);
}
static PyObject*
pure_purify_new_inuse(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_new_inuse, self, args);
+ return call_voidarg_function(purify_new_inuse, self, args);
}
static PyObject*
pure_purify_new_leaks(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_new_leaks, self, args);
+ return call_voidarg_function(purify_new_leaks, self, args);
}
static PyObject*
pure_purify_clear_inuse(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_clear_inuse, self, args);
+ return call_voidarg_function(purify_clear_inuse, self, args);
}
static PyObject*
pure_purify_clear_leaks(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_clear_leaks, self, args);
+ return call_voidarg_function(purify_clear_leaks, self, args);
}
static PyObject*
pure_purify_all_fds_inuse(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_all_fds_inuse, self, args);
+ return call_voidarg_function(purify_all_fds_inuse, self, args);
}
static PyObject*
pure_purify_new_fds_inuse(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_new_fds_inuse, self, args);
+ return call_voidarg_function(purify_new_fds_inuse, self, args);
}
static PyObject*
pure_purify_printf_with_call_chain(PyObject *self, PyObject *args)
{
- return call_printfish_function(purify_printf_with_call_chain,
- self, args);
+ return call_printfish_function(purify_printf_with_call_chain,
+ self, args);
}
static PyObject*
pure_purify_set_pool_id(PyObject *self, PyObject *args)
{
- long memrep;
- int id;
+ long memrep;
+ int id;
- if (!PyArg_ParseTuple(args, "li:purify_set_pool_id", &memrep, &id))
- return NULL;
+ if (!PyArg_ParseTuple(args, "li:purify_set_pool_id", &memrep, &id))
+ return NULL;
- purify_set_pool_id((char*)memrep, id);
- Py_INCREF(Py_None);
- return Py_None;
+ purify_set_pool_id((char*)memrep, id);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject*
pure_purify_get_pool_id(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_get_pool_id, self, args);
+ return call_intasaddr_function(purify_get_pool_id, self, args);
}
static PyObject*
pure_purify_set_user_data(PyObject *self, PyObject *args)
{
- long memrep;
- long datarep;
+ long memrep;
+ long datarep;
- if (!PyArg_ParseTuple(args, "ll:purify_set_user_data", &memrep, &datarep))
- return NULL;
+ if (!PyArg_ParseTuple(args, "ll:purify_set_user_data", &memrep, &datarep))
+ return NULL;
- purify_set_user_data((char*)memrep, (void*)datarep);
- Py_INCREF(Py_None);
- return Py_None;
+ purify_set_user_data((char*)memrep, (void*)datarep);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject*
pure_purify_get_user_data(PyObject *self, PyObject *args)
{
- /* can't use call_intasaddr_function() since purify_get_user_data()
- * returns a void*
- */
- long memrep;
- void* data;
+ /* can't use call_intasaddr_function() since purify_get_user_data()
+ * returns a void*
+ */
+ long memrep;
+ void* data;
- if (!PyArg_ParseTuple(args, "l:purify_get_user_data", &memrep))
- return NULL;
+ if (!PyArg_ParseTuple(args, "l:purify_get_user_data", &memrep))
+ return NULL;
- data = purify_get_user_data((char*)memrep);
- return Py_BuildValue("l", (long)data);
+ data = purify_get_user_data((char*)memrep);
+ return Py_BuildValue("l", (long)data);
}
-
+
/* this global variable is shared by both mapping functions:
* pure_purify_map_pool() and pure_purify_map_pool_id(). Since they cache
* this variable it should be safe in the face of recursion or cross
@@ -341,303 +341,303 @@ static PyObject* MapCallable = NULL;
static void
map_pool_callback(char* mem, int user_size, void *user_aux_data)
{
- long memrep = (long)mem;
- long user_aux_data_rep = (long)user_aux_data;
- PyObject* result;
- PyObject* memobj = Py_BuildValue("lil", memrep, user_size,
- user_aux_data_rep);
+ long memrep = (long)mem;
+ long user_aux_data_rep = (long)user_aux_data;
+ PyObject* result;
+ PyObject* memobj = Py_BuildValue("lil", memrep, user_size,
+ user_aux_data_rep);
- if (memobj == NULL)
- return;
+ if (memobj == NULL)
+ return;
- result = PyEval_CallObject(MapCallable, memobj);
- Py_DECREF(result);
- Py_DECREF(memobj);
+ result = PyEval_CallObject(MapCallable, memobj);
+ Py_DECREF(result);
+ Py_DECREF(memobj);
}
static PyObject*
pure_purify_map_pool(PyObject *self, PyObject *args)
{
- /* cache global variable in case of recursion */
- PyObject* saved_callable = MapCallable;
- PyObject* arg_callable;
- int id;
+ /* cache global variable in case of recursion */
+ PyObject* saved_callable = MapCallable;
+ PyObject* arg_callable;
+ int id;
- if (!PyArg_ParseTuple(args, "iO:purify_map_pool", &id, &arg_callable))
- return NULL;
+ if (!PyArg_ParseTuple(args, "iO:purify_map_pool", &id, &arg_callable))
+ return NULL;
- if (!PyCallable_Check(arg_callable)) {
- PyErr_SetString(PyExc_TypeError,
- "Second argument must be callable");
- return NULL;
- }
- MapCallable = arg_callable;
- purify_map_pool(id, map_pool_callback);
- MapCallable = saved_callable;
+ if (!PyCallable_Check(arg_callable)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Second argument must be callable");
+ return NULL;
+ }
+ MapCallable = arg_callable;
+ purify_map_pool(id, map_pool_callback);
+ MapCallable = saved_callable;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static void
PurifyMapPoolIdCallback(int id)
{
- PyObject* result;
- PyObject* intobj = Py_BuildValue("i", id);
+ PyObject* result;
+ PyObject* intobj = Py_BuildValue("i", id);
- if (intobj == NULL)
- return;
+ if (intobj == NULL)
+ return;
- result = PyEval_CallObject(MapCallable, intobj);
- Py_DECREF(result);
- Py_DECREF(intobj);
+ result = PyEval_CallObject(MapCallable, intobj);
+ Py_DECREF(result);
+ Py_DECREF(intobj);
}
static PyObject*
pure_purify_map_pool_id(PyObject *self, PyObject *args)
{
- /* cache global variable in case of recursion */
- PyObject* saved_callable = MapCallable;
- PyObject* arg_callable;
+ /* cache global variable in case of recursion */
+ PyObject* saved_callable = MapCallable;
+ PyObject* arg_callable;
- if (!PyArg_ParseTuple(args, "O:purify_map_pool_id", &arg_callable))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O:purify_map_pool_id", &arg_callable))
+ return NULL;
- if (!PyCallable_Check(arg_callable)) {
- PyErr_SetString(PyExc_TypeError, "Argument must be callable.");
- return NULL;
- }
+ if (!PyCallable_Check(arg_callable)) {
+ PyErr_SetString(PyExc_TypeError, "Argument must be callable.");
+ return NULL;
+ }
- MapCallable = arg_callable;
- purify_map_pool_id(PurifyMapPoolIdCallback);
- MapCallable = saved_callable;
+ MapCallable = arg_callable;
+ purify_map_pool_id(PurifyMapPoolIdCallback);
+ MapCallable = saved_callable;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject*
pure_purify_new_messages(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_new_messages, self, args);
+ return call_voidarg_function(purify_new_messages, self, args);
}
static PyObject*
pure_purify_all_messages(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_all_messages, self, args);
+ return call_voidarg_function(purify_all_messages, self, args);
}
static PyObject*
pure_purify_clear_messages(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_clear_messages, self, args);
+ return call_voidarg_function(purify_clear_messages, self, args);
}
static PyObject*
pure_purify_clear_new_messages(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_clear_new_messages, self, args);
+ return call_voidarg_function(purify_clear_new_messages, self, args);
}
static PyObject*
pure_purify_start_batch(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_start_batch, self, args);
+ return call_voidarg_function(purify_start_batch, self, args);
}
static PyObject*
pure_purify_start_batch_show_first(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_start_batch_show_first,
- self, args);
+ return call_voidarg_function(purify_start_batch_show_first,
+ self, args);
}
static PyObject*
pure_purify_stop_batch(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_stop_batch, self, args);
+ return call_voidarg_function(purify_stop_batch, self, args);
}
static PyObject*
pure_purify_name_thread(PyObject *self, PyObject *args)
{
- /* can't strictly use call_stringarg_function since
- * purify_name_thread takes a const char*, not a char*
- */
- int status;
- char* stringarg;
+ /* can't strictly use call_stringarg_function since
+ * purify_name_thread takes a const char*, not a char*
+ */
+ int status;
+ char* stringarg;
- if (!PyArg_ParseTuple(args, "s:purify_name_thread", &stringarg))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:purify_name_thread", &stringarg))
+ return NULL;
- status = purify_name_thread(stringarg);
- return Py_BuildValue("i", status);
+ status = purify_name_thread(stringarg);
+ return Py_BuildValue("i", status);
}
static PyObject*
pure_purify_watch(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch, self, args);
+ return call_intasaddr_function(purify_watch, self, args);
}
static PyObject*
pure_purify_watch_1(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_1, self, args);
+ return call_intasaddr_function(purify_watch_1, self, args);
}
static PyObject*
pure_purify_watch_2(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_2, self, args);
+ return call_intasaddr_function(purify_watch_2, self, args);
}
static PyObject*
pure_purify_watch_4(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_4, self, args);
+ return call_intasaddr_function(purify_watch_4, self, args);
}
static PyObject*
pure_purify_watch_8(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_8, self, args);
+ return call_intasaddr_function(purify_watch_8, self, args);
}
static PyObject*
pure_purify_watch_w_1(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_w_1, self, args);
+ return call_intasaddr_function(purify_watch_w_1, self, args);
}
static PyObject*
pure_purify_watch_w_2(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_w_2, self, args);
+ return call_intasaddr_function(purify_watch_w_2, self, args);
}
static PyObject*
pure_purify_watch_w_4(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_w_4, self, args);
+ return call_intasaddr_function(purify_watch_w_4, self, args);
}
static PyObject*
pure_purify_watch_w_8(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_w_8, self, args);
+ return call_intasaddr_function(purify_watch_w_8, self, args);
}
static PyObject*
pure_purify_watch_r_1(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_r_1, self, args);
+ return call_intasaddr_function(purify_watch_r_1, self, args);
}
static PyObject*
pure_purify_watch_r_2(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_r_2, self, args);
+ return call_intasaddr_function(purify_watch_r_2, self, args);
}
static PyObject*
pure_purify_watch_r_4(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_r_4, self, args);
+ return call_intasaddr_function(purify_watch_r_4, self, args);
}
static PyObject*
pure_purify_watch_r_8(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_r_8, self, args);
+ return call_intasaddr_function(purify_watch_r_8, self, args);
}
static PyObject*
pure_purify_watch_rw_1(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_rw_1, self, args);
+ return call_intasaddr_function(purify_watch_rw_1, self, args);
}
static PyObject*
pure_purify_watch_rw_2(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_rw_2, self, args);
+ return call_intasaddr_function(purify_watch_rw_2, self, args);
}
static PyObject*
pure_purify_watch_rw_4(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_rw_4, self, args);
+ return call_intasaddr_function(purify_watch_rw_4, self, args);
}
static PyObject*
pure_purify_watch_rw_8(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_rw_8, self, args);
+ return call_intasaddr_function(purify_watch_rw_8, self, args);
}
static PyObject*
pure_purify_watch_n(PyObject *self, PyObject *args)
{
- long addrrep;
- unsigned int size;
- char* type;
- int status;
+ long addrrep;
+ unsigned int size;
+ char* type;
+ int status;
- if (!PyArg_ParseTuple(args, "lis:purify_watch_n", &addrrep, &size, &type))
- return NULL;
+ if (!PyArg_ParseTuple(args, "lis:purify_watch_n", &addrrep, &size, &type))
+ return NULL;
- status = purify_watch_n((char*)addrrep, size, type);
- return Py_BuildValue("i", status);
+ status = purify_watch_n((char*)addrrep, size, type);
+ return Py_BuildValue("i", status);
}
static PyObject*
pure_purify_watch_info(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_watch_info, self, args);
+ return call_voidarg_function(purify_watch_info, self, args);
}
static PyObject*
pure_purify_watch_remove(PyObject *self, PyObject *args)
{
- int watchno;
- int status;
+ int watchno;
+ int status;
- if (!PyArg_ParseTuple(args, "i:purify_watch_remove", &watchno))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:purify_watch_remove", &watchno))
+ return NULL;
- status = purify_watch_remove(watchno);
- return Py_BuildValue("i", status);
+ status = purify_watch_remove(watchno);
+ return Py_BuildValue("i", status);
}
static PyObject*
pure_purify_watch_remove_all(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_watch_remove_all, self, args);
+ return call_voidarg_function(purify_watch_remove_all, self, args);
}
static PyObject*
pure_purify_describe(PyObject *self, PyObject *args)
{
- long addrrep;
- char* rtn;
+ long addrrep;
+ char* rtn;
- if (!PyArg_ParseTuple(args, "l:purify_describe", &addrrep))
- return NULL;
+ if (!PyArg_ParseTuple(args, "l:purify_describe", &addrrep))
+ return NULL;
- rtn = purify_describe((char*)addrrep);
- return Py_BuildValue("l", (long)rtn);
+ rtn = purify_describe((char*)addrrep);
+ return Py_BuildValue("l", (long)rtn);
}
static PyObject*
pure_purify_what_colors(PyObject *self, PyObject *args)
{
- long addrrep;
- unsigned int size;
- int status;
-
- if (!PyArg_ParseTuple(args, "li:purify_what_colors", &addrrep, &size))
- return NULL;
+ long addrrep;
+ unsigned int size;
+ int status;
+
+ if (!PyArg_ParseTuple(args, "li:purify_what_colors", &addrrep, &size))
+ return NULL;
- status = purify_what_colors((char*)addrrep, size);
- return Py_BuildValue("i", status);
+ status = purify_what_colors((char*)addrrep, size);
+ return Py_BuildValue("i", status);
}
static PyObject*
pure_purify_is_running(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_is_running, self, args);
+ return call_voidarg_function(purify_is_running, self, args);
}
static PyObject*
pure_purify_assert_is_readable(PyObject *self, PyObject *args)
{
- return call_stringandint_function(purify_assert_is_readable,
- self, args);
+ return call_stringandint_function(purify_assert_is_readable,
+ self, args);
}
static PyObject*
pure_purify_assert_is_writable(PyObject *self, PyObject *args)
{
- return call_stringandint_function(purify_assert_is_writable,
- self, args);
+ return call_stringandint_function(purify_assert_is_writable,
+ self, args);
}
#if HAS_PURIFY_EXIT
@@ -649,22 +649,22 @@ pure_purify_assert_is_writable(PyObject *self, PyObject *args)
static PyObject*
pure_purify_exit(PyObject *self, PyObject *args)
{
- int status;
+ int status;
- if (!PyArg_ParseTuple(args, "i:purify_exit", &status))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:purify_exit", &status))
+ return NULL;
- /* purify_exit doesn't always act like exit(). See the manual */
- purify_exit(status);
- Py_INCREF(Py_None);
- return Py_None;
+ /* purify_exit doesn't always act like exit(). See the manual */
+ purify_exit(status);
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* HAS_PURIFY_EXIT */
#endif /* PURIFY_H */
-
+
/* Quantify functions
*
* N.B. Some of these functions are only described in the quantify.h file,
@@ -680,144 +680,144 @@ pure_purify_exit(PyObject *self, PyObject *args)
static PyObject*
pure_quantify_is_running(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_is_running, self, args);
+ return call_voidarg_function(quantify_is_running, self, args);
}
static PyObject*
pure_quantify_help(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_help, self, args);
+ return call_voidarg_function(quantify_help, self, args);
}
static PyObject*
pure_quantify_print_recording_state(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_print_recording_state,
- self, args);
+ return call_voidarg_function(quantify_print_recording_state,
+ self, args);
}
static PyObject*
pure_quantify_start_recording_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_start_recording_data,
- self, args);
+ return call_voidarg_function(quantify_start_recording_data,
+ self, args);
}
static PyObject*
pure_quantify_stop_recording_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_stop_recording_data, self, args);
+ return call_voidarg_function(quantify_stop_recording_data, self, args);
}
static PyObject*
pure_quantify_is_recording_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_is_recording_data, self, args);
+ return call_voidarg_function(quantify_is_recording_data, self, args);
}
static PyObject*
pure_quantify_start_recording_system_calls(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_start_recording_system_calls,
- self, args);
+ return call_voidarg_function(quantify_start_recording_system_calls,
+ self, args);
}
static PyObject*
pure_quantify_stop_recording_system_calls(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_stop_recording_system_calls,
- self, args);
+ return call_voidarg_function(quantify_stop_recording_system_calls,
+ self, args);
}
static PyObject*
pure_quantify_is_recording_system_calls(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_is_recording_system_calls,
- self, args);
+ return call_voidarg_function(quantify_is_recording_system_calls,
+ self, args);
}
static PyObject*
pure_quantify_start_recording_system_call(PyObject *self, PyObject *args)
{
- return call_stringorint_function(quantify_start_recording_system_call,
- self, args);
+ return call_stringorint_function(quantify_start_recording_system_call,
+ self, args);
}
static PyObject*
pure_quantify_stop_recording_system_call(PyObject *self, PyObject *args)
{
- return call_stringorint_function(quantify_stop_recording_system_call,
- self, args);
+ return call_stringorint_function(quantify_stop_recording_system_call,
+ self, args);
}
static PyObject*
pure_quantify_is_recording_system_call(PyObject *self, PyObject *args)
{
- return call_stringorint_function(quantify_is_recording_system_call,
- self, args);
+ return call_stringorint_function(quantify_is_recording_system_call,
+ self, args);
}
static PyObject*
pure_quantify_start_recording_dynamic_library_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(
- quantify_start_recording_dynamic_library_data,
- self, args);
+ return call_voidarg_function(
+ quantify_start_recording_dynamic_library_data,
+ self, args);
}
static PyObject*
pure_quantify_stop_recording_dynamic_library_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(
- quantify_stop_recording_dynamic_library_data,
- self, args);
+ return call_voidarg_function(
+ quantify_stop_recording_dynamic_library_data,
+ self, args);
}
static PyObject*
pure_quantify_is_recording_dynamic_library_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(
- quantify_is_recording_dynamic_library_data,
- self, args);
+ return call_voidarg_function(
+ quantify_is_recording_dynamic_library_data,
+ self, args);
}
static PyObject*
pure_quantify_start_recording_register_window_traps(PyObject *self, PyObject *args)
{
- return call_voidarg_function(
- quantify_start_recording_register_window_traps,
- self, args);
+ return call_voidarg_function(
+ quantify_start_recording_register_window_traps,
+ self, args);
}
static PyObject*
pure_quantify_stop_recording_register_window_traps(PyObject *self, PyObject *args)
{
- return call_voidarg_function(
- quantify_stop_recording_register_window_traps,
- self, args);
+ return call_voidarg_function(
+ quantify_stop_recording_register_window_traps,
+ self, args);
}
static PyObject*
pure_quantify_is_recording_register_window_traps(PyObject *self, PyObject *args)
{
- return call_voidarg_function(
- quantify_is_recording_register_window_traps,
- self, args);
+ return call_voidarg_function(
+ quantify_is_recording_register_window_traps,
+ self, args);
}
static PyObject*
pure_quantify_disable_recording_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_disable_recording_data,
- self, args);
+ return call_voidarg_function(quantify_disable_recording_data,
+ self, args);
}
static PyObject*
pure_quantify_clear_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_clear_data, self, args);
+ return call_voidarg_function(quantify_clear_data, self, args);
}
static PyObject*
pure_quantify_save_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_save_data, self, args);
+ return call_voidarg_function(quantify_save_data, self, args);
}
static PyObject*
pure_quantify_save_data_to_file(PyObject *self, PyObject *args)
{
- return call_stringarg_function(quantify_save_data_to_file, self, args);
+ return call_stringarg_function(quantify_save_data_to_file, self, args);
}
static PyObject*
pure_quantify_add_annotation(PyObject *self, PyObject *args)
{
- return call_stringarg_function(quantify_add_annotation, self, args);
+ return call_stringarg_function(quantify_add_annotation, self, args);
}
#endif /* QUANTIFY_H */
-
+
/* external interface
*/
static struct PyMethodDef
@@ -927,66 +927,66 @@ pure_methods[] = {
{"quantify_save_data_to_file", pure_quantify_save_data_to_file, METH_VARARGS},
{"quantify_add_annotation", pure_quantify_add_annotation, METH_VARARGS},
#endif /* QUANTIFY_H */
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
-
+
static void
ins(d, name, val)
- PyObject *d;
- char* name;
- long val;
+ PyObject *d;
+ char* name;
+ long val;
{
- PyObject *v = PyInt_FromLong(val);
- if (v) {
- (void)PyDict_SetItemString(d, name, v);
- Py_DECREF(v);
- }
+ PyObject *v = PyInt_FromLong(val);
+ if (v) {
+ (void)PyDict_SetItemString(d, name, v);
+ Py_DECREF(v);
+ }
}
void
initpure()
{
- PyObject *m, *d;
+ PyObject *m, *d;
- if (PyErr_WarnPy3k("the pure module has been removed in "
- "Python 3.0", 2) < 0)
- return;
+ if (PyErr_WarnPy3k("the pure module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
- m = Py_InitModule("pure", pure_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
+ m = Py_InitModule("pure", pure_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
- /* this is bogus because we should be able to find this information
- * out from the header files. Pure's current versions don't
- * include this information!
- */
+ /* this is bogus because we should be able to find this information
+ * out from the header files. Pure's current versions don't
+ * include this information!
+ */
#ifdef PURE_PURIFY_VERSION
- ins(d, "PURIFY_VERSION", PURE_PURIFY_VERSION);
+ ins(d, "PURIFY_VERSION", PURE_PURIFY_VERSION);
#else
- PyDict_SetItemString(d, "PURIFY_VERSION", Py_None);
+ PyDict_SetItemString(d, "PURIFY_VERSION", Py_None);
#endif
- /* these aren't terribly useful because purify_exit() isn't
- * exported correctly. See the note at the top of the file.
- */
+ /* these aren't terribly useful because purify_exit() isn't
+ * exported correctly. See the note at the top of the file.
+ */
#ifdef PURIFY_EXIT_ERRORS
- ins(d, "PURIFY_EXIT_ERRORS", PURIFY_EXIT_ERRORS);
+ ins(d, "PURIFY_EXIT_ERRORS", PURIFY_EXIT_ERRORS);
#endif
#ifdef PURIFY_EXIT_LEAKS
- ins(d, "PURIFY_EXIT_LEAKS", PURIFY_EXIT_LEAKS);
+ ins(d, "PURIFY_EXIT_LEAKS", PURIFY_EXIT_LEAKS);
#endif
#ifdef PURIFY_EXIT_PLEAKS
- ins(d, "PURIFY_EXIT_PLEAKS", PURIFY_EXIT_PLEAKS);
+ ins(d, "PURIFY_EXIT_PLEAKS", PURIFY_EXIT_PLEAKS);
#endif
#ifdef PURE_QUANTIFY_VERSION
- ins(d, "QUANTIFY_VERSION", PURE_QUANTIFY_VERSION);
+ ins(d, "QUANTIFY_VERSION", PURE_QUANTIFY_VERSION);
#else
- PyDict_SetItemString(d, "QUANTIFY_VERSION", Py_None);
+ PyDict_SetItemString(d, "QUANTIFY_VERSION", Py_None);
#endif
}
diff --git a/Modules/pwdmodule.c b/Modules/pwdmodule.c
index 2865dc6..ae358e0 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,49 +49,49 @@ static void
sets(PyObject *v, int i, char* val)
{
if (val)
- PyStructSequence_SET_ITEM(v, i, PyString_FromString(val));
+ PyStructSequence_SET_ITEM(v, i, PyString_FromString(val));
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, PyInt_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__,
@@ -103,16 +103,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__,
@@ -124,16 +124,16 @@ See pwd.__doc__ for more on password database entries.");
static PyObject *
pwd_getpwnam(PyObject *self, PyObject *args)
{
- char *name;
- struct passwd *p;
- if (!PyArg_ParseTuple(args, "s:getpwnam", &name))
- return NULL;
- if ((p = getpwnam(name)) == NULL) {
- PyErr_Format(PyExc_KeyError,
- "getpwnam(): name not found: %s", name);
- return NULL;
- }
- return mkpwent(p);
+ char *name;
+ struct passwd *p;
+ if (!PyArg_ParseTuple(args, "s:getpwnam", &name))
+ return NULL;
+ if ((p = getpwnam(name)) == NULL) {
+ PyErr_Format(PyExc_KeyError,
+ "getpwnam(): name not found: %s", name);
+ return NULL;
+ }
+ return mkpwent(p);
}
#ifdef HAVE_GETPWENT
@@ -146,55 +146,55 @@ 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 */
};
PyMODINIT_FUNC
initpwd(void)
{
- PyObject *m;
- m = Py_InitModule3("pwd", pwd_methods, pwd__doc__);
- if (m == NULL)
- return;
-
- if (!initialized)
- PyStructSequence_InitType(&StructPwdType,
- &struct_pwd_type_desc);
- Py_INCREF((PyObject *) &StructPwdType);
- PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType);
- /* And for b/w compatibility (this was defined by mistake): */
- Py_INCREF((PyObject *) &StructPwdType);
- PyModule_AddObject(m, "struct_pwent", (PyObject *) &StructPwdType);
- initialized = 1;
+ PyObject *m;
+ m = Py_InitModule3("pwd", pwd_methods, pwd__doc__);
+ if (m == NULL)
+ return;
+
+ if (!initialized)
+ PyStructSequence_InitType(&StructPwdType,
+ &struct_pwd_type_desc);
+ Py_INCREF((PyObject *) &StructPwdType);
+ PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType);
+ /* And for b/w compatibility (this was defined by mistake): */
+ Py_INCREF((PyObject *) &StructPwdType);
+ PyModule_AddObject(m, "struct_pwent", (PyObject *) &StructPwdType);
+ initialized = 1;
}
diff --git a/Modules/pyexpat.c b/Modules/pyexpat.c
index 01971b7..1e9b89f 100644
--- a/Modules/pyexpat.c
+++ b/Modules/pyexpat.c
@@ -245,7 +245,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. */
}
@@ -278,22 +278,22 @@ getcode(enum HandlerTypes slot, char* func_name, int lineno)
goto failed;
filename = PyString_FromString(__FILE__);
handler_info[slot].tb_code =
- PyCode_New(0, /* argcount */
- 0, /* nlocals */
- 0, /* stacksize */
- 0, /* flags */
- code, /* code */
- nulltuple, /* consts */
- nulltuple, /* names */
- nulltuple, /* varnames */
+ PyCode_New(0, /* argcount */
+ 0, /* nlocals */
+ 0, /* stacksize */
+ 0, /* flags */
+ code, /* code */
+ nulltuple, /* consts */
+ nulltuple, /* names */
+ nulltuple, /* varnames */
#if PYTHON_API_VERSION >= 1010
- nulltuple, /* freevars */
- nulltuple, /* cellvars */
+ nulltuple, /* freevars */
+ nulltuple, /* cellvars */
#endif
- filename, /* filename */
- name, /* name */
- lineno, /* firstlineno */
- code /* lnotab */
+ filename, /* filename */
+ name, /* name */
+ lineno, /* firstlineno */
+ code /* lnotab */
);
if (handler_info[slot].tb_code == NULL)
goto failed;
@@ -315,25 +315,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;
}
@@ -344,12 +344,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);
@@ -357,17 +357,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;
}
@@ -383,31 +383,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
}
@@ -432,12 +432,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;
@@ -460,8 +460,8 @@ call_character_handler(xmlparseobject *self, const XML_Char *buffer, int len)
if (args == NULL)
return -1;
#ifdef Py_USING_UNICODE
- temp = (self->returns_unicode
- ? conv_string_len_to_unicode(buffer, len)
+ temp = (self->returns_unicode
+ ? conv_string_len_to_unicode(buffer, len)
: conv_string_len_to_utf8(buffer, len));
#else
temp = conv_string_len_to_utf8(buffer, len);
@@ -503,7 +503,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)
@@ -643,13 +643,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 = PyInt_AsLong(rv);, rc, \
- (xmlparseobject *)userData)
+ RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \
+ rc = PyInt_AsLong(rv);, rc, \
+ (xmlparseobject *)userData)
VOID_HANDLER(EndElement,
(void *userData, const XML_Char *name),
@@ -822,25 +822,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,
@@ -849,50 +849,50 @@ VOID_HANDLER(Comment,
VOID_HANDLER(StartCdataSection,
(void *userData),
- ("()"))
+ ("()"))
VOID_HANDLER(EndCdataSection,
(void *userData),
- ("()"))
+ ("()"))
#ifndef Py_USING_UNICODE
VOID_HANDLER(Default,
- (void *userData, const XML_Char *s, int len),
- ("(N)", conv_string_len_to_utf8(s,len)))
+ (void *userData, const XML_Char *s, int len),
+ ("(N)", conv_string_len_to_utf8(s,len)))
VOID_HANDLER(DefaultHandlerExpand,
- (void *userData, const XML_Char *s, int len),
- ("(N)", conv_string_len_to_utf8(s,len)))
+ (void *userData, const XML_Char *s, int len),
+ ("(N)", conv_string_len_to_utf8(s,len)))
#else
VOID_HANDLER(Default,
- (void *userData, const XML_Char *s, int len),
- ("(N)", (self->returns_unicode
- ? conv_string_len_to_unicode(s,len)
- : conv_string_len_to_utf8(s,len))))
+ (void *userData, const XML_Char *s, int len),
+ ("(N)", (self->returns_unicode
+ ? conv_string_len_to_unicode(s,len)
+ : conv_string_len_to_utf8(s,len))))
VOID_HANDLER(DefaultHandlerExpand,
- (void *userData, const XML_Char *s, int len),
- ("(N)", (self->returns_unicode
- ? conv_string_len_to_unicode(s,len)
- : conv_string_len_to_utf8(s,len))))
+ (void *userData, const XML_Char *s, int len),
+ ("(N)", (self->returns_unicode
+ ? conv_string_len_to_unicode(s,len)
+ : conv_string_len_to_utf8(s,len))))
#endif
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)",
- STRING_CONV_FUNC,context, string_intern(self, base),
- string_intern(self, systemId), string_intern(self, publicId)),
- rc = PyInt_AsLong(rv);, rc,
- XML_GetUserData(parser))
+ STRING_CONV_FUNC,context, string_intern(self, base),
+ string_intern(self, systemId), string_intern(self, publicId)),
+ rc = PyInt_AsLong(rv);, rc,
+ XML_GetUserData(parser))
/* XXX UnknownEncodingHandler */
@@ -1063,7 +1063,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;
@@ -1154,7 +1154,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);
@@ -1243,25 +1243,25 @@ xmlparse_UseForeignDTD(xmlparseobject *self, PyObject *args)
#endif
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
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
/* ---------- */
@@ -1281,7 +1281,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;
}
@@ -1300,15 +1300,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;
@@ -1509,19 +1509,19 @@ xmlparse_getattr(xmlparseobject *self, char *name)
}
}
-#define APPEND(list, str) \
- do { \
- PyObject *o = PyString_FromString(str); \
- if (o != NULL) \
- PyList_Append(list, o); \
- Py_XDECREF(o); \
+#define APPEND(list, str) \
+ do { \
+ PyObject *o = PyString_FromString(str); \
+ if (o != NULL) \
+ PyList_Append(list, o); \
+ Py_XDECREF(o); \
} while (0)
if (strcmp(name, "__members__") == 0) {
int i;
PyObject *rc = PyList_New(0);
- if (!rc)
- return NULL;
+ if (!rc)
+ return NULL;
for (i = 0; handler_info[i].name != NULL; i++) {
PyObject *o = get_handler_name(&handler_info[i]);
if (o != NULL)
@@ -1653,42 +1653,42 @@ xmlparse_setattr(xmlparseobject *self, char *name, PyObject *v)
if (strcmp(name, "buffer_size") == 0) {
long new_buffer_size;
if (!PyInt_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=PyInt_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;
}
@@ -1731,37 +1731,37 @@ 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*/
- (getattrfunc)xmlparse_getattr, /*tp_getattr*/
- (setattrfunc)xmlparse_setattr, /*tp_setattr*/
- (cmpfunc)0, /*tp_compare*/
- (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 */
+ 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*/
+ (getattrfunc)xmlparse_getattr, /*tp_getattr*/
+ (setattrfunc)xmlparse_setattr, /*tp_setattr*/
+ (cmpfunc)0, /*tp_compare*/
+ (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 */
#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 */
+ Xmlparsetype__doc__, /* tp_doc - Documentation string */
#ifdef WITH_CYCLE_GC
- (traverseproc)xmlparse_traverse, /* tp_traverse */
- (inquiry)xmlparse_clear /* tp_clear */
+ (traverseproc)xmlparse_traverse, /* tp_traverse */
+ (inquiry)xmlparse_clear /* tp_clear */
#else
- 0, 0
+ 0, 0
#endif
};
@@ -1796,21 +1796,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;
}
@@ -1832,12 +1832,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 */
@@ -1909,7 +1909,7 @@ MODULE_INITFUNC(void)
m = Py_InitModule3(MODULE_NAME, pyexpat_methods,
pyexpat_module_documentation);
if (m == NULL)
- return;
+ return;
/* Add some symbolic constants to the module */
if (ErrorObject == NULL) {
@@ -1968,7 +1968,7 @@ MODULE_INITFUNC(void)
if (errors_module == NULL || model_module == NULL)
/* Don't core dump later! */
return;
-
+
#if XML_COMBINED_VERSION > 19505
{
const XML_Feature *features = XML_GetFeatureList();
@@ -2093,7 +2093,7 @@ MODULE_INITFUNC(void)
capi.SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler;
capi.SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler;
capi.SetUserData = XML_SetUserData;
-
+
/* export as cobject */
capi_object = PyCObject_FromVoidPtr(&capi, NULL);
if (capi_object)
@@ -2108,12 +2108,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/readline.c b/Modules/readline.c
index 712b857..038b4d6 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 *);
@@ -47,13 +47,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
@@ -65,7 +65,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 */
@@ -73,18 +73,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,
@@ -97,13 +97,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,
@@ -117,13 +117,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 */
@@ -138,15 +138,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,
@@ -160,11 +160,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,
@@ -179,7 +179,7 @@ history truncation.");
static PyObject*
get_history_length(PyObject *self, PyObject *noarg)
{
- return PyInt_FromLong(_history_length);
+ return PyInt_FromLong(_history_length);
}
PyDoc_STRVAR(get_history_length_doc,
@@ -193,29 +193,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;
}
@@ -231,20 +231,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;
}
@@ -258,7 +258,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,
@@ -275,7 +275,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,
@@ -313,8 +313,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,
@@ -327,8 +327,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,
@@ -341,14 +341,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,
@@ -358,31 +358,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,
@@ -392,34 +392,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,
@@ -431,13 +431,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,
@@ -450,7 +450,7 @@ add a line to the history buffer");
static PyObject *
get_completer_delims(PyObject *self, PyObject *noarg)
{
- return PyString_FromString(rl_completer_word_break_characters);
+ return PyString_FromString(rl_completer_word_break_characters);
}
PyDoc_STRVAR(doc_get_completer_delims,
@@ -463,7 +463,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,
@@ -477,11 +477,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,
@@ -494,39 +494,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 PyString_FromString(hist_ent->line);
- else {
- Py_RETURN_NONE;
- }
+ if ((hist_ent = history_get(idx)))
+ return PyString_FromString(hist_ent->line);
+ else {
+ Py_RETURN_NONE;
+ }
}
PyDoc_STRVAR(doc_get_history_item,
@@ -539,10 +539,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 PyInt_FromLong(hist_st ? (long) hist_st->length : (long) 0);
+ hist_st = history_get_history_state();
+ return PyInt_FromLong(hist_st ? (long) hist_st->length : (long) 0);
}
PyDoc_STRVAR(doc_get_current_history_length,
@@ -555,7 +555,7 @@ return the current (not the maximum) length of history.");
static PyObject *
get_line_buffer(PyObject *self, PyObject *noarg)
{
- return PyString_FromString(rl_line_buffer);
+ return PyString_FromString(rl_line_buffer);
}
PyDoc_STRVAR(doc_get_line_buffer,
@@ -570,8 +570,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,
@@ -585,11 +585,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,
@@ -602,8 +602,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,
@@ -616,50 +616,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}
};
@@ -668,47 +668,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 = PyInt_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 = PyInt_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
@@ -717,43 +717,43 @@ 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 = PyString_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 && PyInt_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 = PyString_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 && PyInt_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;
-#ifdef WITH_THREAD
- PyGILState_STATE gilstate = PyGILState_Ensure();
+ char *result = NULL;
+ if (completer != NULL) {
+ PyObject *r;
+#ifdef WITH_THREAD
+ 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 = PyString_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);
+ 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 = PyString_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);
#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 = PyInt_FromLong((long) start);
- endidx = PyInt_FromLong((long) end);
- return completion_matches(text, *on_completion);
+ Py_XDECREF(begidx);
+ Py_XDECREF(endidx);
+ begidx = PyInt_FromLong((long) start);
+ endidx = PyInt_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 = PyInt_FromLong(0L);
- endidx = PyInt_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 = PyInt_FromLong(0L);
+ endidx = PyInt_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;
- old_inthandler = PyOS_setsig(SIGINT, onintr);
- if (setjmp(jbuf)) {
+ *signal = 0;
+
+ 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;
}
@@ -1075,27 +1075,27 @@ PyDoc_STRVAR(doc_module_le,
PyMODINIT_FUNC
initreadline(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)
- m = Py_InitModule4("readline", readline_methods, doc_module_le,
- (PyObject *)NULL, PYTHON_API_VERSION);
- else
+ if (using_libedit_emulation)
+ m = Py_InitModule4("readline", readline_methods, doc_module_le,
+ (PyObject *)NULL, PYTHON_API_VERSION);
+ else
#endif /* __APPLE__ */
- m = Py_InitModule4("readline", readline_methods, doc_module,
- (PyObject *)NULL, PYTHON_API_VERSION);
- if (m == NULL)
- return;
+ m = Py_InitModule4("readline", readline_methods, doc_module,
+ (PyObject *)NULL, PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
- PyOS_ReadlineFunctionPointer = call_readline;
- setup_readline();
+ PyOS_ReadlineFunctionPointer = call_readline;
+ setup_readline();
}
diff --git a/Modules/resource.c b/Modules/resource.c
index 38974f9..9993b93 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,153 +61,153 @@ 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, PyInt_FromLong(ru.ru_maxrss));
- PyStructSequence_SET_ITEM(result, 3, PyInt_FromLong(ru.ru_ixrss));
- PyStructSequence_SET_ITEM(result, 4, PyInt_FromLong(ru.ru_idrss));
- PyStructSequence_SET_ITEM(result, 5, PyInt_FromLong(ru.ru_isrss));
- PyStructSequence_SET_ITEM(result, 6, PyInt_FromLong(ru.ru_minflt));
- PyStructSequence_SET_ITEM(result, 7, PyInt_FromLong(ru.ru_majflt));
- PyStructSequence_SET_ITEM(result, 8, PyInt_FromLong(ru.ru_nswap));
- PyStructSequence_SET_ITEM(result, 9, PyInt_FromLong(ru.ru_inblock));
- PyStructSequence_SET_ITEM(result, 10, PyInt_FromLong(ru.ru_oublock));
- PyStructSequence_SET_ITEM(result, 11, PyInt_FromLong(ru.ru_msgsnd));
- PyStructSequence_SET_ITEM(result, 12, PyInt_FromLong(ru.ru_msgrcv));
- PyStructSequence_SET_ITEM(result, 13, PyInt_FromLong(ru.ru_nsignals));
- PyStructSequence_SET_ITEM(result, 14, PyInt_FromLong(ru.ru_nvcsw));
- PyStructSequence_SET_ITEM(result, 15, PyInt_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, PyInt_FromLong(ru.ru_maxrss));
+ PyStructSequence_SET_ITEM(result, 3, PyInt_FromLong(ru.ru_ixrss));
+ PyStructSequence_SET_ITEM(result, 4, PyInt_FromLong(ru.ru_idrss));
+ PyStructSequence_SET_ITEM(result, 5, PyInt_FromLong(ru.ru_isrss));
+ PyStructSequence_SET_ITEM(result, 6, PyInt_FromLong(ru.ru_minflt));
+ PyStructSequence_SET_ITEM(result, 7, PyInt_FromLong(ru.ru_majflt));
+ PyStructSequence_SET_ITEM(result, 8, PyInt_FromLong(ru.ru_nswap));
+ PyStructSequence_SET_ITEM(result, 9, PyInt_FromLong(ru.ru_inblock));
+ PyStructSequence_SET_ITEM(result, 10, PyInt_FromLong(ru.ru_oublock));
+ PyStructSequence_SET_ITEM(result, 11, PyInt_FromLong(ru.ru_msgsnd));
+ PyStructSequence_SET_ITEM(result, 12, PyInt_FromLong(ru.ru_msgrcv));
+ PyStructSequence_SET_ITEM(result, 13, PyInt_FromLong(ru.ru_nsignals));
+ PyStructSequence_SET_ITEM(result, 14, PyInt_FromLong(ru.ru_nvcsw));
+ PyStructSequence_SET_ITEM(result, 15, PyInt_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 = PyInt_AsLong(curobj);
- if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
- return NULL;
- rl.rlim_max = PyInt_AsLong(maxobj);
- if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
- return NULL;
+ rl.rlim_cur = PyInt_AsLong(curobj);
+ if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
+ return NULL;
+ rl.rlim_max = PyInt_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_Check(curobj) ?
- PyLong_AsLongLong(curobj) : PyInt_AsLong(curobj);
- if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
- return NULL;
- rl.rlim_max = PyLong_Check(maxobj) ?
- PyLong_AsLongLong(maxobj) : PyInt_AsLong(maxobj);
- if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
- return NULL;
+ /* The limits are probably bigger than a long */
+ rl.rlim_cur = PyLong_Check(curobj) ?
+ PyLong_AsLongLong(curobj) : PyInt_AsLong(curobj);
+ if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
+ return NULL;
+ rl.rlim_max = PyLong_Check(maxobj) ?
+ PyLong_AsLongLong(maxobj) : PyInt_AsLong(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);
}
@@ -215,11 +215,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 */
};
@@ -228,102 +228,102 @@ resource_methods[] = {
PyMODINIT_FUNC
initresource(void)
{
- PyObject *m, *v;
-
- /* Create the module and add the functions */
- m = Py_InitModule("resource", resource_methods);
- if (m == NULL)
- return;
-
- /* 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 = Py_InitModule("resource", resource_methods);
+ if (m == NULL)
+ return;
+
+ /* 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 = PyInt_FromLong((long) RLIM_INFINITY);
- }
- if (v) {
- PyModule_AddObject(m, "RLIM_INFINITY", v);
- }
- initialized = 1;
+ {
+ v = PyInt_FromLong((long) RLIM_INFINITY);
+ }
+ if (v) {
+ PyModule_AddObject(m, "RLIM_INFINITY", v);
+ }
+ initialized = 1;
}
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 09c687c..ba5fdb4 100644
--- a/Modules/selectmodule.c
+++ b/Modules/selectmodule.c
@@ -24,7 +24,7 @@
*/
#if defined(MS_WINDOWS) && !defined(FD_SETSIZE)
#define FD_SETSIZE 512
-#endif
+#endif
#if defined(HAVE_POLL_H)
#include <poll.h>
@@ -61,20 +61,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;
}
@@ -84,106 +84,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
@@ -195,170 +195,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 = PyInt_AsLong(key);
- self->ufds[i].events = (short)PyInt_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 = PyInt_AsLong(key);
+ self->ufds[i].events = (short)PyInt_AsLong(value);
+ i++;
+ }
+ self->ufd_uptodate = 1;
+ return 1;
}
PyDoc_STRVAR(poll_register_doc,
@@ -369,39 +369,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 = PyInt_FromLong(fd);
- if (key == NULL)
- return NULL;
- value = PyInt_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 = PyInt_FromLong(fd);
+ if (key == NULL)
+ return NULL;
+ value = PyInt_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,
@@ -414,41 +414,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 = PyInt_FromLong(fd);
- if (key == NULL)
- return NULL;
- if (PyDict_GetItem(self->dict, key) == NULL) {
- errno = ENOENT;
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- value = PyInt_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 = PyInt_FromLong(fd);
+ if (key == NULL)
+ return NULL;
+ if (PyDict_GetItem(self->dict, key) == NULL) {
+ errno = ENOENT;
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ value = PyInt_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;
}
@@ -457,32 +457,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 = PyInt_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 = PyInt_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,
@@ -491,161 +491,161 @@ 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_Int(tout);
- if (!tout)
- return NULL;
- timeout = PyInt_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 = PyInt_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 = PyInt_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_Int(tout);
+ if (!tout)
+ return NULL;
+ timeout = PyInt_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 = PyInt_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 = PyInt_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 PyObject *
poll_getattr(pollObject *self, char *name)
{
- return Py_FindMethod(poll_methods, (PyObject *)self, name);
+ return Py_FindMethod(poll_methods, (PyObject *)self, name);
}
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*/
- (getattrfunc)poll_getattr, /*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*/
+ /* 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*/
+ (getattrfunc)poll_getattr, /*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*/
};
PyDoc_STRVAR(poll_doc,
@@ -655,36 +655,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__ */
@@ -703,8 +703,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;
@@ -713,92 +713,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,
@@ -810,18 +810,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 PyInt_FromLong(self->epfd);
+ if (self->epfd < 0)
+ return pyepoll_err_closed();
+ return PyInt_FromLong(self->epfd);
}
PyDoc_STRVAR(pyepoll_fileno_doc,
@@ -832,12 +832,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,
@@ -848,65 +848,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,
@@ -923,16 +923,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,
@@ -944,15 +944,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,
@@ -963,76 +963,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,
@@ -1043,27 +1043,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,
@@ -1076,45 +1076,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_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 */
- 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_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 */
+ 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 */
@@ -1169,8 +1169,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;
@@ -1178,8 +1178,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;
@@ -1193,13 +1193,13 @@ static PyTypeObject kqueue_queue_Type;
#define KQ_OFF(x) offsetof(kqueue_event_Object, x)
static struct PyMemberDef kqueue_event_members[] = {
- {"ident", T_UINT, 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_INT, KQ_OFF(e.data)},
- {"udata", T_INT, KQ_OFF(e.udata)},
- {NULL} /* Sentinel */
+ {"ident", T_UINT, 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_INT, KQ_OFF(e.data)},
+ {"udata", T_INT, KQ_OFF(e.udata)},
+ {NULL} /* Sentinel */
};
#undef KQ_OFF
@@ -1207,208 +1207,208 @@ static PyObject *
kqueue_event_repr(kqueue_event_Object *s)
{
- char buf[1024];
- PyOS_snprintf(
- buf, sizeof(buf),
- "<select.kevent ident=%lu filter=%d flags=0x%x fflags=0x%x "
- "data=0x%lx udata=%p>",
- (unsigned long)(s->e.ident), s->e.filter, s->e.flags,
- s->e.fflags, (long)(s->e.data), s->e.udata);
- return PyString_FromString(buf);
+ char buf[1024];
+ PyOS_snprintf(
+ buf, sizeof(buf),
+ "<select.kevent ident=%lu filter=%d flags=0x%x fflags=0x%x "
+ "data=0x%lx udata=%p>",
+ (unsigned long)(s->e.ident), s->e.filter, s->e.flags,
+ s->e.fflags, (long)(s->e.data), s->e.udata);
+ return PyString_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};
-
- EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|hhiii:kevent", kwlist,
- &pfd, &(self->e.filter), &(self->e.flags),
- &(self->e.fflags), &(self->e.data), &(self->e.udata))) {
- return -1;
- }
-
- self->e.ident = PyObject_AsFileDescriptor(pfd);
- if (self->e.ident == -1) {
- return -1;
- }
- return 0;
+ PyObject *pfd;
+ static char *kwlist[] = {"ident", "filter", "flags", "fflags",
+ "data", "udata", NULL};
+
+ EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|hhiii:kevent", kwlist,
+ &pfd, &(self->e.filter), &(self->e.flags),
+ &(self->e.fflags), &(self->e.data), &(self->e.udata))) {
+ return -1;
+ }
+
+ self->e.ident = PyObject_AsFileDescriptor(pfd);
+ if (self->e.ident == -1) {
+ return -1;
+ }
+ return 0;
}
static PyObject *
kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o,
- int op)
+ int op)
{
- int 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(result);
+ int 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(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_compare */
- (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_compare */
+ (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,
@@ -1420,18 +1420,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 PyInt_FromLong(self->kqfd);
+ if (self->kqfd < 0)
+ return kqueue_queue_err_closed();
+ return PyInt_FromLong(self->kqfd);
}
PyDoc_STRVAR(kqueue_queue_fileno_doc,
@@ -1442,12 +1442,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,
@@ -1458,144 +1458,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,
@@ -1611,21 +1611,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,
@@ -1644,45 +1644,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_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* 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_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* 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 */
@@ -1713,11 +1713,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,
@@ -1729,146 +1729,146 @@ On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptor
PyMODINIT_FUNC
initselect(void)
{
- PyObject *m;
- m = Py_InitModule3("select", select_methods, module_doc);
- if (m == NULL)
- return;
+ PyObject *m;
+ m = Py_InitModule3("select", select_methods, module_doc);
+ if (m == NULL)
+ return;
- 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);
#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
- Py_TYPE(&poll_Type) = &PyType_Type;
- 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);
+ Py_TYPE(&poll_Type) = &PyType_Type;
+ 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;
-
- 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;
+
+ 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;
-
- 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;
- 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;
+
+ 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;
+ 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 */
diff --git a/Modules/sgimodule.c b/Modules/sgimodule.c
index f7e1263..0d13248 100644
--- a/Modules/sgimodule.c
+++ b/Modules/sgimodule.c
@@ -10,14 +10,14 @@
static PyObject *
sgi_nap(PyObject *self, PyObject *args)
{
- long ticks;
- if (!PyArg_ParseTuple(args, "l:nap", &ticks))
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- sginap(ticks);
- Py_END_ALLOW_THREADS
- Py_INCREF(Py_None);
- return Py_None;
+ long ticks;
+ if (!PyArg_ParseTuple(args, "l:nap", &ticks))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ sginap(ticks);
+ Py_END_ALLOW_THREADS
+ Py_INCREF(Py_None);
+ return Py_None;
}
extern char *_getpty(int *, int, mode_t, int);
@@ -25,31 +25,31 @@ extern char *_getpty(int *, int, mode_t, int);
static PyObject *
sgi__getpty(PyObject *self, PyObject *args)
{
- int oflag;
- int mode;
- int nofork;
- char *name;
- int fildes;
- if (!PyArg_ParseTuple(args, "iii:_getpty", &oflag, &mode, &nofork))
- return NULL;
- errno = 0;
- name = _getpty(&fildes, oflag, (mode_t)mode, nofork);
- if (name == NULL) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return Py_BuildValue("(si)", name, fildes);
+ int oflag;
+ int mode;
+ int nofork;
+ char *name;
+ int fildes;
+ if (!PyArg_ParseTuple(args, "iii:_getpty", &oflag, &mode, &nofork))
+ return NULL;
+ errno = 0;
+ name = _getpty(&fildes, oflag, (mode_t)mode, nofork);
+ if (name == NULL) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return Py_BuildValue("(si)", name, fildes);
}
static PyMethodDef sgi_methods[] = {
- {"nap", sgi_nap, METH_VARARGS},
- {"_getpty", sgi__getpty, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"nap", sgi_nap, METH_VARARGS},
+ {"_getpty", sgi__getpty, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
void
initsgi(void)
{
- Py_InitModule("sgi", sgi_methods);
+ Py_InitModule("sgi", sgi_methods);
}
diff --git a/Modules/sha256module.c b/Modules/sha256module.c
index 7d56900..029f298 100644
--- a/Modules/sha256module.c
+++ b/Modules/sha256module.c
@@ -22,7 +22,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
@@ -32,7 +32,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
@@ -46,11 +46,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;
@@ -62,7 +62,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--) {
@@ -114,7 +114,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))
@@ -127,13 +127,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];
@@ -211,8 +211,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];
@@ -314,14 +314,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
@@ -454,21 +454,21 @@ SHA256_hexdigest(SHAobject *self, PyObject *unused)
/* Create a new string */
retval = PyString_FromStringAndSize(NULL, self->digestsize * 2);
if (!retval)
- return NULL;
+ return NULL;
hex_digest = PyString_AsString(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;
@@ -493,11 +493,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 *
@@ -537,13 +537,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_compare*/
0, /*tp_repr*/
@@ -559,25 +559,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_compare*/
0, /*tp_repr*/
@@ -593,13 +593,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 */
};
@@ -674,7 +674,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 */
};
@@ -695,5 +695,5 @@ init_sha256(void)
return;
m = Py_InitModule("_sha256", SHA_functions);
if (m == NULL)
- return;
+ return;
}
diff --git a/Modules/sha512module.c b/Modules/sha512module.c
index f2c230b..42548bb 100644
--- a/Modules/sha512module.c
+++ b/Modules/sha512module.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,8 +33,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
@@ -48,11 +48,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;
@@ -64,22 +64,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++;
}
}
@@ -124,7 +124,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))
@@ -143,7 +143,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];
@@ -237,8 +237,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];
@@ -340,14 +340,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
@@ -520,21 +520,21 @@ SHA512_hexdigest(SHAobject *self, PyObject *unused)
/* Create a new string */
retval = PyString_FromStringAndSize(NULL, self->digestsize * 2);
if (!retval)
- return NULL;
+ return NULL;
hex_digest = PyString_AsString(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;
@@ -559,11 +559,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 *
@@ -603,13 +603,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_compare*/
0, /*tp_repr*/
@@ -625,25 +625,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_compare*/
0, /*tp_repr*/
@@ -659,13 +659,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 */
};
@@ -740,7 +740,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 */
};
@@ -761,7 +761,7 @@ init_sha512(void)
return;
m = Py_InitModule("_sha512", SHA_functions);
if (m == NULL)
- return;
+ return;
}
#endif
diff --git a/Modules/shamodule.c b/Modules/shamodule.c
index 1a7fc2c..efd7204 100644
--- a/Modules/shamodule.c
+++ b/Modules/shamodule.c
@@ -21,7 +21,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
@@ -31,7 +31,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
@@ -45,11 +45,11 @@ typedef unsigned int SHA_INT32; /* 32-bit integer */
typedef struct {
PyObject_HEAD
- SHA_INT32 digest[5]; /* Message digest */
- SHA_INT32 count_lo, count_hi; /* 64-bit bit count */
- SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */
+ SHA_INT32 digest[5]; /* 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 */
} SHAobject;
/* When run on a little-endian CPU we need to perform byte reversal on an
@@ -60,7 +60,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--) {
@@ -111,48 +111,48 @@ static void SHAcopy(SHAobject *src, SHAobject *dest)
save one boolean operation each - thanks to Rich Schroeppel,
rcs@cs.arizona.edu for discovering this */
-/*#define f1(x,y,z) ((x & y) | (~x & z)) // Rounds 0-19 */
-#define f1(x,y,z) (z ^ (x & (y ^ z))) /* Rounds 0-19 */
-#define f2(x,y,z) (x ^ y ^ z) /* Rounds 20-39 */
-/*#define f3(x,y,z) ((x & y) | (x & z) | (y & z)) // Rounds 40-59 */
-#define f3(x,y,z) ((x & y) | (z & (x | y))) /* Rounds 40-59 */
-#define f4(x,y,z) (x ^ y ^ z) /* Rounds 60-79 */
+/*#define f1(x,y,z) ((x & y) | (~x & z)) // Rounds 0-19 */
+#define f1(x,y,z) (z ^ (x & (y ^ z))) /* Rounds 0-19 */
+#define f2(x,y,z) (x ^ y ^ z) /* Rounds 20-39 */
+/*#define f3(x,y,z) ((x & y) | (x & z) | (y & z)) // Rounds 40-59 */
+#define f3(x,y,z) ((x & y) | (z & (x | y))) /* Rounds 40-59 */
+#define f4(x,y,z) (x ^ y ^ z) /* Rounds 60-79 */
/* SHA constants */
-#define CONST1 0x5a827999L /* Rounds 0-19 */
-#define CONST2 0x6ed9eba1L /* Rounds 20-39 */
-#define CONST3 0x8f1bbcdcL /* Rounds 40-59 */
-#define CONST4 0xca62c1d6L /* Rounds 60-79 */
+#define CONST1 0x5a827999L /* Rounds 0-19 */
+#define CONST2 0x6ed9eba1L /* Rounds 20-39 */
+#define CONST3 0x8f1bbcdcL /* Rounds 40-59 */
+#define CONST4 0xca62c1d6L /* Rounds 60-79 */
/* 32-bit rotate */
-#define R32(x,n) ((x << n) | (x >> (32 - n)))
+#define R32(x,n) ((x << n) | (x >> (32 - n)))
/* the generic case, for when the overall rotation is not unraveled */
-#define FG(n) \
- T = R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n; \
+#define FG(n) \
+ T = R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n; \
E = D; D = C; C = R32(B,30); B = A; A = T
/* specific cases, for when the overall rotation is unraveled */
-#define FA(n) \
+#define FA(n) \
T = R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n; B = R32(B,30)
-#define FB(n) \
+#define FB(n) \
E = R32(T,5) + f##n(A,B,C) + D + *WP++ + CONST##n; A = R32(A,30)
-#define FC(n) \
+#define FC(n) \
D = R32(E,5) + f##n(T,A,B) + C + *WP++ + CONST##n; T = R32(T,30)
-#define FD(n) \
+#define FD(n) \
C = R32(D,5) + f##n(E,T,A) + B + *WP++ + CONST##n; E = R32(E,30)
-#define FE(n) \
+#define FE(n) \
B = R32(C,5) + f##n(D,E,T) + A + *WP++ + CONST##n; D = R32(D,30)
-#define FT(n) \
+#define FT(n) \
A = R32(B,5) + f##n(C,D,E) + T + *WP++ + CONST##n; C = R32(C,30)
/* do SHA transformation */
@@ -167,10 +167,10 @@ sha_transform(SHAobject *sha_info)
longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness);
for (i = 16; i < 80; ++i) {
- W[i] = W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16];
+ W[i] = W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16];
- /* extra rotation fix */
- W[i] = R32(W[i], 1);
+ /* extra rotation fix */
+ W[i] = R32(W[i], 1);
}
A = sha_info->digest[0];
B = sha_info->digest[1];
@@ -286,14 +286,14 @@ sha_final(unsigned char digest[20], 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
@@ -402,21 +402,21 @@ SHA_hexdigest(SHAobject *self, PyObject *unused)
/* Create a new string */
retval = PyString_FromStringAndSize(NULL, sizeof(digest) * 2);
if (!retval)
- return NULL;
+ return NULL;
hex_digest = PyString_AsString(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<sizeof(digest); 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;
@@ -441,11 +441,11 @@ SHA_update(SHAobject *self, PyObject *args)
}
static PyMethodDef SHA_methods[] = {
- {"copy", (PyCFunction)SHA_copy, METH_NOARGS, SHA_copy__doc__},
- {"digest", (PyCFunction)SHA_digest, METH_NOARGS, SHA_digest__doc__},
+ {"copy", (PyCFunction)SHA_copy, METH_NOARGS, SHA_copy__doc__},
+ {"digest", (PyCFunction)SHA_digest, METH_NOARGS, SHA_digest__doc__},
{"hexdigest", (PyCFunction)SHA_hexdigest, METH_NOARGS, SHA_hexdigest__doc__},
- {"update", (PyCFunction)SHA_update, METH_VARARGS, SHA_update__doc__},
- {NULL, NULL} /* sentinel */
+ {"update", (PyCFunction)SHA_update, METH_VARARGS, SHA_update__doc__},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
@@ -490,12 +490,12 @@ static PyGetSetDef SHA_getseters[] = {
static PyTypeObject SHAtype = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_sha.sha", /*tp_name*/
- sizeof(SHAobject), /*tp_size*/
- 0, /*tp_itemsize*/
+ "_sha.sha", /*tp_name*/
+ sizeof(SHAobject), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- SHA_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
+ SHA_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
@@ -512,12 +512,12 @@ static PyTypeObject SHAtype = {
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 */
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ SHA_methods, /* tp_methods */
0, /* tp_members */
SHA_getseters, /* tp_getset */
};
@@ -563,7 +563,7 @@ SHA_new(PyObject *self, PyObject *args, PyObject *kwdict)
static struct PyMethodDef SHA_functions[] = {
{"new", (PyCFunction)SHA_new, METH_VARARGS|METH_KEYWORDS, SHA_new__doc__},
- {NULL, NULL} /* Sentinel */
+ {NULL, NULL} /* Sentinel */
};
@@ -581,12 +581,12 @@ init_sha(void)
return;
m = Py_InitModule("_sha", SHA_functions);
if (m == NULL)
- return;
+ return;
/* Add some symbolic constants to the module */
insint("blocksize", 1); /* For future use, in case some hash
functions require an integral number of
- blocks */
+ blocks */
insint("digestsize", 20);
insint("digest_size", 20);
}
diff --git a/Modules/signalmodule.c b/Modules/signalmodule.c
index bb364aa..8b1374b 100644
--- a/Modules/signalmodule.c
+++ b/Modules/signalmodule.c
@@ -28,13 +28,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
@@ -76,8 +76,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;
@@ -120,18 +120,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);
@@ -143,8 +143,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,
@@ -157,7 +157,7 @@ It raises KeyboardInterrupt.");
static int
checksignals_witharg(void * unused)
{
- return PyErr_CheckSignals();
+ return PyErr_CheckSignals();
}
static void
@@ -165,38 +165,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
}
@@ -205,11 +205,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 PyInt_FromLong((long)alarm(t));
+ int t;
+ if (!PyArg_ParseTuple(args, "i:alarm", &t))
+ return NULL;
+ /* alarm() returns the number of seconds remaining */
+ return PyInt_FromLong((long)alarm(t));
}
PyDoc_STRVAR(alarm_doc,
@@ -222,17 +222,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\
@@ -245,44 +245,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,
@@ -300,18 +300,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,
@@ -333,23 +333,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
@@ -357,24 +357,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,
@@ -390,11 +390,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;
}
@@ -408,14 +408,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);
@@ -441,11 +441,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);
@@ -461,27 +461,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 */
};
@@ -524,250 +524,250 @@ the first is the signal number, the second is the interrupted stack frame.");
PyMODINIT_FUNC
initsignal(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 = Py_InitModule3("signal", signal_methods, module_doc);
- if (m == NULL)
- return;
-
- /* 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 = PyInt_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 = Py_InitModule3("signal", signal_methods, module_doc);
+ if (m == NULL)
+ return;
+
+ /* 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 = PyInt_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 = PyInt_FromLong(SIGHUP);
- PyDict_SetItemString(d, "SIGHUP", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGHUP);
+ PyDict_SetItemString(d, "SIGHUP", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGINT
- x = PyInt_FromLong(SIGINT);
- PyDict_SetItemString(d, "SIGINT", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGINT);
+ PyDict_SetItemString(d, "SIGINT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGBREAK
- x = PyInt_FromLong(SIGBREAK);
- PyDict_SetItemString(d, "SIGBREAK", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGBREAK);
+ PyDict_SetItemString(d, "SIGBREAK", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGQUIT
- x = PyInt_FromLong(SIGQUIT);
- PyDict_SetItemString(d, "SIGQUIT", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGQUIT);
+ PyDict_SetItemString(d, "SIGQUIT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGILL
- x = PyInt_FromLong(SIGILL);
- PyDict_SetItemString(d, "SIGILL", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGILL);
+ PyDict_SetItemString(d, "SIGILL", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTRAP
- x = PyInt_FromLong(SIGTRAP);
- PyDict_SetItemString(d, "SIGTRAP", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGTRAP);
+ PyDict_SetItemString(d, "SIGTRAP", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGIOT
- x = PyInt_FromLong(SIGIOT);
- PyDict_SetItemString(d, "SIGIOT", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGIOT);
+ PyDict_SetItemString(d, "SIGIOT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGABRT
- x = PyInt_FromLong(SIGABRT);
- PyDict_SetItemString(d, "SIGABRT", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGABRT);
+ PyDict_SetItemString(d, "SIGABRT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGEMT
- x = PyInt_FromLong(SIGEMT);
- PyDict_SetItemString(d, "SIGEMT", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGEMT);
+ PyDict_SetItemString(d, "SIGEMT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGFPE
- x = PyInt_FromLong(SIGFPE);
- PyDict_SetItemString(d, "SIGFPE", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGFPE);
+ PyDict_SetItemString(d, "SIGFPE", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGKILL
- x = PyInt_FromLong(SIGKILL);
- PyDict_SetItemString(d, "SIGKILL", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGKILL);
+ PyDict_SetItemString(d, "SIGKILL", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGBUS
- x = PyInt_FromLong(SIGBUS);
- PyDict_SetItemString(d, "SIGBUS", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGBUS);
+ PyDict_SetItemString(d, "SIGBUS", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGSEGV
- x = PyInt_FromLong(SIGSEGV);
- PyDict_SetItemString(d, "SIGSEGV", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGSEGV);
+ PyDict_SetItemString(d, "SIGSEGV", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGSYS
- x = PyInt_FromLong(SIGSYS);
- PyDict_SetItemString(d, "SIGSYS", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGSYS);
+ PyDict_SetItemString(d, "SIGSYS", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGPIPE
- x = PyInt_FromLong(SIGPIPE);
- PyDict_SetItemString(d, "SIGPIPE", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGPIPE);
+ PyDict_SetItemString(d, "SIGPIPE", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGALRM
- x = PyInt_FromLong(SIGALRM);
- PyDict_SetItemString(d, "SIGALRM", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGALRM);
+ PyDict_SetItemString(d, "SIGALRM", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTERM
- x = PyInt_FromLong(SIGTERM);
- PyDict_SetItemString(d, "SIGTERM", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGTERM);
+ PyDict_SetItemString(d, "SIGTERM", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGUSR1
- x = PyInt_FromLong(SIGUSR1);
- PyDict_SetItemString(d, "SIGUSR1", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGUSR1);
+ PyDict_SetItemString(d, "SIGUSR1", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGUSR2
- x = PyInt_FromLong(SIGUSR2);
- PyDict_SetItemString(d, "SIGUSR2", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGUSR2);
+ PyDict_SetItemString(d, "SIGUSR2", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGCLD
- x = PyInt_FromLong(SIGCLD);
- PyDict_SetItemString(d, "SIGCLD", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGCLD);
+ PyDict_SetItemString(d, "SIGCLD", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGCHLD
- x = PyInt_FromLong(SIGCHLD);
- PyDict_SetItemString(d, "SIGCHLD", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGCHLD);
+ PyDict_SetItemString(d, "SIGCHLD", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGPWR
- x = PyInt_FromLong(SIGPWR);
- PyDict_SetItemString(d, "SIGPWR", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGPWR);
+ PyDict_SetItemString(d, "SIGPWR", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGIO
- x = PyInt_FromLong(SIGIO);
- PyDict_SetItemString(d, "SIGIO", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGIO);
+ PyDict_SetItemString(d, "SIGIO", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGURG
- x = PyInt_FromLong(SIGURG);
- PyDict_SetItemString(d, "SIGURG", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGURG);
+ PyDict_SetItemString(d, "SIGURG", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGWINCH
- x = PyInt_FromLong(SIGWINCH);
- PyDict_SetItemString(d, "SIGWINCH", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGWINCH);
+ PyDict_SetItemString(d, "SIGWINCH", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGPOLL
- x = PyInt_FromLong(SIGPOLL);
- PyDict_SetItemString(d, "SIGPOLL", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGPOLL);
+ PyDict_SetItemString(d, "SIGPOLL", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGSTOP
- x = PyInt_FromLong(SIGSTOP);
- PyDict_SetItemString(d, "SIGSTOP", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGSTOP);
+ PyDict_SetItemString(d, "SIGSTOP", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTSTP
- x = PyInt_FromLong(SIGTSTP);
- PyDict_SetItemString(d, "SIGTSTP", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGTSTP);
+ PyDict_SetItemString(d, "SIGTSTP", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGCONT
- x = PyInt_FromLong(SIGCONT);
- PyDict_SetItemString(d, "SIGCONT", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGCONT);
+ PyDict_SetItemString(d, "SIGCONT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTTIN
- x = PyInt_FromLong(SIGTTIN);
- PyDict_SetItemString(d, "SIGTTIN", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGTTIN);
+ PyDict_SetItemString(d, "SIGTTIN", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTTOU
- x = PyInt_FromLong(SIGTTOU);
- PyDict_SetItemString(d, "SIGTTOU", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGTTOU);
+ PyDict_SetItemString(d, "SIGTTOU", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGVTALRM
- x = PyInt_FromLong(SIGVTALRM);
- PyDict_SetItemString(d, "SIGVTALRM", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGVTALRM);
+ PyDict_SetItemString(d, "SIGVTALRM", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGPROF
- x = PyInt_FromLong(SIGPROF);
- PyDict_SetItemString(d, "SIGPROF", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGPROF);
+ PyDict_SetItemString(d, "SIGPROF", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGXCPU
- x = PyInt_FromLong(SIGXCPU);
- PyDict_SetItemString(d, "SIGXCPU", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGXCPU);
+ PyDict_SetItemString(d, "SIGXCPU", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGXFSZ
- x = PyInt_FromLong(SIGXFSZ);
- PyDict_SetItemString(d, "SIGXFSZ", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGXFSZ);
+ PyDict_SetItemString(d, "SIGXFSZ", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGRTMIN
- x = PyInt_FromLong(SIGRTMIN);
- PyDict_SetItemString(d, "SIGRTMIN", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGRTMIN);
+ PyDict_SetItemString(d, "SIGRTMIN", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGRTMAX
- x = PyInt_FromLong(SIGRTMAX);
- PyDict_SetItemString(d, "SIGRTMAX", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGRTMAX);
+ PyDict_SetItemString(d, "SIGRTMAX", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGINFO
- x = PyInt_FromLong(SIGINFO);
- PyDict_SetItemString(d, "SIGINFO", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGINFO);
+ PyDict_SetItemString(d, "SIGINFO", x);
+ Py_XDECREF(x);
#endif
#ifdef ITIMER_REAL
@@ -787,45 +787,45 @@ initsignal(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
- if (!PyErr_Occurred())
- return;
+ if (!PyErr_Occurred())
+ return;
- /* Check for errors */
+ /* Check for errors */
finally:
- return;
+ return;
}
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;
}
@@ -833,55 +833,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_stripped 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_stripped 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;
}
@@ -891,46 +891,46 @@ 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)
{
- initsignal();
- _PyImport_FixupExtension("signal", "signal");
+ initsignal();
+ _PyImport_FixupExtension("signal", "signal");
}
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 209b72f..bfe53f1 100644
--- a/Modules/socketmodule.c
+++ b/Modules/socketmodule.c
@@ -17,11 +17,11 @@ 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.fromfd(fd, family, type[, proto]) --> new socket object (created
- from an existing file descriptor)
+ from an existing file descriptor)
- 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')
@@ -35,7 +35,7 @@ Module interface:
- 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
@@ -55,22 +55,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:
@@ -295,7 +295,7 @@ int h_errno; /* not used */
#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
@@ -415,7 +415,7 @@ const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
#define SEGMENT_SIZE (32 * 1024 -1)
#endif
-#define SAS2SA(x) ((struct sockaddr *)(x))
+#define SAS2SA(x) ((struct sockaddr *)(x))
/*
* Constants for getnameinfo()
@@ -471,8 +471,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
@@ -482,107 +482,107 @@ 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;
- }
- }
+ 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
#if defined(RISCOS)
- if (_inet_error.errnum != NULL) {
- PyObject *v;
- v = Py_BuildValue("(is)", errno, _inet_err());
- if (v != NULL) {
- PyErr_SetObject(socket_error, v);
- Py_DECREF(v);
- }
- return NULL;
- }
-#endif
-
- return PyErr_SetFromErrno(socket_error);
+ if (_inet_error.errnum != NULL) {
+ PyObject *v;
+ v = Py_BuildValue("(is)", errno, _inet_err());
+ 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
@@ -590,22 +590,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
@@ -616,45 +616,45 @@ internal_setblocking(PySocketSockObject *s, int block)
{
#ifndef RISCOS
#ifndef MS_WINDOWS
- int delay_flag;
+ int delay_flag;
#endif
#endif
- Py_BEGIN_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
#ifdef __BEOS__
- block = !block;
- setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
- (void *)(&block), sizeof(int));
+ block = !block;
+ setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
+ (void *)(&block), sizeof(int));
#else
#ifndef RISCOS
#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 */
#else /* RISCOS */
- block = !block;
- socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
+ block = !block;
+ socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
#endif /* RISCOS */
#endif /* __BEOS__ */
- 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).
@@ -665,53 +665,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. */
@@ -720,25 +720,25 @@ static double defaulttimeout = -1.0; /* Default timeout for new sockets */
PyMODINIT_FUNC
init_sockobject(PySocketSockObject *s,
- SOCKET_T fd, int family, int type, int proto)
+ SOCKET_T fd, int family, int type, int proto)
{
#ifdef RISCOS
- int block = 1;
+ int block = 1;
#endif
- 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);
#ifdef RISCOS
- if (taskwindow)
- socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
+ if (taskwindow)
+ socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
#endif
}
@@ -751,12 +751,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;
}
@@ -776,122 +776,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;
+ }
}
@@ -902,16 +902,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 PyString_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 PyString_FromString(buf);
}
@@ -923,24 +923,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
@@ -950,12 +950,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 PyString_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 PyString_FromString(buf);
}
#endif
@@ -969,199 +969,199 @@ 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;
- }
+ if (addrlen == 0) {
+ /* No address -- may be recvfrom() from known socket */
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
#ifdef __BEOS__
- /* XXX: BeOS version of accept() doesn't set family correctly */
- addr->sa_family = AF_INET;
+ /* XXX: BeOS version of accept() doesn't set family correctly */
+ addr->sa_family = AF_INET;
#endif
- switch (addr->sa_family) {
+ 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;
- }
+ 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 PyString_FromStringAndSize(a->sun_path,
- addrlen);
- }
- else
+ if (a->sun_path[0] == 0) { /* Linux abstract namespace */
+ addrlen -= offsetof(struct sockaddr_un, sun_path);
+ return PyString_FromStringAndSize(a->sun_path,
+ addrlen);
+ }
+ else
#endif /* linux */
- {
- /* regular NULL-terminated string */
- return PyString_FromString(a->sun_path);
- }
- }
+ {
+ /* regular NULL-terminated string */
+ return PyString_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("shbhs#",
- 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("shbhs#",
+ 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 a tuple. */
- return Py_BuildValue("is#",
- 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 a tuple. */
+ return Py_BuildValue("is#",
+ addr->sa_family,
+ addr->sa_data,
+ sizeof(addr->sa_data));
+
+ }
}
@@ -1172,328 +1172,328 @@ 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, "t#", &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, "t#", &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;
- 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;
+ 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;
- 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;
+ 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;
- straddr = PyString_AsString(args);
- if (straddr == NULL) {
- PyErr_SetString(socket_error, "getsockaddrarg: "
- "wrong format");
- return 0;
- }
- 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;
+ straddr = PyString_AsString(args);
+ if (straddr == NULL) {
+ PyErr_SetString(socket_error, "getsockaddrarg: "
+ "wrong format");
+ return 0;
+ }
+ 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|iis#", &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;
- }
- 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|iis#", &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;
+ }
+ 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;
+
+ }
}
@@ -1504,89 +1504,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;
- }
+ }
}
@@ -1595,67 +1595,67 @@ getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
static PyObject *
sock_accept(PySocketSockObject *s)
{
- sock_addr_t addrbuf;
- SOCKET_T newfd;
- socklen_t addrlen;
- PyObject *sock = NULL;
- PyObject *addr = NULL;
- PyObject *res = NULL;
- int timeout;
-
- if (!getsockaddrlen(s, &addrlen))
- return NULL;
- memset(&addrbuf, 0, addrlen);
+ sock_addr_t addrbuf;
+ SOCKET_T newfd;
+ socklen_t addrlen;
+ PyObject *sock = NULL;
+ PyObject *addr = NULL;
+ PyObject *res = NULL;
+ int timeout;
+
+ if (!getsockaddrlen(s, &addrlen))
+ return NULL;
+ memset(&addrbuf, 0, addrlen);
#ifdef MS_WINDOWS
- newfd = INVALID_SOCKET;
+ newfd = INVALID_SOCKET;
#else
- newfd = -1;
+ newfd = -1;
#endif
- if (!IS_SELECTABLE(s))
- return select_error();
+ 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
+ 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 (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return NULL;
+ }
#ifdef MS_WINDOWS
- if (newfd == INVALID_SOCKET)
+ if (newfd == INVALID_SOCKET)
#else
- if (newfd < 0)
+ if (newfd < 0)
#endif
- return s->errorhandler();
+ return s->errorhandler();
- /* Create the new object with unspecified family,
- to avoid calls to bind() etc. on it. */
- sock = (PyObject *) new_sockobject(newfd,
- s->sock_family,
- s->sock_type,
- s->sock_proto);
+ /* Create the new object with unspecified family,
+ to avoid calls to bind() etc. on it. */
+ sock = (PyObject *) new_sockobject(newfd,
+ s->sock_family,
+ s->sock_type,
+ s->sock_proto);
- if (sock == NULL) {
- SOCKETCLOSE(newfd);
- goto finally;
- }
- addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
- addrlen, s->sock_proto);
- if (addr == NULL)
- goto finally;
+ 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);
+ 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,
@@ -1673,17 +1673,17 @@ info is a pair (hostaddr, port).");
static PyObject *
sock_setblocking(PySocketSockObject *s, PyObject *arg)
{
- int block;
+ int block;
- block = PyInt_AsLong(arg);
- if (block == -1 && PyErr_Occurred())
- return NULL;
+ block = PyInt_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,
@@ -1702,25 +1702,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,
@@ -1736,12 +1736,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,
@@ -1757,16 +1757,16 @@ operations are disabled.");
static PyObject *
sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
{
- int block;
- block = PyInt_AsLong(arg);
- if (block == -1 && PyErr_Occurred())
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
- Py_END_ALLOW_THREADS
-
- Py_INCREF(Py_None);
- return Py_None;
+ int block;
+ block = PyInt_AsLong(arg);
+ if (block == -1 && PyErr_Occurred())
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
+ Py_END_ALLOW_THREADS
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(sleeptaskw_doc,
"sleeptaskw(flag)\n\
@@ -1783,29 +1783,29 @@ Allow sleeps in taskwindows.");
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, "iis#: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, "iis#: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,
@@ -1823,53 +1823,53 @@ 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;
+ int level;
+ int optname;
+ int res;
+ PyObject *buf;
+ socklen_t buflen = 0;
#ifdef __BEOS__
- /* We have incomplete socket support. */
- PyErr_SetString(socket_error, "getsockopt not supported");
- return NULL;
+ /* We have incomplete socket support. */
+ PyErr_SetString(socket_error, "getsockopt not supported");
+ return NULL;
#else
- 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 PyInt_FromLong(flag);
- }
+ 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 PyInt_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 = PyString_FromStringAndSize((char *)NULL, buflen);
- if (buf == NULL)
- return NULL;
- res = getsockopt(s->sock_fd, level, optname,
- (void *)PyString_AS_STRING(buf), &buflen);
- if (res < 0) {
- Py_DECREF(buf);
- return s->errorhandler();
- }
- _PyString_Resize(&buf, buflen);
- return buf;
+ if (buflen <= 0 || buflen > 1024) {
+#endif
+ PyErr_SetString(socket_error,
+ "getsockopt buflen out of range");
+ return NULL;
+ }
+ buf = PyString_FromStringAndSize((char *)NULL, buflen);
+ if (buf == NULL)
+ return NULL;
+ res = getsockopt(s->sock_fd, level, optname,
+ (void *)PyString_AS_STRING(buf), &buflen);
+ if (res < 0) {
+ Py_DECREF(buf);
+ return s->errorhandler();
+ }
+ _PyString_Resize(&buf, buflen);
+ return buf;
#endif /* __BEOS__ */
}
@@ -1886,19 +1886,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,
@@ -1916,16 +1916,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,
@@ -1935,90 +1935,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 writeable 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 writeable 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 */
@@ -2026,26 +2026,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,
@@ -2060,26 +2060,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 PyInt_FromLong((long) res);
+ return PyInt_FromLong((long) res);
}
PyDoc_STRVAR(connect_ex_doc,
@@ -2095,9 +2095,9 @@ static PyObject *
sock_fileno(PySocketSockObject *s)
{
#if SIZEOF_SOCKET_T <= SIZEOF_LONG
- return PyInt_FromLong((long) s->sock_fd);
+ return PyInt_FromLong((long) s->sock_fd);
#else
- return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
+ return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
#endif
}
@@ -2113,19 +2113,19 @@ Return the integer file descriptor of the socket.");
static PyObject *
sock_dup(PySocketSockObject *s)
{
- SOCKET_T newfd;
- PyObject *sock;
-
- newfd = dup(s->sock_fd);
- if (newfd < 0)
- return s->errorhandler();
- sock = (PyObject *) new_sockobject(newfd,
- s->sock_family,
- s->sock_type,
- s->sock_proto);
- if (sock == NULL)
- SOCKETCLOSE(newfd);
- return sock;
+ SOCKET_T newfd;
+ PyObject *sock;
+
+ newfd = dup(s->sock_fd);
+ if (newfd < 0)
+ return s->errorhandler();
+ sock = (PyObject *) new_sockobject(newfd,
+ s->sock_family,
+ s->sock_type,
+ s->sock_proto);
+ if (sock == NULL)
+ SOCKETCLOSE(newfd);
+ return sock;
}
PyDoc_STRVAR(dup_doc,
@@ -2141,20 +2141,20 @@ Return a new socket object connected to the same system resource.");
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,
@@ -2164,26 +2164,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,
@@ -2200,21 +2200,21 @@ info is a pair (hostaddr, port).");
static PyObject *
sock_listen(PySocketSockObject *s, PyObject *arg)
{
- int backlog;
- int res;
-
- backlog = PyInt_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 = PyInt_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,
@@ -2236,48 +2236,48 @@ will allow before refusing new connections.");
static PyObject *
sock_makefile(PySocketSockObject *s, PyObject *args)
{
- extern int fclose(FILE *);
- char *mode = "r";
- int bufsize = -1;
+ extern int fclose(FILE *);
+ char *mode = "r";
+ int bufsize = -1;
#ifdef MS_WIN32
- Py_intptr_t fd;
+ Py_intptr_t fd;
#else
- int fd;
+ int fd;
#endif
- FILE *fp;
- PyObject *f;
+ FILE *fp;
+ PyObject *f;
#ifdef __VMS
- char *mode_r = "r";
- char *mode_w = "w";
+ char *mode_r = "r";
+ char *mode_w = "w";
#endif
- if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
- return NULL;
+ if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
+ return NULL;
#ifdef __VMS
- if (strcmp(mode,"rb") == 0) {
- mode = mode_r;
- }
- else {
- if (strcmp(mode,"wb") == 0) {
- mode = mode_w;
- }
- }
+ if (strcmp(mode,"rb") == 0) {
+ mode = mode_r;
+ }
+ else {
+ if (strcmp(mode,"wb") == 0) {
+ mode = mode_w;
+ }
+ }
#endif
#ifdef MS_WIN32
- if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
- ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
+ if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
+ ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
#else
- if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
-#endif
- {
- if (fd >= 0)
- SOCKETCLOSE(fd);
- return s->errorhandler();
- }
- f = PyFile_FromFile(fp, "<socket>", mode, fclose);
- if (f != NULL)
- PyFile_SetBufSize(f, bufsize);
- return f;
+ if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
+#endif
+ {
+ if (fd >= 0)
+ SOCKETCLOSE(fd);
+ return s->errorhandler();
+ }
+ f = PyFile_FromFile(fp, "<socket>", mode, fclose);
+ if (f != NULL)
+ PyFile_SetBufSize(f, bufsize);
+ return f;
}
PyDoc_STRVAR(makefile_doc,
@@ -2299,76 +2299,76 @@ The mode and buffersize arguments are as for the built-in open() function.");
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 (!IS_SELECTABLE(s)) {
+ select_error();
+ return -1;
+ }
#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;
}
@@ -2377,41 +2377,41 @@ 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 = PyString_FromStringAndSize((char *) 0, recvlen);
- if (buf == NULL)
- return NULL;
-
- /* Call the guts */
- outlen = sock_recv_guts(s, PyString_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 succesful. */
- if (_PyString_Resize(&buf, outlen) < 0)
- /* Oopsy, not so succesful after all. */
- return NULL;
- }
-
- 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 = PyString_FromStringAndSize((char *) 0, recvlen);
+ if (buf == NULL)
+ return NULL;
+
+ /* Call the guts */
+ outlen = sock_recv_guts(s, PyString_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 succesful. */
+ if (_PyString_Resize(&buf, outlen) < 0)
+ /* Oopsy, not so succesful after all. */
+ return NULL;
+ }
+
+ return buf;
}
PyDoc_STRVAR(recv_doc,
@@ -2428,46 +2428,46 @@ 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;
- char *buf;
- int buflen;
-
- /* Get the buffer's memory */
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recv_into", kwlist,
- &buf, &buflen, &recvlen, &flags))
- return NULL;
- assert(buf != 0 && buflen > 0);
-
- if (recvlen < 0) {
- 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) {
- 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. */
- return NULL;
- }
-
- /* Return the number of bytes read. Note that we do not do anything
- special here in the case that readlen < recvlen. */
- return PyInt_FromSsize_t(readlen);
+ static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
+
+ int recvlen = 0, flags = 0;
+ ssize_t readlen;
+ char *buf;
+ int buflen;
+
+ /* Get the buffer's memory */
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recv_into", kwlist,
+ &buf, &buflen, &recvlen, &flags))
+ return NULL;
+ assert(buf != 0 && buflen > 0);
+
+ if (recvlen < 0) {
+ 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) {
+ 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. */
+ return NULL;
+ }
+
+ /* Return the number of bytes read. Note that we do not do anything
+ special here in the case that readlen < recvlen. */
+ return PyInt_FromSsize_t(readlen);
}
PyDoc_STRVAR(recv_into_doc,
@@ -2493,56 +2493,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 */
@@ -2550,45 +2550,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 = PyString_FromStringAndSize((char *) 0, recvlen);
- if (buf == NULL)
- return NULL;
-
- outlen = sock_recvfrom_guts(s, PyString_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 (_PyString_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 = PyString_FromStringAndSize((char *) 0, recvlen);
+ if (buf == NULL)
+ return NULL;
+
+ outlen = sock_recvfrom_guts(s, PyString_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 (_PyString_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,
@@ -2602,41 +2602,41 @@ 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;
- char *buf;
- int buflen;
-
- PyObject *addr = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recvfrom_into",
- kwlist, &buf, &buflen,
- &recvlen, &flags))
- return NULL;
- assert(buf != 0 && buflen > 0);
-
- if (recvlen < 0) {
- 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) {
- /* Return an error */
- Py_XDECREF(addr);
- return NULL;
- }
-
- /* 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;
+ char *buf;
+ int buflen;
+
+ PyObject *addr = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recvfrom_into",
+ kwlist, &buf, &buflen,
+ &recvlen, &flags))
+ return NULL;
+ assert(buf != 0 && buflen > 0);
+
+ if (recvlen < 0) {
+ 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) {
+ /* Return an error */
+ Py_XDECREF(addr);
+ return NULL;
+ }
+
+ /* 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,
@@ -2650,39 +2650,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, "s*|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, "s*|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 PyInt_FromLong((long)n);
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return NULL;
+ }
+ if (n < 0)
+ return s->errorhandler();
+ return PyInt_FromLong((long)n);
}
PyDoc_STRVAR(send_doc,
@@ -2698,48 +2698,48 @@ 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, "s*|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, "s*|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);
-#endif
- if (n < 0)
- 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;
+ n = send(s->sock_fd, buf, len, flags);
+#endif
+ if (n < 0)
+ 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,
@@ -2756,47 +2756,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, "s*O:sendto", &pbuf, &addro)) {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "s*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 PyInt_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, "s*O:sendto", &pbuf, &addro)) {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "s*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 PyInt_FromLong((long)n);
}
PyDoc_STRVAR(sendto_doc,
@@ -2811,19 +2811,19 @@ For IP sockets, the address is a pair (hostaddr, port).");
static PyObject *
sock_shutdown(PySocketSockObject *s, PyObject *arg)
{
- int how;
- int res;
-
- how = PyInt_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 = PyInt_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,
@@ -2836,18 +2836,18 @@ 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;
- unsigned int option = RCVALL_ON;
- DWORD recv;
-
- 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);
+ unsigned long cmd = SIO_RCVALL;
+ unsigned int option = RCVALL_ON;
+ DWORD recv;
+
+ 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);
}
PyDoc_STRVAR(sock_ioctl_doc,
"ioctl(cmd, option) -> long\n\
@@ -2861,69 +2861,69 @@ constants.");
/* 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},
+ {"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},
#ifndef NO_DUP
- {"dup", (PyCFunction)sock_dup, METH_NOARGS,
- dup_doc},
+ {"dup", (PyCFunction)sock_dup, METH_NOARGS,
+ dup_doc},
#endif
- {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
- fileno_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},
+ {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS,
+ sock_ioctl_doc},
#endif
- {"listen", (PyCFunction)sock_listen, METH_O,
- listen_doc},
+ {"listen", (PyCFunction)sock_listen, METH_O,
+ listen_doc},
#ifndef NO_DUP
- {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
- makefile_doc},
-#endif
- {"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},
+ {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
+ makefile_doc},
+#endif
+ {"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},
#ifdef RISCOS
- {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
- sleeptaskw_doc},
+ {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
+ sleeptaskw_doc},
#endif
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
/* SockObject members */
@@ -2941,34 +2941,34 @@ 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);
}
static PyObject *
sock_repr(PySocketSockObject *s)
{
- char buf[512];
+ char buf[512];
#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
- PyOS_snprintf(
- buf, sizeof(buf),
- "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
- (long)s->sock_fd, s->sock_family,
- s->sock_type,
- s->sock_proto);
- return PyString_FromString(buf);
+ 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
+ PyOS_snprintf(
+ buf, sizeof(buf),
+ "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
+ (long)s->sock_fd, s->sock_family,
+ s->sock_type,
+ s->sock_proto);
+ return PyString_FromString(buf);
}
@@ -2977,15 +2977,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;
}
@@ -2995,32 +2995,32 @@ sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static int
sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
{
- PySocketSockObject *s = (PySocketSockObject *)self;
- SOCKET_T fd;
- int family = AF_INET, type = SOCK_STREAM, proto = 0;
- static char *keywords[] = {"family", "type", "proto", 0};
+ PySocketSockObject *s = (PySocketSockObject *)self;
+ SOCKET_T fd;
+ int family = AF_INET, type = SOCK_STREAM, proto = 0;
+ static char *keywords[] = {"family", "type", "proto", 0};
- if (!PyArg_ParseTupleAndKeywords(args, kwds,
- "|iii:socket", keywords,
- &family, &type, &proto))
- return -1;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds,
+ "|iii:socket", keywords,
+ &family, &type, &proto))
+ return -1;
- Py_BEGIN_ALLOW_THREADS
- fd = socket(family, type, proto);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ fd = socket(family, type, proto);
+ Py_END_ALLOW_THREADS
#ifdef MS_WINDOWS
- if (fd == INVALID_SOCKET)
+ if (fd == INVALID_SOCKET)
#else
- if (fd < 0)
+ if (fd < 0)
#endif
- {
- set_error();
- return -1;
- }
- init_sockobject(s, fd, family, type, proto);
+ {
+ set_error();
+ return -1;
+ }
+ init_sockobject(s, fd, family, type, proto);
- return 0;
+ return 0;
}
@@ -3028,45 +3028,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_compare */
- (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_compare */
+ (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 */
};
@@ -3076,15 +3076,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 PyString_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 PyString_FromString(buf);
}
PyDoc_STRVAR(gethostname_doc,
@@ -3099,14 +3099,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,
@@ -3120,130 +3120,130 @@ 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;
-
- if (h == NULL) {
- /* Let's get real error message to return */
+ 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 */
#ifndef RISCOS
- set_herror(h_errno);
+ set_herror(h_errno);
#else
- PyErr_SetString(socket_error, "host not found");
+ PyErr_SetString(socket_error, "host not found");
#endif
- return NULL;
- }
+ 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 = PyString_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 = PyString_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;
}
@@ -3253,63 +3253,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,
@@ -3326,84 +3326,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,
@@ -3421,18 +3421,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 PyInt_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 PyInt_FromLong((long) ntohs(sp->s_port));
}
PyDoc_STRVAR(getservbyname_doc,
@@ -3451,19 +3451,19 @@ otherwise any protocol will match.");
static PyObject *
socket_getservbyport(PyObject *self, PyObject *args)
{
- unsigned short port;
- char *proto=NULL;
- struct servent *sp;
- if (!PyArg_ParseTuple(args, "H|s:getservbyport", &port, &proto))
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- sp = getservbyport(htons(port), proto);
- Py_END_ALLOW_THREADS
- if (sp == NULL) {
- PyErr_SetString(socket_error, "port/proto not found");
- return NULL;
- }
- return PyString_FromString(sp->s_name);
+ unsigned short port;
+ char *proto=NULL;
+ struct servent *sp;
+ if (!PyArg_ParseTuple(args, "H|s:getservbyport", &port, &proto))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ sp = getservbyport(htons(port), proto);
+ Py_END_ALLOW_THREADS
+ if (sp == NULL) {
+ PyErr_SetString(socket_error, "port/proto not found");
+ return NULL;
+ }
+ return PyString_FromString(sp->s_name);
}
PyDoc_STRVAR(getservbyport_doc,
@@ -3481,23 +3481,23 @@ otherwise any protocol will match.");
static PyObject *
socket_getprotobyname(PyObject *self, PyObject *args)
{
- char *name;
- struct protoent *sp;
+ char *name;
+ struct protoent *sp;
#ifdef __BEOS__
/* Not available in BeOS yet. - [cjh] */
- PyErr_SetString(socket_error, "getprotobyname not supported");
- return NULL;
+ PyErr_SetString(socket_error, "getprotobyname not supported");
+ return NULL;
#else
- 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 PyInt_FromLong((long) sp->p_proto);
+ 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 PyInt_FromLong((long) sp->p_proto);
#endif
}
@@ -3516,40 +3516,40 @@ Return the protocol number for the named protocol. (Rarely used.)");
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,
@@ -3572,18 +3572,18 @@ AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
static PyObject *
socket_fromfd(PyObject *self, PyObject *args)
{
- PySocketSockObject *s;
- SOCKET_T fd;
- int family, type, proto = 0;
- if (!PyArg_ParseTuple(args, "iii|i:fromfd",
- &fd, &family, &type, &proto))
- return NULL;
- /* Dup the fd so it and the socket can be closed independently */
- fd = dup(fd);
- if (fd < 0)
- return set_error();
- s = new_sockobject(fd, family, type, proto);
- return (PyObject *) s;
+ PySocketSockObject *s;
+ SOCKET_T fd;
+ int family, type, proto = 0;
+ if (!PyArg_ParseTuple(args, "iii|i:fromfd",
+ &fd, &family, &type, &proto))
+ return NULL;
+ /* Dup the fd so it and the socket can be closed independently */
+ fd = dup(fd);
+ if (fd < 0)
+ return set_error();
+ s = new_sockobject(fd, family, type, proto);
+ return (PyObject *) s;
}
PyDoc_STRVAR(fromfd_doc,
@@ -3599,18 +3599,18 @@ The remaining arguments are the same as for socket().");
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 PyInt_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 PyInt_FromLong(x2);
}
PyDoc_STRVAR(ntohs_doc,
@@ -3622,41 +3622,41 @@ Convert a 16-bit integer from network to host byte order.");
static PyObject *
socket_ntohl(PyObject *self, PyObject *arg)
{
- unsigned long x;
-
- if (PyInt_Check(arg)) {
- x = PyInt_AS_LONG(arg);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
- if ((long)x < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "can't convert negative number to unsigned long");
- return NULL;
- }
- }
- else if (PyLong_Check(arg)) {
- x = PyLong_AsUnsignedLong(arg);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
+ unsigned long x;
+
+ if (PyInt_Check(arg)) {
+ x = PyInt_AS_LONG(arg);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return NULL;
+ if ((long)x < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative number to unsigned long");
+ return NULL;
+ }
+ }
+ else 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,
@@ -3668,18 +3668,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 PyInt_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 PyInt_FromLong(x2);
}
PyDoc_STRVAR(htons_doc,
@@ -3691,39 +3691,39 @@ Convert a 16-bit integer from host to network byte order.");
static PyObject *
socket_htonl(PyObject *self, PyObject *arg)
{
- unsigned long x;
-
- if (PyInt_Check(arg)) {
- x = PyInt_AS_LONG(arg);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
- if ((long)x < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "can't convert negative number to unsigned long");
- return NULL;
- }
- }
- else if (PyLong_Check(arg)) {
- x = PyLong_AsUnsignedLong(arg);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
+ unsigned long x;
+
+ if (PyInt_Check(arg)) {
+ x = PyInt_AS_LONG(arg);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return NULL;
+ if ((long)x < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative number to unsigned long");
+ return NULL;
+ }
+ }
+ else 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,
@@ -3746,20 +3746,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
@@ -3767,13 +3767,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 PyString_FromStringAndSize((char *)(&buf),
- sizeof(buf));
+ if (inet_aton(ip_addr, &buf))
+ return PyString_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 {
@@ -3783,22 +3783,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 PyString_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 PyString_FromStringAndSize((char *) &packed_addr,
+ sizeof(packed_addr));
#ifdef USE_INET_ATON_WEAKLINK
}
@@ -3815,23 +3815,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, "s#:inet_ntoa", &packed_str, &addr_len)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s#: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 PyString_FromString(inet_ntoa(packed_addr));
+ return PyString_FromString(inet_ntoa(packed_addr));
}
#ifdef HAVE_INET_PTON
@@ -3845,46 +3845,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 PyString_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 PyString_FromStringAndSize(packed,
+ sizeof(struct in_addr));
#ifdef ENABLE_IPV6
- } else if (af == AF_INET6) {
- return PyString_FromStringAndSize(packed,
- sizeof(struct in6_addr));
-#endif
- } else {
- PyErr_SetString(socket_error, "unknown address family");
- return NULL;
- }
+ } else if (af == AF_INET6) {
+ return PyString_FromStringAndSize(packed,
+ sizeof(struct in6_addr));
+#endif
+ } else {
+ PyErr_SetString(socket_error, "unknown address family");
+ return NULL;
+ }
}
PyDoc_STRVAR(inet_ntop_doc,
@@ -3895,54 +3895,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 PyString_FromString() below */
- memset((void *) &ip[0], '\0', sizeof(ip));
+ /* Guarantee NUL-termination for PyString_FromString() below */
+ memset((void *) &ip[0], '\0', sizeof(ip));
- if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "is#: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 PyString_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 PyString_FromString(retval);
+ }
+
+ /* NOTREACHED */
+ PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
+ return NULL;
}
#endif /* HAVE_INET_PTON */
@@ -3953,95 +3953,95 @@ 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 *single = (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;
- hptr = PyString_AsString(idna);
- } else if (PyString_Check(hobj)) {
- hptr = PyString_AsString(hobj);
- } else {
- PyErr_SetString(PyExc_TypeError,
- "getaddrinfo() argument 1 must be string or None");
- return NULL;
- }
- if (PyInt_Check(pobj)) {
- PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
- pptr = pbuf;
- } else if (PyString_Check(pobj)) {
- pptr = PyString_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 *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 *single = (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;
+ hptr = PyString_AsString(idna);
+ } else if (PyString_Check(hobj)) {
+ hptr = PyString_AsString(hobj);
+ } else {
+ PyErr_SetString(PyExc_TypeError,
+ "getaddrinfo() argument 1 must be string or None");
+ return NULL;
+ }
+ if (PyInt_Check(pobj)) {
+ PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
+ pptr = pbuf;
+ } else if (PyString_Check(pobj)) {
+ pptr = PyString_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 *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(single);
- Py_XDECREF(all);
- Py_XDECREF(idna);
- if (res0)
- freeaddrinfo(res0);
- return (PyObject *)NULL;
+ Py_XDECREF(single);
+ Py_XDECREF(all);
+ Py_XDECREF(idna);
+ if (res0)
+ freeaddrinfo(res0);
+ return (PyObject *)NULL;
}
PyDoc_STRVAR(getaddrinfo_doc,
@@ -4056,77 +4056,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,
@@ -4140,12 +4140,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,
@@ -4158,24 +4158,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,
@@ -4189,55 +4189,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
- {"fromfd", socket_fromfd,
- METH_VARARGS, fromfd_doc},
+ {"fromfd", socket_fromfd,
+ METH_VARARGS, fromfd_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 */
};
@@ -4247,13 +4247,13 @@ static PyMethodDef socket_methods[] = {
static int
os_init(void)
{
- _kernel_swi_regs r;
+ _kernel_swi_regs r;
- r.r[0] = 0;
- _kernel_swi(0x43380, &r, &r);
- taskwindow = r.r[0];
+ r.r[0] = 0;
+ _kernel_swi(0x43380, &r, &r);
+ taskwindow = r.r[0];
- return 1;
+ return 1;
}
#endif /* RISCOS */
@@ -4267,37 +4267,37 @@ os_init(void)
static void
os_cleanup(void)
{
- WSACleanup();
+ WSACleanup();
}
static int
os_init(void)
{
- WSADATA WSAData;
- int ret;
- char buf[100];
- 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:
- PyOS_snprintf(buf, sizeof(buf),
- "WSAStartup failed: error code %d", ret);
- PyErr_SetString(PyExc_ImportError, buf);
- break;
- }
- return 0; /* Failure */
+ WSADATA WSAData;
+ int ret;
+ char buf[100];
+ 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:
+ PyOS_snprintf(buf, sizeof(buf),
+ "WSAStartup failed: error code %d", ret);
+ PyErr_SetString(PyExc_ImportError, buf);
+ break;
+ }
+ return 0; /* Failure */
}
#endif /* MS_WINDOWS */
@@ -4312,21 +4312,21 @@ static int
os_init(void)
{
#ifndef PYCC_GCC
- char reason[64];
- int rc = sock_init();
+ char reason[64];
+ int rc = sock_init();
- if (rc == 0) {
- return 1; /* Success */
- }
+ if (rc == 0) {
+ return 1; /* Success */
+ }
- PyOS_snprintf(reason, sizeof(reason),
- "OS/2 TCP/IP Error# %d", sock_errno());
- PyErr_SetString(PyExc_ImportError, reason);
+ PyOS_snprintf(reason, sizeof(reason),
+ "OS/2 TCP/IP Error# %d", sock_errno());
+ PyErr_SetString(PyExc_ImportError, reason);
- 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
}
@@ -4337,7 +4337,7 @@ os_init(void)
static int
os_init(void)
{
- return 1; /* Success */
+ return 1; /* Success */
}
#endif
@@ -4347,8 +4347,8 @@ os_init(void)
static
PySocketModule_APIObject PySocketModuleAPI =
{
- &sock_type,
- NULL
+ &sock_type,
+ NULL
};
@@ -4373,911 +4373,911 @@ See the socket module for documentation.");
PyMODINIT_FUNC
init_socket(void)
{
- PyObject *m, *has_ipv6;
-
- if (!os_init())
- return;
-
- Py_TYPE(&sock_type) = &PyType_Type;
- m = Py_InitModule3(PySocket_MODULE_NAME,
- socket_methods,
- socket_doc);
- if (m == NULL)
- return;
-
- socket_error = PyErr_NewException("socket.error",
- PyExc_IOError, NULL);
- if (socket_error == NULL)
- return;
- 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;
- Py_INCREF(socket_herror);
- PyModule_AddObject(m, "herror", socket_herror);
- socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
- NULL);
- if (socket_gaierror == NULL)
- return;
- Py_INCREF(socket_gaierror);
- PyModule_AddObject(m, "gaierror", socket_gaierror);
- socket_timeout = PyErr_NewException("socket.timeout",
- socket_error, NULL);
- if (socket_timeout == NULL)
- return;
- 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;
- Py_INCREF((PyObject *)&sock_type);
- if (PyModule_AddObject(m, "socket",
- (PyObject *)&sock_type) != 0)
- return;
+ PyObject *m, *has_ipv6;
+
+ if (!os_init())
+ return;
+
+ Py_TYPE(&sock_type) = &PyType_Type;
+ m = Py_InitModule3(PySocket_MODULE_NAME,
+ socket_methods,
+ socket_doc);
+ if (m == NULL)
+ return;
+
+ socket_error = PyErr_NewException("socket.error",
+ PyExc_IOError, NULL);
+ if (socket_error == NULL)
+ return;
+ 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;
+ Py_INCREF(socket_herror);
+ PyModule_AddObject(m, "herror", socket_herror);
+ socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
+ NULL);
+ if (socket_gaierror == NULL)
+ return;
+ Py_INCREF(socket_gaierror);
+ PyModule_AddObject(m, "gaierror", socket_gaierror);
+ socket_timeout = PyErr_NewException("socket.timeout",
+ socket_error, NULL);
+ if (socket_timeout == NULL)
+ return;
+ 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;
+ Py_INCREF((PyObject *)&sock_type);
+ if (PyModule_AddObject(m, "socket",
+ (PyObject *)&sock_type) != 0)
+ return;
#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,
- PyCObject_FromVoidPtr((void *)&PySocketModuleAPI, NULL)
- ) != 0)
- return;
+ /* Export C API */
+ if (PyModule_AddObject(m, PySocket_CAPI_NAME,
+ PyCObject_FromVoidPtr((void *)&PySocketModuleAPI, NULL)
+ ) != 0)
+ return;
- /* 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);
-#endif
+ 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);
#ifndef __BEOS__
/* 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
#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
- /* 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
- {
- PyObject *tmp;
- tmp = PyLong_FromUnsignedLong(SIO_RCVALL);
- if (tmp == NULL)
- return;
- PyModule_AddObject(m, "SIO_RCVALL", tmp);
- }
- PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
- PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
- PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
+ {
+ PyObject *tmp;
+ tmp = PyLong_FromUnsignedLong(SIO_RCVALL);
+ if (tmp == NULL)
+ return;
+ PyModule_AddObject(m, "SIO_RCVALL", 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
}
@@ -5291,34 +5291,34 @@ init_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 ef8d0fc..9b85773 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,43 +76,43 @@ extern "C" {
#endif
/* Python module and C API name */
-#define PySocket_MODULE_NAME "_socket"
-#define PySocket_CAPI_NAME "CAPI"
+#define PySocket_MODULE_NAME "_socket"
+#define PySocket_CAPI_NAME "CAPI"
/* 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;
@@ -121,16 +121,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 ----------------------------------------------------*/
@@ -138,7 +138,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
@@ -160,24 +160,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.
@@ -185,13 +185,13 @@ typedef struct {
/* C API for usage by other Python modules */
typedef struct {
- PyTypeObject *Sock_Type;
- PyObject *error;
+ PyTypeObject *Sock_Type;
+ PyObject *error;
} PySocketModule_APIObject;
/* XXX The net effect of the following appears to be to define a function
XXX named PySocketModule_APIObject in _ssl.c. It's unclear why it isn't
- XXX defined there directly.
+ XXX defined there directly.
>>> It's defined here because other modules might also want to use
>>> the C API.
@@ -207,8 +207,8 @@ typedef struct {
if (!PyArg_ParseTuple(args, "O!|zz:ssl",
&PySocketModule.Sock_Type, (PyObject*)&Sock,
- &key_file, &cert_file))
- return NULL;
+ &key_file, &cert_file))
+ return NULL;
...
*/
@@ -226,34 +226,34 @@ PySocketModule_APIObject PySocketModule;
static
int PySocketModule_ImportModuleAndAPI(void)
{
- PyObject *mod = 0, *v = 0;
- char *apimodule = PySocket_MODULE_NAME;
- char *apiname = PySocket_CAPI_NAME;
- void *api;
-
- DPRINTF("Importing the %s C API...\n", apimodule);
- mod = PyImport_ImportModuleNoBlock(apimodule);
- if (mod == NULL)
- goto onError;
- DPRINTF(" %s package found\n", apimodule);
- v = PyObject_GetAttrString(mod, apiname);
- if (v == NULL)
- goto onError;
- Py_DECREF(mod);
- DPRINTF(" API object %s found\n", apiname);
- api = PyCObject_AsVoidPtr(v);
- if (api == NULL)
- goto onError;
- Py_DECREF(v);
- memcpy(&PySocketModule, api, sizeof(PySocketModule));
- DPRINTF(" API object loaded and initialized.\n");
- return 0;
+ PyObject *mod = 0, *v = 0;
+ char *apimodule = PySocket_MODULE_NAME;
+ char *apiname = PySocket_CAPI_NAME;
+ void *api;
+
+ DPRINTF("Importing the %s C API...\n", apimodule);
+ mod = PyImport_ImportModuleNoBlock(apimodule);
+ if (mod == NULL)
+ goto onError;
+ DPRINTF(" %s package found\n", apimodule);
+ v = PyObject_GetAttrString(mod, apiname);
+ if (v == NULL)
+ goto onError;
+ Py_DECREF(mod);
+ DPRINTF(" API object %s found\n", apiname);
+ api = PyCObject_AsVoidPtr(v);
+ if (api == NULL)
+ goto onError;
+ Py_DECREF(v);
+ memcpy(&PySocketModule, api, sizeof(PySocketModule));
+ DPRINTF(" API object loaded and initialized.\n");
+ return 0;
onError:
- DPRINTF(" not found.\n");
- Py_XDECREF(mod);
- Py_XDECREF(v);
- return -1;
+ DPRINTF(" not found.\n");
+ Py_XDECREF(mod);
+ Py_XDECREF(v);
+ return -1;
}
#endif /* !PySocket_BUILDING_SOCKET */
diff --git a/Modules/spwdmodule.c b/Modules/spwdmodule.c
index d3f309a..957de58 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,42 +60,42 @@ static void
sets(PyObject *v, int i, char* val)
{
if (val)
- PyStructSequence_SET_ITEM(v, i, PyString_FromString(val));
+ PyStructSequence_SET_ITEM(v, i, PyString_FromString(val));
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, PyInt_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 */
@@ -111,15 +111,15 @@ See spwd.__doc__ for more on shadow password database entries.");
static PyObject* spwd_getspnam(PyObject *self, PyObject *args)
{
- char *name;
- struct spwd *p;
- if (!PyArg_ParseTuple(args, "s:getspnam", &name))
- return NULL;
- if ((p = getspnam(name)) == NULL) {
- PyErr_SetString(PyExc_KeyError, "getspnam(): name not found");
- return NULL;
- }
- return mkspent(p);
+ char *name;
+ struct spwd *p;
+ if (!PyArg_ParseTuple(args, "s:getspnam", &name))
+ return NULL;
+ if ((p = getspnam(name)) == NULL) {
+ PyErr_SetString(PyExc_KeyError, "getspnam(): name not found");
+ return NULL;
+ }
+ return mkspent(p);
}
#endif /* HAVE_GETSPNAM */
@@ -135,49 +135,49 @@ 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 */
};
PyMODINIT_FUNC
initspwd(void)
{
- PyObject *m;
- m=Py_InitModule3("spwd", spwd_methods, spwd__doc__);
- if (m == NULL)
- return;
- if (!initialized)
- PyStructSequence_InitType(&StructSpwdType,
- &struct_spwd_type_desc);
- Py_INCREF((PyObject *) &StructSpwdType);
- PyModule_AddObject(m, "struct_spwd", (PyObject *) &StructSpwdType);
- initialized = 1;
+ PyObject *m;
+ m=Py_InitModule3("spwd", spwd_methods, spwd__doc__);
+ if (m == NULL)
+ return;
+ if (!initialized)
+ PyStructSequence_InitType(&StructSpwdType,
+ &struct_spwd_type_desc);
+ Py_INCREF((PyObject *) &StructSpwdType);
+ PyModule_AddObject(m, "struct_spwd", (PyObject *) &StructSpwdType);
+ initialized = 1;
}
diff --git a/Modules/stropmodule.c b/Modules/stropmodule.c
index 2d88474..090b07e 100644
--- a/Modules/stropmodule.c
+++ b/Modules/stropmodule.c
@@ -14,8 +14,8 @@ PyDoc_STRVAR(strop_module__doc__,
XXX are defined for all 8-bit characters! */
#define WARN if (PyErr_Warn(PyExc_DeprecationWarning, \
- "strop functions are obsolete; use string methods")) \
- return NULL
+ "strop functions are obsolete; use string methods")) \
+ return NULL
/* The lstrip(), rstrip() and strip() functions are implemented
in do_strip(), which uses an additional parameter to indicate what
@@ -29,56 +29,56 @@ PyDoc_STRVAR(strop_module__doc__,
static PyObject *
split_whitespace(char *s, Py_ssize_t len, Py_ssize_t maxsplit)
{
- Py_ssize_t i = 0, j;
- int err;
- Py_ssize_t countsplit = 0;
- PyObject* item;
- PyObject *list = PyList_New(0);
-
- if (list == NULL)
- return NULL;
-
- while (i < len) {
- while (i < len && isspace(Py_CHARMASK(s[i]))) {
- i = i+1;
- }
- j = i;
- while (i < len && !isspace(Py_CHARMASK(s[i]))) {
- i = i+1;
- }
- if (j < i) {
- item = PyString_FromStringAndSize(s+j, i-j);
- if (item == NULL)
- goto finally;
-
- err = PyList_Append(list, item);
- Py_DECREF(item);
- if (err < 0)
- goto finally;
-
- countsplit++;
- while (i < len && isspace(Py_CHARMASK(s[i]))) {
- i = i+1;
- }
- if (maxsplit && (countsplit >= maxsplit) && i < len) {
- item = PyString_FromStringAndSize(
- s+i, len - i);
- if (item == NULL)
- goto finally;
-
- err = PyList_Append(list, item);
- Py_DECREF(item);
- if (err < 0)
- goto finally;
-
- i = len;
- }
- }
- }
- return list;
+ Py_ssize_t i = 0, j;
+ int err;
+ Py_ssize_t countsplit = 0;
+ PyObject* item;
+ PyObject *list = PyList_New(0);
+
+ if (list == NULL)
+ return NULL;
+
+ while (i < len) {
+ while (i < len && isspace(Py_CHARMASK(s[i]))) {
+ i = i+1;
+ }
+ j = i;
+ while (i < len && !isspace(Py_CHARMASK(s[i]))) {
+ i = i+1;
+ }
+ if (j < i) {
+ item = PyString_FromStringAndSize(s+j, i-j);
+ if (item == NULL)
+ goto finally;
+
+ err = PyList_Append(list, item);
+ Py_DECREF(item);
+ if (err < 0)
+ goto finally;
+
+ countsplit++;
+ while (i < len && isspace(Py_CHARMASK(s[i]))) {
+ i = i+1;
+ }
+ if (maxsplit && (countsplit >= maxsplit) && i < len) {
+ item = PyString_FromStringAndSize(
+ s+i, len - i);
+ if (item == NULL)
+ goto finally;
+
+ err = PyList_Append(list, item);
+ Py_DECREF(item);
+ if (err < 0)
+ goto finally;
+
+ i = len;
+ }
+ }
+ }
+ return list;
finally:
- Py_DECREF(list);
- return NULL;
+ Py_DECREF(list);
+ return NULL;
}
@@ -96,60 +96,60 @@ PyDoc_STRVAR(splitfields__doc__,
static PyObject *
strop_splitfields(PyObject *self, PyObject *args)
{
- Py_ssize_t len, n, i, j, err;
- Py_ssize_t splitcount, maxsplit;
- char *s, *sub;
- PyObject *list, *item;
-
- WARN;
- sub = NULL;
- n = 0;
- splitcount = 0;
- maxsplit = 0;
- if (!PyArg_ParseTuple(args, "t#|z#n:split", &s, &len, &sub, &n, &maxsplit))
- return NULL;
- if (sub == NULL)
- return split_whitespace(s, len, maxsplit);
- if (n == 0) {
- PyErr_SetString(PyExc_ValueError, "empty separator");
- return NULL;
- }
-
- list = PyList_New(0);
- if (list == NULL)
- return NULL;
-
- i = j = 0;
- while (i+n <= len) {
- if (s[i] == sub[0] && (n == 1 || memcmp(s+i, sub, n) == 0)) {
- item = PyString_FromStringAndSize(s+j, i-j);
- if (item == NULL)
- goto fail;
- err = PyList_Append(list, item);
- Py_DECREF(item);
- if (err < 0)
- goto fail;
- i = j = i + n;
- splitcount++;
- if (maxsplit && (splitcount >= maxsplit))
- break;
- }
- else
- i++;
- }
- item = PyString_FromStringAndSize(s+j, len-j);
- if (item == NULL)
- goto fail;
- err = PyList_Append(list, item);
- Py_DECREF(item);
- if (err < 0)
- goto fail;
-
- return list;
+ Py_ssize_t len, n, i, j, err;
+ Py_ssize_t splitcount, maxsplit;
+ char *s, *sub;
+ PyObject *list, *item;
+
+ WARN;
+ sub = NULL;
+ n = 0;
+ splitcount = 0;
+ maxsplit = 0;
+ if (!PyArg_ParseTuple(args, "t#|z#n:split", &s, &len, &sub, &n, &maxsplit))
+ return NULL;
+ if (sub == NULL)
+ return split_whitespace(s, len, maxsplit);
+ if (n == 0) {
+ PyErr_SetString(PyExc_ValueError, "empty separator");
+ return NULL;
+ }
+
+ list = PyList_New(0);
+ if (list == NULL)
+ return NULL;
+
+ i = j = 0;
+ while (i+n <= len) {
+ if (s[i] == sub[0] && (n == 1 || memcmp(s+i, sub, n) == 0)) {
+ item = PyString_FromStringAndSize(s+j, i-j);
+ if (item == NULL)
+ goto fail;
+ err = PyList_Append(list, item);
+ Py_DECREF(item);
+ if (err < 0)
+ goto fail;
+ i = j = i + n;
+ splitcount++;
+ if (maxsplit && (splitcount >= maxsplit))
+ break;
+ }
+ else
+ i++;
+ }
+ item = PyString_FromStringAndSize(s+j, len-j);
+ if (item == NULL)
+ goto fail;
+ err = PyList_Append(list, item);
+ Py_DECREF(item);
+ if (err < 0)
+ goto fail;
+
+ return list;
fail:
- Py_DECREF(list);
- return NULL;
+ Py_DECREF(list);
+ return NULL;
}
@@ -166,128 +166,128 @@ PyDoc_STRVAR(joinfields__doc__,
static PyObject *
strop_joinfields(PyObject *self, PyObject *args)
{
- PyObject *seq;
- char *sep = NULL;
- Py_ssize_t seqlen, seplen = 0;
- Py_ssize_t i, reslen = 0, slen = 0, sz = 100;
- PyObject *res = NULL;
- char* p = NULL;
- ssizeargfunc getitemfunc;
-
- WARN;
- if (!PyArg_ParseTuple(args, "O|t#:join", &seq, &sep, &seplen))
- return NULL;
- if (sep == NULL) {
- sep = " ";
- seplen = 1;
- }
-
- seqlen = PySequence_Size(seq);
- if (seqlen < 0 && PyErr_Occurred())
- return NULL;
-
- if (seqlen == 1) {
- /* Optimization if there's only one item */
- PyObject *item = PySequence_GetItem(seq, 0);
- if (item && !PyString_Check(item)) {
- PyErr_SetString(PyExc_TypeError,
- "first argument must be sequence of strings");
- Py_DECREF(item);
- return NULL;
- }
- return item;
- }
-
- if (!(res = PyString_FromStringAndSize((char*)NULL, sz)))
- return NULL;
- p = PyString_AsString(res);
-
- /* optimize for lists, since it's the most common case. all others
- * (tuples and arbitrary sequences) just use the sequence abstract
- * interface.
- */
- if (PyList_Check(seq)) {
- for (i = 0; i < seqlen; i++) {
- PyObject *item = PyList_GET_ITEM(seq, i);
- if (!PyString_Check(item)) {
- PyErr_SetString(PyExc_TypeError,
- "first argument must be sequence of strings");
- Py_DECREF(res);
- return NULL;
- }
- slen = PyString_GET_SIZE(item);
- if (slen > PY_SSIZE_T_MAX - reslen ||
- seplen > PY_SSIZE_T_MAX - reslen - seplen) {
- PyErr_SetString(PyExc_OverflowError,
- "input too long");
- Py_DECREF(res);
- return NULL;
- }
- while (reslen + slen + seplen >= sz) {
- if (_PyString_Resize(&res, sz * 2) < 0)
- return NULL;
- sz *= 2;
- p = PyString_AsString(res) + reslen;
- }
- if (i > 0) {
- memcpy(p, sep, seplen);
- p += seplen;
- reslen += seplen;
- }
- memcpy(p, PyString_AS_STRING(item), slen);
- p += slen;
- reslen += slen;
- }
- _PyString_Resize(&res, reslen);
- return res;
- }
-
- if (seq->ob_type->tp_as_sequence == NULL ||
- (getitemfunc = seq->ob_type->tp_as_sequence->sq_item) == NULL)
- {
- PyErr_SetString(PyExc_TypeError,
- "first argument must be a sequence");
- return NULL;
- }
- /* This is now type safe */
- for (i = 0; i < seqlen; i++) {
- PyObject *item = getitemfunc(seq, i);
- if (!item || !PyString_Check(item)) {
- PyErr_SetString(PyExc_TypeError,
- "first argument must be sequence of strings");
- Py_DECREF(res);
- Py_XDECREF(item);
- return NULL;
- }
- slen = PyString_GET_SIZE(item);
- if (slen > PY_SSIZE_T_MAX - reslen ||
- seplen > PY_SSIZE_T_MAX - reslen - seplen) {
- PyErr_SetString(PyExc_OverflowError,
- "input too long");
- Py_DECREF(res);
- Py_XDECREF(item);
- return NULL;
- }
- while (reslen + slen + seplen >= sz) {
- if (_PyString_Resize(&res, sz * 2) < 0) {
- Py_DECREF(item);
- return NULL;
- }
- sz *= 2;
- p = PyString_AsString(res) + reslen;
- }
- if (i > 0) {
- memcpy(p, sep, seplen);
- p += seplen;
- reslen += seplen;
- }
- memcpy(p, PyString_AS_STRING(item), slen);
- p += slen;
- reslen += slen;
- Py_DECREF(item);
- }
- _PyString_Resize(&res, reslen);
- return res;
+ PyObject *seq;
+ char *sep = NULL;
+ Py_ssize_t seqlen, seplen = 0;
+ Py_ssize_t i, reslen = 0, slen = 0, sz = 100;
+ PyObject *res = NULL;
+ char* p = NULL;
+ ssizeargfunc getitemfunc;
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "O|t#:join", &seq, &sep, &seplen))
+ return NULL;
+ if (sep == NULL) {
+ sep = " ";
+ seplen = 1;
+ }
+
+ seqlen = PySequence_Size(seq);
+ if (seqlen < 0 && PyErr_Occurred())
+ return NULL;
+
+ if (seqlen == 1) {
+ /* Optimization if there's only one item */
+ PyObject *item = PySequence_GetItem(seq, 0);
+ if (item && !PyString_Check(item)) {
+ PyErr_SetString(PyExc_TypeError,
+ "first argument must be sequence of strings");
+ Py_DECREF(item);
+ return NULL;
+ }
+ return item;
+ }
+
+ if (!(res = PyString_FromStringAndSize((char*)NULL, sz)))
+ return NULL;
+ p = PyString_AsString(res);
+
+ /* optimize for lists, since it's the most common case. all others
+ * (tuples and arbitrary sequences) just use the sequence abstract
+ * interface.
+ */
+ if (PyList_Check(seq)) {
+ for (i = 0; i < seqlen; i++) {
+ PyObject *item = PyList_GET_ITEM(seq, i);
+ if (!PyString_Check(item)) {
+ PyErr_SetString(PyExc_TypeError,
+ "first argument must be sequence of strings");
+ Py_DECREF(res);
+ return NULL;
+ }
+ slen = PyString_GET_SIZE(item);
+ if (slen > PY_SSIZE_T_MAX - reslen ||
+ seplen > PY_SSIZE_T_MAX - reslen - seplen) {
+ PyErr_SetString(PyExc_OverflowError,
+ "input too long");
+ Py_DECREF(res);
+ return NULL;
+ }
+ while (reslen + slen + seplen >= sz) {
+ if (_PyString_Resize(&res, sz * 2) < 0)
+ return NULL;
+ sz *= 2;
+ p = PyString_AsString(res) + reslen;
+ }
+ if (i > 0) {
+ memcpy(p, sep, seplen);
+ p += seplen;
+ reslen += seplen;
+ }
+ memcpy(p, PyString_AS_STRING(item), slen);
+ p += slen;
+ reslen += slen;
+ }
+ _PyString_Resize(&res, reslen);
+ return res;
+ }
+
+ if (seq->ob_type->tp_as_sequence == NULL ||
+ (getitemfunc = seq->ob_type->tp_as_sequence->sq_item) == NULL)
+ {
+ PyErr_SetString(PyExc_TypeError,
+ "first argument must be a sequence");
+ return NULL;
+ }
+ /* This is now type safe */
+ for (i = 0; i < seqlen; i++) {
+ PyObject *item = getitemfunc(seq, i);
+ if (!item || !PyString_Check(item)) {
+ PyErr_SetString(PyExc_TypeError,
+ "first argument must be sequence of strings");
+ Py_DECREF(res);
+ Py_XDECREF(item);
+ return NULL;
+ }
+ slen = PyString_GET_SIZE(item);
+ if (slen > PY_SSIZE_T_MAX - reslen ||
+ seplen > PY_SSIZE_T_MAX - reslen - seplen) {
+ PyErr_SetString(PyExc_OverflowError,
+ "input too long");
+ Py_DECREF(res);
+ Py_XDECREF(item);
+ return NULL;
+ }
+ while (reslen + slen + seplen >= sz) {
+ if (_PyString_Resize(&res, sz * 2) < 0) {
+ Py_DECREF(item);
+ return NULL;
+ }
+ sz *= 2;
+ p = PyString_AsString(res) + reslen;
+ }
+ if (i > 0) {
+ memcpy(p, sep, seplen);
+ p += seplen;
+ reslen += seplen;
+ }
+ memcpy(p, PyString_AS_STRING(item), slen);
+ p += slen;
+ reslen += slen;
+ Py_DECREF(item);
+ }
+ _PyString_Resize(&res, reslen);
+ return res;
}
@@ -303,34 +303,34 @@ PyDoc_STRVAR(find__doc__,
static PyObject *
strop_find(PyObject *self, PyObject *args)
{
- char *s, *sub;
- Py_ssize_t len, n, i = 0, last = PY_SSIZE_T_MAX;
-
- WARN;
- if (!PyArg_ParseTuple(args, "t#t#|nn:find", &s, &len, &sub, &n, &i, &last))
- return NULL;
-
- if (last > len)
- last = len;
- if (last < 0)
- last += len;
- if (last < 0)
- last = 0;
- if (i < 0)
- i += len;
- if (i < 0)
- i = 0;
-
- if (n == 0 && i <= last)
- return PyInt_FromLong((long)i);
-
- last -= n;
- for (; i <= last; ++i)
- if (s[i] == sub[0] &&
- (n == 1 || memcmp(&s[i+1], &sub[1], n-1) == 0))
- return PyInt_FromLong((long)i);
-
- return PyInt_FromLong(-1L);
+ char *s, *sub;
+ Py_ssize_t len, n, i = 0, last = PY_SSIZE_T_MAX;
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "t#t#|nn:find", &s, &len, &sub, &n, &i, &last))
+ return NULL;
+
+ if (last > len)
+ last = len;
+ if (last < 0)
+ last += len;
+ if (last < 0)
+ last = 0;
+ if (i < 0)
+ i += len;
+ if (i < 0)
+ i = 0;
+
+ if (n == 0 && i <= last)
+ return PyInt_FromLong((long)i);
+
+ last -= n;
+ for (; i <= last; ++i)
+ if (s[i] == sub[0] &&
+ (n == 1 || memcmp(&s[i+1], &sub[1], n-1) == 0))
+ return PyInt_FromLong((long)i);
+
+ return PyInt_FromLong(-1L);
}
@@ -346,68 +346,68 @@ PyDoc_STRVAR(rfind__doc__,
static PyObject *
strop_rfind(PyObject *self, PyObject *args)
{
- char *s, *sub;
- Py_ssize_t len, n, j;
- Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
-
- WARN;
- if (!PyArg_ParseTuple(args, "t#t#|nn:rfind", &s, &len, &sub, &n, &i, &last))
- return NULL;
-
- if (last > len)
- last = len;
- if (last < 0)
- last += len;
- if (last < 0)
- last = 0;
- if (i < 0)
- i += len;
- if (i < 0)
- i = 0;
-
- if (n == 0 && i <= last)
- return PyInt_FromLong((long)last);
-
- for (j = last-n; j >= i; --j)
- if (s[j] == sub[0] &&
- (n == 1 || memcmp(&s[j+1], &sub[1], n-1) == 0))
- return PyInt_FromLong((long)j);
-
- return PyInt_FromLong(-1L);
+ char *s, *sub;
+ Py_ssize_t len, n, j;
+ Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "t#t#|nn:rfind", &s, &len, &sub, &n, &i, &last))
+ return NULL;
+
+ if (last > len)
+ last = len;
+ if (last < 0)
+ last += len;
+ if (last < 0)
+ last = 0;
+ if (i < 0)
+ i += len;
+ if (i < 0)
+ i = 0;
+
+ if (n == 0 && i <= last)
+ return PyInt_FromLong((long)last);
+
+ for (j = last-n; j >= i; --j)
+ if (s[j] == sub[0] &&
+ (n == 1 || memcmp(&s[j+1], &sub[1], n-1) == 0))
+ return PyInt_FromLong((long)j);
+
+ return PyInt_FromLong(-1L);
}
static PyObject *
do_strip(PyObject *args, int striptype)
{
- char *s;
- Py_ssize_t len, i, j;
-
-
- if (PyString_AsStringAndSize(args, &s, &len))
- return NULL;
-
- i = 0;
- if (striptype != RIGHTSTRIP) {
- while (i < len && isspace(Py_CHARMASK(s[i]))) {
- i++;
- }
- }
-
- j = len;
- if (striptype != LEFTSTRIP) {
- do {
- j--;
- } while (j >= i && isspace(Py_CHARMASK(s[j])));
- j++;
- }
-
- if (i == 0 && j == len) {
- Py_INCREF(args);
- return args;
- }
- else
- return PyString_FromStringAndSize(s+i, j-i);
+ char *s;
+ Py_ssize_t len, i, j;
+
+
+ if (PyString_AsStringAndSize(args, &s, &len))
+ return NULL;
+
+ i = 0;
+ if (striptype != RIGHTSTRIP) {
+ while (i < len && isspace(Py_CHARMASK(s[i]))) {
+ i++;
+ }
+ }
+
+ j = len;
+ if (striptype != LEFTSTRIP) {
+ do {
+ j--;
+ } while (j >= i && isspace(Py_CHARMASK(s[j])));
+ j++;
+ }
+
+ if (i == 0 && j == len) {
+ Py_INCREF(args);
+ return args;
+ }
+ else
+ return PyString_FromStringAndSize(s+i, j-i);
}
@@ -420,8 +420,8 @@ PyDoc_STRVAR(strip__doc__,
static PyObject *
strop_strip(PyObject *self, PyObject *args)
{
- WARN;
- return do_strip(args, BOTHSTRIP);
+ WARN;
+ return do_strip(args, BOTHSTRIP);
}
@@ -433,8 +433,8 @@ PyDoc_STRVAR(lstrip__doc__,
static PyObject *
strop_lstrip(PyObject *self, PyObject *args)
{
- WARN;
- return do_strip(args, LEFTSTRIP);
+ WARN;
+ return do_strip(args, LEFTSTRIP);
}
@@ -446,8 +446,8 @@ PyDoc_STRVAR(rstrip__doc__,
static PyObject *
strop_rstrip(PyObject *self, PyObject *args)
{
- WARN;
- return do_strip(args, RIGHTSTRIP);
+ WARN;
+ return do_strip(args, RIGHTSTRIP);
}
@@ -459,34 +459,34 @@ PyDoc_STRVAR(lower__doc__,
static PyObject *
strop_lower(PyObject *self, PyObject *args)
{
- char *s, *s_new;
- Py_ssize_t i, n;
- PyObject *newstr;
- int changed;
-
- WARN;
- if (PyString_AsStringAndSize(args, &s, &n))
- return NULL;
- newstr = PyString_FromStringAndSize(NULL, n);
- if (newstr == NULL)
- return NULL;
- s_new = PyString_AsString(newstr);
- changed = 0;
- for (i = 0; i < n; i++) {
- int c = Py_CHARMASK(*s++);
- if (isupper(c)) {
- changed = 1;
- *s_new = tolower(c);
- } else
- *s_new = c;
- s_new++;
- }
- if (!changed) {
- Py_DECREF(newstr);
- Py_INCREF(args);
- return args;
- }
- return newstr;
+ char *s, *s_new;
+ Py_ssize_t i, n;
+ PyObject *newstr;
+ int changed;
+
+ WARN;
+ if (PyString_AsStringAndSize(args, &s, &n))
+ return NULL;
+ newstr = PyString_FromStringAndSize(NULL, n);
+ if (newstr == NULL)
+ return NULL;
+ s_new = PyString_AsString(newstr);
+ changed = 0;
+ for (i = 0; i < n; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (isupper(c)) {
+ changed = 1;
+ *s_new = tolower(c);
+ } else
+ *s_new = c;
+ s_new++;
+ }
+ if (!changed) {
+ Py_DECREF(newstr);
+ Py_INCREF(args);
+ return args;
+ }
+ return newstr;
}
@@ -498,34 +498,34 @@ PyDoc_STRVAR(upper__doc__,
static PyObject *
strop_upper(PyObject *self, PyObject *args)
{
- char *s, *s_new;
- Py_ssize_t i, n;
- PyObject *newstr;
- int changed;
-
- WARN;
- if (PyString_AsStringAndSize(args, &s, &n))
- return NULL;
- newstr = PyString_FromStringAndSize(NULL, n);
- if (newstr == NULL)
- return NULL;
- s_new = PyString_AsString(newstr);
- changed = 0;
- for (i = 0; i < n; i++) {
- int c = Py_CHARMASK(*s++);
- if (islower(c)) {
- changed = 1;
- *s_new = toupper(c);
- } else
- *s_new = c;
- s_new++;
- }
- if (!changed) {
- Py_DECREF(newstr);
- Py_INCREF(args);
- return args;
- }
- return newstr;
+ char *s, *s_new;
+ Py_ssize_t i, n;
+ PyObject *newstr;
+ int changed;
+
+ WARN;
+ if (PyString_AsStringAndSize(args, &s, &n))
+ return NULL;
+ newstr = PyString_FromStringAndSize(NULL, n);
+ if (newstr == NULL)
+ return NULL;
+ s_new = PyString_AsString(newstr);
+ changed = 0;
+ for (i = 0; i < n; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (islower(c)) {
+ changed = 1;
+ *s_new = toupper(c);
+ } else
+ *s_new = c;
+ s_new++;
+ }
+ if (!changed) {
+ Py_DECREF(newstr);
+ Py_INCREF(args);
+ return args;
+ }
+ return newstr;
}
@@ -538,43 +538,43 @@ PyDoc_STRVAR(capitalize__doc__,
static PyObject *
strop_capitalize(PyObject *self, PyObject *args)
{
- char *s, *s_new;
- Py_ssize_t i, n;
- PyObject *newstr;
- int changed;
-
- WARN;
- if (PyString_AsStringAndSize(args, &s, &n))
- return NULL;
- newstr = PyString_FromStringAndSize(NULL, n);
- if (newstr == NULL)
- return NULL;
- s_new = PyString_AsString(newstr);
- changed = 0;
- if (0 < n) {
- int c = Py_CHARMASK(*s++);
- if (islower(c)) {
- changed = 1;
- *s_new = toupper(c);
- } else
- *s_new = c;
- s_new++;
- }
- for (i = 1; i < n; i++) {
- int c = Py_CHARMASK(*s++);
- if (isupper(c)) {
- changed = 1;
- *s_new = tolower(c);
- } else
- *s_new = c;
- s_new++;
- }
- if (!changed) {
- Py_DECREF(newstr);
- Py_INCREF(args);
- return args;
- }
- return newstr;
+ char *s, *s_new;
+ Py_ssize_t i, n;
+ PyObject *newstr;
+ int changed;
+
+ WARN;
+ if (PyString_AsStringAndSize(args, &s, &n))
+ return NULL;
+ newstr = PyString_FromStringAndSize(NULL, n);
+ if (newstr == NULL)
+ return NULL;
+ s_new = PyString_AsString(newstr);
+ changed = 0;
+ if (0 < n) {
+ int c = Py_CHARMASK(*s++);
+ if (islower(c)) {
+ changed = 1;
+ *s_new = toupper(c);
+ } else
+ *s_new = c;
+ s_new++;
+ }
+ for (i = 1; i < n; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (isupper(c)) {
+ changed = 1;
+ *s_new = tolower(c);
+ } else
+ *s_new = c;
+ s_new++;
+ }
+ if (!changed) {
+ Py_DECREF(newstr);
+ Py_INCREF(args);
+ return args;
+ }
+ return newstr;
}
@@ -589,75 +589,75 @@ PyDoc_STRVAR(expandtabs__doc__,
static PyObject *
strop_expandtabs(PyObject *self, PyObject *args)
{
- /* Original by Fredrik Lundh */
- char* e;
- char* p;
- char* q;
- Py_ssize_t i, j, old_j;
- PyObject* out;
- char* string;
- Py_ssize_t stringlen;
- int tabsize = 8;
-
- WARN;
- /* Get arguments */
- if (!PyArg_ParseTuple(args, "s#|i:expandtabs", &string, &stringlen, &tabsize))
- return NULL;
- if (tabsize < 1) {
- PyErr_SetString(PyExc_ValueError,
- "tabsize must be at least 1");
- return NULL;
- }
-
- /* First pass: determine size of output string */
- i = j = old_j = 0; /* j: current column; i: total of previous lines */
- e = string + stringlen;
- for (p = string; p < e; p++) {
- if (*p == '\t') {
- j += tabsize - (j%tabsize);
- if (old_j > j) {
- PyErr_SetString(PyExc_OverflowError,
- "new string is too long");
- return NULL;
- }
- old_j = j;
- } else {
- j++;
- if (*p == '\n') {
- i += j;
- j = 0;
- }
- }
- }
-
- if ((i + j) < 0) {
- PyErr_SetString(PyExc_OverflowError, "new string is too long");
- return NULL;
- }
-
- /* Second pass: create output string and fill it */
- out = PyString_FromStringAndSize(NULL, i+j);
- if (out == NULL)
- return NULL;
-
- i = 0;
- q = PyString_AS_STRING(out);
-
- for (p = string; p < e; p++) {
- if (*p == '\t') {
- j = tabsize - (i%tabsize);
- i += j;
- while (j-- > 0)
- *q++ = ' ';
- } else {
- *q++ = *p;
- i++;
- if (*p == '\n')
- i = 0;
- }
- }
-
- return out;
+ /* Original by Fredrik Lundh */
+ char* e;
+ char* p;
+ char* q;
+ Py_ssize_t i, j, old_j;
+ PyObject* out;
+ char* string;
+ Py_ssize_t stringlen;
+ int tabsize = 8;
+
+ WARN;
+ /* Get arguments */
+ if (!PyArg_ParseTuple(args, "s#|i:expandtabs", &string, &stringlen, &tabsize))
+ return NULL;
+ if (tabsize < 1) {
+ PyErr_SetString(PyExc_ValueError,
+ "tabsize must be at least 1");
+ return NULL;
+ }
+
+ /* First pass: determine size of output string */
+ i = j = old_j = 0; /* j: current column; i: total of previous lines */
+ e = string + stringlen;
+ for (p = string; p < e; p++) {
+ if (*p == '\t') {
+ j += tabsize - (j%tabsize);
+ if (old_j > j) {
+ PyErr_SetString(PyExc_OverflowError,
+ "new string is too long");
+ return NULL;
+ }
+ old_j = j;
+ } else {
+ j++;
+ if (*p == '\n') {
+ i += j;
+ j = 0;
+ }
+ }
+ }
+
+ if ((i + j) < 0) {
+ PyErr_SetString(PyExc_OverflowError, "new string is too long");
+ return NULL;
+ }
+
+ /* Second pass: create output string and fill it */
+ out = PyString_FromStringAndSize(NULL, i+j);
+ if (out == NULL)
+ return NULL;
+
+ i = 0;
+ q = PyString_AS_STRING(out);
+
+ for (p = string; p < e; p++) {
+ if (*p == '\t') {
+ j = tabsize - (i%tabsize);
+ i += j;
+ while (j-- > 0)
+ *q++ = ' ';
+ } else {
+ *q++ = *p;
+ i++;
+ if (*p == '\n')
+ i = 0;
+ }
+ }
+
+ return out;
}
@@ -671,38 +671,38 @@ PyDoc_STRVAR(count__doc__,
static PyObject *
strop_count(PyObject *self, PyObject *args)
{
- char *s, *sub;
- Py_ssize_t len, n;
- Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
- Py_ssize_t m, r;
-
- WARN;
- if (!PyArg_ParseTuple(args, "t#t#|nn:count", &s, &len, &sub, &n, &i, &last))
- return NULL;
- if (last > len)
- last = len;
- if (last < 0)
- last += len;
- if (last < 0)
- last = 0;
- if (i < 0)
- i += len;
- if (i < 0)
- i = 0;
- m = last + 1 - n;
- if (n == 0)
- return PyInt_FromLong((long) (m-i));
-
- r = 0;
- while (i < m) {
- if (!memcmp(s+i, sub, n)) {
- r++;
- i += n;
- } else {
- i++;
- }
- }
- return PyInt_FromLong((long) r);
+ char *s, *sub;
+ Py_ssize_t len, n;
+ Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
+ Py_ssize_t m, r;
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "t#t#|nn:count", &s, &len, &sub, &n, &i, &last))
+ return NULL;
+ if (last > len)
+ last = len;
+ if (last < 0)
+ last += len;
+ if (last < 0)
+ last = 0;
+ if (i < 0)
+ i += len;
+ if (i < 0)
+ i = 0;
+ m = last + 1 - n;
+ if (n == 0)
+ return PyInt_FromLong((long) (m-i));
+
+ r = 0;
+ while (i < m) {
+ if (!memcmp(s+i, sub, n)) {
+ r++;
+ i += n;
+ } else {
+ i++;
+ }
+ }
+ return PyInt_FromLong((long) r);
}
@@ -715,39 +715,39 @@ PyDoc_STRVAR(swapcase__doc__,
static PyObject *
strop_swapcase(PyObject *self, PyObject *args)
{
- char *s, *s_new;
- Py_ssize_t i, n;
- PyObject *newstr;
- int changed;
-
- WARN;
- if (PyString_AsStringAndSize(args, &s, &n))
- return NULL;
- newstr = PyString_FromStringAndSize(NULL, n);
- if (newstr == NULL)
- return NULL;
- s_new = PyString_AsString(newstr);
- changed = 0;
- for (i = 0; i < n; i++) {
- int c = Py_CHARMASK(*s++);
- if (islower(c)) {
- changed = 1;
- *s_new = toupper(c);
- }
- else if (isupper(c)) {
- changed = 1;
- *s_new = tolower(c);
- }
- else
- *s_new = c;
- s_new++;
- }
- if (!changed) {
- Py_DECREF(newstr);
- Py_INCREF(args);
- return args;
- }
- return newstr;
+ char *s, *s_new;
+ Py_ssize_t i, n;
+ PyObject *newstr;
+ int changed;
+
+ WARN;
+ if (PyString_AsStringAndSize(args, &s, &n))
+ return NULL;
+ newstr = PyString_FromStringAndSize(NULL, n);
+ if (newstr == NULL)
+ return NULL;
+ s_new = PyString_AsString(newstr);
+ changed = 0;
+ for (i = 0; i < n; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (islower(c)) {
+ changed = 1;
+ *s_new = toupper(c);
+ }
+ else if (isupper(c)) {
+ changed = 1;
+ *s_new = tolower(c);
+ }
+ else
+ *s_new = c;
+ s_new++;
+ }
+ if (!changed) {
+ Py_DECREF(newstr);
+ Py_INCREF(args);
+ return args;
+ }
+ return newstr;
}
@@ -764,45 +764,45 @@ PyDoc_STRVAR(atoi__doc__,
static PyObject *
strop_atoi(PyObject *self, PyObject *args)
{
- char *s, *end;
- int base = 10;
- long x;
- char buffer[256]; /* For errors */
-
- WARN;
- if (!PyArg_ParseTuple(args, "s|i:atoi", &s, &base))
- return NULL;
-
- if ((base != 0 && base < 2) || base > 36) {
- PyErr_SetString(PyExc_ValueError, "invalid base for atoi()");
- return NULL;
- }
-
- while (*s && isspace(Py_CHARMASK(*s)))
- s++;
- errno = 0;
- if (base == 0 && s[0] == '0')
- x = (long) PyOS_strtoul(s, &end, base);
- else
- x = PyOS_strtol(s, &end, base);
- if (end == s || !isalnum(Py_CHARMASK(end[-1])))
- goto bad;
- while (*end && isspace(Py_CHARMASK(*end)))
- end++;
- if (*end != '\0') {
+ char *s, *end;
+ int base = 10;
+ long x;
+ char buffer[256]; /* For errors */
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "s|i:atoi", &s, &base))
+ return NULL;
+
+ if ((base != 0 && base < 2) || base > 36) {
+ PyErr_SetString(PyExc_ValueError, "invalid base for atoi()");
+ return NULL;
+ }
+
+ while (*s && isspace(Py_CHARMASK(*s)))
+ s++;
+ errno = 0;
+ if (base == 0 && s[0] == '0')
+ x = (long) PyOS_strtoul(s, &end, base);
+ else
+ x = PyOS_strtol(s, &end, base);
+ if (end == s || !isalnum(Py_CHARMASK(end[-1])))
+ goto bad;
+ while (*end && isspace(Py_CHARMASK(*end)))
+ end++;
+ if (*end != '\0') {
bad:
- PyOS_snprintf(buffer, sizeof(buffer),
- "invalid literal for atoi(): %.200s", s);
- PyErr_SetString(PyExc_ValueError, buffer);
- return NULL;
- }
- else if (errno != 0) {
- PyOS_snprintf(buffer, sizeof(buffer),
- "atoi() literal too large: %.200s", s);
- PyErr_SetString(PyExc_ValueError, buffer);
- return NULL;
- }
- return PyInt_FromLong(x);
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "invalid literal for atoi(): %.200s", s);
+ PyErr_SetString(PyExc_ValueError, buffer);
+ return NULL;
+ }
+ else if (errno != 0) {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "atoi() literal too large: %.200s", s);
+ PyErr_SetString(PyExc_ValueError, buffer);
+ return NULL;
+ }
+ return PyInt_FromLong(x);
}
@@ -820,41 +820,41 @@ PyDoc_STRVAR(atol__doc__,
static PyObject *
strop_atol(PyObject *self, PyObject *args)
{
- char *s, *end;
- int base = 10;
- PyObject *x;
- char buffer[256]; /* For errors */
-
- WARN;
- if (!PyArg_ParseTuple(args, "s|i:atol", &s, &base))
- return NULL;
-
- if ((base != 0 && base < 2) || base > 36) {
- PyErr_SetString(PyExc_ValueError, "invalid base for atol()");
- return NULL;
- }
-
- while (*s && isspace(Py_CHARMASK(*s)))
- s++;
- if (s[0] == '\0') {
- PyErr_SetString(PyExc_ValueError, "empty string for atol()");
- return NULL;
- }
- x = PyLong_FromString(s, &end, base);
- if (x == NULL)
- return NULL;
- if (base == 0 && (*end == 'l' || *end == 'L'))
- end++;
- while (*end && isspace(Py_CHARMASK(*end)))
- end++;
- if (*end != '\0') {
- PyOS_snprintf(buffer, sizeof(buffer),
- "invalid literal for atol(): %.200s", s);
- PyErr_SetString(PyExc_ValueError, buffer);
- Py_DECREF(x);
- return NULL;
- }
- return x;
+ char *s, *end;
+ int base = 10;
+ PyObject *x;
+ char buffer[256]; /* For errors */
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "s|i:atol", &s, &base))
+ return NULL;
+
+ if ((base != 0 && base < 2) || base > 36) {
+ PyErr_SetString(PyExc_ValueError, "invalid base for atol()");
+ return NULL;
+ }
+
+ while (*s && isspace(Py_CHARMASK(*s)))
+ s++;
+ if (s[0] == '\0') {
+ PyErr_SetString(PyExc_ValueError, "empty string for atol()");
+ return NULL;
+ }
+ x = PyLong_FromString(s, &end, base);
+ if (x == NULL)
+ return NULL;
+ if (base == 0 && (*end == 'l' || *end == 'L'))
+ end++;
+ while (*end && isspace(Py_CHARMASK(*end)))
+ end++;
+ if (*end != '\0') {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "invalid literal for atol(): %.200s", s);
+ PyErr_SetString(PyExc_ValueError, buffer);
+ Py_DECREF(x);
+ return NULL;
+ }
+ return x;
}
@@ -866,38 +866,38 @@ PyDoc_STRVAR(atof__doc__,
static PyObject *
strop_atof(PyObject *self, PyObject *args)
{
- char *s, *end;
- double x;
- char buffer[256]; /* For errors */
-
- WARN;
- if (!PyArg_ParseTuple(args, "s:atof", &s))
- return NULL;
- while (*s && isspace(Py_CHARMASK(*s)))
- s++;
- if (s[0] == '\0') {
- PyErr_SetString(PyExc_ValueError, "empty string for atof()");
- return NULL;
- }
- errno = 0;
- PyFPE_START_PROTECT("strop_atof", return 0)
- x = PyOS_ascii_strtod(s, &end);
- PyFPE_END_PROTECT(x)
- while (*end && isspace(Py_CHARMASK(*end)))
- end++;
- if (*end != '\0') {
- PyOS_snprintf(buffer, sizeof(buffer),
- "invalid literal for atof(): %.200s", s);
- PyErr_SetString(PyExc_ValueError, buffer);
- return NULL;
- }
- else if (errno != 0) {
- PyOS_snprintf(buffer, sizeof(buffer),
- "atof() literal too large: %.200s", s);
- PyErr_SetString(PyExc_ValueError, buffer);
- return NULL;
- }
- return PyFloat_FromDouble(x);
+ char *s, *end;
+ double x;
+ char buffer[256]; /* For errors */
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "s:atof", &s))
+ return NULL;
+ while (*s && isspace(Py_CHARMASK(*s)))
+ s++;
+ if (s[0] == '\0') {
+ PyErr_SetString(PyExc_ValueError, "empty string for atof()");
+ return NULL;
+ }
+ errno = 0;
+ PyFPE_START_PROTECT("strop_atof", return 0)
+ x = PyOS_ascii_strtod(s, &end);
+ PyFPE_END_PROTECT(x)
+ while (*end && isspace(Py_CHARMASK(*end)))
+ end++;
+ if (*end != '\0') {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "invalid literal for atof(): %.200s", s);
+ PyErr_SetString(PyExc_ValueError, buffer);
+ return NULL;
+ }
+ else if (errno != 0) {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "atof() literal too large: %.200s", s);
+ PyErr_SetString(PyExc_ValueError, buffer);
+ return NULL;
+ }
+ return PyFloat_FromDouble(x);
}
@@ -911,29 +911,29 @@ PyDoc_STRVAR(maketrans__doc__,
static PyObject *
strop_maketrans(PyObject *self, PyObject *args)
{
- unsigned char *c, *from=NULL, *to=NULL;
- Py_ssize_t i, fromlen=0, tolen=0;
- PyObject *result;
-
- if (!PyArg_ParseTuple(args, "t#t#:maketrans", &from, &fromlen, &to, &tolen))
- return NULL;
-
- if (fromlen != tolen) {
- PyErr_SetString(PyExc_ValueError,
- "maketrans arguments must have same length");
- return NULL;
- }
-
- result = PyString_FromStringAndSize((char *)NULL, 256);
- if (result == NULL)
- return NULL;
- c = (unsigned char *) PyString_AS_STRING((PyStringObject *)result);
- for (i = 0; i < 256; i++)
- c[i]=(unsigned char)i;
- for (i = 0; i < fromlen; i++)
- c[from[i]]=to[i];
-
- return result;
+ unsigned char *c, *from=NULL, *to=NULL;
+ Py_ssize_t i, fromlen=0, tolen=0;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple(args, "t#t#:maketrans", &from, &fromlen, &to, &tolen))
+ return NULL;
+
+ if (fromlen != tolen) {
+ PyErr_SetString(PyExc_ValueError,
+ "maketrans arguments must have same length");
+ return NULL;
+ }
+
+ result = PyString_FromStringAndSize((char *)NULL, 256);
+ if (result == NULL)
+ return NULL;
+ c = (unsigned char *) PyString_AS_STRING((PyStringObject *)result);
+ for (i = 0; i < 256; i++)
+ c[i]=(unsigned char)i;
+ for (i = 0; i < fromlen; i++)
+ c[from[i]]=to[i];
+
+ return result;
}
@@ -948,69 +948,69 @@ PyDoc_STRVAR(translate__doc__,
static PyObject *
strop_translate(PyObject *self, PyObject *args)
{
- register char *input, *table, *output;
- Py_ssize_t i;
- int c, changed = 0;
- PyObject *input_obj;
- char *table1, *output_start, *del_table=NULL;
- Py_ssize_t inlen, tablen, dellen = 0;
- PyObject *result;
- int trans_table[256];
-
- WARN;
- if (!PyArg_ParseTuple(args, "St#|t#:translate", &input_obj,
- &table1, &tablen, &del_table, &dellen))
- return NULL;
- if (tablen != 256) {
- PyErr_SetString(PyExc_ValueError,
- "translation table must be 256 characters long");
- return NULL;
- }
-
- table = table1;
- inlen = PyString_GET_SIZE(input_obj);
- result = PyString_FromStringAndSize((char *)NULL, inlen);
- if (result == NULL)
- return NULL;
- output_start = output = PyString_AsString(result);
- input = PyString_AsString(input_obj);
-
- if (dellen == 0) {
- /* If no deletions are required, use faster code */
- for (i = inlen; --i >= 0; ) {
- c = Py_CHARMASK(*input++);
- if (Py_CHARMASK((*output++ = table[c])) != c)
- changed = 1;
- }
- if (changed)
- return result;
- Py_DECREF(result);
- Py_INCREF(input_obj);
- return input_obj;
- }
-
- for (i = 0; i < 256; i++)
- trans_table[i] = Py_CHARMASK(table[i]);
-
- for (i = 0; i < dellen; i++)
- trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
-
- for (i = inlen; --i >= 0; ) {
- c = Py_CHARMASK(*input++);
- if (trans_table[c] != -1)
- if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
- continue;
- changed = 1;
- }
- if (!changed) {
- Py_DECREF(result);
- Py_INCREF(input_obj);
- return input_obj;
- }
- /* Fix the size of the resulting string */
- if (inlen > 0)
- _PyString_Resize(&result, output - output_start);
- return result;
+ register char *input, *table, *output;
+ Py_ssize_t i;
+ int c, changed = 0;
+ PyObject *input_obj;
+ char *table1, *output_start, *del_table=NULL;
+ Py_ssize_t inlen, tablen, dellen = 0;
+ PyObject *result;
+ int trans_table[256];
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "St#|t#:translate", &input_obj,
+ &table1, &tablen, &del_table, &dellen))
+ return NULL;
+ if (tablen != 256) {
+ PyErr_SetString(PyExc_ValueError,
+ "translation table must be 256 characters long");
+ return NULL;
+ }
+
+ table = table1;
+ inlen = PyString_GET_SIZE(input_obj);
+ result = PyString_FromStringAndSize((char *)NULL, inlen);
+ if (result == NULL)
+ return NULL;
+ output_start = output = PyString_AsString(result);
+ input = PyString_AsString(input_obj);
+
+ if (dellen == 0) {
+ /* If no deletions are required, use faster code */
+ for (i = inlen; --i >= 0; ) {
+ c = Py_CHARMASK(*input++);
+ if (Py_CHARMASK((*output++ = table[c])) != c)
+ changed = 1;
+ }
+ if (changed)
+ return result;
+ Py_DECREF(result);
+ Py_INCREF(input_obj);
+ return input_obj;
+ }
+
+ for (i = 0; i < 256; i++)
+ trans_table[i] = Py_CHARMASK(table[i]);
+
+ for (i = 0; i < dellen; i++)
+ trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
+
+ for (i = inlen; --i >= 0; ) {
+ c = Py_CHARMASK(*input++);
+ if (trans_table[c] != -1)
+ if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
+ continue;
+ changed = 1;
+ }
+ if (!changed) {
+ Py_DECREF(result);
+ Py_INCREF(input_obj);
+ return input_obj;
+ }
+ /* Fix the size of the resulting string */
+ if (inlen > 0)
+ _PyString_Resize(&result, output - output_start);
+ return result;
}
@@ -1026,22 +1026,22 @@ strop_translate(PyObject *self, PyObject *args)
found, or -1 if not found. If len of PAT is greater than length of
MEM, the function returns -1.
*/
-static Py_ssize_t
+static Py_ssize_t
mymemfind(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
{
- register Py_ssize_t ii;
-
- /* pattern can not occur in the last pat_len-1 chars */
- len -= pat_len;
-
- for (ii = 0; ii <= len; ii++) {
- if (mem[ii] == pat[0] &&
- (pat_len == 1 ||
- memcmp(&mem[ii+1], &pat[1], pat_len-1) == 0)) {
- return ii;
- }
- }
- return -1;
+ register Py_ssize_t ii;
+
+ /* pattern can not occur in the last pat_len-1 chars */
+ len -= pat_len;
+
+ for (ii = 0; ii <= len; ii++) {
+ if (mem[ii] == pat[0] &&
+ (pat_len == 1 ||
+ memcmp(&mem[ii+1], &pat[1], pat_len-1) == 0)) {
+ return ii;
+ }
+ }
+ return -1;
}
/*
@@ -1049,23 +1049,23 @@ mymemfind(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
Return the number of distinct times PAT is found in MEM.
meaning mem=1111 and pat==11 returns 2.
- mem=11111 and pat==11 also return 2.
+ mem=11111 and pat==11 also return 2.
*/
-static Py_ssize_t
+static Py_ssize_t
mymemcnt(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
{
- register Py_ssize_t offset = 0;
- Py_ssize_t nfound = 0;
-
- while (len >= 0) {
- offset = mymemfind(mem, len, pat, pat_len);
- if (offset == -1)
- break;
- mem += offset + pat_len;
- len -= offset + pat_len;
- nfound++;
- }
- return nfound;
+ register Py_ssize_t offset = 0;
+ Py_ssize_t nfound = 0;
+
+ while (len >= 0) {
+ offset = mymemfind(mem, len, pat, pat_len);
+ if (offset == -1)
+ break;
+ mem += offset + pat_len;
+ len -= offset + pat_len;
+ nfound++;
+ }
+ return nfound;
}
/*
@@ -1088,69 +1088,69 @@ mymemcnt(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
NULL if an error occurred.
*/
static char *
-mymemreplace(const char *str, Py_ssize_t len, /* input string */
- const char *pat, Py_ssize_t pat_len, /* pattern string to find */
- const char *sub, Py_ssize_t sub_len, /* substitution string */
- Py_ssize_t count, /* number of replacements */
- Py_ssize_t *out_len)
+mymemreplace(const char *str, Py_ssize_t len, /* input string */
+ const char *pat, Py_ssize_t pat_len, /* pattern string to find */
+ const char *sub, Py_ssize_t sub_len, /* substitution string */
+ Py_ssize_t count, /* number of replacements */
+ Py_ssize_t *out_len)
{
- char *out_s;
- char *new_s;
- Py_ssize_t nfound, offset, new_len;
-
- if (len == 0 || pat_len > len)
- goto return_same;
-
- /* find length of output string */
- nfound = mymemcnt(str, len, pat, pat_len);
- if (count < 0)
- count = PY_SSIZE_T_MAX;
- else if (nfound > count)
- nfound = count;
- if (nfound == 0)
- goto return_same;
-
- new_len = len + nfound*(sub_len - pat_len);
- if (new_len == 0) {
- /* Have to allocate something for the caller to free(). */
- out_s = (char *)PyMem_MALLOC(1);
- if (out_s == NULL)
- return NULL;
- out_s[0] = '\0';
- }
- else {
- assert(new_len > 0);
- new_s = (char *)PyMem_MALLOC(new_len);
- if (new_s == NULL)
- return NULL;
- out_s = new_s;
-
- for (; count > 0 && len > 0; --count) {
- /* find index of next instance of pattern */
- offset = mymemfind(str, len, pat, pat_len);
- if (offset == -1)
- break;
-
- /* copy non matching part of input string */
- memcpy(new_s, str, offset);
- str += offset + pat_len;
- len -= offset + pat_len;
-
- /* copy substitute into the output string */
- new_s += offset;
- memcpy(new_s, sub, sub_len);
- new_s += sub_len;
- }
- /* copy any remaining values into output string */
- if (len > 0)
- memcpy(new_s, str, len);
- }
- *out_len = new_len;
- return out_s;
+ char *out_s;
+ char *new_s;
+ Py_ssize_t nfound, offset, new_len;
+
+ if (len == 0 || pat_len > len)
+ goto return_same;
+
+ /* find length of output string */
+ nfound = mymemcnt(str, len, pat, pat_len);
+ if (count < 0)
+ count = PY_SSIZE_T_MAX;
+ else if (nfound > count)
+ nfound = count;
+ if (nfound == 0)
+ goto return_same;
+
+ new_len = len + nfound*(sub_len - pat_len);
+ if (new_len == 0) {
+ /* Have to allocate something for the caller to free(). */
+ out_s = (char *)PyMem_MALLOC(1);
+ if (out_s == NULL)
+ return NULL;
+ out_s[0] = '\0';
+ }
+ else {
+ assert(new_len > 0);
+ new_s = (char *)PyMem_MALLOC(new_len);
+ if (new_s == NULL)
+ return NULL;
+ out_s = new_s;
+
+ for (; count > 0 && len > 0; --count) {
+ /* find index of next instance of pattern */
+ offset = mymemfind(str, len, pat, pat_len);
+ if (offset == -1)
+ break;
+
+ /* copy non matching part of input string */
+ memcpy(new_s, str, offset);
+ str += offset + pat_len;
+ len -= offset + pat_len;
+
+ /* copy substitute into the output string */
+ new_s += offset;
+ memcpy(new_s, sub, sub_len);
+ new_s += sub_len;
+ }
+ /* copy any remaining values into output string */
+ if (len > 0)
+ memcpy(new_s, str, len);
+ }
+ *out_len = new_len;
+ return out_s;
return_same:
- *out_len = -1;
- return (char *)str; /* cast away const */
+ *out_len = -1;
+ return (char *)str; /* cast away const */
}
@@ -1164,41 +1164,41 @@ PyDoc_STRVAR(replace__doc__,
static PyObject *
strop_replace(PyObject *self, PyObject *args)
{
- char *str, *pat,*sub,*new_s;
- Py_ssize_t len,pat_len,sub_len,out_len;
- Py_ssize_t count = -1;
- PyObject *newstr;
-
- WARN;
- if (!PyArg_ParseTuple(args, "t#t#t#|n:replace",
- &str, &len, &pat, &pat_len, &sub, &sub_len,
- &count))
- return NULL;
- if (pat_len <= 0) {
- PyErr_SetString(PyExc_ValueError, "empty pattern string");
- return NULL;
- }
- /* CAUTION: strop treats a replace count of 0 as infinity, unlke
- * current (2.1) string.py and string methods. Preserve this for
- * ... well, hard to say for what <wink>.
- */
- if (count == 0)
- count = -1;
- new_s = mymemreplace(str,len,pat,pat_len,sub,sub_len,count,&out_len);
- if (new_s == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- if (out_len == -1) {
- /* we're returning another reference to the input string */
- newstr = PyTuple_GetItem(args, 0);
- Py_XINCREF(newstr);
- }
- else {
- newstr = PyString_FromStringAndSize(new_s, out_len);
- PyMem_FREE(new_s);
- }
- return newstr;
+ char *str, *pat,*sub,*new_s;
+ Py_ssize_t len,pat_len,sub_len,out_len;
+ Py_ssize_t count = -1;
+ PyObject *newstr;
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "t#t#t#|n:replace",
+ &str, &len, &pat, &pat_len, &sub, &sub_len,
+ &count))
+ return NULL;
+ if (pat_len <= 0) {
+ PyErr_SetString(PyExc_ValueError, "empty pattern string");
+ return NULL;
+ }
+ /* CAUTION: strop treats a replace count of 0 as infinity, unlke
+ * current (2.1) string.py and string methods. Preserve this for
+ * ... well, hard to say for what <wink>.
+ */
+ if (count == 0)
+ count = -1;
+ new_s = mymemreplace(str,len,pat,pat_len,sub,sub_len,count,&out_len);
+ if (new_s == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ if (out_len == -1) {
+ /* we're returning another reference to the input string */
+ newstr = PyTuple_GetItem(args, 0);
+ Py_XINCREF(newstr);
+ }
+ else {
+ newstr = PyString_FromStringAndSize(new_s, out_len);
+ PyMem_FREE(new_s);
+ }
+ return newstr;
}
@@ -1206,69 +1206,69 @@ strop_replace(PyObject *self, PyObject *args)
static PyMethodDef
strop_methods[] = {
- {"atof", strop_atof, METH_VARARGS, atof__doc__},
- {"atoi", strop_atoi, METH_VARARGS, atoi__doc__},
- {"atol", strop_atol, METH_VARARGS, atol__doc__},
- {"capitalize", strop_capitalize, METH_O, capitalize__doc__},
- {"count", strop_count, METH_VARARGS, count__doc__},
- {"expandtabs", strop_expandtabs, METH_VARARGS, expandtabs__doc__},
- {"find", strop_find, METH_VARARGS, find__doc__},
- {"join", strop_joinfields, METH_VARARGS, joinfields__doc__},
- {"joinfields", strop_joinfields, METH_VARARGS, joinfields__doc__},
- {"lstrip", strop_lstrip, METH_O, lstrip__doc__},
- {"lower", strop_lower, METH_O, lower__doc__},
- {"maketrans", strop_maketrans, METH_VARARGS, maketrans__doc__},
- {"replace", strop_replace, METH_VARARGS, replace__doc__},
- {"rfind", strop_rfind, METH_VARARGS, rfind__doc__},
- {"rstrip", strop_rstrip, METH_O, rstrip__doc__},
- {"split", strop_splitfields, METH_VARARGS, splitfields__doc__},
- {"splitfields", strop_splitfields, METH_VARARGS, splitfields__doc__},
- {"strip", strop_strip, METH_O, strip__doc__},
- {"swapcase", strop_swapcase, METH_O, swapcase__doc__},
- {"translate", strop_translate, METH_VARARGS, translate__doc__},
- {"upper", strop_upper, METH_O, upper__doc__},
- {NULL, NULL} /* sentinel */
+ {"atof", strop_atof, METH_VARARGS, atof__doc__},
+ {"atoi", strop_atoi, METH_VARARGS, atoi__doc__},
+ {"atol", strop_atol, METH_VARARGS, atol__doc__},
+ {"capitalize", strop_capitalize, METH_O, capitalize__doc__},
+ {"count", strop_count, METH_VARARGS, count__doc__},
+ {"expandtabs", strop_expandtabs, METH_VARARGS, expandtabs__doc__},
+ {"find", strop_find, METH_VARARGS, find__doc__},
+ {"join", strop_joinfields, METH_VARARGS, joinfields__doc__},
+ {"joinfields", strop_joinfields, METH_VARARGS, joinfields__doc__},
+ {"lstrip", strop_lstrip, METH_O, lstrip__doc__},
+ {"lower", strop_lower, METH_O, lower__doc__},
+ {"maketrans", strop_maketrans, METH_VARARGS, maketrans__doc__},
+ {"replace", strop_replace, METH_VARARGS, replace__doc__},
+ {"rfind", strop_rfind, METH_VARARGS, rfind__doc__},
+ {"rstrip", strop_rstrip, METH_O, rstrip__doc__},
+ {"split", strop_splitfields, METH_VARARGS, splitfields__doc__},
+ {"splitfields", strop_splitfields, METH_VARARGS, splitfields__doc__},
+ {"strip", strop_strip, METH_O, strip__doc__},
+ {"swapcase", strop_swapcase, METH_O, swapcase__doc__},
+ {"translate", strop_translate, METH_VARARGS, translate__doc__},
+ {"upper", strop_upper, METH_O, upper__doc__},
+ {NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
initstrop(void)
{
- PyObject *m, *s;
- char buf[256];
- int c, n;
- m = Py_InitModule4("strop", strop_methods, strop_module__doc__,
- (PyObject*)NULL, PYTHON_API_VERSION);
- if (m == NULL)
- return;
-
- /* Create 'whitespace' object */
- n = 0;
- for (c = 0; c < 256; c++) {
- if (isspace(c))
- buf[n++] = c;
- }
- s = PyString_FromStringAndSize(buf, n);
- if (s)
- PyModule_AddObject(m, "whitespace", s);
-
- /* Create 'lowercase' object */
- n = 0;
- for (c = 0; c < 256; c++) {
- if (islower(c))
- buf[n++] = c;
- }
- s = PyString_FromStringAndSize(buf, n);
- if (s)
- PyModule_AddObject(m, "lowercase", s);
-
- /* Create 'uppercase' object */
- n = 0;
- for (c = 0; c < 256; c++) {
- if (isupper(c))
- buf[n++] = c;
- }
- s = PyString_FromStringAndSize(buf, n);
- if (s)
- PyModule_AddObject(m, "uppercase", s);
+ PyObject *m, *s;
+ char buf[256];
+ int c, n;
+ m = Py_InitModule4("strop", strop_methods, strop_module__doc__,
+ (PyObject*)NULL, PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
+
+ /* Create 'whitespace' object */
+ n = 0;
+ for (c = 0; c < 256; c++) {
+ if (isspace(c))
+ buf[n++] = c;
+ }
+ s = PyString_FromStringAndSize(buf, n);
+ if (s)
+ PyModule_AddObject(m, "whitespace", s);
+
+ /* Create 'lowercase' object */
+ n = 0;
+ for (c = 0; c < 256; c++) {
+ if (islower(c))
+ buf[n++] = c;
+ }
+ s = PyString_FromStringAndSize(buf, n);
+ if (s)
+ PyModule_AddObject(m, "lowercase", s);
+
+ /* Create 'uppercase' object */
+ n = 0;
+ for (c = 0; c < 256; c++) {
+ if (isupper(c))
+ buf[n++] = c;
+ }
+ s = PyString_FromStringAndSize(buf, n);
+ if (s)
+ PyModule_AddObject(m, "uppercase", s);
}
diff --git a/Modules/sunaudiodev.c b/Modules/sunaudiodev.c
index 285dc66..0c32fe3 100644
--- a/Modules/sunaudiodev.c
+++ b/Modules/sunaudiodev.c
@@ -23,98 +23,98 @@
/* #define offsetof(str,mem) ((int)(((str *)0)->mem)) */
typedef struct {
- PyObject_HEAD
- int x_fd; /* The open file */
- int x_icount; /* # samples read */
- int x_ocount; /* # samples written */
- int x_isctl; /* True if control device */
-
+ PyObject_HEAD
+ int x_fd; /* The open file */
+ int x_icount; /* # samples read */
+ int x_ocount; /* # samples written */
+ int x_isctl; /* True if control device */
+
} sadobject;
typedef struct {
- PyObject_HEAD
- audio_info_t ai;
+ PyObject_HEAD
+ audio_info_t ai;
} sadstatusobject;
static PyTypeObject Sadtype;
static PyTypeObject Sadstatustype;
-static sadstatusobject *sads_alloc(void); /* Forward */
+static sadstatusobject *sads_alloc(void); /* Forward */
static PyObject *SunAudioError;
-#define is_sadobject(v) (Py_TYPE(v) == &Sadtype)
-#define is_sadstatusobject(v) (Py_TYPE(v) == &Sadstatustype)
+#define is_sadobject(v) (Py_TYPE(v) == &Sadtype)
+#define is_sadstatusobject(v) (Py_TYPE(v) == &Sadstatustype)
static sadobject *
newsadobject(PyObject *args)
{
- sadobject *xp;
- int fd;
- char *mode;
- int imode;
- char* basedev;
- char* ctldev;
- char* opendev;
-
- /* Check arg for r/w/rw */
- if (!PyArg_ParseTuple(args, "s", &mode))
- return NULL;
- if (strcmp(mode, "r") == 0)
- imode = 0;
- else if (strcmp(mode, "w") == 0)
- imode = 1;
- else if (strcmp(mode, "rw") == 0)
- imode = 2;
- else if (strcmp(mode, "control") == 0)
- imode = -1;
- else {
- PyErr_SetString(SunAudioError,
- "Mode should be one of 'r', 'w', 'rw' or 'control'");
- return NULL;
- }
-
- /* Open the correct device. The base device name comes from the
- * AUDIODEV environment variable first, then /dev/audio. The
- * control device tacks "ctl" onto the base device name.
- */
- basedev = getenv("AUDIODEV");
- if (!basedev)
- basedev = "/dev/audio";
- ctldev = PyMem_NEW(char, strlen(basedev) + 4);
- if (!ctldev) {
- PyErr_NoMemory();
- return NULL;
- }
- strcpy(ctldev, basedev);
- strcat(ctldev, "ctl");
-
- if (imode < 0) {
- opendev = ctldev;
- fd = open(ctldev, 2);
- }
- else {
- opendev = basedev;
- fd = open(basedev, imode);
- }
- if (fd < 0) {
- PyErr_SetFromErrnoWithFilename(SunAudioError, opendev);
- PyMem_DEL(ctldev);
- return NULL;
- }
- PyMem_DEL(ctldev);
-
- /* Create and initialize the object */
- xp = PyObject_New(sadobject, &Sadtype);
- if (xp == NULL) {
- close(fd);
- return NULL;
- }
- xp->x_fd = fd;
- xp->x_icount = xp->x_ocount = 0;
- xp->x_isctl = (imode < 0);
-
- return xp;
+ sadobject *xp;
+ int fd;
+ char *mode;
+ int imode;
+ char* basedev;
+ char* ctldev;
+ char* opendev;
+
+ /* Check arg for r/w/rw */
+ if (!PyArg_ParseTuple(args, "s", &mode))
+ return NULL;
+ if (strcmp(mode, "r") == 0)
+ imode = 0;
+ else if (strcmp(mode, "w") == 0)
+ imode = 1;
+ else if (strcmp(mode, "rw") == 0)
+ imode = 2;
+ else if (strcmp(mode, "control") == 0)
+ imode = -1;
+ else {
+ PyErr_SetString(SunAudioError,
+ "Mode should be one of 'r', 'w', 'rw' or 'control'");
+ return NULL;
+ }
+
+ /* Open the correct device. The base device name comes from the
+ * AUDIODEV environment variable first, then /dev/audio. The
+ * control device tacks "ctl" onto the base device name.
+ */
+ basedev = getenv("AUDIODEV");
+ if (!basedev)
+ basedev = "/dev/audio";
+ ctldev = PyMem_NEW(char, strlen(basedev) + 4);
+ if (!ctldev) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ strcpy(ctldev, basedev);
+ strcat(ctldev, "ctl");
+
+ if (imode < 0) {
+ opendev = ctldev;
+ fd = open(ctldev, 2);
+ }
+ else {
+ opendev = basedev;
+ fd = open(basedev, imode);
+ }
+ if (fd < 0) {
+ PyErr_SetFromErrnoWithFilename(SunAudioError, opendev);
+ PyMem_DEL(ctldev);
+ return NULL;
+ }
+ PyMem_DEL(ctldev);
+
+ /* Create and initialize the object */
+ xp = PyObject_New(sadobject, &Sadtype);
+ if (xp == NULL) {
+ close(fd);
+ return NULL;
+ }
+ xp->x_fd = fd;
+ xp->x_icount = xp->x_ocount = 0;
+ xp->x_isctl = (imode < 0);
+
+ return xp;
}
/* Sad methods */
@@ -122,327 +122,327 @@ newsadobject(PyObject *args)
static void
sad_dealloc(sadobject *xp)
{
- close(xp->x_fd);
- PyObject_Del(xp);
+ close(xp->x_fd);
+ PyObject_Del(xp);
}
static PyObject *
sad_read(sadobject *self, PyObject *args)
{
- int size, count;
- char *cp;
- PyObject *rv;
-
- if (!PyArg_ParseTuple(args, "i:read", &size))
- return NULL;
- rv = PyString_FromStringAndSize(NULL, size);
- if (rv == NULL)
- return NULL;
-
- if (!(cp = PyString_AsString(rv)))
- goto finally;
-
- count = read(self->x_fd, cp, size);
- if (count < 0) {
- PyErr_SetFromErrno(SunAudioError);
- goto finally;
- }
+ int size, count;
+ char *cp;
+ PyObject *rv;
+
+ if (!PyArg_ParseTuple(args, "i:read", &size))
+ return NULL;
+ rv = PyString_FromStringAndSize(NULL, size);
+ if (rv == NULL)
+ return NULL;
+
+ if (!(cp = PyString_AsString(rv)))
+ goto finally;
+
+ count = read(self->x_fd, cp, size);
+ if (count < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ goto finally;
+ }
#if 0
- /* TBD: why print this message if you can handle the condition?
- * assume it's debugging info which we can just as well get rid
- * of. in any case this message should *not* be using printf!
- */
- if (count != size)
- printf("sunaudio: funny read rv %d wtd %d\n", count, size);
+ /* TBD: why print this message if you can handle the condition?
+ * assume it's debugging info which we can just as well get rid
+ * of. in any case this message should *not* be using printf!
+ */
+ if (count != size)
+ printf("sunaudio: funny read rv %d wtd %d\n", count, size);
#endif
- self->x_icount += count;
- return rv;
+ self->x_icount += count;
+ return rv;
finally:
- Py_DECREF(rv);
- return NULL;
+ Py_DECREF(rv);
+ return NULL;
}
static PyObject *
sad_write(sadobject *self, PyObject *args)
{
- char *cp;
- int count, size;
-
- if (!PyArg_ParseTuple(args, "s#:write", &cp, &size))
- return NULL;
-
- count = write(self->x_fd, cp, size);
- if (count < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
+ char *cp;
+ int count, size;
+
+ if (!PyArg_ParseTuple(args, "s#:write", &cp, &size))
+ return NULL;
+
+ count = write(self->x_fd, cp, size);
+ if (count < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
#if 0
- if (count != size)
- printf("sunaudio: funny write rv %d wanted %d\n", count, size);
+ if (count != size)
+ printf("sunaudio: funny write rv %d wanted %d\n", count, size);
#endif
- self->x_ocount += count;
-
- Py_INCREF(Py_None);
- return Py_None;
+ self->x_ocount += count;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sad_getinfo(sadobject *self)
{
- sadstatusobject *rv;
+ sadstatusobject *rv;
- if (!(rv = sads_alloc()))
- return NULL;
+ if (!(rv = sads_alloc()))
+ return NULL;
- if (ioctl(self->x_fd, AUDIO_GETINFO, &rv->ai) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- Py_DECREF(rv);
- return NULL;
- }
- return (PyObject *)rv;
+ if (ioctl(self->x_fd, AUDIO_GETINFO, &rv->ai) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ Py_DECREF(rv);
+ return NULL;
+ }
+ return (PyObject *)rv;
}
static PyObject *
sad_setinfo(sadobject *self, sadstatusobject *arg)
{
- if (!is_sadstatusobject(arg)) {
- PyErr_SetString(PyExc_TypeError,
- "Must be sun audio status object");
- return NULL;
- }
- if (ioctl(self->x_fd, AUDIO_SETINFO, &arg->ai) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (!is_sadstatusobject(arg)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Must be sun audio status object");
+ return NULL;
+ }
+ if (ioctl(self->x_fd, AUDIO_SETINFO, &arg->ai) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sad_ibufcount(sadobject *self)
{
- audio_info_t ai;
-
- if (ioctl(self->x_fd, AUDIO_GETINFO, &ai) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
- return PyInt_FromLong(ai.record.samples - self->x_icount);
+ audio_info_t ai;
+
+ if (ioctl(self->x_fd, AUDIO_GETINFO, &ai) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
+ return PyInt_FromLong(ai.record.samples - self->x_icount);
}
static PyObject *
sad_obufcount(sadobject *self)
{
- audio_info_t ai;
-
- if (ioctl(self->x_fd, AUDIO_GETINFO, &ai) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
- /* x_ocount is in bytes, whereas play.samples is in frames */
- /* we want frames */
- return PyInt_FromLong(self->x_ocount / (ai.play.channels *
- ai.play.precision / 8) -
- ai.play.samples);
+ audio_info_t ai;
+
+ if (ioctl(self->x_fd, AUDIO_GETINFO, &ai) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
+ /* x_ocount is in bytes, whereas play.samples is in frames */
+ /* we want frames */
+ return PyInt_FromLong(self->x_ocount / (ai.play.channels *
+ ai.play.precision / 8) -
+ ai.play.samples);
}
static PyObject *
sad_drain(sadobject *self)
{
- if (ioctl(self->x_fd, AUDIO_DRAIN, 0) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (ioctl(self->x_fd, AUDIO_DRAIN, 0) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
#ifdef SOLARIS
static PyObject *
sad_getdev(sadobject *self)
{
- struct audio_device ad;
+ struct audio_device ad;
- if (ioctl(self->x_fd, AUDIO_GETDEV, &ad) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
- return Py_BuildValue("(sss)", ad.name, ad.version, ad.config);
+ if (ioctl(self->x_fd, AUDIO_GETDEV, &ad) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
+ return Py_BuildValue("(sss)", ad.name, ad.version, ad.config);
}
#endif
static PyObject *
sad_flush(sadobject *self)
{
- if (ioctl(self->x_fd, I_FLUSH, FLUSHW) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (ioctl(self->x_fd, I_FLUSH, FLUSHW) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sad_close(sadobject *self)
{
-
- if (self->x_fd >= 0) {
- close(self->x_fd);
- self->x_fd = -1;
- }
- Py_INCREF(Py_None);
- return Py_None;
+
+ if (self->x_fd >= 0) {
+ close(self->x_fd);
+ self->x_fd = -1;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sad_fileno(sadobject *self)
{
- return PyInt_FromLong(self->x_fd);
+ return PyInt_FromLong(self->x_fd);
}
static PyMethodDef sad_methods[] = {
- { "read", (PyCFunction)sad_read, METH_VARARGS },
- { "write", (PyCFunction)sad_write, METH_VARARGS },
- { "ibufcount", (PyCFunction)sad_ibufcount, METH_NOARGS },
- { "obufcount", (PyCFunction)sad_obufcount, METH_NOARGS },
+ { "read", (PyCFunction)sad_read, METH_VARARGS },
+ { "write", (PyCFunction)sad_write, METH_VARARGS },
+ { "ibufcount", (PyCFunction)sad_ibufcount, METH_NOARGS },
+ { "obufcount", (PyCFunction)sad_obufcount, METH_NOARGS },
#define CTL_METHODS 4
- { "getinfo", (PyCFunction)sad_getinfo, METH_NOARGS },
- { "setinfo", (PyCFunction)sad_setinfo, METH_O},
- { "drain", (PyCFunction)sad_drain, METH_NOARGS },
- { "flush", (PyCFunction)sad_flush, METH_NOARGS },
+ { "getinfo", (PyCFunction)sad_getinfo, METH_NOARGS },
+ { "setinfo", (PyCFunction)sad_setinfo, METH_O},
+ { "drain", (PyCFunction)sad_drain, METH_NOARGS },
+ { "flush", (PyCFunction)sad_flush, METH_NOARGS },
#ifdef SOLARIS
- { "getdev", (PyCFunction)sad_getdev, METH_NOARGS },
+ { "getdev", (PyCFunction)sad_getdev, METH_NOARGS },
#endif
- { "close", (PyCFunction)sad_close, METH_NOARGS },
- { "fileno", (PyCFunction)sad_fileno, METH_NOARGS },
- {NULL, NULL} /* sentinel */
+ { "close", (PyCFunction)sad_close, METH_NOARGS },
+ { "fileno", (PyCFunction)sad_fileno, METH_NOARGS },
+ {NULL, NULL} /* sentinel */
};
static PyObject *
sad_getattr(sadobject *xp, char *name)
{
- if (xp->x_isctl)
- return Py_FindMethod(sad_methods+CTL_METHODS,
- (PyObject *)xp, name);
- else
- return Py_FindMethod(sad_methods, (PyObject *)xp, name);
+ if (xp->x_isctl)
+ return Py_FindMethod(sad_methods+CTL_METHODS,
+ (PyObject *)xp, name);
+ else
+ return Py_FindMethod(sad_methods, (PyObject *)xp, name);
}
/* ----------------------------------------------------------------- */
static sadstatusobject *
sads_alloc(void) {
- return PyObject_New(sadstatusobject, &Sadstatustype);
+ return PyObject_New(sadstatusobject, &Sadstatustype);
}
static void
sads_dealloc(sadstatusobject *xp)
{
- PyMem_DEL(xp);
+ PyMem_DEL(xp);
}
#define OFF(x) offsetof(audio_info_t,x)
static struct memberlist sads_ml[] = {
- { "i_sample_rate", T_UINT, OFF(record.sample_rate) },
- { "i_channels", T_UINT, OFF(record.channels) },
- { "i_precision", T_UINT, OFF(record.precision) },
- { "i_encoding", T_UINT, OFF(record.encoding) },
- { "i_gain", T_UINT, OFF(record.gain) },
- { "i_port", T_UINT, OFF(record.port) },
- { "i_samples", T_UINT, OFF(record.samples) },
- { "i_eof", T_UINT, OFF(record.eof) },
- { "i_pause", T_UBYTE, OFF(record.pause) },
- { "i_error", T_UBYTE, OFF(record.error) },
- { "i_waiting", T_UBYTE, OFF(record.waiting) },
- { "i_open", T_UBYTE, OFF(record.open) , RO},
- { "i_active", T_UBYTE, OFF(record.active) , RO},
+ { "i_sample_rate", T_UINT, OFF(record.sample_rate) },
+ { "i_channels", T_UINT, OFF(record.channels) },
+ { "i_precision", T_UINT, OFF(record.precision) },
+ { "i_encoding", T_UINT, OFF(record.encoding) },
+ { "i_gain", T_UINT, OFF(record.gain) },
+ { "i_port", T_UINT, OFF(record.port) },
+ { "i_samples", T_UINT, OFF(record.samples) },
+ { "i_eof", T_UINT, OFF(record.eof) },
+ { "i_pause", T_UBYTE, OFF(record.pause) },
+ { "i_error", T_UBYTE, OFF(record.error) },
+ { "i_waiting", T_UBYTE, OFF(record.waiting) },
+ { "i_open", T_UBYTE, OFF(record.open) , RO},
+ { "i_active", T_UBYTE, OFF(record.active) , RO},
#ifdef SOLARIS
- { "i_buffer_size", T_UINT, OFF(record.buffer_size) },
- { "i_balance", T_UBYTE, OFF(record.balance) },
- { "i_avail_ports", T_UINT, OFF(record.avail_ports) },
+ { "i_buffer_size", T_UINT, OFF(record.buffer_size) },
+ { "i_balance", T_UBYTE, OFF(record.balance) },
+ { "i_avail_ports", T_UINT, OFF(record.avail_ports) },
#endif
- { "o_sample_rate", T_UINT, OFF(play.sample_rate) },
- { "o_channels", T_UINT, OFF(play.channels) },
- { "o_precision", T_UINT, OFF(play.precision) },
- { "o_encoding", T_UINT, OFF(play.encoding) },
- { "o_gain", T_UINT, OFF(play.gain) },
- { "o_port", T_UINT, OFF(play.port) },
- { "o_samples", T_UINT, OFF(play.samples) },
- { "o_eof", T_UINT, OFF(play.eof) },
- { "o_pause", T_UBYTE, OFF(play.pause) },
- { "o_error", T_UBYTE, OFF(play.error) },
- { "o_waiting", T_UBYTE, OFF(play.waiting) },
- { "o_open", T_UBYTE, OFF(play.open) , RO},
- { "o_active", T_UBYTE, OFF(play.active) , RO},
+ { "o_sample_rate", T_UINT, OFF(play.sample_rate) },
+ { "o_channels", T_UINT, OFF(play.channels) },
+ { "o_precision", T_UINT, OFF(play.precision) },
+ { "o_encoding", T_UINT, OFF(play.encoding) },
+ { "o_gain", T_UINT, OFF(play.gain) },
+ { "o_port", T_UINT, OFF(play.port) },
+ { "o_samples", T_UINT, OFF(play.samples) },
+ { "o_eof", T_UINT, OFF(play.eof) },
+ { "o_pause", T_UBYTE, OFF(play.pause) },
+ { "o_error", T_UBYTE, OFF(play.error) },
+ { "o_waiting", T_UBYTE, OFF(play.waiting) },
+ { "o_open", T_UBYTE, OFF(play.open) , RO},
+ { "o_active", T_UBYTE, OFF(play.active) , RO},
#ifdef SOLARIS
- { "o_buffer_size", T_UINT, OFF(play.buffer_size) },
- { "o_balance", T_UBYTE, OFF(play.balance) },
- { "o_avail_ports", T_UINT, OFF(play.avail_ports) },
+ { "o_buffer_size", T_UINT, OFF(play.buffer_size) },
+ { "o_balance", T_UBYTE, OFF(play.balance) },
+ { "o_avail_ports", T_UINT, OFF(play.avail_ports) },
#endif
- { "monitor_gain", T_UINT, OFF(monitor_gain) },
- { NULL, 0, 0},
+ { "monitor_gain", T_UINT, OFF(monitor_gain) },
+ { NULL, 0, 0},
};
static PyObject *
sads_getattr(sadstatusobject *xp, char *name)
{
- return PyMember_Get((char *)&xp->ai, sads_ml, name);
+ return PyMember_Get((char *)&xp->ai, sads_ml, name);
}
static int
sads_setattr(sadstatusobject *xp, char *name, PyObject *v)
{
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete sun audio status attributes");
- return -1;
- }
- return PyMember_Set((char *)&xp->ai, sads_ml, name, v);
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete sun audio status attributes");
+ return -1;
+ }
+ return PyMember_Set((char *)&xp->ai, sads_ml, name, v);
}
/* ------------------------------------------------------------------- */
static PyTypeObject Sadtype = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "sunaudiodev.sun_audio_device", /*tp_name*/
- sizeof(sadobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)sad_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)sad_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "sunaudiodev.sun_audio_device", /*tp_name*/
+ sizeof(sadobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)sad_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)sad_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
static PyTypeObject Sadstatustype = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "sunaudiodev.sun_audio_device_status", /*tp_name*/
- sizeof(sadstatusobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)sads_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)sads_getattr, /*tp_getattr*/
- (setattrfunc)sads_setattr, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "sunaudiodev.sun_audio_device_status", /*tp_name*/
+ sizeof(sadstatusobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)sads_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)sads_getattr, /*tp_getattr*/
+ (setattrfunc)sads_setattr, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
/* ------------------------------------------------------------------- */
static PyObject *
sadopen(PyObject *self, PyObject *args)
{
- return (PyObject *)newsadobject(args);
+ return (PyObject *)newsadobject(args);
}
-
+
static PyMethodDef sunaudiodev_methods[] = {
{ "open", sadopen, METH_VARARGS },
{ 0, 0 },
@@ -451,17 +451,17 @@ static PyMethodDef sunaudiodev_methods[] = {
void
initsunaudiodev(void)
{
- PyObject *m, *d;
-
- if (PyErr_WarnPy3k("the sunaudiodev module has been removed in "
- "Python 3.0", 2) < 0)
- return;
-
- m = Py_InitModule("sunaudiodev", sunaudiodev_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- SunAudioError = PyErr_NewException("sunaudiodev.error", NULL, NULL);
- if (SunAudioError)
- PyDict_SetItemString(d, "error", SunAudioError);
+ PyObject *m, *d;
+
+ if (PyErr_WarnPy3k("the sunaudiodev module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
+
+ m = Py_InitModule("sunaudiodev", sunaudiodev_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ SunAudioError = PyErr_NewException("sunaudiodev.error", NULL, NULL);
+ if (SunAudioError)
+ PyDict_SetItemString(d, "error", SunAudioError);
}
diff --git a/Modules/svmodule.c b/Modules/svmodule.c
index 3845e20..6e419ce 100644
--- a/Modules/svmodule.c
+++ b/Modules/svmodule.c
@@ -9,23 +9,23 @@
#include <svideo.h>
#include "Python.h"
#include "compile.h"
-#include "yuv.h" /* for YUV conversion functions */
+#include "yuv.h" /* for YUV conversion functions */
typedef struct {
- PyObject_HEAD
- SV_nodeP ob_svideo;
- svCaptureInfo ob_info;
+ PyObject_HEAD
+ SV_nodeP ob_svideo;
+ svCaptureInfo ob_info;
} svobject;
typedef struct {
- PyObject_HEAD
- void *ob_capture;
- int ob_mustunlock;
- svCaptureInfo ob_info;
- svobject *ob_svideo;
+ PyObject_HEAD
+ void *ob_capture;
+ int ob_mustunlock;
+ svCaptureInfo ob_info;
+ svobject *ob_svideo;
} captureobject;
-static PyObject *SvError; /* exception sv.error */
+static PyObject *SvError; /* exception sv.error */
static PyObject *newcaptureobject(svobject *, void *, int);
@@ -33,36 +33,36 @@ static PyObject *newcaptureobject(svobject *, void *, int);
static PyObject *
sv_error(void)
{
- PyErr_SetString(SvError, svStrerror(svideo_errno));
- return NULL;
+ PyErr_SetString(SvError, svStrerror(svideo_errno));
+ return NULL;
}
static PyObject *
-svc_conversion(captureobject *self, PyObject *args, void (*function)(), float factor)
+svc_conversion(captureobject *self, PyObject *args, void (*function)(), float factor)
{
- PyObject *output;
- int invert;
- char* outstr;
+ PyObject *output;
+ int invert;
+ char* outstr;
- if (!PyArg_Parse(args, "i", &invert))
- return NULL;
+ if (!PyArg_Parse(args, "i", &invert))
+ return NULL;
- if (!(output = PyString_FromStringAndSize(
- NULL,
- (int)(self->ob_info.width * self->ob_info.height * factor))))
- {
- return NULL;
- }
- if (!(outstr = PyString_AsString(output))) {
- Py_DECREF(output);
- return NULL;
- }
+ if (!(output = PyString_FromStringAndSize(
+ NULL,
+ (int)(self->ob_info.width * self->ob_info.height * factor))))
+ {
+ return NULL;
+ }
+ if (!(outstr = PyString_AsString(output))) {
+ Py_DECREF(output);
+ return NULL;
+ }
- (*function)((boolean)invert, self->ob_capture,
- outstr,
- self->ob_info.width, self->ob_info.height);
+ (*function)((boolean)invert, self->ob_capture,
+ outstr,
+ self->ob_info.width, self->ob_info.height);
- return output;
+ return output;
}
/*
@@ -72,117 +72,117 @@ svc_conversion(captureobject *self, PyObject *args, void (*function)(), float fa
static PyObject *
svc_YUVtoYUV422DC(captureobject *self, PyObject *args)
{
- if (self->ob_info.format != SV_YUV411_FRAMES) {
- PyErr_SetString(SvError, "data has bad format");
- return NULL;
- }
- return svc_conversion(self, args, yuv_sv411_to_cl422dc, 2.0);
+ if (self->ob_info.format != SV_YUV411_FRAMES) {
+ PyErr_SetString(SvError, "data has bad format");
+ return NULL;
+ }
+ return svc_conversion(self, args, yuv_sv411_to_cl422dc, 2.0);
}
static PyObject *
svc_YUVtoYUV422DC_quarter(captureobject *self, PyObject *args)
{
- if (self->ob_info.format != SV_YUV411_FRAMES) {
- PyErr_SetString(SvError, "data has bad format");
- return NULL;
- }
- return svc_conversion(self, args,
- yuv_sv411_to_cl422dc_quartersize, 0.5);
+ if (self->ob_info.format != SV_YUV411_FRAMES) {
+ PyErr_SetString(SvError, "data has bad format");
+ return NULL;
+ }
+ return svc_conversion(self, args,
+ yuv_sv411_to_cl422dc_quartersize, 0.5);
}
static PyObject *
svc_YUVtoYUV422DC_sixteenth(captureobject *self, PyObject *args)
{
- if (self->ob_info.format != SV_YUV411_FRAMES) {
- PyErr_SetString(SvError, "data has bad format");
- return NULL;
- }
- return svc_conversion(self, args,
- yuv_sv411_to_cl422dc_sixteenthsize, 0.125);
+ if (self->ob_info.format != SV_YUV411_FRAMES) {
+ PyErr_SetString(SvError, "data has bad format");
+ return NULL;
+ }
+ return svc_conversion(self, args,
+ yuv_sv411_to_cl422dc_sixteenthsize, 0.125);
}
static PyObject *
svc_YUVtoRGB(captureobject *self, PyObject *args)
{
- switch (self->ob_info.format) {
- case SV_YUV411_FRAMES:
- case SV_YUV411_FRAMES_AND_BLANKING_BUFFER:
- break;
- default:
- PyErr_SetString(SvError, "data had bad format");
- return NULL;
- }
- return svc_conversion(self, args, svYUVtoRGB, (float) sizeof(long));
+ switch (self->ob_info.format) {
+ case SV_YUV411_FRAMES:
+ case SV_YUV411_FRAMES_AND_BLANKING_BUFFER:
+ break;
+ default:
+ PyErr_SetString(SvError, "data had bad format");
+ return NULL;
+ }
+ return svc_conversion(self, args, svYUVtoRGB, (float) sizeof(long));
}
static PyObject *
svc_RGB8toRGB32(captureobject *self, PyObject *args)
{
- if (self->ob_info.format != SV_RGB8_FRAMES) {
- PyErr_SetString(SvError, "data has bad format");
- return NULL;
- }
- return svc_conversion(self, args, svRGB8toRGB32, (float) sizeof(long));
+ if (self->ob_info.format != SV_RGB8_FRAMES) {
+ PyErr_SetString(SvError, "data has bad format");
+ return NULL;
+ }
+ return svc_conversion(self, args, svRGB8toRGB32, (float) sizeof(long));
}
static PyObject *
svc_InterleaveFields(captureobject *self, PyObject *args)
{
- if (self->ob_info.format != SV_RGB8_FRAMES) {
- PyErr_SetString(SvError, "data has bad format");
- return NULL;
- }
- return svc_conversion(self, args, svInterleaveFields, 1.0);
+ if (self->ob_info.format != SV_RGB8_FRAMES) {
+ PyErr_SetString(SvError, "data has bad format");
+ return NULL;
+ }
+ return svc_conversion(self, args, svInterleaveFields, 1.0);
}
static PyObject *
svc_GetFields(captureobject *self, PyObject *args)
{
- PyObject *f1 = NULL;
- PyObject *f2 = NULL;
- PyObject *ret = NULL;
- int fieldsize;
- char* obcapture;
-
- if (self->ob_info.format != SV_RGB8_FRAMES) {
- PyErr_SetString(SvError, "data has bad format");
- return NULL;
- }
-
- fieldsize = self->ob_info.width * self->ob_info.height / 2;
- obcapture = (char*)self->ob_capture;
-
- if (!(f1 = PyString_FromStringAndSize(obcapture, fieldsize)))
- goto finally;
- if (!(f2 = PyString_FromStringAndSize(obcapture + fieldsize,
- fieldsize)))
- goto finally;
- ret = PyTuple_Pack(2, f1, f2);
+ PyObject *f1 = NULL;
+ PyObject *f2 = NULL;
+ PyObject *ret = NULL;
+ int fieldsize;
+ char* obcapture;
+
+ if (self->ob_info.format != SV_RGB8_FRAMES) {
+ PyErr_SetString(SvError, "data has bad format");
+ return NULL;
+ }
+
+ fieldsize = self->ob_info.width * self->ob_info.height / 2;
+ obcapture = (char*)self->ob_capture;
+
+ if (!(f1 = PyString_FromStringAndSize(obcapture, fieldsize)))
+ goto finally;
+ if (!(f2 = PyString_FromStringAndSize(obcapture + fieldsize,
+ fieldsize)))
+ goto finally;
+ ret = PyTuple_Pack(2, f1, f2);
finally:
- Py_XDECREF(f1);
- Py_XDECREF(f2);
- return ret;
+ Py_XDECREF(f1);
+ Py_XDECREF(f2);
+ return ret;
}
-
+
static PyObject *
svc_UnlockCaptureData(captureobject *self, PyObject *args)
{
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- if (!self->ob_mustunlock) {
- PyErr_SetString(SvError, "buffer should not be unlocked");
- return NULL;
- }
+ if (!self->ob_mustunlock) {
+ PyErr_SetString(SvError, "buffer should not be unlocked");
+ return NULL;
+ }
- if (svUnlockCaptureData(self->ob_svideo->ob_svideo, self->ob_capture))
- return sv_error();
+ if (svUnlockCaptureData(self->ob_svideo->ob_svideo, self->ob_capture))
+ return sv_error();
- self->ob_mustunlock = 0;
+ self->ob_mustunlock = 0;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#ifdef USE_GL
@@ -191,780 +191,780 @@ svc_UnlockCaptureData(captureobject *self, PyObject *args)
static PyObject *
svc_lrectwrite(captureobject *self, PyObject *args)
{
- Screencoord x1, x2, y1, y2;
+ Screencoord x1, x2, y1, y2;
- if (!PyArg_Parse(args, "(hhhh)", &x1, &x2, &y1, &y2))
- return NULL;
+ if (!PyArg_Parse(args, "(hhhh)", &x1, &x2, &y1, &y2))
+ return NULL;
- lrectwrite(x1, x2, y1, y2, (unsigned long *) self->ob_capture);
+ lrectwrite(x1, x2, y1, y2, (unsigned long *) self->ob_capture);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif
static PyObject *
svc_writefile(captureobject *self, PyObject *args)
{
- PyObject *file;
- int size;
- FILE* fp;
+ PyObject *file;
+ int size;
+ FILE* fp;
- if (!PyArg_Parse(args, "O", &file))
- return NULL;
+ if (!PyArg_Parse(args, "O", &file))
+ return NULL;
- if (!PyFile_Check(file)) {
- PyErr_SetString(SvError, "not a file object");
- return NULL;
- }
+ if (!PyFile_Check(file)) {
+ PyErr_SetString(SvError, "not a file object");
+ return NULL;
+ }
- if (!(fp = PyFile_AsFile(file)))
- return NULL;
+ if (!(fp = PyFile_AsFile(file)))
+ return NULL;
- size = self->ob_info.width * self->ob_info.height;
+ size = self->ob_info.width * self->ob_info.height;
- if (fwrite(self->ob_capture, sizeof(long), size, fp) != size) {
- PyErr_SetString(SvError, "writing failed");
- return NULL;
- }
+ if (fwrite(self->ob_capture, sizeof(long), size, fp) != size) {
+ PyErr_SetString(SvError, "writing failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
svc_FindVisibleRegion(captureobject *self, PyObject *args)
{
- void *visible;
- int width;
+ void *visible;
+ int width;
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- if (svFindVisibleRegion(self->ob_svideo->ob_svideo,
- self->ob_capture, &visible,
- self->ob_info.width))
- return sv_error();
+ if (svFindVisibleRegion(self->ob_svideo->ob_svideo,
+ self->ob_capture, &visible,
+ self->ob_info.width))
+ return sv_error();
- if (visible == NULL) {
- PyErr_SetString(SvError, "data in wrong format");
- return NULL;
- }
+ if (visible == NULL) {
+ PyErr_SetString(SvError, "data in wrong format");
+ return NULL;
+ }
- return newcaptureobject(self->ob_svideo, visible, 0);
+ return newcaptureobject(self->ob_svideo, visible, 0);
}
static PyMethodDef capture_methods[] = {
- {"YUVtoRGB", (PyCFunction)svc_YUVtoRGB, METH_OLDARGS},
- {"RGB8toRGB32", (PyCFunction)svc_RGB8toRGB32, METH_OLDARGS},
- {"InterleaveFields", (PyCFunction)svc_InterleaveFields, METH_OLDARGS},
- {"UnlockCaptureData", (PyCFunction)svc_UnlockCaptureData, METH_OLDARGS},
- {"FindVisibleRegion", (PyCFunction)svc_FindVisibleRegion, METH_OLDARGS},
- {"GetFields", (PyCFunction)svc_GetFields, METH_OLDARGS},
- {"YUVtoYUV422DC", (PyCFunction)svc_YUVtoYUV422DC, METH_OLDARGS},
- {"YUVtoYUV422DC_quarter",(PyCFunction)svc_YUVtoYUV422DC_quarter, METH_OLDARGS},
- {"YUVtoYUV422DC_sixteenth",(PyCFunction)svc_YUVtoYUV422DC_sixteenth, METH_OLDARGS},
+ {"YUVtoRGB", (PyCFunction)svc_YUVtoRGB, METH_OLDARGS},
+ {"RGB8toRGB32", (PyCFunction)svc_RGB8toRGB32, METH_OLDARGS},
+ {"InterleaveFields", (PyCFunction)svc_InterleaveFields, METH_OLDARGS},
+ {"UnlockCaptureData", (PyCFunction)svc_UnlockCaptureData, METH_OLDARGS},
+ {"FindVisibleRegion", (PyCFunction)svc_FindVisibleRegion, METH_OLDARGS},
+ {"GetFields", (PyCFunction)svc_GetFields, METH_OLDARGS},
+ {"YUVtoYUV422DC", (PyCFunction)svc_YUVtoYUV422DC, METH_OLDARGS},
+ {"YUVtoYUV422DC_quarter",(PyCFunction)svc_YUVtoYUV422DC_quarter, METH_OLDARGS},
+ {"YUVtoYUV422DC_sixteenth",(PyCFunction)svc_YUVtoYUV422DC_sixteenth, METH_OLDARGS},
#ifdef USE_GL
- {"lrectwrite", (PyCFunction)svc_lrectwrite, METH_OLDARGS},
+ {"lrectwrite", (PyCFunction)svc_lrectwrite, METH_OLDARGS},
#endif
- {"writefile", (PyCFunction)svc_writefile, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"writefile", (PyCFunction)svc_writefile, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
static void
capture_dealloc(captureobject *self)
{
- if (self->ob_capture != NULL) {
- if (self->ob_mustunlock)
- (void)svUnlockCaptureData(self->ob_svideo->ob_svideo,
- self->ob_capture);
- self->ob_capture = NULL;
- Py_DECREF(self->ob_svideo);
- self->ob_svideo = NULL;
- }
- PyObject_Del(self);
+ if (self->ob_capture != NULL) {
+ if (self->ob_mustunlock)
+ (void)svUnlockCaptureData(self->ob_svideo->ob_svideo,
+ self->ob_capture);
+ self->ob_capture = NULL;
+ Py_DECREF(self->ob_svideo);
+ self->ob_svideo = NULL;
+ }
+ PyObject_Del(self);
}
static PyObject *
capture_getattr(svobject *self, char *name)
{
- return Py_FindMethod(capture_methods, (PyObject *)self, name);
+ return Py_FindMethod(capture_methods, (PyObject *)self, name);
}
PyTypeObject Capturetype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "sv.capture", /*tp_name*/
- sizeof(captureobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)capture_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)capture_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "sv.capture", /*tp_name*/
+ sizeof(captureobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)capture_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)capture_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
static PyObject *
newcaptureobject(svobject *self, void *ptr, int mustunlock)
{
- captureobject *p;
+ captureobject *p;
- p = PyObject_New(captureobject, &Capturetype);
- if (p == NULL)
- return NULL;
- p->ob_svideo = self;
- Py_INCREF(self);
- p->ob_capture = ptr;
- p->ob_mustunlock = mustunlock;
- p->ob_info = self->ob_info;
- return (PyObject *) p;
+ p = PyObject_New(captureobject, &Capturetype);
+ if (p == NULL)
+ return NULL;
+ p->ob_svideo = self;
+ Py_INCREF(self);
+ p->ob_capture = ptr;
+ p->ob_mustunlock = mustunlock;
+ p->ob_info = self->ob_info;
+ return (PyObject *) p;
}
static PyObject *
sv_GetCaptureData(svobject *self, PyObject *args)
{
- void *ptr;
- long fieldID;
- PyObject *res, *c;
+ void *ptr;
+ long fieldID;
+ PyObject *res, *c;
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- if (svGetCaptureData(self->ob_svideo, &ptr, &fieldID))
- return sv_error();
+ if (svGetCaptureData(self->ob_svideo, &ptr, &fieldID))
+ return sv_error();
- if (ptr == NULL) {
- PyErr_SetString(SvError, "no data available");
- return NULL;
- }
+ if (ptr == NULL) {
+ PyErr_SetString(SvError, "no data available");
+ return NULL;
+ }
- c = newcaptureobject(self, ptr, 1);
- if (c == NULL)
- return NULL;
- res = Py_BuildValue("(Oi)", c, fieldID);
- Py_DECREF(c);
- return res;
+ c = newcaptureobject(self, ptr, 1);
+ if (c == NULL)
+ return NULL;
+ res = Py_BuildValue("(Oi)", c, fieldID);
+ Py_DECREF(c);
+ return res;
}
static PyObject *
sv_BindGLWindow(svobject *self, PyObject *args)
{
- long wid;
- int mode;
+ long wid;
+ int mode;
- if (!PyArg_Parse(args, "(ii)", &wid, &mode))
- return NULL;
+ if (!PyArg_Parse(args, "(ii)", &wid, &mode))
+ return NULL;
- if (svBindGLWindow(self->ob_svideo, wid, mode))
- return sv_error();
+ if (svBindGLWindow(self->ob_svideo, wid, mode))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_EndContinuousCapture(svobject *self, PyObject *args)
{
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- if (svEndContinuousCapture(self->ob_svideo))
- return sv_error();
+ if (svEndContinuousCapture(self->ob_svideo))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_IsVideoDisplayed(svobject *self, PyObject *args)
{
- int v;
+ int v;
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- v = svIsVideoDisplayed(self->ob_svideo);
- if (v == -1)
- return sv_error();
+ v = svIsVideoDisplayed(self->ob_svideo);
+ if (v == -1)
+ return sv_error();
- return PyInt_FromLong((long) v);
+ return PyInt_FromLong((long) v);
}
static PyObject *
sv_OutputOffset(svobject *self, PyObject *args)
{
- int x_offset;
- int y_offset;
+ int x_offset;
+ int y_offset;
- if (!PyArg_Parse(args, "(ii)", &x_offset, &y_offset))
- return NULL;
+ if (!PyArg_Parse(args, "(ii)", &x_offset, &y_offset))
+ return NULL;
- if (svOutputOffset(self->ob_svideo, x_offset, y_offset))
- return sv_error();
+ if (svOutputOffset(self->ob_svideo, x_offset, y_offset))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_PutFrame(svobject *self, PyObject *args)
{
- char *buffer;
+ char *buffer;
- if (!PyArg_Parse(args, "s", &buffer))
- return NULL;
+ if (!PyArg_Parse(args, "s", &buffer))
+ return NULL;
- if (svPutFrame(self->ob_svideo, buffer))
- return sv_error();
+ if (svPutFrame(self->ob_svideo, buffer))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_QuerySize(svobject *self, PyObject *args)
{
- int w;
- int h;
- int rw;
- int rh;
+ int w;
+ int h;
+ int rw;
+ int rh;
- if (!PyArg_Parse(args, "(ii)", &w, &h))
- return NULL;
+ if (!PyArg_Parse(args, "(ii)", &w, &h))
+ return NULL;
- if (svQuerySize(self->ob_svideo, w, h, &rw, &rh))
- return sv_error();
+ if (svQuerySize(self->ob_svideo, w, h, &rw, &rh))
+ return sv_error();
- return Py_BuildValue("(ii)", (long) rw, (long) rh);
+ return Py_BuildValue("(ii)", (long) rw, (long) rh);
}
static PyObject *
sv_SetSize(svobject *self, PyObject *args)
{
- int w;
- int h;
+ int w;
+ int h;
- if (!PyArg_Parse(args, "(ii)", &w, &h))
- return NULL;
+ if (!PyArg_Parse(args, "(ii)", &w, &h))
+ return NULL;
- if (svSetSize(self->ob_svideo, w, h))
- return sv_error();
+ if (svSetSize(self->ob_svideo, w, h))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_SetStdDefaults(svobject *self, PyObject *args)
{
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- if (svSetStdDefaults(self->ob_svideo))
- return sv_error();
+ if (svSetStdDefaults(self->ob_svideo))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_UseExclusive(svobject *self, PyObject *args)
{
- boolean onoff;
- int mode;
+ boolean onoff;
+ int mode;
- if (!PyArg_Parse(args, "(ii)", &onoff, &mode))
- return NULL;
+ if (!PyArg_Parse(args, "(ii)", &onoff, &mode))
+ return NULL;
- if (svUseExclusive(self->ob_svideo, onoff, mode))
- return sv_error();
+ if (svUseExclusive(self->ob_svideo, onoff, mode))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_WindowOffset(svobject *self, PyObject *args)
{
- int x_offset;
- int y_offset;
+ int x_offset;
+ int y_offset;
- if (!PyArg_Parse(args, "(ii)", &x_offset, &y_offset))
- return NULL;
+ if (!PyArg_Parse(args, "(ii)", &x_offset, &y_offset))
+ return NULL;
- if (svWindowOffset(self->ob_svideo, x_offset, y_offset))
- return sv_error();
+ if (svWindowOffset(self->ob_svideo, x_offset, y_offset))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_CaptureBurst(svobject *self, PyObject *args)
{
- int bytes, i;
- svCaptureInfo info;
- void *bitvector = NULL;
- PyObject *videodata = NULL;
- PyObject *bitvecobj = NULL;
- PyObject *res = NULL;
- static PyObject *evenitem, *odditem;
-
- if (!PyArg_Parse(args, "(iiiii)", &info.format,
- &info.width, &info.height,
- &info.size, &info.samplingrate))
- return NULL;
-
- switch (info.format) {
- case SV_RGB8_FRAMES:
- bitvector = malloc(SV_BITVEC_SIZE(info.size));
- break;
- case SV_YUV411_FRAMES_AND_BLANKING_BUFFER:
- break;
- default:
- PyErr_SetString(SvError, "illegal format specified");
- return NULL;
- }
-
- if (svQueryCaptureBufferSize(self->ob_svideo, &info, &bytes)) {
- res = sv_error();
- goto finally;
- }
-
- if (!(videodata = PyString_FromStringAndSize(NULL, bytes)))
- goto finally;
-
- /* XXX -- need to do something about the bitvector */
- {
- char* str = PyString_AsString(videodata);
- if (!str)
- goto finally;
-
- if (svCaptureBurst(self->ob_svideo, &info, str, bitvector)) {
- res = sv_error();
- goto finally;
- }
- }
-
- if (bitvector) {
- if (evenitem == NULL) {
- if (!(evenitem = PyInt_FromLong(0)))
- goto finally;
- }
- if (odditem == NULL) {
- if (!(odditem = PyInt_FromLong(1)))
- goto finally;
- }
- if (!(bitvecobj = PyTuple_New(2 * info.size)))
- goto finally;
-
- for (i = 0; i < 2 * info.size; i++) {
- int sts;
-
- if (SV_GET_FIELD(bitvector, i) == SV_EVEN_FIELD) {
- Py_INCREF(evenitem);
- sts = PyTuple_SetItem(bitvecobj, i, evenitem);
- } else {
- Py_INCREF(odditem);
- sts = PyTuple_SetItem(bitvecobj, i, odditem);
- }
- if (sts < 0)
- goto finally;
- }
- } else {
- bitvecobj = Py_None;
- Py_INCREF(Py_None);
- }
-
- res = Py_BuildValue("((iiiii)OO)", info.format,
- info.width, info.height,
- info.size, info.samplingrate,
- videodata, bitvecobj);
+ int bytes, i;
+ svCaptureInfo info;
+ void *bitvector = NULL;
+ PyObject *videodata = NULL;
+ PyObject *bitvecobj = NULL;
+ PyObject *res = NULL;
+ static PyObject *evenitem, *odditem;
+
+ if (!PyArg_Parse(args, "(iiiii)", &info.format,
+ &info.width, &info.height,
+ &info.size, &info.samplingrate))
+ return NULL;
+
+ switch (info.format) {
+ case SV_RGB8_FRAMES:
+ bitvector = malloc(SV_BITVEC_SIZE(info.size));
+ break;
+ case SV_YUV411_FRAMES_AND_BLANKING_BUFFER:
+ break;
+ default:
+ PyErr_SetString(SvError, "illegal format specified");
+ return NULL;
+ }
+
+ if (svQueryCaptureBufferSize(self->ob_svideo, &info, &bytes)) {
+ res = sv_error();
+ goto finally;
+ }
+
+ if (!(videodata = PyString_FromStringAndSize(NULL, bytes)))
+ goto finally;
+
+ /* XXX -- need to do something about the bitvector */
+ {
+ char* str = PyString_AsString(videodata);
+ if (!str)
+ goto finally;
+
+ if (svCaptureBurst(self->ob_svideo, &info, str, bitvector)) {
+ res = sv_error();
+ goto finally;
+ }
+ }
+
+ if (bitvector) {
+ if (evenitem == NULL) {
+ if (!(evenitem = PyInt_FromLong(0)))
+ goto finally;
+ }
+ if (odditem == NULL) {
+ if (!(odditem = PyInt_FromLong(1)))
+ goto finally;
+ }
+ if (!(bitvecobj = PyTuple_New(2 * info.size)))
+ goto finally;
+
+ for (i = 0; i < 2 * info.size; i++) {
+ int sts;
+
+ if (SV_GET_FIELD(bitvector, i) == SV_EVEN_FIELD) {
+ Py_INCREF(evenitem);
+ sts = PyTuple_SetItem(bitvecobj, i, evenitem);
+ } else {
+ Py_INCREF(odditem);
+ sts = PyTuple_SetItem(bitvecobj, i, odditem);
+ }
+ if (sts < 0)
+ goto finally;
+ }
+ } else {
+ bitvecobj = Py_None;
+ Py_INCREF(Py_None);
+ }
+
+ res = Py_BuildValue("((iiiii)OO)", info.format,
+ info.width, info.height,
+ info.size, info.samplingrate,
+ videodata, bitvecobj);
finally:
- if (bitvector)
- free(bitvector);
+ if (bitvector)
+ free(bitvector);
- Py_XDECREF(videodata);
- Py_XDECREF(bitvecobj);
- return res;
+ Py_XDECREF(videodata);
+ Py_XDECREF(bitvecobj);
+ return res;
}
static PyObject *
sv_CaptureOneFrame(svobject *self, PyObject *args)
{
- svCaptureInfo info;
- int format, width, height;
- int bytes;
- PyObject *videodata = NULL;
- PyObject *res = NULL;
- char *str;
-
- if (!PyArg_Parse(args, "(iii)", &format, &width, &height))
- return NULL;
-
- info.format = format;
- info.width = width;
- info.height = height;
- info.size = 0;
- info.samplingrate = 0;
- if (svQueryCaptureBufferSize(self->ob_svideo, &info, &bytes))
- return sv_error();
-
- if (!(videodata = PyString_FromStringAndSize(NULL, bytes)))
- return NULL;
-
- str = PyString_AsString(videodata);
- if (!str)
- goto finally;
-
- if (svCaptureOneFrame(self->ob_svideo, format, &width, &height, str)) {
- res = sv_error();
- goto finally;
- }
-
- res = Py_BuildValue("(iiO)", width, height, videodata);
+ svCaptureInfo info;
+ int format, width, height;
+ int bytes;
+ PyObject *videodata = NULL;
+ PyObject *res = NULL;
+ char *str;
+
+ if (!PyArg_Parse(args, "(iii)", &format, &width, &height))
+ return NULL;
+
+ info.format = format;
+ info.width = width;
+ info.height = height;
+ info.size = 0;
+ info.samplingrate = 0;
+ if (svQueryCaptureBufferSize(self->ob_svideo, &info, &bytes))
+ return sv_error();
+
+ if (!(videodata = PyString_FromStringAndSize(NULL, bytes)))
+ return NULL;
+
+ str = PyString_AsString(videodata);
+ if (!str)
+ goto finally;
+
+ if (svCaptureOneFrame(self->ob_svideo, format, &width, &height, str)) {
+ res = sv_error();
+ goto finally;
+ }
+
+ res = Py_BuildValue("(iiO)", width, height, videodata);
finally:
- Py_XDECREF(videodata);
- return res;
+ Py_XDECREF(videodata);
+ return res;
}
static PyObject *
sv_InitContinuousCapture(svobject *self, PyObject *args)
{
- svCaptureInfo info;
+ svCaptureInfo info;
- if (!PyArg_Parse(args, "(iiiii)", &info.format,
- &info.width, &info.height,
- &info.size, &info.samplingrate))
- return NULL;
+ if (!PyArg_Parse(args, "(iiiii)", &info.format,
+ &info.width, &info.height,
+ &info.size, &info.samplingrate))
+ return NULL;
- if (svInitContinuousCapture(self->ob_svideo, &info))
- return sv_error();
+ if (svInitContinuousCapture(self->ob_svideo, &info))
+ return sv_error();
- self->ob_info = info;
+ self->ob_info = info;
- return Py_BuildValue("(iiiii)", info.format, info.width, info.height,
- info.size, info.samplingrate);
+ return Py_BuildValue("(iiiii)", info.format, info.width, info.height,
+ info.size, info.samplingrate);
}
static PyObject *
sv_LoadMap(svobject *self, PyObject *args)
{
- PyObject *rgb;
- PyObject *res = NULL;
- rgb_tuple *mapp = NULL;
- int maptype;
- int i, j; /* indices */
-
- if (!PyArg_Parse(args, "(iO)", &maptype, &rgb))
- return NULL;
-
- if (!PyList_Check(rgb) || PyList_Size(rgb) != 256) {
- PyErr_BadArgument();
- return NULL;
- }
-
- if (!(mapp = PyMem_NEW(rgb_tuple, 256)))
- return PyErr_NoMemory();
-
- for (i = 0; i < 256; i++) {
- PyObject* v = PyList_GetItem(rgb, i);
- if (!v)
- goto finally;
-
- if (!PyTuple_Check(v) || PyTuple_Size(v) != 3) {
- PyErr_BadArgument();
- goto finally;
- }
- for (j = 0; j < 3; j++) {
- PyObject* cell = PyTuple_GetItem(v, j);
- if (!cell)
- goto finally;
-
- if (!PyInt_Check(cell)) {
- PyErr_BadArgument();
- goto finally;
- }
- switch (j) {
- case 0: mapp[i].red = PyInt_AsLong(cell); break;
- case 1: mapp[i].blue = PyInt_AsLong(cell); break;
- case 2: mapp[i].green = PyInt_AsLong(cell); break;
- }
- if (PyErr_Occurred())
- goto finally;
- }
- }
-
- if (svLoadMap(self->ob_svideo, maptype, mapp)) {
- res = sv_error();
- goto finally;
- }
-
- Py_INCREF(Py_None);
- res = Py_None;
+ PyObject *rgb;
+ PyObject *res = NULL;
+ rgb_tuple *mapp = NULL;
+ int maptype;
+ int i, j; /* indices */
+
+ if (!PyArg_Parse(args, "(iO)", &maptype, &rgb))
+ return NULL;
+
+ if (!PyList_Check(rgb) || PyList_Size(rgb) != 256) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ if (!(mapp = PyMem_NEW(rgb_tuple, 256)))
+ return PyErr_NoMemory();
+
+ for (i = 0; i < 256; i++) {
+ PyObject* v = PyList_GetItem(rgb, i);
+ if (!v)
+ goto finally;
+
+ if (!PyTuple_Check(v) || PyTuple_Size(v) != 3) {
+ PyErr_BadArgument();
+ goto finally;
+ }
+ for (j = 0; j < 3; j++) {
+ PyObject* cell = PyTuple_GetItem(v, j);
+ if (!cell)
+ goto finally;
+
+ if (!PyInt_Check(cell)) {
+ PyErr_BadArgument();
+ goto finally;
+ }
+ switch (j) {
+ case 0: mapp[i].red = PyInt_AsLong(cell); break;
+ case 1: mapp[i].blue = PyInt_AsLong(cell); break;
+ case 2: mapp[i].green = PyInt_AsLong(cell); break;
+ }
+ if (PyErr_Occurred())
+ goto finally;
+ }
+ }
+
+ if (svLoadMap(self->ob_svideo, maptype, mapp)) {
+ res = sv_error();
+ goto finally;
+ }
+
+ Py_INCREF(Py_None);
+ res = Py_None;
finally:
- PyMem_DEL(mapp);
- return res;
+ PyMem_DEL(mapp);
+ return res;
}
-
+
static PyObject *
sv_CloseVideo(svobject *self, PyObject *args)
{
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- if (svCloseVideo(self->ob_svideo))
- return sv_error();
+ if (svCloseVideo(self->ob_svideo))
+ return sv_error();
- self->ob_svideo = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ self->ob_svideo = NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
doParams(svobject *self, PyObject *args,
int (*func)(SV_nodeP, long *, int), int modified)
{
- PyObject *list;
- PyObject *res = NULL;
- long *PVbuffer = NULL;
- long length;
- int i;
-
- if (!PyArg_Parse(args, "O", &list))
- return NULL;
-
- if (!PyList_Check(list)) {
- PyErr_BadArgument();
- return NULL;
- }
-
- if ((length = PyList_Size(list)) < 0)
- return NULL;
-
- PVbuffer = PyMem_NEW(long, length);
- if (PVbuffer == NULL)
- return PyErr_NoMemory();
-
- for (i = 0; i < length; i++) {
- PyObject *v = PyList_GetItem(list, i);
- if (!v)
- goto finally;
-
- if (!PyInt_Check(v)) {
- PyErr_BadArgument();
- goto finally;
- }
- PVbuffer[i] = PyInt_AsLong(v);
- /* can't just test the return value, because what if the
- value was -1?!
- */
- if (PVbuffer[i] == -1 && PyErr_Occurred())
- goto finally;
- }
-
- if ((*func)(self->ob_svideo, PVbuffer, length)) {
- res = sv_error();
- goto finally;
- }
-
- if (modified) {
- for (i = 0; i < length; i++) {
- PyObject* v = PyInt_FromLong(PVbuffer[i]);
- if (!v || PyList_SetItem(list, i, v) < 0)
- goto finally;
- }
- }
-
- Py_INCREF(Py_None);
- res = Py_None;
+ PyObject *list;
+ PyObject *res = NULL;
+ long *PVbuffer = NULL;
+ long length;
+ int i;
+
+ if (!PyArg_Parse(args, "O", &list))
+ return NULL;
+
+ if (!PyList_Check(list)) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ if ((length = PyList_Size(list)) < 0)
+ return NULL;
+
+ PVbuffer = PyMem_NEW(long, length);
+ if (PVbuffer == NULL)
+ return PyErr_NoMemory();
+
+ for (i = 0; i < length; i++) {
+ PyObject *v = PyList_GetItem(list, i);
+ if (!v)
+ goto finally;
+
+ if (!PyInt_Check(v)) {
+ PyErr_BadArgument();
+ goto finally;
+ }
+ PVbuffer[i] = PyInt_AsLong(v);
+ /* can't just test the return value, because what if the
+ value was -1?!
+ */
+ if (PVbuffer[i] == -1 && PyErr_Occurred())
+ goto finally;
+ }
+
+ if ((*func)(self->ob_svideo, PVbuffer, length)) {
+ res = sv_error();
+ goto finally;
+ }
+
+ if (modified) {
+ for (i = 0; i < length; i++) {
+ PyObject* v = PyInt_FromLong(PVbuffer[i]);
+ if (!v || PyList_SetItem(list, i, v) < 0)
+ goto finally;
+ }
+ }
+
+ Py_INCREF(Py_None);
+ res = Py_None;
finally:
- PyMem_DEL(PVbuffer);
- return res;
+ PyMem_DEL(PVbuffer);
+ return res;
}
static PyObject *
sv_GetParam(PyObject *self, PyObject *args)
{
- return doParams(self, args, svGetParam, 1);
+ return doParams(self, args, svGetParam, 1);
}
static PyObject *
sv_GetParamRange(PyObject *self, PyObject *args)
{
- return doParams(self, args, svGetParamRange, 1);
+ return doParams(self, args, svGetParamRange, 1);
}
static PyObject *
sv_SetParam(PyObject *self, PyObject *args)
{
- return doParams(self, args, svSetParam, 0);
+ return doParams(self, args, svSetParam, 0);
}
static PyMethodDef svideo_methods[] = {
- {"BindGLWindow", (PyCFunction)sv_BindGLWindow, METH_OLDARGS},
- {"EndContinuousCapture",(PyCFunction)sv_EndContinuousCapture, METH_OLDARGS},
- {"IsVideoDisplayed", (PyCFunction)sv_IsVideoDisplayed, METH_OLDARGS},
- {"OutputOffset", (PyCFunction)sv_OutputOffset, METH_OLDARGS},
- {"PutFrame", (PyCFunction)sv_PutFrame, METH_OLDARGS},
- {"QuerySize", (PyCFunction)sv_QuerySize, METH_OLDARGS},
- {"SetSize", (PyCFunction)sv_SetSize, METH_OLDARGS},
- {"SetStdDefaults", (PyCFunction)sv_SetStdDefaults, METH_OLDARGS},
- {"UseExclusive", (PyCFunction)sv_UseExclusive, METH_OLDARGS},
- {"WindowOffset", (PyCFunction)sv_WindowOffset, METH_OLDARGS},
- {"InitContinuousCapture",(PyCFunction)sv_InitContinuousCapture, METH_OLDARGS},
- {"CaptureBurst", (PyCFunction)sv_CaptureBurst, METH_OLDARGS},
- {"CaptureOneFrame", (PyCFunction)sv_CaptureOneFrame, METH_OLDARGS},
- {"GetCaptureData", (PyCFunction)sv_GetCaptureData, METH_OLDARGS},
- {"CloseVideo", (PyCFunction)sv_CloseVideo, METH_OLDARGS},
- {"LoadMap", (PyCFunction)sv_LoadMap, METH_OLDARGS},
- {"GetParam", (PyCFunction)sv_GetParam, METH_OLDARGS},
- {"GetParamRange", (PyCFunction)sv_GetParamRange, METH_OLDARGS},
- {"SetParam", (PyCFunction)sv_SetParam, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"BindGLWindow", (PyCFunction)sv_BindGLWindow, METH_OLDARGS},
+ {"EndContinuousCapture",(PyCFunction)sv_EndContinuousCapture, METH_OLDARGS},
+ {"IsVideoDisplayed", (PyCFunction)sv_IsVideoDisplayed, METH_OLDARGS},
+ {"OutputOffset", (PyCFunction)sv_OutputOffset, METH_OLDARGS},
+ {"PutFrame", (PyCFunction)sv_PutFrame, METH_OLDARGS},
+ {"QuerySize", (PyCFunction)sv_QuerySize, METH_OLDARGS},
+ {"SetSize", (PyCFunction)sv_SetSize, METH_OLDARGS},
+ {"SetStdDefaults", (PyCFunction)sv_SetStdDefaults, METH_OLDARGS},
+ {"UseExclusive", (PyCFunction)sv_UseExclusive, METH_OLDARGS},
+ {"WindowOffset", (PyCFunction)sv_WindowOffset, METH_OLDARGS},
+ {"InitContinuousCapture",(PyCFunction)sv_InitContinuousCapture, METH_OLDARGS},
+ {"CaptureBurst", (PyCFunction)sv_CaptureBurst, METH_OLDARGS},
+ {"CaptureOneFrame", (PyCFunction)sv_CaptureOneFrame, METH_OLDARGS},
+ {"GetCaptureData", (PyCFunction)sv_GetCaptureData, METH_OLDARGS},
+ {"CloseVideo", (PyCFunction)sv_CloseVideo, METH_OLDARGS},
+ {"LoadMap", (PyCFunction)sv_LoadMap, METH_OLDARGS},
+ {"GetParam", (PyCFunction)sv_GetParam, METH_OLDARGS},
+ {"GetParamRange", (PyCFunction)sv_GetParamRange, METH_OLDARGS},
+ {"SetParam", (PyCFunction)sv_SetParam, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
sv_conversion(PyObject *self, PyObject *args, void (*function)(),
int inputfactor, float factor)
{
- int invert, width, height, inputlength;
- char *input, *str;
- PyObject *output;
+ int invert, width, height, inputlength;
+ char *input, *str;
+ PyObject *output;
- if (!PyArg_Parse(args, "(is#ii)", &invert,
- &input, &inputlength, &width, &height))
- return NULL;
+ if (!PyArg_Parse(args, "(is#ii)", &invert,
+ &input, &inputlength, &width, &height))
+ return NULL;
- if (width * height * inputfactor > inputlength) {
- PyErr_SetString(SvError, "input buffer not long enough");
- return NULL;
- }
+ if (width * height * inputfactor > inputlength) {
+ PyErr_SetString(SvError, "input buffer not long enough");
+ return NULL;
+ }
- if (!(output = PyString_FromStringAndSize(NULL,
- (int)(width * height * factor))))
- return NULL;
+ if (!(output = PyString_FromStringAndSize(NULL,
+ (int)(width * height * factor))))
+ return NULL;
- str = PyString_AsString(output);
- if (!str) {
- Py_DECREF(output);
- return NULL;
- }
- (*function)(invert, input, str, width, height);
+ str = PyString_AsString(output);
+ if (!str) {
+ Py_DECREF(output);
+ return NULL;
+ }
+ (*function)(invert, input, str, width, height);
- return output;
+ return output;
}
static PyObject *
sv_InterleaveFields(PyObject *self, PyObject *args)
{
- return sv_conversion(self, args, svInterleaveFields, 1, 1.0);
+ return sv_conversion(self, args, svInterleaveFields, 1, 1.0);
}
static PyObject *
sv_RGB8toRGB32(PyObject *self, PyObject *args)
{
- return sv_conversion(self, args, svRGB8toRGB32, 1, (float) sizeof(long));
+ return sv_conversion(self, args, svRGB8toRGB32, 1, (float) sizeof(long));
}
static PyObject *
sv_YUVtoRGB(PyObject *self, PyObject *args)
{
- return sv_conversion(self, args, svYUVtoRGB, 2, (float) sizeof(long));
+ return sv_conversion(self, args, svYUVtoRGB, 2, (float) sizeof(long));
}
static void
svideo_dealloc(svobject *self)
{
- if (self->ob_svideo != NULL)
- (void) svCloseVideo(self->ob_svideo);
- PyObject_Del(self);
+ if (self->ob_svideo != NULL)
+ (void) svCloseVideo(self->ob_svideo);
+ PyObject_Del(self);
}
static PyObject *
svideo_getattr(svobject *self, char *name)
{
- return Py_FindMethod(svideo_methods, (PyObject *)self, name);
+ return Py_FindMethod(svideo_methods, (PyObject *)self, name);
}
PyTypeObject Svtype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "sv.sv", /*tp_name*/
- sizeof(svobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)svideo_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)svideo_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "sv.sv", /*tp_name*/
+ sizeof(svobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)svideo_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)svideo_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
static PyObject *
newsvobject(SV_nodeP svp)
{
- svobject *p;
+ svobject *p;
- p = PyObject_New(svobject, &Svtype);
- if (p == NULL)
- return NULL;
- p->ob_svideo = svp;
- p->ob_info.format = 0;
- p->ob_info.size = 0;
- p->ob_info.width = 0;
- p->ob_info.height = 0;
- p->ob_info.samplingrate = 0;
- return (PyObject *) p;
+ p = PyObject_New(svobject, &Svtype);
+ if (p == NULL)
+ return NULL;
+ p->ob_svideo = svp;
+ p->ob_info.format = 0;
+ p->ob_info.size = 0;
+ p->ob_info.width = 0;
+ p->ob_info.height = 0;
+ p->ob_info.samplingrate = 0;
+ return (PyObject *) p;
}
static PyObject *
sv_OpenVideo(PyObject *self, PyObject *args)
{
- SV_nodeP svp;
+ SV_nodeP svp;
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- svp = svOpenVideo();
- if (svp == NULL)
- return sv_error();
+ svp = svOpenVideo();
+ if (svp == NULL)
+ return sv_error();
- return newsvobject(svp);
+ return newsvobject(svp);
}
static PyMethodDef sv_methods[] = {
- {"InterleaveFields", (PyCFunction)sv_InterleaveFields, METH_OLDARGS},
- {"RGB8toRGB32", (PyCFunction)sv_RGB8toRGB32, METH_OLDARGS},
- {"YUVtoRGB", (PyCFunction)sv_YUVtoRGB, METH_OLDARGS},
- {"OpenVideo", (PyCFunction)sv_OpenVideo, METH_OLDARGS},
- {NULL, NULL} /* Sentinel */
+ {"InterleaveFields", (PyCFunction)sv_InterleaveFields, METH_OLDARGS},
+ {"RGB8toRGB32", (PyCFunction)sv_RGB8toRGB32, METH_OLDARGS},
+ {"YUVtoRGB", (PyCFunction)sv_YUVtoRGB, METH_OLDARGS},
+ {"OpenVideo", (PyCFunction)sv_OpenVideo, METH_OLDARGS},
+ {NULL, NULL} /* Sentinel */
};
void
initsv(void)
{
- PyObject *m, *d;
-
- if (PyErr_WarnPy3k("the sv module has been removed in "
- "Python 3.0", 2) < 0)
- return;
+ PyObject *m, *d;
+
+ if (PyErr_WarnPy3k("the sv module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
- m = Py_InitModule("sv", sv_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
+ m = Py_InitModule("sv", sv_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
- SvError = PyErr_NewException("sv.error", NULL, NULL);
- if (SvError == NULL || PyDict_SetItemString(d, "error", SvError) != 0)
- return;
+ SvError = PyErr_NewException("sv.error", NULL, NULL);
+ if (SvError == NULL || PyDict_SetItemString(d, "error", SvError) != 0)
+ return;
}
diff --git a/Modules/symtablemodule.c b/Modules/symtablemodule.c
index 53e987e..86c6481 100644
--- a/Modules/symtablemodule.c
+++ b/Modules/symtablemodule.c
@@ -8,80 +8,80 @@
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_symbols;
- 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_symbols;
+ 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 */
};
PyMODINIT_FUNC
init_symtable(void)
{
- PyObject *m;
+ PyObject *m;
- m = Py_InitModule("_symtable", symtable_methods);
- if (m == NULL)
- return;
- 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_STAR", DEF_STAR);
- PyModule_AddIntConstant(m, "DEF_DOUBLESTAR", DEF_DOUBLESTAR);
- PyModule_AddIntConstant(m, "DEF_INTUPLE", DEF_INTUPLE);
- PyModule_AddIntConstant(m, "DEF_FREE", DEF_FREE);
- PyModule_AddIntConstant(m, "DEF_FREE_GLOBAL", DEF_FREE_GLOBAL);
- PyModule_AddIntConstant(m, "DEF_FREE_CLASS", DEF_FREE_CLASS);
- PyModule_AddIntConstant(m, "DEF_IMPORT", DEF_IMPORT);
- PyModule_AddIntConstant(m, "DEF_BOUND", DEF_BOUND);
+ m = Py_InitModule("_symtable", symtable_methods);
+ if (m == NULL)
+ return;
+ 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_STAR", DEF_STAR);
+ PyModule_AddIntConstant(m, "DEF_DOUBLESTAR", DEF_DOUBLESTAR);
+ PyModule_AddIntConstant(m, "DEF_INTUPLE", DEF_INTUPLE);
+ PyModule_AddIntConstant(m, "DEF_FREE", DEF_FREE);
+ PyModule_AddIntConstant(m, "DEF_FREE_GLOBAL", DEF_FREE_GLOBAL);
+ 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_EXEC", OPT_EXEC);
- PyModule_AddIntConstant(m, "OPT_BARE_EXEC", OPT_BARE_EXEC);
+ PyModule_AddIntConstant(m, "OPT_IMPORT_STAR", OPT_IMPORT_STAR);
+ PyModule_AddIntConstant(m, "OPT_EXEC", OPT_EXEC);
+ PyModule_AddIntConstant(m, "OPT_BARE_EXEC", OPT_BARE_EXEC);
- 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_OFF);
- PyModule_AddIntConstant(m, "SCOPE_MASK", SCOPE_MASK);
+ PyModule_AddIntConstant(m, "SCOPE_OFF", SCOPE_OFF);
+ PyModule_AddIntConstant(m, "SCOPE_MASK", SCOPE_MASK);
}
diff --git a/Modules/syslogmodule.c b/Modules/syslogmodule.c
index 9e1ed06..e0fca0d 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.
******************************************************************/
@@ -49,109 +49,109 @@ 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 PyObject *
+static PyObject *
syslog_openlog(PyObject * self, PyObject * args)
{
- long logopt = 0;
- long facility = LOG_USER;
- PyObject *new_S_ident_o;
-
- if (!PyArg_ParseTuple(args,
- "S|ll;ident string [, logoption [, facility]]",
- &new_S_ident_o, &logopt, &facility))
- return NULL;
-
- /* This is needed because openlog() does NOT make a copy
- * and syslog() later uses it.. cannot trash it.
- */
- Py_XDECREF(S_ident_o);
- S_ident_o = new_S_ident_o;
- Py_INCREF(S_ident_o);
-
- openlog(PyString_AsString(S_ident_o), logopt, facility);
-
- Py_INCREF(Py_None);
- return Py_None;
+ long logopt = 0;
+ long facility = LOG_USER;
+ PyObject *new_S_ident_o;
+
+ if (!PyArg_ParseTuple(args,
+ "S|ll;ident string [, logoption [, facility]]",
+ &new_S_ident_o, &logopt, &facility))
+ return NULL;
+
+ /* This is needed because openlog() does NOT make a copy
+ * and syslog() later uses it.. cannot trash it.
+ */
+ Py_XDECREF(S_ident_o);
+ S_ident_o = new_S_ident_o;
+ Py_INCREF(S_ident_o);
+
+ openlog(PyString_AsString(S_ident_o), logopt, facility);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
-static PyObject *
+static PyObject *
syslog_syslog(PyObject * self, PyObject * args)
{
- char *message;
- int priority = LOG_INFO;
-
- if (!PyArg_ParseTuple(args, "is;[priority,] message string",
- &priority, &message)) {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "s;[priority,] message string",
- &message))
- return NULL;
- }
-
- Py_BEGIN_ALLOW_THREADS;
- syslog(priority, "%s", message);
- Py_END_ALLOW_THREADS;
- Py_INCREF(Py_None);
- return Py_None;
+ char *message;
+ int priority = LOG_INFO;
+
+ if (!PyArg_ParseTuple(args, "is;[priority,] message string",
+ &priority, &message)) {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "s;[priority,] message string",
+ &message))
+ return NULL;
+ }
+
+ Py_BEGIN_ALLOW_THREADS;
+ syslog(priority, "%s", message);
+ Py_END_ALLOW_THREADS;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-static PyObject *
+static PyObject *
syslog_closelog(PyObject *self, PyObject *unused)
{
- closelog();
- Py_XDECREF(S_ident_o);
- S_ident_o = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ closelog();
+ Py_XDECREF(S_ident_o);
+ S_ident_o = NULL;
+ 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 PyInt_FromLong(omaskpri);
+ if (!PyArg_ParseTuple(args, "l;mask for priority", &maskpri))
+ return NULL;
+ omaskpri = setlogmask(maskpri);
+ return PyInt_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 PyInt_FromLong(mask);
+ long mask;
+ long pri;
+ if (!PyArg_ParseTuple(args, "l:LOG_MASK", &pri))
+ return NULL;
+ mask = LOG_MASK(pri);
+ return PyInt_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 PyInt_FromLong(mask);
+ long mask;
+ long pri;
+ if (!PyArg_ParseTuple(args, "l:LOG_UPTO", &pri))
+ return NULL;
+ mask = LOG_UPTO(pri);
+ return PyInt_FromLong(mask);
}
/* List of functions defined in the module */
static PyMethodDef syslog_methods[] = {
- {"openlog", syslog_openlog, METH_VARARGS},
- {"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", syslog_openlog, METH_VARARGS},
+ {"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 */
@@ -159,67 +159,67 @@ static PyMethodDef syslog_methods[] = {
PyMODINIT_FUNC
initsyslog(void)
{
- PyObject *m;
-
- /* Create the module and add the functions */
- m = Py_InitModule("syslog", syslog_methods);
- if (m == NULL)
- return;
-
- /* 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 = Py_InitModule("syslog", syslog_methods);
+ if (m == NULL)
+ return;
+
+ /* 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);
+ 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);
}
diff --git a/Modules/termios.c b/Modules/termios.c
index c53566c..8459257 100644
--- a/Modules/termios.c
+++ b/Modules/termios.c
@@ -44,14 +44,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__,
@@ -68,67 +68,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 = PyString_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 = PyInt_FromLong((long)mode.c_cc[VMIN]);
- if (v == NULL)
- goto err;
- PyList_SetItem(cc, VMIN, v);
- v = PyInt_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, PyInt_FromLong((long)mode.c_iflag));
- PyList_SetItem(v, 1, PyInt_FromLong((long)mode.c_oflag));
- PyList_SetItem(v, 2, PyInt_FromLong((long)mode.c_cflag));
- PyList_SetItem(v, 3, PyInt_FromLong((long)mode.c_lflag));
- PyList_SetItem(v, 4, PyInt_FromLong((long)ispeed));
- PyList_SetItem(v, 5, PyInt_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 = PyString_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 = PyInt_FromLong((long)mode.c_cc[VMIN]);
+ if (v == NULL)
+ goto err;
+ PyList_SetItem(cc, VMIN, v);
+ v = PyInt_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, PyInt_FromLong((long)mode.c_iflag));
+ PyList_SetItem(v, 1, PyInt_FromLong((long)mode.c_oflag));
+ PyList_SetItem(v, 2, PyInt_FromLong((long)mode.c_cflag));
+ PyList_SetItem(v, 3, PyInt_FromLong((long)mode.c_lflag));
+ PyList_SetItem(v, 4, PyInt_FromLong((long)ispeed));
+ PyList_SetItem(v, 5, PyInt_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__,
@@ -145,64 +145,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) PyInt_AsLong(PyList_GetItem(term, 0));
- mode.c_oflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 1));
- mode.c_cflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 2));
- mode.c_lflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 3));
- ispeed = (speed_t) PyInt_AsLong(PyList_GetItem(term, 4));
- ospeed = (speed_t) PyInt_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 (PyString_Check(v) && PyString_Size(v) == 1)
- mode.c_cc[i] = (cc_t) * PyString_AsString(v);
- else if (PyInt_Check(v))
- mode.c_cc[i] = (cc_t) PyInt_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) PyInt_AsLong(PyList_GetItem(term, 0));
+ mode.c_oflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 1));
+ mode.c_cflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 2));
+ mode.c_lflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 3));
+ ispeed = (speed_t) PyInt_AsLong(PyList_GetItem(term, 4));
+ ospeed = (speed_t) PyInt_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 (PyString_Check(v) && PyString_Size(v) == 1)
+ mode.c_cc[i] = (cc_t) * PyString_AsString(v);
+ else if (PyInt_Check(v))
+ mode.c_cc[i] = (cc_t) PyInt_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__,
@@ -215,16 +215,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__,
@@ -235,16 +235,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__,
@@ -258,16 +258,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__,
@@ -281,33 +281,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}
};
@@ -320,607 +320,607 @@ 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},
-#endif
-
- /* tcsetattr() constants */
- {"TCSANOW", TCSANOW},
- {"TCSADRAIN", TCSADRAIN},
- {"TCSAFLUSH", TCSAFLUSH},
-
- /* 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},
+ {"CBAUDEX", CBAUDEX},
+#endif
+
+ /* tcsetattr() constants */
+ {"TCSANOW", TCSANOW},
+ {"TCSADRAIN", TCSADRAIN},
+ {"TCSAFLUSH", TCSAFLUSH},
+
+ /* 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}
};
PyMODINIT_FUNC
PyInit_termios(void)
{
- PyObject *m;
- struct constant *constant = termios_constants;
-
- m = Py_InitModule4("termios", termios_methods, termios__doc__,
- (PyObject *)NULL, PYTHON_API_VERSION);
- if (m == NULL)
- return;
-
- 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;
- }
+ PyObject *m;
+ struct constant *constant = termios_constants;
+
+ m = Py_InitModule4("termios", termios_methods, termios__doc__,
+ (PyObject *)NULL, PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
+
+ 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;
+ }
}
diff --git a/Modules/testcapi_long.h b/Modules/testcapi_long.h
index 8ed6b02..d9b6663 100644
--- a/Modules/testcapi_long.h
+++ b/Modules/testcapi_long.h
@@ -1,166 +1,166 @@
/* 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");
- 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");
- 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");
- 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");
- 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");
+ 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");
+ 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");
+ 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");
+ PyErr_Clear();
+ UNBIND(y);
+
+ Py_XDECREF(x);
+ Py_XDECREF(y);
+ Py_DECREF(one);
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
diff --git a/Modules/threadmodule.c b/Modules/threadmodule.c
index ccd88e0..de34ae2 100644
--- a/Modules/threadmodule.c
+++ b/Modules/threadmodule.c
@@ -18,36 +18,36 @@ static PyObject *ThreadError;
/* Lock objects */
typedef struct {
- PyObject_HEAD
- PyThread_type_lock lock_lock;
+ PyObject_HEAD
+ PyThread_type_lock lock_lock;
} lockobject;
static void
lock_dealloc(lockobject *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->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)
{
- int i = 1;
+ int i = 1;
- if (!PyArg_ParseTuple(args, "|i:acquire", &i))
- return NULL;
+ if (!PyArg_ParseTuple(args, "|i:acquire", &i))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- i = PyThread_acquire_lock(self->lock_lock, i);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ i = PyThread_acquire_lock(self->lock_lock, i);
+ Py_END_ALLOW_THREADS
- return PyBool_FromLong((long)i);
+ return PyBool_FromLong((long)i);
}
PyDoc_STRVAR(acquire_doc,
@@ -64,16 +64,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,
@@ -87,11 +87,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,
@@ -101,59 +101,59 @@ 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, acquire_doc},
- {"acquire", (PyCFunction)lock_PyThread_acquire_lock,
- METH_VARARGS, 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, acquire_doc},
- {"__exit__", (PyCFunction)lock_PyThread_release_lock,
- METH_VARARGS, release_doc},
- {NULL, NULL} /* sentinel */
+ {"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock,
+ METH_VARARGS, acquire_doc},
+ {"acquire", (PyCFunction)lock_PyThread_acquire_lock,
+ METH_VARARGS, 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, acquire_doc},
+ {"__exit__", (PyCFunction)lock_PyThread_release_lock,
+ METH_VARARGS, release_doc},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
lock_getattr(lockobject *self, char *name)
{
- return Py_FindMethod(lock_methods, (PyObject *)self, name);
+ return Py_FindMethod(lock_methods, (PyObject *)self, name);
}
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*/
- (getattrfunc)lock_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ 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*/
+ (getattrfunc)lock_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
static lockobject *
newlockobject(void)
{
- lockobject *self;
- self = PyObject_New(lockobject, &Locktype);
- if (self == NULL)
- return NULL;
- self->lock_lock = PyThread_allocate_lock();
- 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();
+ if (self->lock_lock == NULL) {
+ Py_DECREF(self);
+ PyErr_SetString(ThreadError, "can't allocate lock");
+ return NULL;
+ }
+ return self;
}
/* Thread-local objects */
@@ -161,351 +161,351 @@ 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 = PyString_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 = PyString_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;
- return PyObject_GenericSetAttr((PyObject *)self, name, v);
+ ldict = _ldict(self);
+ if (ldict == NULL)
+ return -1;
+
+ 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_compare */ 0,
- /* tp_repr */ 0,
- /* tp_as_number */ 0,
- /* tp_as_sequence */ 0,
- /* tp_as_mapping */ 0,
- /* tp_hash */ 0,
- /* tp_call */ 0,
- /* tp_str */ 0,
- /* tp_getattro */ (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_compare */ 0,
+ /* tp_repr */ 0,
+ /* tp_as_number */ 0,
+ /* tp_as_sequence */ 0,
+ /* tp_as_mapping */ 0,
+ /* tp_hash */ 0,
+ /* tp_call */ 0,
+ /* tp_str */ 0,
+ /* tp_getattro */ (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);
- 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)
- 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);
- 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);
+ 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)
+ 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);
+ 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 PyInt_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 PyInt_FromLong(ident);
}
PyDoc_STRVAR(start_new_doc,
@@ -522,8 +522,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,
@@ -536,9 +536,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,
@@ -552,11 +552,11 @@ A subthread can use this function to interrupt the main thread."
static PyObject *
thread_PyThread_exit_prog(PyObject *self, PyObject *args)
{
- int sts;
- if (!PyArg_ParseTuple(args, "i:exit_prog", &sts))
- return NULL;
- Py_Exit(sts); /* Calls PyThread_exit_prog(sts) or _PyThread_exit_prog(sts) */
- for (;;) { } /* Should not be reached */
+ int sts;
+ if (!PyArg_ParseTuple(args, "i:exit_prog", &sts))
+ return NULL;
+ Py_Exit(sts); /* Calls PyThread_exit_prog(sts) or _PyThread_exit_prog(sts) */
+ for (;;) { } /* Should not be reached */
}
#endif
@@ -565,7 +565,7 @@ static lockobject *newlockobject(void);
static PyObject *
thread_PyThread_allocate_lock(PyObject *self)
{
- return (PyObject *) newlockobject();
+ return (PyObject *) newlockobject();
}
PyDoc_STRVAR(allocate_doc,
@@ -577,13 +577,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 PyInt_FromLong(ident);
+ long ident;
+ ident = PyThread_get_thread_ident();
+ if (ident == -1) {
+ PyErr_SetString(ThreadError, "no current thread ident");
+ return NULL;
+ }
+ return PyInt_FromLong(ident);
}
PyDoc_STRVAR(get_ident_doc,
@@ -600,35 +600,35 @@ A thread's identity may be reused for another thread after it exits.");
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 PyInt_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 PyInt_FromSsize_t((Py_ssize_t) old_size);
}
PyDoc_STRVAR(stack_size_doc,
@@ -652,32 +652,32 @@ 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},
- {"stack_size", (PyCFunction)thread_stack_size,
- METH_VARARGS,
- stack_size_doc},
+ {"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},
+ {"stack_size", (PyCFunction)thread_stack_size,
+ METH_VARARGS,
+ stack_size_doc},
#ifndef NO_EXIT_PROG
- {"exit_prog", (PyCFunction)thread_PyThread_exit_prog,
- METH_VARARGS},
+ {"exit_prog", (PyCFunction)thread_PyThread_exit_prog,
+ METH_VARARGS},
#endif
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
@@ -702,29 +702,29 @@ will block until another thread unlocks it. Deadlocks may ensue.");
PyMODINIT_FUNC
initthread(void)
{
- PyObject *m, *d;
-
- /* Initialize types: */
- if (PyType_Ready(&localtype) < 0)
- return;
-
- /* Create the module and add the functions */
- m = Py_InitModule3("thread", thread_methods, thread_doc);
- if (m == NULL)
- return;
-
- /* 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(&localtype);
- if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0)
- return;
-
- /* Initialize the C thread library */
- PyThread_init_thread();
+ PyObject *m, *d;
+
+ /* Initialize types: */
+ if (PyType_Ready(&localtype) < 0)
+ return;
+
+ /* Create the module and add the functions */
+ m = Py_InitModule3("thread", thread_methods, thread_doc);
+ if (m == NULL)
+ return;
+
+ /* 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(&localtype);
+ if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0)
+ return;
+
+ /* Initialize the C thread library */
+ PyThread_init_thread();
}
diff --git a/Modules/timemodule.c b/Modules/timemodule.c
index e8de2c5..d6d4160 100644
--- a/Modules/timemodule.c
+++ b/Modules/timemodule.c
@@ -46,12 +46,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;
@@ -102,38 +102,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,
@@ -155,7 +155,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 */
@@ -164,25 +164,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 */
@@ -200,13 +200,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,
@@ -216,23 +216,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;
@@ -241,48 +241,48 @@ 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, PyInt_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 *
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;
@@ -292,28 +292,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,
@@ -326,15 +326,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.");
@@ -342,166 +342,166 @@ When 'seconds' is not passed in, convert the current time instead.");
static int
gettmarg(PyObject *args, struct tm *p)
{
- int y;
- memset((void *) p, '\0', sizeof(struct tm));
-
- if (!PyArg_Parse(args, "(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))
- return 0;
- if (y < 1900) {
- PyObject *accept = PyDict_GetItemString(moddict,
- "accept2dyear");
- if (accept == NULL || !PyInt_Check(accept) ||
- PyInt_AsLong(accept) == 0) {
- 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;
+ memset((void *) p, '\0', sizeof(struct tm));
+
+ if (!PyArg_Parse(args, "(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))
+ return 0;
+ if (y < 1900) {
+ PyObject *accept = PyDict_GetItemString(moddict,
+ "accept2dyear");
+ if (accept == NULL || !PyInt_Check(accept) ||
+ PyInt_AsLong(accept) == 0) {
+ 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
static PyObject *
time_strftime(PyObject *self, PyObject *args)
{
- PyObject *tup = NULL;
- struct tm buf;
- const char *fmt;
- size_t fmtlen, buflen;
- char *outbuf = 0;
- size_t i;
-
- memset((void *) &buf, '\0', sizeof(buf));
-
- if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &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;
+ PyObject *tup = NULL;
+ struct tm buf;
+ const char *fmt;
+ size_t fmtlen, buflen;
+ char *outbuf = 0;
+ size_t i;
+
+ memset((void *) &buf, '\0', sizeof(buf));
+
+ if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &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;
+ }
+ if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
+ PyErr_SetString(PyExc_ValueError,
+ "daylight savings flag out of range");
+ return NULL;
+ }
+
+ fmtlen = 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 = (char *)malloc(i);
+ if (outbuf == NULL) {
+ return PyErr_NoMemory();
}
- if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
- PyErr_SetString(PyExc_ValueError,
- "daylight savings flag out of range");
- return NULL;
+ buflen = strftime(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;
+ ret = PyString_FromStringAndSize(outbuf, buflen);
+ free(outbuf);
+ return ret;
}
-
- fmtlen = 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 = (char *)malloc(i);
- if (outbuf == NULL) {
- return PyErr_NoMemory();
- }
- buflen = strftime(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;
- ret = PyString_FromStringAndSize(outbuf, buflen);
- free(outbuf);
- return ret;
- }
- free(outbuf);
+ 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");
- return 0;
- }
+ /* VisualStudio .NET 2005 does this properly */
+ if (buflen == 0 && errno == EINVAL) {
+ PyErr_SetString(PyExc_ValueError, "Invalid format string");
+ return 0;
+ }
#endif
-
- }
+
+ }
}
PyDoc_STRVAR(strftime_doc,
@@ -519,7 +519,7 @@ time_strptime(PyObject *self, PyObject *args)
PyObject *strptime_result;
if (!strptime_module)
- return NULL;
+ return NULL;
strptime_result = PyObject_CallMethod(strptime_module, "_strptime_time", "O", args);
Py_DECREF(strptime_module);
return strptime_result;
@@ -535,20 +535,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 PyString_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 PyString_FromString(p);
}
PyDoc_STRVAR(asctime_doc,
@@ -561,30 +561,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 PyString_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 PyString_FromString(p);
}
PyDoc_STRVAR(ctime_doc,
@@ -598,17 +598,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,
@@ -623,21 +623,21 @@ static void inittimezone(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 */
- inittimezone(m);
- Py_DECREF(m);
+ /* Reset timezone, altzone, daylight and tzname */
+ inittimezone(m);
+ Py_DECREF(m);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(tzset_doc,
@@ -657,113 +657,113 @@ should not be relied on.");
static void
inittimezone(PyObject *m) {
/* This code moved from inittime 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__)
- tzset();
+ 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);
- PyModule_AddObject(m, "tzname",
- Py_BuildValue("(zz)", tzname[0], tzname[1]));
+ PyModule_AddIntConstant(m, "daylight", daylight);
+ PyModule_AddObject(m, "tzname",
+ Py_BuildValue("(zz)", tzname[0], tzname[1]));
#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 */
};
@@ -816,38 +816,38 @@ tzset() -- change the local timezone");
PyMODINIT_FUNC
inittime(void)
{
- PyObject *m;
- char *p;
- m = Py_InitModule3("time", time_methods, module_doc);
- if (m == NULL)
- return;
-
- /* 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 */
- inittimezone(m);
+ PyObject *m;
+ char *p;
+ m = Py_InitModule3("time", time_methods, module_doc);
+ if (m == NULL)
+ return;
+
+ /* 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 */
+ inittimezone(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;
+ if (!initialized) {
+ PyStructSequence_InitType(&StructTimeType,
+ &struct_time_type_desc);
+ }
+ Py_INCREF(&StructTimeType);
+ PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
+ initialized = 1;
}
@@ -856,38 +856,38 @@ inittime(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 */
- }
+ }
}
@@ -900,122 +900,122 @@ floatsleep(double secs)
{
/* XXX Should test for MS_WINDOWS first! */
#if defined(HAVE_SELECT) && !defined(__BEOS__) && !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
#elif defined(__BEOS__)
- /* This sleep *CAN BE* interrupted. */
- {
- if( secs <= 0.0 ) {
- return;
- }
-
- Py_BEGIN_ALLOW_THREADS
- /* BeOS snooze() is in microseconds... */
- if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
- Py_BLOCK_THREADS
- PyErr_SetFromErrno( PyExc_IOError );
- return -1;
- }
- Py_END_ALLOW_THREADS
- }
+ /* This sleep *CAN BE* interrupted. */
+ {
+ if( secs <= 0.0 ) {
+ return;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ /* BeOS snooze() is in microseconds... */
+ if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
+ Py_BLOCK_THREADS
+ PyErr_SetFromErrno( PyExc_IOError );
+ return -1;
+ }
+ Py_END_ALLOW_THREADS
+ }
#elif defined(RISCOS)
- if (secs <= 0.0)
- return 0;
- Py_BEGIN_ALLOW_THREADS
- /* This sleep *CAN BE* interrupted. */
- if ( riscos_sleep(secs) )
- return -1;
- Py_END_ALLOW_THREADS
+ if (secs <= 0.0)
+ return 0;
+ Py_BEGIN_ALLOW_THREADS
+ /* This sleep *CAN BE* interrupted. */
+ if ( riscos_sleep(secs) )
+ return -1;
+ Py_END_ALLOW_THREADS
#elif defined(PLAN9)
- {
- double millisecs = secs * 1000.0;
- if (millisecs > (double)LONG_MAX) {
- PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
- return -1;
- }
- /* This sleep *CAN BE* interrupted. */
- Py_BEGIN_ALLOW_THREADS
- if(sleep((long)millisecs) < 0){
- Py_BLOCK_THREADS
- PyErr_SetFromErrno(PyExc_IOError);
- return -1;
- }
- Py_END_ALLOW_THREADS
- }
+ {
+ double millisecs = secs * 1000.0;
+ if (millisecs > (double)LONG_MAX) {
+ PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
+ return -1;
+ }
+ /* This sleep *CAN BE* interrupted. */
+ Py_BEGIN_ALLOW_THREADS
+ if(sleep((long)millisecs) < 0){
+ 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/timingmodule.c b/Modules/timingmodule.c
index 0da5c6b..a4e2c7e 100644
--- a/Modules/timingmodule.c
+++ b/Modules/timingmodule.c
@@ -10,45 +10,45 @@
static PyObject *
start_timing(PyObject *self)
{
- Py_INCREF(Py_None);
- BEGINTIMING;
- return Py_None;
+ Py_INCREF(Py_None);
+ BEGINTIMING;
+ return Py_None;
}
static PyObject *
finish_timing(PyObject *self)
{
- ENDTIMING
- Py_INCREF(Py_None);
- return Py_None;
+ ENDTIMING
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
seconds(PyObject *self)
{
- return PyInt_FromLong(TIMINGS);
+ return PyInt_FromLong(TIMINGS);
}
static PyObject *
milli(PyObject *self)
{
- return PyInt_FromLong(TIMINGMS);
+ return PyInt_FromLong(TIMINGMS);
}
static PyObject *
micro(PyObject *self)
{
- return PyInt_FromLong(TIMINGUS);
+ return PyInt_FromLong(TIMINGUS);
}
static PyMethodDef timing_methods[] = {
- {"start", (PyCFunction)start_timing, METH_NOARGS},
- {"finish", (PyCFunction)finish_timing, METH_NOARGS},
- {"seconds", (PyCFunction)seconds, METH_NOARGS},
- {"milli", (PyCFunction)milli, METH_NOARGS},
- {"micro", (PyCFunction)micro, METH_NOARGS},
- {NULL, NULL}
+ {"start", (PyCFunction)start_timing, METH_NOARGS},
+ {"finish", (PyCFunction)finish_timing, METH_NOARGS},
+ {"seconds", (PyCFunction)seconds, METH_NOARGS},
+ {"milli", (PyCFunction)milli, METH_NOARGS},
+ {"micro", (PyCFunction)micro, METH_NOARGS},
+ {NULL, NULL}
};
@@ -56,7 +56,7 @@ PyMODINIT_FUNC inittiming(void)
{
if (PyErr_WarnPy3k("the timing module has been removed in "
"Python 3.0; use time.clock() instead", 2) < 0)
- return;
-
- (void)Py_InitModule("timing", timing_methods);
+ return;
+
+ (void)Py_InitModule("timing", timing_methods);
}
diff --git a/Modules/tkappinit.c b/Modules/tkappinit.c
index de04b0d..05c48a4 100644
--- a/Modules/tkappinit.c
+++ b/Modules/tkappinit.c
@@ -19,131 +19,131 @@
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 TK_AQUA
#ifndef MAX_PATH_LEN
#define MAX_PATH_LEN 1024
#endif
- 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);
-
- 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);
- }
+ 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);
+
+ 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;
- }
- if (Tk_Init(interp) == TCL_ERROR)
- 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;
+ }
+ if (Tk_Init(interp) == 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;
-
- Tcl_CreateCommand(interp, "studbutton", studButtonCmd,
- (ClientData) main_window, NULL);
- Tcl_CreateCommand(interp, "tributton", triButtonCmd,
- (ClientData) main_window, NULL);
- }
+ {
+ 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);
+ }
#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 0e61877..8291d58 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 */
} _PyUnicode_DatabaseRecord;
typedef struct change_record {
@@ -66,7 +66,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}
};
@@ -77,14 +77,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;
}
@@ -93,12 +93,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");
@@ -135,7 +135,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;
@@ -145,15 +145,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 PyInt_FromLong(rc);
}
@@ -180,14 +180,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 PyInt_FromLong(rc);
}
@@ -220,7 +220,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;
@@ -230,14 +230,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);
}
@@ -256,8 +256,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;
@@ -285,8 +285,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;
@@ -316,8 +316,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;
@@ -345,8 +345,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;
@@ -375,8 +375,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;
@@ -406,8 +406,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;
@@ -453,7 +453,7 @@ unicodedata_decomposition(PyObject *self, PyObject *args)
decomp_data[++index]);
i += strlen(decomp + i);
}
-
+
decomp[i] = '\0';
return PyString_FromString(decomp);
@@ -473,7 +473,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;
@@ -498,11 +498,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. */
@@ -639,12 +639,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--;
@@ -655,7 +655,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;
@@ -704,7 +704,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. */
@@ -720,7 +720,7 @@ nfc_nfkc(PyObject *self, PyObject *input, int k)
PyUnicode_Resize(&result, o - PyUnicode_AS_UNICODE(result));
return result;
}
-
+
PyDoc_STRVAR(unicodedata_normalize__doc__,
"normalize(form, unistr)\n\
\n\
@@ -836,29 +836,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)) {
@@ -925,23 +925,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;
}
}
@@ -954,18 +954,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;
}
@@ -1025,7 +1025,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,
@@ -1057,14 +1057,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 Py_BuildValue("s", name);
@@ -1102,7 +1102,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. */
@@ -1127,27 +1127,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_compare*/
- 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_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*/
@@ -1213,7 +1213,7 @@ initunicodedata(void)
PyModule_AddObject(m, "ucnhash_CAPI", v);
}
-/*
+/*
Local variables:
c-basic-offset: 4
indent-tabs-mode: nil
diff --git a/Modules/xxmodule.c b/Modules/xxmodule.c
index 6b498dd..1d9b08a 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_getattr(XxoObject *self, char *name)
{
- if (self->x_attr != NULL) {
- PyObject *v = PyDict_GetItemString(self->x_attr, name);
- if (v != NULL) {
- Py_INCREF(v);
- return v;
- }
- }
- return Py_FindMethod(Xxo_methods, (PyObject *)self, name);
+ if (self->x_attr != NULL) {
+ PyObject *v = PyDict_GetItemString(self->x_attr, name);
+ if (v != NULL) {
+ Py_INCREF(v);
+ return v;
+ }
+ }
+ return Py_FindMethod(Xxo_methods, (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)Xxo_getattr, /*tp_getattr*/
- (setattrfunc)Xxo_setattr, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*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*/
- 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)Xxo_getattr, /*tp_getattr*/
+ (setattrfunc)Xxo_setattr, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*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*/
+ 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 PyInt_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 PyInt_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, PyInt_FromLong(0L));
- PyObject_Print(item, stdout, 0);
- printf("\n");
- /* Py_DECREF(item); */
+ item = PyList_GetItem(list, 0);
+ /* Py_INCREF(item); */
+ PyList_SetItem(list, 1, PyInt_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_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
- 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 initxx */ /*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_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
+ 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 initxx */ /*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_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
- 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 initxx */ /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- 0, /*tp_init*/
- 0, /*tp_alloc*/
- 0, /* see initxx */ /*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_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
+ 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 initxx */ /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ 0, /*tp_init*/
+ 0, /*tp_alloc*/
+ 0, /* see initxx */ /*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,
@@ -339,41 +339,41 @@ PyDoc_STRVAR(module_doc,
PyMODINIT_FUNC
initxx(void)
{
- PyObject *m;
-
- /* 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)
- return;
-
- /* Create the module and add the functions */
- m = Py_InitModule3("xx", xx_methods, module_doc);
- if (m == NULL)
- return;
-
- /* Add some symbolic constants to the module */
- if (ErrorObject == NULL) {
- ErrorObject = PyErr_NewException("xx.error", NULL, NULL);
- if (ErrorObject == NULL)
- return;
- }
- Py_INCREF(ErrorObject);
- PyModule_AddObject(m, "error", ErrorObject);
-
- /* Add Str */
- if (PyType_Ready(&Str_Type) < 0)
- return;
- PyModule_AddObject(m, "Str", (PyObject *)&Str_Type);
-
- /* Add Null */
- if (PyType_Ready(&Null_Type) < 0)
- return;
- PyModule_AddObject(m, "Null", (PyObject *)&Null_Type);
+ PyObject *m;
+
+ /* 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)
+ return;
+
+ /* Create the module and add the functions */
+ m = Py_InitModule3("xx", xx_methods, module_doc);
+ if (m == NULL)
+ return;
+
+ /* Add some symbolic constants to the module */
+ if (ErrorObject == NULL) {
+ ErrorObject = PyErr_NewException("xx.error", NULL, NULL);
+ if (ErrorObject == NULL)
+ return;
+ }
+ Py_INCREF(ErrorObject);
+ PyModule_AddObject(m, "error", ErrorObject);
+
+ /* Add Str */
+ if (PyType_Ready(&Str_Type) < 0)
+ return;
+ PyModule_AddObject(m, "Str", (PyObject *)&Str_Type);
+
+ /* Add Null */
+ if (PyType_Ready(&Null_Type) < 0)
+ return;
+ PyModule_AddObject(m, "Null", (PyObject *)&Null_Type);
}
diff --git a/Modules/xxsubtype.c b/Modules/xxsubtype.c
index 0cf0b81..d4316e7 100644
--- a/Modules/xxsubtype.c
+++ b/Modules/xxsubtype.c
@@ -19,279 +19,279 @@ 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 PyInt_FromLong(self->state);
+ if (!PyArg_ParseTuple(args, ":getstate"))
+ return NULL;
+ return PyInt_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 PyInt_FromLong(self->state);
+ return PyInt_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_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- 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_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 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 PyInt_FromLong(self->state);
+ if (!PyArg_ParseTuple(args, ":getstate"))
+ return NULL;
+ return PyInt_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_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- 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_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 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 */
};
PyMODINIT_FUNC
initxxsubtype(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;
-
- spamlist_type.tp_base = &PyList_Type;
- if (PyType_Ready(&spamlist_type) < 0)
- return;
-
- m = Py_InitModule3("xxsubtype",
- xxsubtype_functions,
- xxsubtype__doc__);
- if (m == NULL)
- return;
-
- if (PyType_Ready(&spamlist_type) < 0)
- return;
- if (PyType_Ready(&spamdict_type) < 0)
- return;
-
- Py_INCREF(&spamlist_type);
- if (PyModule_AddObject(m, "spamlist",
- (PyObject *) &spamlist_type) < 0)
- return;
-
- Py_INCREF(&spamdict_type);
- if (PyModule_AddObject(m, "spamdict",
- (PyObject *) &spamdict_type) < 0)
- return;
+ 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;
+
+ spamlist_type.tp_base = &PyList_Type;
+ if (PyType_Ready(&spamlist_type) < 0)
+ return;
+
+ m = Py_InitModule3("xxsubtype",
+ xxsubtype_functions,
+ xxsubtype__doc__);
+ if (m == NULL)
+ return;
+
+ if (PyType_Ready(&spamlist_type) < 0)
+ return;
+ if (PyType_Ready(&spamdict_type) < 0)
+ return;
+
+ Py_INCREF(&spamlist_type);
+ if (PyModule_AddObject(m, "spamlist",
+ (PyObject *) &spamlist_type) < 0)
+ return;
+
+ Py_INCREF(&spamdict_type);
+ if (PyModule_AddObject(m, "spamdict",
+ (PyObject *) &spamdict_type) < 0)
+ return;
}
diff --git a/Modules/yuv.h b/Modules/yuv.h
index 738c4e5..1e5fd28 100644
--- a/Modules/yuv.h
+++ b/Modules/yuv.h
@@ -19,41 +19,41 @@ extern "C" {
* +-------------------+
*/
struct yuv411 {
- struct {
- unsigned int dummy:8;
- unsigned int y0:8;
- unsigned int u0:2;
- unsigned int v0:2;
- unsigned int y1:8;
- unsigned int u1:2;
- unsigned int v1:2;
- } v[4];
+ struct {
+ unsigned int dummy:8;
+ unsigned int y0:8;
+ unsigned int u0:2;
+ unsigned int v0:2;
+ unsigned int y1:8;
+ unsigned int u1:2;
+ unsigned int v1:2;
+ } v[4];
};
-#define YUV411_Y00(y) (y).v[0].y0
-#define YUV411_Y01(y) (y).v[1].y0
-#define YUV411_Y02(y) (y).v[2].y0
-#define YUV411_Y03(y) (y).v[3].y0
-#define YUV411_Y10(y) (y).v[0].y1
-#define YUV411_Y11(y) (y).v[1].y1
-#define YUV411_Y12(y) (y).v[2].y1
-#define YUV411_Y13(y) (y).v[3].y1
-#define YUV411_U00(y) ((y).v[0].u0<<6|(y).v[1].u0<<4|(y).v[2].u0<<2|(y).v[3].u0)
-#define YUV411_U01(y) YUV411_U00(y)
-#define YUV411_U02(y) YUV411_U00(y)
-#define YUV411_U03(y) YUV411_U00(y)
-#define YUV411_U10(y) ((y).v[0].u1<<6|(y).v[1].u1<<4|(y).v[2].u1<<2|(y).v[3].u1)
-#define YUV411_U11(y) YUV411_U10(y)
-#define YUV411_U12(y) YUV411_U10(y)
-#define YUV411_U13(y) YUV411_U10(y)
-#define YUV411_V00(y) ((y).v[0].v0<<6|(y).v[1].v0<<4|(y).v[2].v0<<2|(y).v[3].v0)
-#define YUV411_V01(y) YUV411_V00(y)
-#define YUV411_V02(y) YUV411_V00(y)
-#define YUV411_V03(y) YUV411_V00(y)
-#define YUV411_V10(y) ((y).v[0].v1<<6|(y).v[1].v1<<4|(y).v[2].v1<<2|(y).v[3].v1)
-#define YUV411_V11(y) YUV411_V10(y)
-#define YUV411_V12(y) YUV411_V10(y)
-#define YUV411_V13(y) YUV411_V10(y)
+#define YUV411_Y00(y) (y).v[0].y0
+#define YUV411_Y01(y) (y).v[1].y0
+#define YUV411_Y02(y) (y).v[2].y0
+#define YUV411_Y03(y) (y).v[3].y0
+#define YUV411_Y10(y) (y).v[0].y1
+#define YUV411_Y11(y) (y).v[1].y1
+#define YUV411_Y12(y) (y).v[2].y1
+#define YUV411_Y13(y) (y).v[3].y1
+#define YUV411_U00(y) ((y).v[0].u0<<6|(y).v[1].u0<<4|(y).v[2].u0<<2|(y).v[3].u0)
+#define YUV411_U01(y) YUV411_U00(y)
+#define YUV411_U02(y) YUV411_U00(y)
+#define YUV411_U03(y) YUV411_U00(y)
+#define YUV411_U10(y) ((y).v[0].u1<<6|(y).v[1].u1<<4|(y).v[2].u1<<2|(y).v[3].u1)
+#define YUV411_U11(y) YUV411_U10(y)
+#define YUV411_U12(y) YUV411_U10(y)
+#define YUV411_U13(y) YUV411_U10(y)
+#define YUV411_V00(y) ((y).v[0].v0<<6|(y).v[1].v0<<4|(y).v[2].v0<<2|(y).v[3].v0)
+#define YUV411_V01(y) YUV411_V00(y)
+#define YUV411_V02(y) YUV411_V00(y)
+#define YUV411_V03(y) YUV411_V00(y)
+#define YUV411_V10(y) ((y).v[0].v1<<6|(y).v[1].v1<<4|(y).v[2].v1<<2|(y).v[3].v1)
+#define YUV411_V11(y) YUV411_V10(y)
+#define YUV411_V12(y) YUV411_V10(y)
+#define YUV411_V13(y) YUV411_V10(y)
/*
* Compression Library YUV 4:2:2 format.
@@ -65,17 +65,17 @@ struct yuv411 {
* +-------+
*/
struct yuv422 {
- unsigned int u:8;
- unsigned int y0:8;
- unsigned int v:8;
- unsigned int y1:8;
+ unsigned int u:8;
+ unsigned int y0:8;
+ unsigned int v:8;
+ unsigned int y1:8;
};
-#define YUV422_Y0(y) (y).y0
-#define YUV422_Y1(y) (y).y1
-#define YUV422_U0(y) (y).u
-#define YUV422_U1(y) (y).u
-#define YUV422_V0(y) (y).v
-#define YUV422_V1(y) (y).v
+#define YUV422_Y0(y) (y).y0
+#define YUV422_Y1(y) (y).y1
+#define YUV422_U0(y) (y).u
+#define YUV422_U1(y) (y).u
+#define YUV422_V0(y) (y).v
+#define YUV422_V1(y) (y).v
/*
* Compression library YUV 4:2:2 Duplicate Chroma format.
diff --git a/Modules/yuvconvert.c b/Modules/yuvconvert.c
index e5333d9..a0fa639 100644
--- a/Modules/yuvconvert.c
+++ b/Modules/yuvconvert.c
@@ -4,115 +4,115 @@
void
yuv_sv411_to_cl422dc(int invert, void *data, void *yuv, int width, int height)
{
- struct yuv411 *in = data;
- struct yuv422 *out_even = yuv;
- struct yuv422 *out_odd = out_even + width / 2;
- int i, j; /* counters */
+ struct yuv411 *in = data;
+ struct yuv422 *out_even = yuv;
+ struct yuv422 *out_odd = out_even + width / 2;
+ int i, j; /* counters */
- for (i = height / 2; i--; ) {
- for (j = width / 4; j--; ) {
- YUV422_Y0(*out_even) = YUV411_Y00(*in);
- YUV422_U0(*out_even) = YUV411_U00(*in);
- YUV422_V0(*out_even) = YUV411_V00(*in);
- YUV422_Y1(*out_even) = YUV411_Y01(*in);
- out_even++;
- YUV422_Y0(*out_even) = YUV411_Y02(*in);
- YUV422_U0(*out_even) = YUV411_U02(*in);
- YUV422_V0(*out_even) = YUV411_V02(*in);
- YUV422_Y1(*out_even) = YUV411_Y03(*in);
- out_even++;
- YUV422_Y0(*out_odd) = YUV411_Y10(*in);
- YUV422_U0(*out_odd) = YUV411_U10(*in);
- YUV422_V0(*out_odd) = YUV411_V10(*in);
- YUV422_Y1(*out_odd) = YUV411_Y11(*in);
- out_odd++;
- YUV422_Y0(*out_odd) = YUV411_Y12(*in);
- YUV422_U0(*out_odd) = YUV411_U12(*in);
- YUV422_V0(*out_odd) = YUV411_V12(*in);
- YUV422_Y1(*out_odd) = YUV411_Y13(*in);
- out_odd++;
- in++;
- }
- out_even += width / 2;
- out_odd += width / 2;
- }
+ for (i = height / 2; i--; ) {
+ for (j = width / 4; j--; ) {
+ YUV422_Y0(*out_even) = YUV411_Y00(*in);
+ YUV422_U0(*out_even) = YUV411_U00(*in);
+ YUV422_V0(*out_even) = YUV411_V00(*in);
+ YUV422_Y1(*out_even) = YUV411_Y01(*in);
+ out_even++;
+ YUV422_Y0(*out_even) = YUV411_Y02(*in);
+ YUV422_U0(*out_even) = YUV411_U02(*in);
+ YUV422_V0(*out_even) = YUV411_V02(*in);
+ YUV422_Y1(*out_even) = YUV411_Y03(*in);
+ out_even++;
+ YUV422_Y0(*out_odd) = YUV411_Y10(*in);
+ YUV422_U0(*out_odd) = YUV411_U10(*in);
+ YUV422_V0(*out_odd) = YUV411_V10(*in);
+ YUV422_Y1(*out_odd) = YUV411_Y11(*in);
+ out_odd++;
+ YUV422_Y0(*out_odd) = YUV411_Y12(*in);
+ YUV422_U0(*out_odd) = YUV411_U12(*in);
+ YUV422_V0(*out_odd) = YUV411_V12(*in);
+ YUV422_Y1(*out_odd) = YUV411_Y13(*in);
+ out_odd++;
+ in++;
+ }
+ out_even += width / 2;
+ out_odd += width / 2;
+ }
}
void
yuv_sv411_to_cl422dc_quartersize(int invert, void *data, void *yuv,
- int width, int height)
+ int width, int height)
{
- int w4 = width / 4; /* quarter of width is used often */
- struct yuv411 *in_even = data;
- struct yuv411 *in_odd = in_even + w4;
- struct yuv422 *out_even = yuv;
- struct yuv422 *out_odd = out_even + w4;
- int i, j; /* counters */
- int u, v; /* U and V values */
+ int w4 = width / 4; /* quarter of width is used often */
+ struct yuv411 *in_even = data;
+ struct yuv411 *in_odd = in_even + w4;
+ struct yuv422 *out_even = yuv;
+ struct yuv422 *out_odd = out_even + w4;
+ int i, j; /* counters */
+ int u, v; /* U and V values */
- for (i = height / 4; i--; ) {
- for (j = w4; j--; ) {
- u = YUV411_U00(*in_even);
- v = YUV411_V00(*in_even);
+ for (i = height / 4; i--; ) {
+ for (j = w4; j--; ) {
+ u = YUV411_U00(*in_even);
+ v = YUV411_V00(*in_even);
- YUV422_Y0(*out_even) = YUV411_Y00(*in_even);
- YUV422_U0(*out_even) = u;
- YUV422_V0(*out_even) = v;
- YUV422_Y1(*out_even) = YUV411_Y02(*in_even);
+ YUV422_Y0(*out_even) = YUV411_Y00(*in_even);
+ YUV422_U0(*out_even) = u;
+ YUV422_V0(*out_even) = v;
+ YUV422_Y1(*out_even) = YUV411_Y02(*in_even);
- YUV422_Y0(*out_odd) = YUV411_Y10(*in_odd);
- YUV422_U0(*out_odd) = u;
- YUV422_V0(*out_odd) = v;
- YUV422_Y1(*out_odd) = YUV411_Y12(*in_odd);
+ YUV422_Y0(*out_odd) = YUV411_Y10(*in_odd);
+ YUV422_U0(*out_odd) = u;
+ YUV422_V0(*out_odd) = v;
+ YUV422_Y1(*out_odd) = YUV411_Y12(*in_odd);
- in_even++;
- in_odd++;
- out_even++;
- out_odd++;
- }
- in_even += w4;
- in_odd += w4;
- out_even += w4;
- out_odd += w4;
- }
+ in_even++;
+ in_odd++;
+ out_even++;
+ out_odd++;
+ }
+ in_even += w4;
+ in_odd += w4;
+ out_even += w4;
+ out_odd += w4;
+ }
}
void
yuv_sv411_to_cl422dc_sixteenthsize(int invert, void *data, void *yuv,
- int width, int height)
+ int width, int height)
{
- int w4_3 = 3 * width / 4; /* three quarters of width is used often */
- int w8 = width / 8; /* and so is one eighth */
- struct yuv411 *in_even = data;
- struct yuv411 *in_odd = in_even + width / 2;
- struct yuv422 *out_even = yuv;
- struct yuv422 *out_odd = out_even + w8;
- int i, j; /* counters */
- int u, v; /* U and V values */
+ int w4_3 = 3 * width / 4; /* three quarters of width is used often */
+ int w8 = width / 8; /* and so is one eighth */
+ struct yuv411 *in_even = data;
+ struct yuv411 *in_odd = in_even + width / 2;
+ struct yuv422 *out_even = yuv;
+ struct yuv422 *out_odd = out_even + w8;
+ int i, j; /* counters */
+ int u, v; /* U and V values */
- for (i = height / 8; i--; ) {
- for (j = w8; j--; ) {
- u = YUV411_U00(in_even[0]);
- v = YUV411_V00(in_even[0]);
+ for (i = height / 8; i--; ) {
+ for (j = w8; j--; ) {
+ u = YUV411_U00(in_even[0]);
+ v = YUV411_V00(in_even[0]);
- YUV422_Y0(*out_even) = YUV411_Y00(in_even[0]);
- YUV422_U0(*out_even) = u;
- YUV422_V0(*out_even) = v;
- YUV422_Y1(*out_even) = YUV411_Y00(in_even[1]);
+ YUV422_Y0(*out_even) = YUV411_Y00(in_even[0]);
+ YUV422_U0(*out_even) = u;
+ YUV422_V0(*out_even) = v;
+ YUV422_Y1(*out_even) = YUV411_Y00(in_even[1]);
- YUV422_Y0(*out_odd) = YUV411_Y00(in_odd[0]);
- YUV422_U0(*out_odd) = u;
- YUV422_V0(*out_odd) = v;
- YUV422_Y1(*out_odd) = YUV411_Y00(in_even[1]);
+ YUV422_Y0(*out_odd) = YUV411_Y00(in_odd[0]);
+ YUV422_U0(*out_odd) = u;
+ YUV422_V0(*out_odd) = v;
+ YUV422_Y1(*out_odd) = YUV411_Y00(in_even[1]);
- in_even += 2;
- in_odd += 2;
- out_even++;
- out_odd++;
- }
- in_even += w4_3;
- in_odd += w4_3;
- out_even += w8;
- out_odd += w8;
- }
+ in_even += 2;
+ in_odd += 2;
+ out_even++;
+ out_odd++;
+ }
+ in_even += w4_3;
+ in_odd += w4_3;
+ out_even += w8;
+ out_odd += w8;
+ }
}
diff --git a/Modules/zipimport.c b/Modules/zipimport.c
index e320dd9..18c5a7d 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,162 +60,162 @@ 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 (;;) {
+ path = NULL;
+ prefix = NULL;
+ for (;;) {
#ifndef RISCOS
- 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;
- }
+ 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;
+ }
#else
- if (object_exists(buf)) {
- /* it exists */
- if (isfile(buf))
- /* it's a file */
- path = buf;
- break;
- }
+ if (object_exists(buf)) {
+ /* it exists */
+ if (isfile(buf))
+ /* it's a file */
+ path = buf;
+ break;
+ }
#endif
- /* 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 = PyString_FromString(buf);
- if (self->archive == NULL)
- return -1;
-
- self->prefix = PyString_FromString(prefix);
- if (self->prefix == NULL)
- return -1;
-
- return 0;
+ /* 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 = PyString_FromString(buf);
+ if (self->archive == NULL)
+ return -1;
+
+ self->prefix = PyString_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 buf[500];
- char *archive = "???";
- char *prefix = "";
-
- if (self->archive != NULL && PyString_Check(self->archive))
- archive = PyString_AsString(self->archive);
- if (self->prefix != NULL && PyString_Check(self->prefix))
- prefix = PyString_AsString(self->prefix);
- if (prefix != NULL && *prefix)
- PyOS_snprintf(buf, sizeof(buf),
- "<zipimporter object \"%.300s%c%.150s\">",
- archive, SEP, prefix);
- else
- PyOS_snprintf(buf, sizeof(buf),
- "<zipimporter object \"%.300s\">",
- archive);
- return PyString_FromString(buf);
+ char buf[500];
+ char *archive = "???";
+ char *prefix = "";
+
+ if (self->archive != NULL && PyString_Check(self->archive))
+ archive = PyString_AsString(self->archive);
+ if (self->prefix != NULL && PyString_Check(self->prefix))
+ prefix = PyString_AsString(self->prefix);
+ if (prefix != NULL && *prefix)
+ PyOS_snprintf(buf, sizeof(buf),
+ "<zipimporter object \"%.300s%c%.150s\">",
+ archive, SEP, prefix);
+ else
+ PyOS_snprintf(buf, sizeof(buf),
+ "<zipimporter object \"%.300s\">",
+ archive);
+ return PyString_FromString(buf);
}
/* 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
@@ -224,59 +224,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(PyString_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(PyString_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
@@ -284,89 +284,89 @@ 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 *prefix = PyString_AsString(self->prefix);
- char *subname = get_subname(fullname);
- int err;
-
- fullpath = PyString_FromFormat("%s%c%s%s",
- PyString_AsString(self->archive),
- SEP,
- *prefix ? 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 *prefix = PyString_AsString(self->prefix);
+ char *subname = get_subname(fullname);
+ int err;
+
+ fullpath = PyString_FromFormat("%s%c%s%s",
+ PyString_AsString(self->archive),
+ SEP,
+ *prefix ? 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 */
@@ -380,13 +380,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 PyString_FromString(modpath);
@@ -396,118 +396,118 @@ 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;
+ PyObject *toc_entry;
+ Py_ssize_t len;
- 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
- len = PyString_Size(self->archive);
- if ((size_t)len < strlen(path) &&
- strncmp(path, PyString_AsString(self->archive), 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(PyString_AsString(self->archive), toc_entry);
+ len = PyString_Size(self->archive);
+ if ((size_t)len < strlen(path) &&
+ strncmp(path, PyString_AsString(self->archive), 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(PyString_AsString(self->archive), 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(PyString_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)
- return get_data(PyString_AsString(self->archive), toc_entry);
-
- /* 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(PyString_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)
+ return get_data(PyString_AsString(self->archive), toc_entry);
+
+ /* we have the module, but no source */
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(doc_find_module,
@@ -558,28 +558,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,
@@ -599,46 +599,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_compare */
- (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_compare */
+ (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 */
};
@@ -649,16 +649,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;
}
/*
@@ -670,13 +670,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,
@@ -685,115 +685,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
@@ -803,31 +803,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)
@@ -835,85 +835,85 @@ 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;
- 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 */
-
- raw_data = PyString_FromStringAndSize((char *)NULL, compress == 0 ?
- data_size : data_size + 1);
- if (raw_data == NULL) {
- fclose(fp);
- return NULL;
- }
- buf = PyString_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 */
- return raw_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;
+ 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 */
+
+ raw_data = PyString_FromStringAndSize((char *)NULL, compress == 0 ?
+ data_size : data_size + 1);
+ if (raw_data == NULL) {
+ fclose(fp);
+ return NULL;
+ }
+ buf = PyString_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 */
+ return raw_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
@@ -922,11 +922,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
@@ -937,44 +937,44 @@ eq_mtime(time_t t1, time_t t2)
static PyObject *
unmarshal_code(char *pathname, PyObject *data, time_t mtime)
{
- PyObject *code;
- char *buf = PyString_AsString(data);
- Py_ssize_t size = PyString_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 = PyString_AsString(data);
+ Py_ssize_t size = PyString_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".
@@ -984,35 +984,35 @@ unmarshal_code(char *pathname, PyObject *data, time_t mtime)
static PyObject *
normalize_line_endings(PyObject *source)
{
- char *buf, *q, *p = PyString_AsString(source);
- PyObject *fixed_source;
-
- if (!p)
- return NULL;
-
- /* one char extra for trailing \n and one for terminating \0 */
- buf = (char *)PyMem_Malloc(PyString_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;
- }
- *q++ = '\n'; /* add trailing \n */
- *q = '\0';
- fixed_source = PyString_FromString(buf);
- PyMem_Free(buf);
- return fixed_source;
+ char *buf, *q, *p = PyString_AsString(source);
+ PyObject *fixed_source;
+
+ if (!p)
+ return NULL;
+
+ /* one char extra for trailing \n and one for terminating \0 */
+ buf = (char *)PyMem_Malloc(PyString_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;
+ }
+ *q++ = '\n'; /* add trailing \n */
+ *q = '\0';
+ fixed_source = PyString_FromString(buf);
+ PyMem_Free(buf);
+ return fixed_source;
}
/* Given a string buffer containing Python source code, compile it
@@ -1020,16 +1020,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(PyString_AsString(fixed_source), pathname,
- Py_file_input);
- Py_DECREF(fixed_source);
- return code;
+ code = Py_CompileString(PyString_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
@@ -1037,19 +1037,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
@@ -1058,106 +1058,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 = PyInt_AsLong(PyTuple_GetItem(toc_entry, 5));
- date = PyInt_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 = PyInt_AsLong(PyTuple_GetItem(toc_entry, 5));
+ date = PyInt_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 = PyString_AsString(self->archive);
-
- if (archive == NULL)
- return NULL;
-
- data = get_data(archive, toc_entry);
- if (data == NULL)
- return NULL;
-
- modpath = PyString_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 = PyString_AsString(self->archive);
+
+ if (archive == NULL)
+ return NULL;
+
+ data = get_data(archive, toc_entry);
+ if (data == NULL)
+ return NULL;
+
+ modpath = PyString_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(PyString_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",
- PyString_AsString(self->archive),
- 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 = PyString_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(PyString_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",
+ PyString_AsString(self->archive),
+ 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 = PyString_AsString(
+ PyTuple_GetItem(toc_entry, 0));
+ return code;
+ }
+ }
+ PyErr_Format(ZipImportError, "can't find module '%.200s'", fullname);
+ return NULL;
}
@@ -1180,51 +1180,51 @@ to Zip archives.");
PyMODINIT_FUNC
initzipimport(void)
{
- PyObject *mod;
-
- if (PyType_Ready(&ZipImporter_Type) < 0)
- return;
-
- /* 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 = Py_InitModule4("zipimport", NULL, zipimport_doc,
- NULL, PYTHON_API_VERSION);
- if (mod == NULL)
- return;
-
- ZipImportError = PyErr_NewException("zipimport.ZipImportError",
- PyExc_ImportError, NULL);
- if (ZipImportError == NULL)
- return;
-
- Py_INCREF(ZipImportError);
- if (PyModule_AddObject(mod, "ZipImportError",
- ZipImportError) < 0)
- return;
-
- Py_INCREF(&ZipImporter_Type);
- if (PyModule_AddObject(mod, "zipimporter",
- (PyObject *)&ZipImporter_Type) < 0)
- return;
-
- zip_directory_cache = PyDict_New();
- if (zip_directory_cache == NULL)
- return;
- Py_INCREF(zip_directory_cache);
- if (PyModule_AddObject(mod, "_zip_directory_cache",
- zip_directory_cache) < 0)
- return;
+ PyObject *mod;
+
+ if (PyType_Ready(&ZipImporter_Type) < 0)
+ return;
+
+ /* 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 = Py_InitModule4("zipimport", NULL, zipimport_doc,
+ NULL, PYTHON_API_VERSION);
+ if (mod == NULL)
+ return;
+
+ ZipImportError = PyErr_NewException("zipimport.ZipImportError",
+ PyExc_ImportError, NULL);
+ if (ZipImportError == NULL)
+ return;
+
+ Py_INCREF(ZipImportError);
+ if (PyModule_AddObject(mod, "ZipImportError",
+ ZipImportError) < 0)
+ return;
+
+ Py_INCREF(&ZipImporter_Type);
+ if (PyModule_AddObject(mod, "zipimporter",
+ (PyObject *)&ZipImporter_Type) < 0)
+ return;
+
+ zip_directory_cache = PyDict_New();
+ if (zip_directory_cache == NULL)
+ return;
+ Py_INCREF(zip_directory_cache);
+ if (PyModule_AddObject(mod, "_zip_directory_cache",
+ zip_directory_cache) < 0)
+ return;
}
diff --git a/Modules/zlibmodule.c b/Modules/zlibmodule.c
index 0cb1e64..bb52fdc 100644
--- a/Modules/zlibmodule.c
+++ b/Modules/zlibmodule.c
@@ -28,12 +28,12 @@
static PyThread_type_lock zlib_lock = NULL; /* initialized on module load */
#define ENTER_ZLIB \
- Py_BEGIN_ALLOW_THREADS \
- PyThread_acquire_lock(zlib_lock, 1); \
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS \
+ PyThread_acquire_lock(zlib_lock, 1); \
+ Py_END_ALLOW_THREADS
#define LEAVE_ZLIB \
- PyThread_release_lock(zlib_lock);
+ PyThread_release_lock(zlib_lock);
#else
@@ -73,9 +73,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__,
@@ -94,17 +94,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 = PyString_FromString("");
if (self->unused_data == NULL) {
- Py_DECREF(self);
- return NULL;
+ Py_DECREF(self);
+ return NULL;
}
self->unconsumed_tail = PyString_FromString("");
if (self->unconsumed_tail == NULL) {
- Py_DECREF(self);
- return NULL;
+ Py_DECREF(self);
+ return NULL;
}
return self;
}
@@ -124,15 +124,15 @@ PyZlib_compress(PyObject *self, PyObject *args)
/* require Python string object, optional 'level' arg */
if (!PyArg_ParseTuple(args, "s#|i:compress", &input, &length, &level))
- return NULL;
+ return NULL;
zst.avail_out = length + length/1000 + 12 + 1;
output = (Byte*)malloc(zst.avail_out);
if (output == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Can't allocate memory to compress data");
- return NULL;
+ 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
@@ -147,19 +147,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;
@@ -167,17 +167,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 = PyString_FromStringAndSize((char *)output,
- zst.total_out);
+ ReturnVal = PyString_FromStringAndSize((char *)output,
+ zst.total_out);
else
- zlib_error(zst, err, "while finishing compression");
+ zlib_error(zst, err, "while finishing compression");
error:
free(output);
@@ -202,17 +202,17 @@ PyZlib_decompress(PyObject *self, PyObject *args)
z_stream zst;
if (!PyArg_ParseTuple(args, "s#|in:decompress",
- &input, &length, &wsize, &r_strlen))
- return NULL;
+ &input, &length, &wsize, &r_strlen))
+ return NULL;
if (r_strlen <= 0)
- r_strlen = 1;
+ r_strlen = 1;
zst.avail_in = length;
zst.avail_out = r_strlen;
if (!(result_str = PyString_FromStringAndSize(NULL, r_strlen)))
- return NULL;
+ return NULL;
zst.zalloc = (alloc_func)NULL;
zst.zfree = (free_func)Z_NULL;
@@ -222,60 +222,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 (_PyString_Resize(&result_str, r_strlen << 1) < 0) {
- inflateEnd(&zst);
- goto error;
- }
- zst.next_out = (unsigned char *)PyString_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;
- }
+ 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 (_PyString_Resize(&result_str, r_strlen << 1) < 0) {
+ inflateEnd(&zst);
+ goto error;
+ }
+ zst.next_out = (unsigned char *)PyString_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;
+ }
} 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;
}
_PyString_Resize(&result_str, zst.total_out);
@@ -294,12 +294,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;
@@ -307,21 +307,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;
}
}
@@ -331,11 +331,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;
@@ -343,21 +343,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;
}
}
@@ -365,7 +365,7 @@ static void
Comp_dealloc(compobject *self)
{
if (self->is_initialised)
- deflateEnd(&self->zst);
+ deflateEnd(&self->zst);
Py_XDECREF(self->unused_data);
Py_XDECREF(self->unconsumed_tail);
PyObject_Del(self);
@@ -375,7 +375,7 @@ static void
Decomp_dealloc(compobject *self)
{
if (self->is_initialised)
- inflateEnd(&self->zst);
+ inflateEnd(&self->zst);
Py_XDECREF(self->unused_data);
Py_XDECREF(self->unconsumed_tail);
PyObject_Del(self);
@@ -399,10 +399,10 @@ PyZlib_objcompress(compobject *self, PyObject *args)
unsigned long start_total_out;
if (!PyArg_ParseTuple(args, "s#:compress", &input, &inplen))
- return NULL;
+ return NULL;
if (!(RetVal = PyString_FromStringAndSize(NULL, length)))
- return NULL;
+ return NULL;
ENTER_ZLIB
@@ -419,16 +419,16 @@ 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 (_PyString_Resize(&RetVal, length << 1) < 0)
- goto error;
- self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
- + length;
- self->zst.avail_out = length;
- length = length << 1;
-
- Py_BEGIN_ALLOW_THREADS
- err = deflate(&(self->zst), Z_NO_FLUSH);
- Py_END_ALLOW_THREADS
+ if (_PyString_Resize(&RetVal, length << 1) < 0)
+ goto error;
+ self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
+ + length;
+ self->zst.avail_out = length;
+ length = length << 1;
+
+ 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
@@ -436,10 +436,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;
}
_PyString_Resize(&RetVal, self->zst.total_out - start_total_out);
@@ -469,19 +469,19 @@ PyZlib_objdecompress(compobject *self, PyObject *args)
unsigned long start_total_out;
if (!PyArg_ParseTuple(args, "s#|i:decompress", &input,
- &inplen, &max_length))
- return NULL;
+ &inplen, &max_length))
+ return NULL;
if (max_length < 0) {
- PyErr_SetString(PyExc_ValueError,
- "max_length must be greater than zero");
- return NULL;
+ 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 = PyString_FromStringAndSize(NULL, length)))
- return NULL;
+ return NULL;
ENTER_ZLIB
@@ -499,40 +499,40 @@ 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 (_PyString_Resize(&RetVal, length) < 0)
- goto error;
- self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
- + old_length;
- self->zst.avail_out = length - old_length;
-
- Py_BEGIN_ALLOW_THREADS
- err = inflate(&(self->zst), Z_SYNC_FLUSH);
- Py_END_ALLOW_THREADS
+ /* 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 (_PyString_Resize(&RetVal, length) < 0)
+ goto error;
+ self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
+ + old_length;
+ self->zst.avail_out = length - old_length;
+
+ 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 = PyString_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 = PyString_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
@@ -542,22 +542,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 = PyString_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 = PyString_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;
}
_PyString_Resize(&RetVal, self->zst.total_out - start_total_out);
@@ -585,16 +585,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 PyString_FromStringAndSize(NULL, 0);
+ return PyString_FromStringAndSize(NULL, 0);
}
if (!(RetVal = PyString_FromStringAndSize(NULL, length)))
- return NULL;
+ return NULL;
ENTER_ZLIB
@@ -610,41 +610,41 @@ 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 (_PyString_Resize(&RetVal, length << 1) < 0)
- goto error;
- self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
- + length;
- self->zst.avail_out = length;
- length = length << 1;
-
- Py_BEGIN_ALLOW_THREADS
- err = deflate(&(self->zst), flushmode);
- Py_END_ALLOW_THREADS
+ if (_PyString_Resize(&RetVal, length << 1) < 0)
+ goto error;
+ self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
+ + length;
+ self->zst.avail_out = length;
+ length = length << 1;
+
+ 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;
}
_PyString_Resize(&RetVal, self->zst.total_out - start_total_out);
@@ -774,13 +774,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 = PyString_FromStringAndSize(NULL, length)))
- return NULL;
+ return NULL;
ENTER_ZLIB
@@ -796,29 +796,29 @@ 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 (_PyString_Resize(&retval, length << 1) < 0)
- goto error;
- self->zst.next_out = (Byte *)PyString_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
+ if (_PyString_Resize(&retval, length << 1) < 0)
+ goto error;
+ self->zst.next_out = (Byte *)PyString_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
}
/* 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;
+ }
}
_PyString_Resize(&retval, self->zst.total_out - start_total_out);
@@ -872,13 +872,13 @@ Decomp_getattr(compobject *self, char *name)
ENTER_ZLIB
if (strcmp(name, "unused_data") == 0) {
- Py_INCREF(self->unused_data);
- retval = self->unused_data;
+ Py_INCREF(self->unused_data);
+ retval = self->unused_data;
} else if (strcmp(name, "unconsumed_tail") == 0) {
- Py_INCREF(self->unconsumed_tail);
- retval = self->unconsumed_tail;
+ Py_INCREF(self->unconsumed_tail);
+ retval = self->unconsumed_tail;
} else
- retval = Py_FindMethod(Decomp_methods, (PyObject *)self, name);
+ retval = Py_FindMethod(Decomp_methods, (PyObject *)self, name);
LEAVE_ZLIB
@@ -899,7 +899,7 @@ PyZlib_adler32(PyObject *self, PyObject *args)
int len, signed_val;
if (!PyArg_ParseTuple(args, "s#|I:adler32", &buf, &len, &adler32val))
- return NULL;
+ return NULL;
/* In Python 2.x we return a signed integer regardless of native platform
* long size (the 32bit unsigned long is treated as 32-bit signed and sign
* extended into a 64-bit long inside the integer object). 3.0 does the
@@ -922,7 +922,7 @@ PyZlib_crc32(PyObject *self, PyObject *args)
int len, signed_val;
if (!PyArg_ParseTuple(args, "s#|I:crc32", &buf, &len, &crc32val))
- return NULL;
+ return NULL;
/* In Python 2.x we return a signed integer regardless of native platform
* long size (the 32bit unsigned long is treated as 32-bit signed and sign
* extended into a 64-bit long inside the integer object). 3.0 does the
@@ -1003,15 +1003,15 @@ PyInit_zlib(void)
Py_TYPE(&Comptype) = &PyType_Type;
Py_TYPE(&Decomptype) = &PyType_Type;
m = Py_InitModule4("zlib", zlib_methods,
- zlib_module_documentation,
- (PyObject*)NULL,PYTHON_API_VERSION);
+ zlib_module_documentation,
+ (PyObject*)NULL,PYTHON_API_VERSION);
if (m == NULL)
- return;
+ return;
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);
@@ -1030,7 +1030,7 @@ PyInit_zlib(void)
ver = PyString_FromString(ZLIB_VERSION);
if (ver != NULL)
- PyModule_AddObject(m, "ZLIB_VERSION", ver);
+ PyModule_AddObject(m, "ZLIB_VERSION", ver);
PyModule_AddStringConstant(m, "__version__", "1.0");