--- /dev/null
+/* Abstract Object Interface (many thanks to Jim Fulton) */\r
+\r
+#include "Python.h"\r
+#include <ctype.h>\r
+#include "structmember.h" /* we need the offsetof() macro from there */\r
+#include "longintrepr.h"\r
+\r
+#define NEW_STYLE_NUMBER(o) PyType_HasFeature((o)->ob_type, \\r
+ Py_TPFLAGS_CHECKTYPES)\r
+\r
+\r
+/* Shorthands to return certain errors */\r
+\r
+static PyObject *\r
+type_error(const char *msg, PyObject *obj)\r
+{\r
+ PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name);\r
+ return NULL;\r
+}\r
+\r
+static PyObject *\r
+null_error(void)\r
+{\r
+ if (!PyErr_Occurred())\r
+ PyErr_SetString(PyExc_SystemError,\r
+ "null argument to internal routine");\r
+ return NULL;\r
+}\r
+\r
+/* Operations on any object */\r
+\r
+int\r
+PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)\r
+{\r
+ int r;\r
+\r
+ if (o1 == NULL || o2 == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+ r = PyObject_Compare(o1, o2);\r
+ if (PyErr_Occurred())\r
+ return -1;\r
+ *result = r;\r
+ return 0;\r
+}\r
+\r
+PyObject *\r
+PyObject_Type(PyObject *o)\r
+{\r
+ PyObject *v;\r
+\r
+ if (o == NULL)\r
+ return null_error();\r
+ v = (PyObject *)o->ob_type;\r
+ Py_INCREF(v);\r
+ return v;\r
+}\r
+\r
+Py_ssize_t\r
+PyObject_Size(PyObject *o)\r
+{\r
+ PySequenceMethods *m;\r
+\r
+ if (o == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+\r
+ m = o->ob_type->tp_as_sequence;\r
+ if (m && m->sq_length)\r
+ return m->sq_length(o);\r
+\r
+ return PyMapping_Size(o);\r
+}\r
+\r
+#undef PyObject_Length\r
+Py_ssize_t\r
+PyObject_Length(PyObject *o)\r
+{\r
+ return PyObject_Size(o);\r
+}\r
+#define PyObject_Length PyObject_Size\r
+\r
+\r
+/* The length hint function returns a non-negative value from o.__len__()\r
+ or o.__length_hint__(). If those methods aren't found or return a negative\r
+ value, then the defaultvalue is returned. If one of the calls fails,\r
+ this function returns -1.\r
+*/\r
+\r
+Py_ssize_t\r
+_PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)\r
+{\r
+ static PyObject *hintstrobj = NULL;\r
+ PyObject *ro, *hintmeth;\r
+ Py_ssize_t rv;\r
+\r
+ /* try o.__len__() */\r
+ rv = PyObject_Size(o);\r
+ if (rv >= 0)\r
+ return rv;\r
+ if (PyErr_Occurred()) {\r
+ if (!PyErr_ExceptionMatches(PyExc_TypeError) &&\r
+ !PyErr_ExceptionMatches(PyExc_AttributeError))\r
+ return -1;\r
+ PyErr_Clear();\r
+ }\r
+\r
+ if (PyInstance_Check(o))\r
+ return defaultvalue;\r
+ /* try o.__length_hint__() */\r
+ hintmeth = _PyObject_LookupSpecial(o, "__length_hint__", &hintstrobj);\r
+ if (hintmeth == NULL) {\r
+ if (PyErr_Occurred())\r
+ return -1;\r
+ else\r
+ return defaultvalue;\r
+ }\r
+ ro = PyObject_CallFunctionObjArgs(hintmeth, NULL);\r
+ Py_DECREF(hintmeth);\r
+ if (ro == NULL) {\r
+ if (!PyErr_ExceptionMatches(PyExc_TypeError) &&\r
+ !PyErr_ExceptionMatches(PyExc_AttributeError))\r
+ return -1;\r
+ PyErr_Clear();\r
+ return defaultvalue;\r
+ }\r
+ rv = PyNumber_Check(ro) ? PyInt_AsSsize_t(ro) : defaultvalue;\r
+ Py_DECREF(ro);\r
+ return rv;\r
+}\r
+\r
+PyObject *\r
+PyObject_GetItem(PyObject *o, PyObject *key)\r
+{\r
+ PyMappingMethods *m;\r
+\r
+ if (o == NULL || key == NULL)\r
+ return null_error();\r
+\r
+ m = o->ob_type->tp_as_mapping;\r
+ if (m && m->mp_subscript)\r
+ return m->mp_subscript(o, key);\r
+\r
+ if (o->ob_type->tp_as_sequence) {\r
+ if (PyIndex_Check(key)) {\r
+ Py_ssize_t key_value;\r
+ key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);\r
+ if (key_value == -1 && PyErr_Occurred())\r
+ return NULL;\r
+ return PySequence_GetItem(o, key_value);\r
+ }\r
+ else if (o->ob_type->tp_as_sequence->sq_item)\r
+ return type_error("sequence index must "\r
+ "be integer, not '%.200s'", key);\r
+ }\r
+\r
+ return type_error("'%.200s' object has no attribute '__getitem__'", o);\r
+}\r
+\r
+int\r
+PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)\r
+{\r
+ PyMappingMethods *m;\r
+\r
+ if (o == NULL || key == NULL || value == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+ m = o->ob_type->tp_as_mapping;\r
+ if (m && m->mp_ass_subscript)\r
+ return m->mp_ass_subscript(o, key, value);\r
+\r
+ if (o->ob_type->tp_as_sequence) {\r
+ if (PyIndex_Check(key)) {\r
+ Py_ssize_t key_value;\r
+ key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);\r
+ if (key_value == -1 && PyErr_Occurred())\r
+ return -1;\r
+ return PySequence_SetItem(o, key_value, value);\r
+ }\r
+ else if (o->ob_type->tp_as_sequence->sq_ass_item) {\r
+ type_error("sequence index must be "\r
+ "integer, not '%.200s'", key);\r
+ return -1;\r
+ }\r
+ }\r
+\r
+ type_error("'%.200s' object does not support item assignment", o);\r
+ return -1;\r
+}\r
+\r
+int\r
+PyObject_DelItem(PyObject *o, PyObject *key)\r
+{\r
+ PyMappingMethods *m;\r
+\r
+ if (o == NULL || key == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+ m = o->ob_type->tp_as_mapping;\r
+ if (m && m->mp_ass_subscript)\r
+ return m->mp_ass_subscript(o, key, (PyObject*)NULL);\r
+\r
+ if (o->ob_type->tp_as_sequence) {\r
+ if (PyIndex_Check(key)) {\r
+ Py_ssize_t key_value;\r
+ key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);\r
+ if (key_value == -1 && PyErr_Occurred())\r
+ return -1;\r
+ return PySequence_DelItem(o, key_value);\r
+ }\r
+ else if (o->ob_type->tp_as_sequence->sq_ass_item) {\r
+ type_error("sequence index must be "\r
+ "integer, not '%.200s'", key);\r
+ return -1;\r
+ }\r
+ }\r
+\r
+ type_error("'%.200s' object does not support item deletion", o);\r
+ return -1;\r
+}\r
+\r
+int\r
+PyObject_DelItemString(PyObject *o, char *key)\r
+{\r
+ PyObject *okey;\r
+ int ret;\r
+\r
+ if (o == NULL || key == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+ okey = PyString_FromString(key);\r
+ if (okey == NULL)\r
+ return -1;\r
+ ret = PyObject_DelItem(o, okey);\r
+ Py_DECREF(okey);\r
+ return ret;\r
+}\r
+\r
+int\r
+PyObject_AsCharBuffer(PyObject *obj,\r
+ const char **buffer,\r
+ Py_ssize_t *buffer_len)\r
+{\r
+ PyBufferProcs *pb;\r
+ char *pp;\r
+ Py_ssize_t len;\r
+\r
+ if (obj == NULL || buffer == NULL || buffer_len == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+ pb = obj->ob_type->tp_as_buffer;\r
+ if (pb == NULL ||\r
+ pb->bf_getcharbuffer == NULL ||\r
+ pb->bf_getsegcount == NULL) {\r
+ PyErr_SetString(PyExc_TypeError,\r
+ "expected a character buffer object");\r
+ return -1;\r
+ }\r
+ if ((*pb->bf_getsegcount)(obj,NULL) != 1) {\r
+ PyErr_SetString(PyExc_TypeError,\r
+ "expected a single-segment buffer object");\r
+ return -1;\r
+ }\r
+ len = (*pb->bf_getcharbuffer)(obj, 0, &pp);\r
+ if (len < 0)\r
+ return -1;\r
+ *buffer = pp;\r
+ *buffer_len = len;\r
+ return 0;\r
+}\r
+\r
+int\r
+PyObject_CheckReadBuffer(PyObject *obj)\r
+{\r
+ PyBufferProcs *pb = obj->ob_type->tp_as_buffer;\r
+\r
+ if (pb == NULL ||\r
+ pb->bf_getreadbuffer == NULL ||\r
+ pb->bf_getsegcount == NULL ||\r
+ (*pb->bf_getsegcount)(obj, NULL) != 1)\r
+ return 0;\r
+ return 1;\r
+}\r
+\r
+int PyObject_AsReadBuffer(PyObject *obj,\r
+ const void **buffer,\r
+ Py_ssize_t *buffer_len)\r
+{\r
+ PyBufferProcs *pb;\r
+ void *pp;\r
+ Py_ssize_t len;\r
+\r
+ if (obj == NULL || buffer == NULL || buffer_len == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+ pb = obj->ob_type->tp_as_buffer;\r
+ if (pb == NULL ||\r
+ pb->bf_getreadbuffer == NULL ||\r
+ pb->bf_getsegcount == NULL) {\r
+ PyErr_SetString(PyExc_TypeError,\r
+ "expected a readable buffer object");\r
+ return -1;\r
+ }\r
+ if ((*pb->bf_getsegcount)(obj, NULL) != 1) {\r
+ PyErr_SetString(PyExc_TypeError,\r
+ "expected a single-segment buffer object");\r
+ return -1;\r
+ }\r
+ len = (*pb->bf_getreadbuffer)(obj, 0, &pp);\r
+ if (len < 0)\r
+ return -1;\r
+ *buffer = pp;\r
+ *buffer_len = len;\r
+ return 0;\r
+}\r
+\r
+int PyObject_AsWriteBuffer(PyObject *obj,\r
+ void **buffer,\r
+ Py_ssize_t *buffer_len)\r
+{\r
+ PyBufferProcs *pb;\r
+ void*pp;\r
+ Py_ssize_t len;\r
+\r
+ if (obj == NULL || buffer == NULL || buffer_len == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+ pb = obj->ob_type->tp_as_buffer;\r
+ if (pb == NULL ||\r
+ pb->bf_getwritebuffer == NULL ||\r
+ pb->bf_getsegcount == NULL) {\r
+ PyErr_SetString(PyExc_TypeError,\r
+ "expected a writeable buffer object");\r
+ return -1;\r
+ }\r
+ if ((*pb->bf_getsegcount)(obj, NULL) != 1) {\r
+ PyErr_SetString(PyExc_TypeError,\r
+ "expected a single-segment buffer object");\r
+ return -1;\r
+ }\r
+ len = (*pb->bf_getwritebuffer)(obj,0,&pp);\r
+ if (len < 0)\r
+ return -1;\r
+ *buffer = pp;\r
+ *buffer_len = len;\r
+ return 0;\r
+}\r
+\r
+/* Buffer C-API for Python 3.0 */\r
+\r
+int\r
+PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)\r
+{\r
+ if (!PyObject_CheckBuffer(obj)) {\r
+ PyErr_Format(PyExc_TypeError,\r
+ "'%100s' does not have the buffer interface",\r
+ Py_TYPE(obj)->tp_name);\r
+ return -1;\r
+ }\r
+ return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags);\r
+}\r
+\r
+static int\r
+_IsFortranContiguous(Py_buffer *view)\r
+{\r
+ Py_ssize_t sd, dim;\r
+ int i;\r
+\r
+ if (view->ndim == 0) return 1;\r
+ if (view->strides == NULL) return (view->ndim == 1);\r
+\r
+ sd = view->itemsize;\r
+ if (view->ndim == 1) return (view->shape[0] == 1 ||\r
+ sd == view->strides[0]);\r
+ for (i=0; i<view->ndim; i++) {\r
+ dim = view->shape[i];\r
+ if (dim == 0) return 1;\r
+ if (view->strides[i] != sd) return 0;\r
+ sd *= dim;\r
+ }\r
+ return 1;\r
+}\r
+\r
+static int\r
+_IsCContiguous(Py_buffer *view)\r
+{\r
+ Py_ssize_t sd, dim;\r
+ int i;\r
+\r
+ if (view->ndim == 0) return 1;\r
+ if (view->strides == NULL) return 1;\r
+\r
+ sd = view->itemsize;\r
+ if (view->ndim == 1) return (view->shape[0] == 1 ||\r
+ sd == view->strides[0]);\r
+ for (i=view->ndim-1; i>=0; i--) {\r
+ dim = view->shape[i];\r
+ if (dim == 0) return 1;\r
+ if (view->strides[i] != sd) return 0;\r
+ sd *= dim;\r
+ }\r
+ return 1;\r
+}\r
+\r
+int\r
+PyBuffer_IsContiguous(Py_buffer *view, char fort)\r
+{\r
+\r
+ if (view->suboffsets != NULL) return 0;\r
+\r
+ if (fort == 'C')\r
+ return _IsCContiguous(view);\r
+ else if (fort == 'F')\r
+ return _IsFortranContiguous(view);\r
+ else if (fort == 'A')\r
+ return (_IsCContiguous(view) || _IsFortranContiguous(view));\r
+ return 0;\r
+}\r
+\r
+\r
+void*\r
+PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)\r
+{\r
+ char* pointer;\r
+ int i;\r
+ pointer = (char *)view->buf;\r
+ for (i = 0; i < view->ndim; i++) {\r
+ pointer += view->strides[i]*indices[i];\r
+ if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {\r
+ pointer = *((char**)pointer) + view->suboffsets[i];\r
+ }\r
+ }\r
+ return (void*)pointer;\r
+}\r
+\r
+\r
+void\r
+_Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape)\r
+{\r
+ int k;\r
+\r
+ for (k=0; k<nd; k++) {\r
+ if (index[k] < shape[k]-1) {\r
+ index[k]++;\r
+ break;\r
+ }\r
+ else {\r
+ index[k] = 0;\r
+ }\r
+ }\r
+}\r
+\r
+void\r
+_Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape)\r
+{\r
+ int k;\r
+\r
+ for (k=nd-1; k>=0; k--) {\r
+ if (index[k] < shape[k]-1) {\r
+ index[k]++;\r
+ break;\r
+ }\r
+ else {\r
+ index[k] = 0;\r
+ }\r
+ }\r
+}\r
+\r
+ /* view is not checked for consistency in either of these. It is\r
+ assumed that the size of the buffer is view->len in\r
+ view->len / view->itemsize elements.\r
+ */\r
+\r
+int\r
+PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort)\r
+{\r
+ int k;\r
+ void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);\r
+ Py_ssize_t *indices, elements;\r
+ char *dest, *ptr;\r
+\r
+ if (len > view->len) {\r
+ len = view->len;\r
+ }\r
+\r
+ if (PyBuffer_IsContiguous(view, fort)) {\r
+ /* simplest copy is all that is needed */\r
+ memcpy(buf, view->buf, len);\r
+ return 0;\r
+ }\r
+\r
+ /* Otherwise a more elaborate scheme is needed */\r
+\r
+ /* view->ndim <= 64 */\r
+ indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));\r
+ if (indices == NULL) {\r
+ PyErr_NoMemory();\r
+ return -1;\r
+ }\r
+ for (k=0; k<view->ndim;k++) {\r
+ indices[k] = 0;\r
+ }\r
+\r
+ if (fort == 'F') {\r
+ addone = _Py_add_one_to_index_F;\r
+ }\r
+ else {\r
+ addone = _Py_add_one_to_index_C;\r
+ }\r
+ dest = buf;\r
+ /* XXX : This is not going to be the fastest code in the world\r
+ several optimizations are possible.\r
+ */\r
+ elements = len / view->itemsize;\r
+ while (elements--) {\r
+ ptr = PyBuffer_GetPointer(view, indices);\r
+ memcpy(dest, ptr, view->itemsize);\r
+ dest += view->itemsize;\r
+ addone(view->ndim, indices, view->shape);\r
+ }\r
+ PyMem_Free(indices);\r
+ return 0;\r
+}\r
+\r
+int\r
+PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)\r
+{\r
+ int k;\r
+ void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);\r
+ Py_ssize_t *indices, elements;\r
+ char *src, *ptr;\r
+\r
+ if (len > view->len) {\r
+ len = view->len;\r
+ }\r
+\r
+ if (PyBuffer_IsContiguous(view, fort)) {\r
+ /* simplest copy is all that is needed */\r
+ memcpy(view->buf, buf, len);\r
+ return 0;\r
+ }\r
+\r
+ /* Otherwise a more elaborate scheme is needed */\r
+\r
+ /* view->ndim <= 64 */\r
+ indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));\r
+ if (indices == NULL) {\r
+ PyErr_NoMemory();\r
+ return -1;\r
+ }\r
+ for (k=0; k<view->ndim;k++) {\r
+ indices[k] = 0;\r
+ }\r
+\r
+ if (fort == 'F') {\r
+ addone = _Py_add_one_to_index_F;\r
+ }\r
+ else {\r
+ addone = _Py_add_one_to_index_C;\r
+ }\r
+ src = buf;\r
+ /* XXX : This is not going to be the fastest code in the world\r
+ several optimizations are possible.\r
+ */\r
+ elements = len / view->itemsize;\r
+ while (elements--) {\r
+ ptr = PyBuffer_GetPointer(view, indices);\r
+ memcpy(ptr, src, view->itemsize);\r
+ src += view->itemsize;\r
+ addone(view->ndim, indices, view->shape);\r
+ }\r
+\r
+ PyMem_Free(indices);\r
+ return 0;\r
+}\r
+\r
+int PyObject_CopyData(PyObject *dest, PyObject *src)\r
+{\r
+ Py_buffer view_dest, view_src;\r
+ int k;\r
+ Py_ssize_t *indices, elements;\r
+ char *dptr, *sptr;\r
+\r
+ if (!PyObject_CheckBuffer(dest) ||\r
+ !PyObject_CheckBuffer(src)) {\r
+ PyErr_SetString(PyExc_TypeError,\r
+ "both destination and source must have the "\\r
+ "buffer interface");\r
+ return -1;\r
+ }\r
+\r
+ if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;\r
+ if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {\r
+ PyBuffer_Release(&view_dest);\r
+ return -1;\r
+ }\r
+\r
+ if (view_dest.len < view_src.len) {\r
+ PyErr_SetString(PyExc_BufferError,\r
+ "destination is too small to receive data from source");\r
+ PyBuffer_Release(&view_dest);\r
+ PyBuffer_Release(&view_src);\r
+ return -1;\r
+ }\r
+\r
+ if ((PyBuffer_IsContiguous(&view_dest, 'C') &&\r
+ PyBuffer_IsContiguous(&view_src, 'C')) ||\r
+ (PyBuffer_IsContiguous(&view_dest, 'F') &&\r
+ PyBuffer_IsContiguous(&view_src, 'F'))) {\r
+ /* simplest copy is all that is needed */\r
+ memcpy(view_dest.buf, view_src.buf, view_src.len);\r
+ PyBuffer_Release(&view_dest);\r
+ PyBuffer_Release(&view_src);\r
+ return 0;\r
+ }\r
+\r
+ /* Otherwise a more elaborate copy scheme is needed */\r
+\r
+ /* XXX(nnorwitz): need to check for overflow! */\r
+ indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);\r
+ if (indices == NULL) {\r
+ PyErr_NoMemory();\r
+ PyBuffer_Release(&view_dest);\r
+ PyBuffer_Release(&view_src);\r
+ return -1;\r
+ }\r
+ for (k=0; k<view_src.ndim;k++) {\r
+ indices[k] = 0;\r
+ }\r
+ elements = 1;\r
+ for (k=0; k<view_src.ndim; k++) {\r
+ /* XXX(nnorwitz): can this overflow? */\r
+ elements *= view_src.shape[k];\r
+ }\r
+ while (elements--) {\r
+ _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);\r
+ dptr = PyBuffer_GetPointer(&view_dest, indices);\r
+ sptr = PyBuffer_GetPointer(&view_src, indices);\r
+ memcpy(dptr, sptr, view_src.itemsize);\r
+ }\r
+ PyMem_Free(indices);\r
+ PyBuffer_Release(&view_dest);\r
+ PyBuffer_Release(&view_src);\r
+ return 0;\r
+}\r
+\r
+void\r
+PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,\r
+ Py_ssize_t *strides, int itemsize,\r
+ char fort)\r
+{\r
+ int k;\r
+ Py_ssize_t sd;\r
+\r
+ sd = itemsize;\r
+ if (fort == 'F') {\r
+ for (k=0; k<nd; k++) {\r
+ strides[k] = sd;\r
+ sd *= shape[k];\r
+ }\r
+ }\r
+ else {\r
+ for (k=nd-1; k>=0; k--) {\r
+ strides[k] = sd;\r
+ sd *= shape[k];\r
+ }\r
+ }\r
+ return;\r
+}\r
+\r
+int\r
+PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,\r
+ int readonly, int flags)\r
+{\r
+ if (view == NULL) return 0;\r
+ if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&\r
+ (readonly == 1)) {\r
+ PyErr_SetString(PyExc_BufferError,\r
+ "Object is not writable.");\r
+ return -1;\r
+ }\r
+\r
+ view->obj = obj;\r
+ if (obj)\r
+ Py_INCREF(obj);\r
+ view->buf = buf;\r
+ view->len = len;\r
+ view->readonly = readonly;\r
+ view->itemsize = 1;\r
+ view->format = NULL;\r
+ if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)\r
+ view->format = "B";\r
+ view->ndim = 1;\r
+ view->shape = NULL;\r
+ if ((flags & PyBUF_ND) == PyBUF_ND)\r
+ view->shape = &(view->len);\r
+ view->strides = NULL;\r
+ if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)\r
+ view->strides = &(view->itemsize);\r
+ view->suboffsets = NULL;\r
+ view->internal = NULL;\r
+ return 0;\r
+}\r
+\r
+void\r
+PyBuffer_Release(Py_buffer *view)\r
+{\r
+ PyObject *obj = view->obj;\r
+ if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer)\r
+ Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view);\r
+ Py_XDECREF(obj);\r
+ view->obj = NULL;\r
+}\r
+\r
+PyObject *\r
+PyObject_Format(PyObject* obj, PyObject *format_spec)\r
+{\r
+ PyObject *empty = NULL;\r
+ PyObject *result = NULL;\r
+#ifdef Py_USING_UNICODE\r
+ int spec_is_unicode;\r
+ int result_is_unicode;\r
+#endif\r
+\r
+ /* If no format_spec is provided, use an empty string */\r
+ if (format_spec == NULL) {\r
+ empty = PyString_FromStringAndSize(NULL, 0);\r
+ format_spec = empty;\r
+ }\r
+\r
+ /* Check the format_spec type, and make sure it's str or unicode */\r
+#ifdef Py_USING_UNICODE\r
+ if (PyUnicode_Check(format_spec))\r
+ spec_is_unicode = 1;\r
+ else if (PyString_Check(format_spec))\r
+ spec_is_unicode = 0;\r
+ else {\r
+#else\r
+ if (!PyString_Check(format_spec)) {\r
+#endif\r
+ PyErr_Format(PyExc_TypeError,\r
+ "format expects arg 2 to be string "\r
+ "or unicode, not %.100s", Py_TYPE(format_spec)->tp_name);\r
+ goto done;\r
+ }\r
+\r
+ /* Check for a __format__ method and call it. */\r
+ if (PyInstance_Check(obj)) {\r
+ /* We're an instance of a classic class */\r
+ PyObject *bound_method = PyObject_GetAttrString(obj, "__format__");\r
+ if (bound_method != NULL) {\r
+ result = PyObject_CallFunctionObjArgs(bound_method,\r
+ format_spec,\r
+ NULL);\r
+ Py_DECREF(bound_method);\r
+ } else {\r
+ PyObject *self_as_str = NULL;\r
+ PyObject *format_method = NULL;\r
+ Py_ssize_t format_len;\r
+\r
+ PyErr_Clear();\r
+ /* Per the PEP, convert to str (or unicode,\r
+ depending on the type of the format\r
+ specifier). For new-style classes, this\r
+ logic is done by object.__format__(). */\r
+#ifdef Py_USING_UNICODE\r
+ if (spec_is_unicode) {\r
+ format_len = PyUnicode_GET_SIZE(format_spec);\r
+ self_as_str = PyObject_Unicode(obj);\r
+ } else\r
+#endif\r
+ {\r
+ format_len = PyString_GET_SIZE(format_spec);\r
+ self_as_str = PyObject_Str(obj);\r
+ }\r
+ if (self_as_str == NULL)\r
+ goto done1;\r
+\r
+ if (format_len > 0) {\r
+ /* See the almost identical code in\r
+ typeobject.c for new-style\r
+ classes. */\r
+ if (PyErr_WarnEx(\r
+ PyExc_PendingDeprecationWarning,\r
+ "object.__format__ with a non-empty "\r
+ "format string is deprecated", 1)\r
+ < 0) {\r
+ goto done1;\r
+ }\r
+ /* Eventually this will become an\r
+ error:\r
+ PyErr_Format(PyExc_TypeError,\r
+ "non-empty format string passed to "\r
+ "object.__format__");\r
+ goto done1;\r
+ */\r
+ }\r
+\r
+ /* Then call str.__format__ on that result */\r
+ format_method = PyObject_GetAttrString(self_as_str, "__format__");\r
+ if (format_method == NULL) {\r
+ goto done1;\r
+ }\r
+ result = PyObject_CallFunctionObjArgs(format_method,\r
+ format_spec,\r
+ NULL);\r
+done1:\r
+ Py_XDECREF(self_as_str);\r
+ Py_XDECREF(format_method);\r
+ if (result == NULL)\r
+ goto done;\r
+ }\r
+ } else {\r
+ /* Not an instance of a classic class, use the code\r
+ from py3k */\r
+ static PyObject *format_cache = NULL;\r
+\r
+ /* Find the (unbound!) __format__ method (a borrowed\r
+ reference) */\r
+ PyObject *method = _PyObject_LookupSpecial(obj, "__format__",\r
+ &format_cache);\r
+ if (method == NULL) {\r
+ if (!PyErr_Occurred())\r
+ PyErr_Format(PyExc_TypeError,\r
+ "Type %.100s doesn't define __format__",\r
+ Py_TYPE(obj)->tp_name);\r
+ goto done;\r
+ }\r
+ /* And call it. */\r
+ result = PyObject_CallFunctionObjArgs(method, format_spec, NULL);\r
+ Py_DECREF(method);\r
+ }\r
+\r
+ if (result == NULL)\r
+ goto done;\r
+\r
+ /* Check the result type, and make sure it's str or unicode */\r
+#ifdef Py_USING_UNICODE\r
+ if (PyUnicode_Check(result))\r
+ result_is_unicode = 1;\r
+ else if (PyString_Check(result))\r
+ result_is_unicode = 0;\r
+ else {\r
+#else\r
+ if (!PyString_Check(result)) {\r
+#endif\r
+ PyErr_Format(PyExc_TypeError,\r
+ "%.100s.__format__ must return string or "\r
+ "unicode, not %.100s", Py_TYPE(obj)->tp_name,\r
+ Py_TYPE(result)->tp_name);\r
+ Py_DECREF(result);\r
+ result = NULL;\r
+ goto done;\r
+ }\r
+\r
+ /* Convert to unicode, if needed. Required if spec is unicode\r
+ and result is str */\r
+#ifdef Py_USING_UNICODE\r
+ if (spec_is_unicode && !result_is_unicode) {\r
+ PyObject *tmp = PyObject_Unicode(result);\r
+ /* This logic works whether or not tmp is NULL */\r
+ Py_DECREF(result);\r
+ result = tmp;\r
+ }\r
+#endif\r
+\r
+done:\r
+ Py_XDECREF(empty);\r
+ return result;\r
+}\r
+\r
+/* Operations on numbers */\r
+\r
+int\r
+PyNumber_Check(PyObject *o)\r
+{\r
+ return o && o->ob_type->tp_as_number &&\r
+ (o->ob_type->tp_as_number->nb_int ||\r
+ o->ob_type->tp_as_number->nb_float);\r
+}\r
+\r
+/* Binary operators */\r
+\r
+/* New style number protocol support */\r
+\r
+#define NB_SLOT(x) offsetof(PyNumberMethods, x)\r
+#define NB_BINOP(nb_methods, slot) \\r
+ (*(binaryfunc*)(& ((char*)nb_methods)[slot]))\r
+#define NB_TERNOP(nb_methods, slot) \\r
+ (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))\r
+\r
+/*\r
+ Calling scheme used for binary operations:\r
+\r
+ v w Action\r
+ -------------------------------------------------------------------\r
+ new new w.op(v,w)[*], v.op(v,w), w.op(v,w)\r
+ new old v.op(v,w), coerce(v,w), v.op(v,w)\r
+ old new w.op(v,w), coerce(v,w), v.op(v,w)\r
+ old old coerce(v,w), v.op(v,w)\r
+\r
+ [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of\r
+ v->ob_type\r
+\r
+ Legend:\r
+ -------\r
+ * new == new style number\r
+ * old == old style number\r
+ * Action indicates the order in which operations are tried until either\r
+ a valid result is produced or an error occurs.\r
+\r
+ */\r
+\r
+static PyObject *\r
+binary_op1(PyObject *v, PyObject *w, const int op_slot)\r
+{\r
+ PyObject *x;\r
+ binaryfunc slotv = NULL;\r
+ binaryfunc slotw = NULL;\r
+\r
+ if (v->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(v))\r
+ slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);\r
+ if (w->ob_type != v->ob_type &&\r
+ w->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(w)) {\r
+ slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);\r
+ if (slotw == slotv)\r
+ slotw = NULL;\r
+ }\r
+ if (slotv) {\r
+ if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {\r
+ x = slotw(v, w);\r
+ if (x != Py_NotImplemented)\r
+ return x;\r
+ Py_DECREF(x); /* can't do it */\r
+ slotw = NULL;\r
+ }\r
+ x = slotv(v, w);\r
+ if (x != Py_NotImplemented)\r
+ return x;\r
+ Py_DECREF(x); /* can't do it */\r
+ }\r
+ if (slotw) {\r
+ x = slotw(v, w);\r
+ if (x != Py_NotImplemented)\r
+ return x;\r
+ Py_DECREF(x); /* can't do it */\r
+ }\r
+ if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w)) {\r
+ int err = PyNumber_CoerceEx(&v, &w);\r
+ if (err < 0) {\r
+ return NULL;\r
+ }\r
+ if (err == 0) {\r
+ PyNumberMethods *mv = v->ob_type->tp_as_number;\r
+ if (mv) {\r
+ binaryfunc slot;\r
+ slot = NB_BINOP(mv, op_slot);\r
+ if (slot) {\r
+ x = slot(v, w);\r
+ Py_DECREF(v);\r
+ Py_DECREF(w);\r
+ return x;\r
+ }\r
+ }\r
+ /* CoerceEx incremented the reference counts */\r
+ Py_DECREF(v);\r
+ Py_DECREF(w);\r
+ }\r
+ }\r
+ Py_INCREF(Py_NotImplemented);\r
+ return Py_NotImplemented;\r
+}\r
+\r
+static PyObject *\r
+binop_type_error(PyObject *v, PyObject *w, const char *op_name)\r
+{\r
+ PyErr_Format(PyExc_TypeError,\r
+ "unsupported operand type(s) for %.100s: "\r
+ "'%.100s' and '%.100s'",\r
+ op_name,\r
+ v->ob_type->tp_name,\r
+ w->ob_type->tp_name);\r
+ return NULL;\r
+}\r
+\r
+static PyObject *\r
+binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)\r
+{\r
+ PyObject *result = binary_op1(v, w, op_slot);\r
+ if (result == Py_NotImplemented) {\r
+ Py_DECREF(result);\r
+ return binop_type_error(v, w, op_name);\r
+ }\r
+ return result;\r
+}\r
+\r
+\r
+/*\r
+ Calling scheme used for ternary operations:\r
+\r
+ *** In some cases, w.op is called before v.op; see binary_op1. ***\r
+\r
+ v w z Action\r
+ -------------------------------------------------------------------\r
+ new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)\r
+ new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)\r
+ old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)\r
+ old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)\r
+ new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)\r
+ new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)\r
+ old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)\r
+ old old old coerce(v,w,z), v.op(v,w,z)\r
+\r
+ Legend:\r
+ -------\r
+ * new == new style number\r
+ * old == old style number\r
+ * Action indicates the order in which operations are tried until either\r
+ a valid result is produced or an error occurs.\r
+ * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and\r
+ only if z != Py_None; if z == Py_None, then it is treated as absent\r
+ variable and only coerce(v,w) is tried.\r
+\r
+ */\r
+\r
+static PyObject *\r
+ternary_op(PyObject *v,\r
+ PyObject *w,\r
+ PyObject *z,\r
+ const int op_slot,\r
+ const char *op_name)\r
+{\r
+ PyNumberMethods *mv, *mw, *mz;\r
+ PyObject *x = NULL;\r
+ ternaryfunc slotv = NULL;\r
+ ternaryfunc slotw = NULL;\r
+ ternaryfunc slotz = NULL;\r
+\r
+ mv = v->ob_type->tp_as_number;\r
+ mw = w->ob_type->tp_as_number;\r
+ if (mv != NULL && NEW_STYLE_NUMBER(v))\r
+ slotv = NB_TERNOP(mv, op_slot);\r
+ if (w->ob_type != v->ob_type &&\r
+ mw != NULL && NEW_STYLE_NUMBER(w)) {\r
+ slotw = NB_TERNOP(mw, op_slot);\r
+ if (slotw == slotv)\r
+ slotw = NULL;\r
+ }\r
+ if (slotv) {\r
+ if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {\r
+ x = slotw(v, w, z);\r
+ if (x != Py_NotImplemented)\r
+ return x;\r
+ Py_DECREF(x); /* can't do it */\r
+ slotw = NULL;\r
+ }\r
+ x = slotv(v, w, z);\r
+ if (x != Py_NotImplemented)\r
+ return x;\r
+ Py_DECREF(x); /* can't do it */\r
+ }\r
+ if (slotw) {\r
+ x = slotw(v, w, z);\r
+ if (x != Py_NotImplemented)\r
+ return x;\r
+ Py_DECREF(x); /* can't do it */\r
+ }\r
+ mz = z->ob_type->tp_as_number;\r
+ if (mz != NULL && NEW_STYLE_NUMBER(z)) {\r
+ slotz = NB_TERNOP(mz, op_slot);\r
+ if (slotz == slotv || slotz == slotw)\r
+ slotz = NULL;\r
+ if (slotz) {\r
+ x = slotz(v, w, z);\r
+ if (x != Py_NotImplemented)\r
+ return x;\r
+ Py_DECREF(x); /* can't do it */\r
+ }\r
+ }\r
+\r
+ if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w) ||\r
+ (z != Py_None && !NEW_STYLE_NUMBER(z))) {\r
+ /* we have an old style operand, coerce */\r
+ PyObject *v1, *z1, *w2, *z2;\r
+ int c;\r
+\r
+ c = PyNumber_Coerce(&v, &w);\r
+ if (c != 0)\r
+ goto error3;\r
+\r
+ /* Special case: if the third argument is None, it is\r
+ treated as absent argument and not coerced. */\r
+ if (z == Py_None) {\r
+ if (v->ob_type->tp_as_number) {\r
+ slotz = NB_TERNOP(v->ob_type->tp_as_number,\r
+ op_slot);\r
+ if (slotz)\r
+ x = slotz(v, w, z);\r
+ else\r
+ c = -1;\r
+ }\r
+ else\r
+ c = -1;\r
+ goto error2;\r
+ }\r
+ v1 = v;\r
+ z1 = z;\r
+ c = PyNumber_Coerce(&v1, &z1);\r
+ if (c != 0)\r
+ goto error2;\r
+ w2 = w;\r
+ z2 = z1;\r
+ c = PyNumber_Coerce(&w2, &z2);\r
+ if (c != 0)\r
+ goto error1;\r
+\r
+ if (v1->ob_type->tp_as_number != NULL) {\r
+ slotv = NB_TERNOP(v1->ob_type->tp_as_number,\r
+ op_slot);\r
+ if (slotv)\r
+ x = slotv(v1, w2, z2);\r
+ else\r
+ c = -1;\r
+ }\r
+ else\r
+ c = -1;\r
+\r
+ Py_DECREF(w2);\r
+ Py_DECREF(z2);\r
+ error1:\r
+ Py_DECREF(v1);\r
+ Py_DECREF(z1);\r
+ error2:\r
+ Py_DECREF(v);\r
+ Py_DECREF(w);\r
+ error3:\r
+ if (c >= 0)\r
+ return x;\r
+ }\r
+\r
+ if (z == Py_None)\r
+ PyErr_Format(\r
+ PyExc_TypeError,\r
+ "unsupported operand type(s) for ** or pow(): "\r
+ "'%.100s' and '%.100s'",\r
+ v->ob_type->tp_name,\r
+ w->ob_type->tp_name);\r
+ else\r
+ PyErr_Format(\r
+ PyExc_TypeError,\r
+ "unsupported operand type(s) for pow(): "\r
+ "'%.100s', '%.100s', '%.100s'",\r
+ v->ob_type->tp_name,\r
+ w->ob_type->tp_name,\r
+ z->ob_type->tp_name);\r
+ return NULL;\r
+}\r
+\r
+#define BINARY_FUNC(func, op, op_name) \\r
+ PyObject * \\r
+ func(PyObject *v, PyObject *w) { \\r
+ return binary_op(v, w, NB_SLOT(op), op_name); \\r
+ }\r
+\r
+BINARY_FUNC(PyNumber_Or, nb_or, "|")\r
+BINARY_FUNC(PyNumber_Xor, nb_xor, "^")\r
+BINARY_FUNC(PyNumber_And, nb_and, "&")\r
+BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")\r
+BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")\r
+BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")\r
+BINARY_FUNC(PyNumber_Divide, nb_divide, "/")\r
+BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")\r
+\r
+PyObject *\r
+PyNumber_Add(PyObject *v, PyObject *w)\r
+{\r
+ PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));\r
+ if (result == Py_NotImplemented) {\r
+ PySequenceMethods *m = v->ob_type->tp_as_sequence;\r
+ Py_DECREF(result);\r
+ if (m && m->sq_concat) {\r
+ return (*m->sq_concat)(v, w);\r
+ }\r
+ result = binop_type_error(v, w, "+");\r
+ }\r
+ return result;\r
+}\r
+\r
+static PyObject *\r
+sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)\r
+{\r
+ Py_ssize_t count;\r
+ if (PyIndex_Check(n)) {\r
+ count = PyNumber_AsSsize_t(n, PyExc_OverflowError);\r
+ if (count == -1 && PyErr_Occurred())\r
+ return NULL;\r
+ }\r
+ else {\r
+ return type_error("can't multiply sequence by "\r
+ "non-int of type '%.200s'", n);\r
+ }\r
+ return (*repeatfunc)(seq, count);\r
+}\r
+\r
+PyObject *\r
+PyNumber_Multiply(PyObject *v, PyObject *w)\r
+{\r
+ PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));\r
+ if (result == Py_NotImplemented) {\r
+ PySequenceMethods *mv = v->ob_type->tp_as_sequence;\r
+ PySequenceMethods *mw = w->ob_type->tp_as_sequence;\r
+ Py_DECREF(result);\r
+ if (mv && mv->sq_repeat) {\r
+ return sequence_repeat(mv->sq_repeat, v, w);\r
+ }\r
+ else if (mw && mw->sq_repeat) {\r
+ return sequence_repeat(mw->sq_repeat, w, v);\r
+ }\r
+ result = binop_type_error(v, w, "*");\r
+ }\r
+ return result;\r
+}\r
+\r
+PyObject *\r
+PyNumber_FloorDivide(PyObject *v, PyObject *w)\r
+{\r
+ /* XXX tp_flags test */\r
+ return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");\r
+}\r
+\r
+PyObject *\r
+PyNumber_TrueDivide(PyObject *v, PyObject *w)\r
+{\r
+ /* XXX tp_flags test */\r
+ return binary_op(v, w, NB_SLOT(nb_true_divide), "/");\r
+}\r
+\r
+PyObject *\r
+PyNumber_Remainder(PyObject *v, PyObject *w)\r
+{\r
+ return binary_op(v, w, NB_SLOT(nb_remainder), "%");\r
+}\r
+\r
+PyObject *\r
+PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)\r
+{\r
+ return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");\r
+}\r
+\r
+/* Binary in-place operators */\r
+\r
+/* The in-place operators are defined to fall back to the 'normal',\r
+ non in-place operations, if the in-place methods are not in place.\r
+\r
+ - If the left hand object has the appropriate struct members, and\r
+ they are filled, call the appropriate function and return the\r
+ result. No coercion is done on the arguments; the left-hand object\r
+ is the one the operation is performed on, and it's up to the\r
+ function to deal with the right-hand object.\r
+\r
+ - Otherwise, in-place modification is not supported. Handle it exactly as\r
+ a non in-place operation of the same kind.\r
+\r
+ */\r
+\r
+#define HASINPLACE(t) \\r
+ PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)\r
+\r
+static PyObject *\r
+binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)\r
+{\r
+ PyNumberMethods *mv = v->ob_type->tp_as_number;\r
+ if (mv != NULL && HASINPLACE(v)) {\r
+ binaryfunc slot = NB_BINOP(mv, iop_slot);\r
+ if (slot) {\r
+ PyObject *x = (slot)(v, w);\r
+ if (x != Py_NotImplemented) {\r
+ return x;\r
+ }\r
+ Py_DECREF(x);\r
+ }\r
+ }\r
+ return binary_op1(v, w, op_slot);\r
+}\r
+\r
+static PyObject *\r
+binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,\r
+ const char *op_name)\r
+{\r
+ PyObject *result = binary_iop1(v, w, iop_slot, op_slot);\r
+ if (result == Py_NotImplemented) {\r
+ Py_DECREF(result);\r
+ return binop_type_error(v, w, op_name);\r
+ }\r
+ return result;\r
+}\r
+\r
+#define INPLACE_BINOP(func, iop, op, op_name) \\r
+ PyObject * \\r
+ func(PyObject *v, PyObject *w) { \\r
+ return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \\r
+ }\r
+\r
+INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")\r
+INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")\r
+INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")\r
+INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")\r
+INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")\r
+INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")\r
+INPLACE_BINOP(PyNumber_InPlaceDivide, nb_inplace_divide, nb_divide, "/=")\r
+\r
+PyObject *\r
+PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)\r
+{\r
+ /* XXX tp_flags test */\r
+ return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),\r
+ NB_SLOT(nb_floor_divide), "//=");\r
+}\r
+\r
+PyObject *\r
+PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)\r
+{\r
+ /* XXX tp_flags test */\r
+ return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),\r
+ NB_SLOT(nb_true_divide), "/=");\r
+}\r
+\r
+PyObject *\r
+PyNumber_InPlaceAdd(PyObject *v, PyObject *w)\r
+{\r
+ PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),\r
+ NB_SLOT(nb_add));\r
+ if (result == Py_NotImplemented) {\r
+ PySequenceMethods *m = v->ob_type->tp_as_sequence;\r
+ Py_DECREF(result);\r
+ if (m != NULL) {\r
+ binaryfunc f = NULL;\r
+ if (HASINPLACE(v))\r
+ f = m->sq_inplace_concat;\r
+ if (f == NULL)\r
+ f = m->sq_concat;\r
+ if (f != NULL)\r
+ return (*f)(v, w);\r
+ }\r
+ result = binop_type_error(v, w, "+=");\r
+ }\r
+ return result;\r
+}\r
+\r
+PyObject *\r
+PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)\r
+{\r
+ PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),\r
+ NB_SLOT(nb_multiply));\r
+ if (result == Py_NotImplemented) {\r
+ ssizeargfunc f = NULL;\r
+ PySequenceMethods *mv = v->ob_type->tp_as_sequence;\r
+ PySequenceMethods *mw = w->ob_type->tp_as_sequence;\r
+ Py_DECREF(result);\r
+ if (mv != NULL) {\r
+ if (HASINPLACE(v))\r
+ f = mv->sq_inplace_repeat;\r
+ if (f == NULL)\r
+ f = mv->sq_repeat;\r
+ if (f != NULL)\r
+ return sequence_repeat(f, v, w);\r
+ }\r
+ else if (mw != NULL) {\r
+ /* Note that the right hand operand should not be\r
+ * mutated in this case so sq_inplace_repeat is not\r
+ * used. */\r
+ if (mw->sq_repeat)\r
+ return sequence_repeat(mw->sq_repeat, w, v);\r
+ }\r
+ result = binop_type_error(v, w, "*=");\r
+ }\r
+ return result;\r
+}\r
+\r
+PyObject *\r
+PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)\r
+{\r
+ return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),\r
+ NB_SLOT(nb_remainder), "%=");\r
+}\r
+\r
+PyObject *\r
+PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)\r
+{\r
+ if (HASINPLACE(v) && v->ob_type->tp_as_number &&\r
+ v->ob_type->tp_as_number->nb_inplace_power != NULL) {\r
+ return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");\r
+ }\r
+ else {\r
+ return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");\r
+ }\r
+}\r
+\r
+\r
+/* Unary operators and functions */\r
+\r
+PyObject *\r
+PyNumber_Negative(PyObject *o)\r
+{\r
+ PyNumberMethods *m;\r
+\r
+ if (o == NULL)\r
+ return null_error();\r
+ m = o->ob_type->tp_as_number;\r
+ if (m && m->nb_negative)\r
+ return (*m->nb_negative)(o);\r
+\r
+ return type_error("bad operand type for unary -: '%.200s'", o);\r
+}\r
+\r
+PyObject *\r
+PyNumber_Positive(PyObject *o)\r
+{\r
+ PyNumberMethods *m;\r
+\r
+ if (o == NULL)\r
+ return null_error();\r
+ m = o->ob_type->tp_as_number;\r
+ if (m && m->nb_positive)\r
+ return (*m->nb_positive)(o);\r
+\r
+ return type_error("bad operand type for unary +: '%.200s'", o);\r
+}\r
+\r
+PyObject *\r
+PyNumber_Invert(PyObject *o)\r
+{\r
+ PyNumberMethods *m;\r
+\r
+ if (o == NULL)\r
+ return null_error();\r
+ m = o->ob_type->tp_as_number;\r
+ if (m && m->nb_invert)\r
+ return (*m->nb_invert)(o);\r
+\r
+ return type_error("bad operand type for unary ~: '%.200s'", o);\r
+}\r
+\r
+PyObject *\r
+PyNumber_Absolute(PyObject *o)\r
+{\r
+ PyNumberMethods *m;\r
+\r
+ if (o == NULL)\r
+ return null_error();\r
+ m = o->ob_type->tp_as_number;\r
+ if (m && m->nb_absolute)\r
+ return m->nb_absolute(o);\r
+\r
+ return type_error("bad operand type for abs(): '%.200s'", o);\r
+}\r
+\r
+/* Add a check for embedded NULL-bytes in the argument. */\r
+static PyObject *\r
+int_from_string(const char *s, Py_ssize_t len)\r
+{\r
+ char *end;\r
+ PyObject *x;\r
+\r
+ x = PyInt_FromString((char*)s, &end, 10);\r
+ if (x == NULL)\r
+ return NULL;\r
+ if (end != s + len) {\r
+ PyErr_SetString(PyExc_ValueError,\r
+ "null byte in argument for int()");\r
+ Py_DECREF(x);\r
+ return NULL;\r
+ }\r
+ return x;\r
+}\r
+\r
+/* Return a Python Int or Long from the object item\r
+ Raise TypeError if the result is not an int-or-long\r
+ or if the object cannot be interpreted as an index.\r
+*/\r
+PyObject *\r
+PyNumber_Index(PyObject *item)\r
+{\r
+ PyObject *result = NULL;\r
+ if (item == NULL)\r
+ return null_error();\r
+ if (PyInt_Check(item) || PyLong_Check(item)) {\r
+ Py_INCREF(item);\r
+ return item;\r
+ }\r
+ if (PyIndex_Check(item)) {\r
+ result = item->ob_type->tp_as_number->nb_index(item);\r
+ if (result &&\r
+ !PyInt_Check(result) && !PyLong_Check(result)) {\r
+ PyErr_Format(PyExc_TypeError,\r
+ "__index__ returned non-(int,long) " \\r
+ "(type %.200s)",\r
+ result->ob_type->tp_name);\r
+ Py_DECREF(result);\r
+ return NULL;\r
+ }\r
+ }\r
+ else {\r
+ PyErr_Format(PyExc_TypeError,\r
+ "'%.200s' object cannot be interpreted "\r
+ "as an index", item->ob_type->tp_name);\r
+ }\r
+ return result;\r
+}\r
+\r
+/* Return an error on Overflow only if err is not NULL*/\r
+\r
+Py_ssize_t\r
+PyNumber_AsSsize_t(PyObject *item, PyObject *err)\r
+{\r
+ Py_ssize_t result;\r
+ PyObject *runerr;\r
+ PyObject *value = PyNumber_Index(item);\r
+ if (value == NULL)\r
+ return -1;\r
+\r
+ /* We're done if PyInt_AsSsize_t() returns without error. */\r
+ result = PyInt_AsSsize_t(value);\r
+ if (result != -1 || !(runerr = PyErr_Occurred()))\r
+ goto finish;\r
+\r
+ /* Error handling code -- only manage OverflowError differently */\r
+ if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))\r
+ goto finish;\r
+\r
+ PyErr_Clear();\r
+ /* If no error-handling desired then the default clipping\r
+ is sufficient.\r
+ */\r
+ if (!err) {\r
+ assert(PyLong_Check(value));\r
+ /* Whether or not it is less than or equal to\r
+ zero is determined by the sign of ob_size\r
+ */\r
+ if (_PyLong_Sign(value) < 0)\r
+ result = PY_SSIZE_T_MIN;\r
+ else\r
+ result = PY_SSIZE_T_MAX;\r
+ }\r
+ else {\r
+ /* Otherwise replace the error with caller's error object. */\r
+ PyErr_Format(err,\r
+ "cannot fit '%.200s' into an index-sized integer",\r
+ item->ob_type->tp_name);\r
+ }\r
+\r
+ finish:\r
+ Py_DECREF(value);\r
+ return result;\r
+}\r
+\r
+\r
+PyObject *\r
+_PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format)\r
+{\r
+ const char *type_name;\r
+ static PyObject *int_name = NULL;\r
+ if (int_name == NULL) {\r
+ int_name = PyString_InternFromString("__int__");\r
+ if (int_name == NULL)\r
+ return NULL;\r
+ }\r
+\r
+ if (integral && (!PyInt_Check(integral) &&\r
+ !PyLong_Check(integral))) {\r
+ /* Don't go through tp_as_number->nb_int to avoid\r
+ hitting the classic class fallback to __trunc__. */\r
+ PyObject *int_func = PyObject_GetAttr(integral, int_name);\r
+ if (int_func == NULL) {\r
+ PyErr_Clear(); /* Raise a different error. */\r
+ goto non_integral_error;\r
+ }\r
+ Py_DECREF(integral);\r
+ integral = PyEval_CallObject(int_func, NULL);\r
+ Py_DECREF(int_func);\r
+ if (integral && (!PyInt_Check(integral) &&\r
+ !PyLong_Check(integral))) {\r
+ goto non_integral_error;\r
+ }\r
+ }\r
+ return integral;\r
+\r
+non_integral_error:\r
+ if (PyInstance_Check(integral)) {\r
+ type_name = PyString_AS_STRING(((PyInstanceObject *)integral)\r
+ ->in_class->cl_name);\r
+ }\r
+ else {\r
+ type_name = integral->ob_type->tp_name;\r
+ }\r
+ PyErr_Format(PyExc_TypeError, error_format, type_name);\r
+ Py_DECREF(integral);\r
+ return NULL;\r
+}\r
+\r
+\r
+PyObject *\r
+PyNumber_Int(PyObject *o)\r
+{\r
+ PyNumberMethods *m;\r
+ static PyObject *trunc_name = NULL;\r
+ PyObject *trunc_func;\r
+ const char *buffer;\r
+ Py_ssize_t buffer_len;\r
+\r
+ if (trunc_name == NULL) {\r
+ trunc_name = PyString_InternFromString("__trunc__");\r
+ if (trunc_name == NULL)\r
+ return NULL;\r
+ }\r
+\r
+ if (o == NULL)\r
+ return null_error();\r
+ if (PyInt_CheckExact(o)) {\r
+ Py_INCREF(o);\r
+ return o;\r
+ }\r
+ m = o->ob_type->tp_as_number;\r
+ if (m && m->nb_int) { /* This should include subclasses of int */\r
+ /* Classic classes always take this branch. */\r
+ PyObject *res = m->nb_int(o);\r
+ if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {\r
+ PyErr_Format(PyExc_TypeError,\r
+ "__int__ returned non-int (type %.200s)",\r
+ res->ob_type->tp_name);\r
+ Py_DECREF(res);\r
+ return NULL;\r
+ }\r
+ return res;\r
+ }\r
+ if (PyInt_Check(o)) { /* A int subclass without nb_int */\r
+ PyIntObject *io = (PyIntObject*)o;\r
+ return PyInt_FromLong(io->ob_ival);\r
+ }\r
+ trunc_func = PyObject_GetAttr(o, trunc_name);\r
+ if (trunc_func) {\r
+ PyObject *truncated = PyEval_CallObject(trunc_func, NULL);\r
+ Py_DECREF(trunc_func);\r
+ /* __trunc__ is specified to return an Integral type, but\r
+ int() needs to return an int. */\r
+ return _PyNumber_ConvertIntegralToInt(\r
+ truncated,\r
+ "__trunc__ returned non-Integral (type %.200s)");\r
+ }\r
+ PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */\r
+\r
+ if (PyString_Check(o))\r
+ return int_from_string(PyString_AS_STRING(o),\r
+ PyString_GET_SIZE(o));\r
+#ifdef Py_USING_UNICODE\r
+ if (PyUnicode_Check(o))\r
+ return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),\r
+ PyUnicode_GET_SIZE(o),\r
+ 10);\r
+#endif\r
+ if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))\r
+ return int_from_string((char*)buffer, buffer_len);\r
+\r
+ return type_error("int() argument must be a string or a "\r
+ "number, not '%.200s'", o);\r
+}\r
+\r
+/* Add a check for embedded NULL-bytes in the argument. */\r
+static PyObject *\r
+long_from_string(const char *s, Py_ssize_t len)\r
+{\r
+ char *end;\r
+ PyObject *x;\r
+\r
+ x = PyLong_FromString((char*)s, &end, 10);\r
+ if (x == NULL)\r
+ return NULL;\r
+ if (end != s + len) {\r
+ PyErr_SetString(PyExc_ValueError,\r
+ "null byte in argument for long()");\r
+ Py_DECREF(x);\r
+ return NULL;\r
+ }\r
+ return x;\r
+}\r
+\r
+PyObject *\r
+PyNumber_Long(PyObject *o)\r
+{\r
+ PyNumberMethods *m;\r
+ static PyObject *trunc_name = NULL;\r
+ PyObject *trunc_func;\r
+ const char *buffer;\r
+ Py_ssize_t buffer_len;\r
+\r
+ if (trunc_name == NULL) {\r
+ trunc_name = PyString_InternFromString("__trunc__");\r
+ if (trunc_name == NULL)\r
+ return NULL;\r
+ }\r
+\r
+ if (o == NULL)\r
+ return null_error();\r
+ m = o->ob_type->tp_as_number;\r
+ if (m && m->nb_long) { /* This should include subclasses of long */\r
+ /* Classic classes always take this branch. */\r
+ PyObject *res = m->nb_long(o);\r
+ if (res == NULL)\r
+ return NULL;\r
+ if (PyInt_Check(res)) {\r
+ long value = PyInt_AS_LONG(res);\r
+ Py_DECREF(res);\r
+ return PyLong_FromLong(value);\r
+ }\r
+ else if (!PyLong_Check(res)) {\r
+ PyErr_Format(PyExc_TypeError,\r
+ "__long__ returned non-long (type %.200s)",\r
+ res->ob_type->tp_name);\r
+ Py_DECREF(res);\r
+ return NULL;\r
+ }\r
+ return res;\r
+ }\r
+ if (PyLong_Check(o)) /* A long subclass without nb_long */\r
+ return _PyLong_Copy((PyLongObject *)o);\r
+ trunc_func = PyObject_GetAttr(o, trunc_name);\r
+ if (trunc_func) {\r
+ PyObject *truncated = PyEval_CallObject(trunc_func, NULL);\r
+ PyObject *int_instance;\r
+ Py_DECREF(trunc_func);\r
+ /* __trunc__ is specified to return an Integral type,\r
+ but long() needs to return a long. */\r
+ int_instance = _PyNumber_ConvertIntegralToInt(\r
+ truncated,\r
+ "__trunc__ returned non-Integral (type %.200s)");\r
+ if (int_instance && PyInt_Check(int_instance)) {\r
+ /* Make sure that long() returns a long instance. */\r
+ long value = PyInt_AS_LONG(int_instance);\r
+ Py_DECREF(int_instance);\r
+ return PyLong_FromLong(value);\r
+ }\r
+ return int_instance;\r
+ }\r
+ PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */\r
+\r
+ if (PyString_Check(o))\r
+ /* need to do extra error checking that PyLong_FromString()\r
+ * doesn't do. In particular long('9.5') must raise an\r
+ * exception, not truncate the float.\r
+ */\r
+ return long_from_string(PyString_AS_STRING(o),\r
+ PyString_GET_SIZE(o));\r
+#ifdef Py_USING_UNICODE\r
+ if (PyUnicode_Check(o))\r
+ /* The above check is done in PyLong_FromUnicode(). */\r
+ return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),\r
+ PyUnicode_GET_SIZE(o),\r
+ 10);\r
+#endif\r
+ if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))\r
+ return long_from_string(buffer, buffer_len);\r
+\r
+ return type_error("long() argument must be a string or a "\r
+ "number, not '%.200s'", o);\r
+}\r
+\r
+PyObject *\r
+PyNumber_Float(PyObject *o)\r
+{\r
+ PyNumberMethods *m;\r
+\r
+ if (o == NULL)\r
+ return null_error();\r
+ m = o->ob_type->tp_as_number;\r
+ if (m && m->nb_float) { /* This should include subclasses of float */\r
+ PyObject *res = m->nb_float(o);\r
+ if (res && !PyFloat_Check(res)) {\r
+ PyErr_Format(PyExc_TypeError,\r
+ "__float__ returned non-float (type %.200s)",\r
+ res->ob_type->tp_name);\r
+ Py_DECREF(res);\r
+ return NULL;\r
+ }\r
+ return res;\r
+ }\r
+ if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */\r
+ PyFloatObject *po = (PyFloatObject *)o;\r
+ return PyFloat_FromDouble(po->ob_fval);\r
+ }\r
+ return PyFloat_FromString(o, NULL);\r
+}\r
+\r
+PyObject *\r
+PyNumber_ToBase(PyObject *n, int base)\r
+{\r
+ PyObject *res = NULL;\r
+ PyObject *index = PyNumber_Index(n);\r
+\r
+ if (!index)\r
+ return NULL;\r
+ if (PyLong_Check(index))\r
+ res = _PyLong_Format(index, base, 0, 1);\r
+ else if (PyInt_Check(index))\r
+ res = _PyInt_Format((PyIntObject*)index, base, 1);\r
+ else\r
+ /* It should not be possible to get here, as\r
+ PyNumber_Index already has a check for the same\r
+ condition */\r
+ PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "\r
+ "int or long");\r
+ Py_DECREF(index);\r
+ return res;\r
+}\r
+\r
+\r
+/* Operations on sequences */\r
+\r
+int\r
+PySequence_Check(PyObject *s)\r
+{\r
+ if (s == NULL)\r
+ return 0;\r
+ if (PyInstance_Check(s))\r
+ return PyObject_HasAttrString(s, "__getitem__");\r
+ if (PyDict_Check(s))\r
+ return 0;\r
+ return s->ob_type->tp_as_sequence &&\r
+ s->ob_type->tp_as_sequence->sq_item != NULL;\r
+}\r
+\r
+Py_ssize_t\r
+PySequence_Size(PyObject *s)\r
+{\r
+ PySequenceMethods *m;\r
+\r
+ if (s == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+\r
+ m = s->ob_type->tp_as_sequence;\r
+ if (m && m->sq_length)\r
+ return m->sq_length(s);\r
+\r
+ type_error("object of type '%.200s' has no len()", s);\r
+ return -1;\r
+}\r
+\r
+#undef PySequence_Length\r
+Py_ssize_t\r
+PySequence_Length(PyObject *s)\r
+{\r
+ return PySequence_Size(s);\r
+}\r
+#define PySequence_Length PySequence_Size\r
+\r
+PyObject *\r
+PySequence_Concat(PyObject *s, PyObject *o)\r
+{\r
+ PySequenceMethods *m;\r
+\r
+ if (s == NULL || o == NULL)\r
+ return null_error();\r
+\r
+ m = s->ob_type->tp_as_sequence;\r
+ if (m && m->sq_concat)\r
+ return m->sq_concat(s, o);\r
+\r
+ /* Instances of user classes defining an __add__() method only\r
+ have an nb_add slot, not an sq_concat slot. So we fall back\r
+ to nb_add if both arguments appear to be sequences. */\r
+ if (PySequence_Check(s) && PySequence_Check(o)) {\r
+ PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));\r
+ if (result != Py_NotImplemented)\r
+ return result;\r
+ Py_DECREF(result);\r
+ }\r
+ return type_error("'%.200s' object can't be concatenated", s);\r
+}\r
+\r
+PyObject *\r
+PySequence_Repeat(PyObject *o, Py_ssize_t count)\r
+{\r
+ PySequenceMethods *m;\r
+\r
+ if (o == NULL)\r
+ return null_error();\r
+\r
+ m = o->ob_type->tp_as_sequence;\r
+ if (m && m->sq_repeat)\r
+ return m->sq_repeat(o, count);\r
+\r
+ /* Instances of user classes defining a __mul__() method only\r
+ have an nb_multiply slot, not an sq_repeat slot. so we fall back\r
+ to nb_multiply if o appears to be a sequence. */\r
+ if (PySequence_Check(o)) {\r
+ PyObject *n, *result;\r
+ n = PyInt_FromSsize_t(count);\r
+ if (n == NULL)\r
+ return NULL;\r
+ result = binary_op1(o, n, NB_SLOT(nb_multiply));\r
+ Py_DECREF(n);\r
+ if (result != Py_NotImplemented)\r
+ return result;\r
+ Py_DECREF(result);\r
+ }\r
+ return type_error("'%.200s' object can't be repeated", o);\r
+}\r
+\r
+PyObject *\r
+PySequence_InPlaceConcat(PyObject *s, PyObject *o)\r
+{\r
+ PySequenceMethods *m;\r
+\r
+ if (s == NULL || o == NULL)\r
+ return null_error();\r
+\r
+ m = s->ob_type->tp_as_sequence;\r
+ if (m && HASINPLACE(s) && m->sq_inplace_concat)\r
+ return m->sq_inplace_concat(s, o);\r
+ if (m && m->sq_concat)\r
+ return m->sq_concat(s, o);\r
+\r
+ if (PySequence_Check(s) && PySequence_Check(o)) {\r
+ PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),\r
+ NB_SLOT(nb_add));\r
+ if (result != Py_NotImplemented)\r
+ return result;\r
+ Py_DECREF(result);\r
+ }\r
+ return type_error("'%.200s' object can't be concatenated", s);\r
+}\r
+\r
+PyObject *\r
+PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)\r
+{\r
+ PySequenceMethods *m;\r
+\r
+ if (o == NULL)\r
+ return null_error();\r
+\r
+ m = o->ob_type->tp_as_sequence;\r
+ if (m && HASINPLACE(o) && m->sq_inplace_repeat)\r
+ return m->sq_inplace_repeat(o, count);\r
+ if (m && m->sq_repeat)\r
+ return m->sq_repeat(o, count);\r
+\r
+ if (PySequence_Check(o)) {\r
+ PyObject *n, *result;\r
+ n = PyInt_FromSsize_t(count);\r
+ if (n == NULL)\r
+ return NULL;\r
+ result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),\r
+ NB_SLOT(nb_multiply));\r
+ Py_DECREF(n);\r
+ if (result != Py_NotImplemented)\r
+ return result;\r
+ Py_DECREF(result);\r
+ }\r
+ return type_error("'%.200s' object can't be repeated", o);\r
+}\r
+\r
+PyObject *\r
+PySequence_GetItem(PyObject *s, Py_ssize_t i)\r
+{\r
+ PySequenceMethods *m;\r
+\r
+ if (s == NULL)\r
+ return null_error();\r
+\r
+ m = s->ob_type->tp_as_sequence;\r
+ if (m && m->sq_item) {\r
+ if (i < 0) {\r
+ if (m->sq_length) {\r
+ Py_ssize_t l = (*m->sq_length)(s);\r
+ if (l < 0)\r
+ return NULL;\r
+ i += l;\r
+ }\r
+ }\r
+ return m->sq_item(s, i);\r
+ }\r
+\r
+ return type_error("'%.200s' object does not support indexing", s);\r
+}\r
+\r
+PyObject *\r
+PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)\r
+{\r
+ PySequenceMethods *m;\r
+ PyMappingMethods *mp;\r
+\r
+ if (!s) return null_error();\r
+\r
+ m = s->ob_type->tp_as_sequence;\r
+ if (m && m->sq_slice) {\r
+ if (i1 < 0 || i2 < 0) {\r
+ if (m->sq_length) {\r
+ Py_ssize_t l = (*m->sq_length)(s);\r
+ if (l < 0)\r
+ return NULL;\r
+ if (i1 < 0)\r
+ i1 += l;\r
+ if (i2 < 0)\r
+ i2 += l;\r
+ }\r
+ }\r
+ return m->sq_slice(s, i1, i2);\r
+ } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_subscript) {\r
+ PyObject *res;\r
+ PyObject *slice = _PySlice_FromIndices(i1, i2);\r
+ if (!slice)\r
+ return NULL;\r
+ res = mp->mp_subscript(s, slice);\r
+ Py_DECREF(slice);\r
+ return res;\r
+ }\r
+\r
+ return type_error("'%.200s' object is unsliceable", s);\r
+}\r
+\r
+int\r
+PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)\r
+{\r
+ PySequenceMethods *m;\r
+\r
+ if (s == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+\r
+ m = s->ob_type->tp_as_sequence;\r
+ if (m && m->sq_ass_item) {\r
+ if (i < 0) {\r
+ if (m->sq_length) {\r
+ Py_ssize_t l = (*m->sq_length)(s);\r
+ if (l < 0)\r
+ return -1;\r
+ i += l;\r
+ }\r
+ }\r
+ return m->sq_ass_item(s, i, o);\r
+ }\r
+\r
+ type_error("'%.200s' object does not support item assignment", s);\r
+ return -1;\r
+}\r
+\r
+int\r
+PySequence_DelItem(PyObject *s, Py_ssize_t i)\r
+{\r
+ PySequenceMethods *m;\r
+\r
+ if (s == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+\r
+ m = s->ob_type->tp_as_sequence;\r
+ if (m && m->sq_ass_item) {\r
+ if (i < 0) {\r
+ if (m->sq_length) {\r
+ Py_ssize_t l = (*m->sq_length)(s);\r
+ if (l < 0)\r
+ return -1;\r
+ i += l;\r
+ }\r
+ }\r
+ return m->sq_ass_item(s, i, (PyObject *)NULL);\r
+ }\r
+\r
+ type_error("'%.200s' object doesn't support item deletion", s);\r
+ return -1;\r
+}\r
+\r
+int\r
+PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)\r
+{\r
+ PySequenceMethods *m;\r
+ PyMappingMethods *mp;\r
+\r
+ if (s == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+\r
+ m = s->ob_type->tp_as_sequence;\r
+ if (m && m->sq_ass_slice) {\r
+ if (i1 < 0 || i2 < 0) {\r
+ if (m->sq_length) {\r
+ Py_ssize_t l = (*m->sq_length)(s);\r
+ if (l < 0)\r
+ return -1;\r
+ if (i1 < 0)\r
+ i1 += l;\r
+ if (i2 < 0)\r
+ i2 += l;\r
+ }\r
+ }\r
+ return m->sq_ass_slice(s, i1, i2, o);\r
+ } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_ass_subscript) {\r
+ int res;\r
+ PyObject *slice = _PySlice_FromIndices(i1, i2);\r
+ if (!slice)\r
+ return -1;\r
+ res = mp->mp_ass_subscript(s, slice, o);\r
+ Py_DECREF(slice);\r
+ return res;\r
+ }\r
+\r
+ type_error("'%.200s' object doesn't support slice assignment", s);\r
+ return -1;\r
+}\r
+\r
+int\r
+PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)\r
+{\r
+ PySequenceMethods *m;\r
+\r
+ if (s == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+\r
+ m = s->ob_type->tp_as_sequence;\r
+ if (m && m->sq_ass_slice) {\r
+ if (i1 < 0 || i2 < 0) {\r
+ if (m->sq_length) {\r
+ Py_ssize_t l = (*m->sq_length)(s);\r
+ if (l < 0)\r
+ return -1;\r
+ if (i1 < 0)\r
+ i1 += l;\r
+ if (i2 < 0)\r
+ i2 += l;\r
+ }\r
+ }\r
+ return m->sq_ass_slice(s, i1, i2, (PyObject *)NULL);\r
+ }\r
+ type_error("'%.200s' object doesn't support slice deletion", s);\r
+ return -1;\r
+}\r
+\r
+PyObject *\r
+PySequence_Tuple(PyObject *v)\r
+{\r
+ PyObject *it; /* iter(v) */\r
+ Py_ssize_t n; /* guess for result tuple size */\r
+ PyObject *result = NULL;\r
+ Py_ssize_t j;\r
+\r
+ if (v == NULL)\r
+ return null_error();\r
+\r
+ /* Special-case the common tuple and list cases, for efficiency. */\r
+ if (PyTuple_CheckExact(v)) {\r
+ /* Note that we can't know whether it's safe to return\r
+ a tuple *subclass* instance as-is, hence the restriction\r
+ to exact tuples here. In contrast, lists always make\r
+ a copy, so there's no need for exactness below. */\r
+ Py_INCREF(v);\r
+ return v;\r
+ }\r
+ if (PyList_Check(v))\r
+ return PyList_AsTuple(v);\r
+\r
+ /* Get iterator. */\r
+ it = PyObject_GetIter(v);\r
+ if (it == NULL)\r
+ return NULL;\r
+\r
+ /* Guess result size and allocate space. */\r
+ n = _PyObject_LengthHint(v, 10);\r
+ if (n == -1)\r
+ goto Fail;\r
+ result = PyTuple_New(n);\r
+ if (result == NULL)\r
+ goto Fail;\r
+\r
+ /* Fill the tuple. */\r
+ for (j = 0; ; ++j) {\r
+ PyObject *item = PyIter_Next(it);\r
+ if (item == NULL) {\r
+ if (PyErr_Occurred())\r
+ goto Fail;\r
+ break;\r
+ }\r
+ if (j >= n) {\r
+ Py_ssize_t oldn = n;\r
+ /* The over-allocation strategy can grow a bit faster\r
+ than for lists because unlike lists the\r
+ over-allocation isn't permanent -- we reclaim\r
+ the excess before the end of this routine.\r
+ So, grow by ten and then add 25%.\r
+ */\r
+ n += 10;\r
+ n += n >> 2;\r
+ if (n < oldn) {\r
+ /* Check for overflow */\r
+ PyErr_NoMemory();\r
+ Py_DECREF(item);\r
+ goto Fail;\r
+ }\r
+ if (_PyTuple_Resize(&result, n) != 0) {\r
+ Py_DECREF(item);\r
+ goto Fail;\r
+ }\r
+ }\r
+ PyTuple_SET_ITEM(result, j, item);\r
+ }\r
+\r
+ /* Cut tuple back if guess was too large. */\r
+ if (j < n &&\r
+ _PyTuple_Resize(&result, j) != 0)\r
+ goto Fail;\r
+\r
+ Py_DECREF(it);\r
+ return result;\r
+\r
+Fail:\r
+ Py_XDECREF(result);\r
+ Py_DECREF(it);\r
+ return NULL;\r
+}\r
+\r
+PyObject *\r
+PySequence_List(PyObject *v)\r
+{\r
+ PyObject *result; /* result list */\r
+ PyObject *rv; /* return value from PyList_Extend */\r
+\r
+ if (v == NULL)\r
+ return null_error();\r
+\r
+ result = PyList_New(0);\r
+ if (result == NULL)\r
+ return NULL;\r
+\r
+ rv = _PyList_Extend((PyListObject *)result, v);\r
+ if (rv == NULL) {\r
+ Py_DECREF(result);\r
+ return NULL;\r
+ }\r
+ Py_DECREF(rv);\r
+ return result;\r
+}\r
+\r
+PyObject *\r
+PySequence_Fast(PyObject *v, const char *m)\r
+{\r
+ PyObject *it;\r
+\r
+ if (v == NULL)\r
+ return null_error();\r
+\r
+ if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {\r
+ Py_INCREF(v);\r
+ return v;\r
+ }\r
+\r
+ it = PyObject_GetIter(v);\r
+ if (it == NULL) {\r
+ if (PyErr_ExceptionMatches(PyExc_TypeError))\r
+ PyErr_SetString(PyExc_TypeError, m);\r
+ return NULL;\r
+ }\r
+\r
+ v = PySequence_List(it);\r
+ Py_DECREF(it);\r
+\r
+ return v;\r
+}\r
+\r
+/* Iterate over seq. Result depends on the operation:\r
+ PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.\r
+ PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;\r
+ set ValueError and return -1 if none found; also return -1 on error.\r
+ Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.\r
+*/\r
+Py_ssize_t\r
+_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)\r
+{\r
+ Py_ssize_t n;\r
+ int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */\r
+ PyObject *it; /* iter(seq) */\r
+\r
+ if (seq == NULL || obj == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+\r
+ it = PyObject_GetIter(seq);\r
+ if (it == NULL) {\r
+ type_error("argument of type '%.200s' is not iterable", seq);\r
+ return -1;\r
+ }\r
+\r
+ n = wrapped = 0;\r
+ for (;;) {\r
+ int cmp;\r
+ PyObject *item = PyIter_Next(it);\r
+ if (item == NULL) {\r
+ if (PyErr_Occurred())\r
+ goto Fail;\r
+ break;\r
+ }\r
+\r
+ cmp = PyObject_RichCompareBool(obj, item, Py_EQ);\r
+ Py_DECREF(item);\r
+ if (cmp < 0)\r
+ goto Fail;\r
+ if (cmp > 0) {\r
+ switch (operation) {\r
+ case PY_ITERSEARCH_COUNT:\r
+ if (n == PY_SSIZE_T_MAX) {\r
+ PyErr_SetString(PyExc_OverflowError,\r
+ "count exceeds C integer size");\r
+ goto Fail;\r
+ }\r
+ ++n;\r
+ break;\r
+\r
+ case PY_ITERSEARCH_INDEX:\r
+ if (wrapped) {\r
+ PyErr_SetString(PyExc_OverflowError,\r
+ "index exceeds C integer size");\r
+ goto Fail;\r
+ }\r
+ goto Done;\r
+\r
+ case PY_ITERSEARCH_CONTAINS:\r
+ n = 1;\r
+ goto Done;\r
+\r
+ default:\r
+ assert(!"unknown operation");\r
+ }\r
+ }\r
+\r
+ if (operation == PY_ITERSEARCH_INDEX) {\r
+ if (n == PY_SSIZE_T_MAX)\r
+ wrapped = 1;\r
+ ++n;\r
+ }\r
+ }\r
+\r
+ if (operation != PY_ITERSEARCH_INDEX)\r
+ goto Done;\r
+\r
+ PyErr_SetString(PyExc_ValueError,\r
+ "sequence.index(x): x not in sequence");\r
+ /* fall into failure code */\r
+Fail:\r
+ n = -1;\r
+ /* fall through */\r
+Done:\r
+ Py_DECREF(it);\r
+ return n;\r
+\r
+}\r
+\r
+/* Return # of times o appears in s. */\r
+Py_ssize_t\r
+PySequence_Count(PyObject *s, PyObject *o)\r
+{\r
+ return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);\r
+}\r
+\r
+/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.\r
+ * Use sq_contains if possible, else defer to _PySequence_IterSearch().\r
+ */\r
+int\r
+PySequence_Contains(PyObject *seq, PyObject *ob)\r
+{\r
+ Py_ssize_t result;\r
+ if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {\r
+ PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;\r
+ if (sqm != NULL && sqm->sq_contains != NULL)\r
+ return (*sqm->sq_contains)(seq, ob);\r
+ }\r
+ result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);\r
+ return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);\r
+}\r
+\r
+/* Backwards compatibility */\r
+#undef PySequence_In\r
+int\r
+PySequence_In(PyObject *w, PyObject *v)\r
+{\r
+ return PySequence_Contains(w, v);\r
+}\r
+\r
+Py_ssize_t\r
+PySequence_Index(PyObject *s, PyObject *o)\r
+{\r
+ return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);\r
+}\r
+\r
+/* Operations on mappings */\r
+\r
+int\r
+PyMapping_Check(PyObject *o)\r
+{\r
+ if (o && PyInstance_Check(o))\r
+ return PyObject_HasAttrString(o, "__getitem__");\r
+\r
+ return o && o->ob_type->tp_as_mapping &&\r
+ o->ob_type->tp_as_mapping->mp_subscript &&\r
+ !(o->ob_type->tp_as_sequence &&\r
+ o->ob_type->tp_as_sequence->sq_slice);\r
+}\r
+\r
+Py_ssize_t\r
+PyMapping_Size(PyObject *o)\r
+{\r
+ PyMappingMethods *m;\r
+\r
+ if (o == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+\r
+ m = o->ob_type->tp_as_mapping;\r
+ if (m && m->mp_length)\r
+ return m->mp_length(o);\r
+\r
+ type_error("object of type '%.200s' has no len()", o);\r
+ return -1;\r
+}\r
+\r
+#undef PyMapping_Length\r
+Py_ssize_t\r
+PyMapping_Length(PyObject *o)\r
+{\r
+ return PyMapping_Size(o);\r
+}\r
+#define PyMapping_Length PyMapping_Size\r
+\r
+PyObject *\r
+PyMapping_GetItemString(PyObject *o, char *key)\r
+{\r
+ PyObject *okey, *r;\r
+\r
+ if (key == NULL)\r
+ return null_error();\r
+\r
+ okey = PyString_FromString(key);\r
+ if (okey == NULL)\r
+ return NULL;\r
+ r = PyObject_GetItem(o, okey);\r
+ Py_DECREF(okey);\r
+ return r;\r
+}\r
+\r
+int\r
+PyMapping_SetItemString(PyObject *o, char *key, PyObject *value)\r
+{\r
+ PyObject *okey;\r
+ int r;\r
+\r
+ if (key == NULL) {\r
+ null_error();\r
+ return -1;\r
+ }\r
+\r
+ okey = PyString_FromString(key);\r
+ if (okey == NULL)\r
+ return -1;\r
+ r = PyObject_SetItem(o, okey, value);\r
+ Py_DECREF(okey);\r
+ return r;\r
+}\r
+\r
+int\r
+PyMapping_HasKeyString(PyObject *o, char *key)\r
+{\r
+ PyObject *v;\r
+\r
+ v = PyMapping_GetItemString(o, key);\r
+ if (v) {\r
+ Py_DECREF(v);\r
+ return 1;\r
+ }\r
+ PyErr_Clear();\r
+ return 0;\r
+}\r
+\r
+int\r
+PyMapping_HasKey(PyObject *o, PyObject *key)\r
+{\r
+ PyObject *v;\r
+\r
+ v = PyObject_GetItem(o, key);\r
+ if (v) {\r
+ Py_DECREF(v);\r
+ return 1;\r
+ }\r
+ PyErr_Clear();\r
+ return 0;\r
+}\r
+\r
+/* Operations on callable objects */\r
+\r
+/* XXX PyCallable_Check() is in object.c */\r
+\r
+PyObject *\r
+PyObject_CallObject(PyObject *o, PyObject *a)\r
+{\r
+ return PyEval_CallObjectWithKeywords(o, a, NULL);\r
+}\r
+\r
+PyObject *\r
+PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw)\r
+{\r
+ ternaryfunc call;\r
+\r
+ if ((call = func->ob_type->tp_call) != NULL) {\r
+ PyObject *result;\r
+ if (Py_EnterRecursiveCall(" while calling a Python object"))\r
+ return NULL;\r
+ result = (*call)(func, arg, kw);\r
+ Py_LeaveRecursiveCall();\r
+ if (result == NULL && !PyErr_Occurred())\r
+ PyErr_SetString(\r
+ PyExc_SystemError,\r
+ "NULL result without error in PyObject_Call");\r
+ return result;\r
+ }\r
+ PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",\r
+ func->ob_type->tp_name);\r
+ return NULL;\r
+}\r
+\r
+static PyObject*\r
+call_function_tail(PyObject *callable, PyObject *args)\r
+{\r
+ PyObject *retval;\r
+\r
+ if (args == NULL)\r
+ return NULL;\r
+\r
+ if (!PyTuple_Check(args)) {\r
+ PyObject *a;\r
+\r
+ a = PyTuple_New(1);\r
+ if (a == NULL) {\r
+ Py_DECREF(args);\r
+ return NULL;\r
+ }\r
+ PyTuple_SET_ITEM(a, 0, args);\r
+ args = a;\r
+ }\r
+ retval = PyObject_Call(callable, args, NULL);\r
+\r
+ Py_DECREF(args);\r
+\r
+ return retval;\r
+}\r
+\r
+PyObject *\r
+PyObject_CallFunction(PyObject *callable, char *format, ...)\r
+{\r
+ va_list va;\r
+ PyObject *args;\r
+\r
+ if (callable == NULL)\r
+ return null_error();\r
+\r
+ if (format && *format) {\r
+ va_start(va, format);\r
+ args = Py_VaBuildValue(format, va);\r
+ va_end(va);\r
+ }\r
+ else\r
+ args = PyTuple_New(0);\r
+\r
+ return call_function_tail(callable, args);\r
+}\r
+\r
+PyObject *\r
+_PyObject_CallFunction_SizeT(PyObject *callable, char *format, ...)\r
+{\r
+ va_list va;\r
+ PyObject *args;\r
+\r
+ if (callable == NULL)\r
+ return null_error();\r
+\r
+ if (format && *format) {\r
+ va_start(va, format);\r
+ args = _Py_VaBuildValue_SizeT(format, va);\r
+ va_end(va);\r
+ }\r
+ else\r
+ args = PyTuple_New(0);\r
+\r
+ return call_function_tail(callable, args);\r
+}\r
+\r
+PyObject *\r
+PyObject_CallMethod(PyObject *o, char *name, char *format, ...)\r
+{\r
+ va_list va;\r
+ PyObject *args;\r
+ PyObject *func = NULL;\r
+ PyObject *retval = NULL;\r
+\r
+ if (o == NULL || name == NULL)\r
+ return null_error();\r
+\r
+ func = PyObject_GetAttrString(o, name);\r
+ if (func == NULL)\r
+ return NULL;\r
+\r
+ if (!PyCallable_Check(func)) {\r
+ type_error("attribute of type '%.200s' is not callable", func);\r
+ goto exit;\r
+ }\r
+\r
+ if (format && *format) {\r
+ va_start(va, format);\r
+ args = Py_VaBuildValue(format, va);\r
+ va_end(va);\r
+ }\r
+ else\r
+ args = PyTuple_New(0);\r
+\r
+ retval = call_function_tail(func, args);\r
+\r
+ exit:\r
+ /* args gets consumed in call_function_tail */\r
+ Py_XDECREF(func);\r
+\r
+ return retval;\r
+}\r
+\r
+PyObject *\r
+_PyObject_CallMethod_SizeT(PyObject *o, char *name, char *format, ...)\r
+{\r
+ va_list va;\r
+ PyObject *args;\r
+ PyObject *func = NULL;\r
+ PyObject *retval = NULL;\r
+\r
+ if (o == NULL || name == NULL)\r
+ return null_error();\r
+\r
+ func = PyObject_GetAttrString(o, name);\r
+ if (func == NULL)\r
+ return NULL;\r
+\r
+ if (!PyCallable_Check(func)) {\r
+ type_error("attribute of type '%.200s' is not callable", func);\r
+ goto exit;\r
+ }\r
+\r
+ if (format && *format) {\r
+ va_start(va, format);\r
+ args = _Py_VaBuildValue_SizeT(format, va);\r
+ va_end(va);\r
+ }\r
+ else\r
+ args = PyTuple_New(0);\r
+\r
+ retval = call_function_tail(func, args);\r
+\r
+ exit:\r
+ /* args gets consumed in call_function_tail */\r
+ Py_XDECREF(func);\r
+\r
+ return retval;\r
+}\r
+\r
+\r
+static PyObject *\r
+objargs_mktuple(va_list va)\r
+{\r
+ int i, n = 0;\r
+ va_list countva;\r
+ PyObject *result, *tmp;\r
+\r
+#ifdef VA_LIST_IS_ARRAY\r
+ memcpy(countva, va, sizeof(va_list));\r
+#else\r
+#ifdef __va_copy\r
+ __va_copy(countva, va);\r
+#else\r
+ countva = va;\r
+#endif\r
+#endif\r
+\r
+ while (((PyObject *)va_arg(countva, PyObject *)) != NULL)\r
+ ++n;\r
+ result = PyTuple_New(n);\r
+ if (result != NULL && n > 0) {\r
+ for (i = 0; i < n; ++i) {\r
+ tmp = (PyObject *)va_arg(va, PyObject *);\r
+ PyTuple_SET_ITEM(result, i, tmp);\r
+ Py_INCREF(tmp);\r
+ }\r
+ }\r
+ return result;\r
+}\r
+\r
+PyObject *\r
+PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)\r
+{\r
+ PyObject *args, *tmp;\r
+ va_list vargs;\r
+\r
+ if (callable == NULL || name == NULL)\r
+ return null_error();\r
+\r
+ callable = PyObject_GetAttr(callable, name);\r
+ if (callable == NULL)\r
+ return NULL;\r
+\r
+ /* count the args */\r
+ va_start(vargs, name);\r
+ args = objargs_mktuple(vargs);\r
+ va_end(vargs);\r
+ if (args == NULL) {\r
+ Py_DECREF(callable);\r
+ return NULL;\r
+ }\r
+ tmp = PyObject_Call(callable, args, NULL);\r
+ Py_DECREF(args);\r
+ Py_DECREF(callable);\r
+\r
+ return tmp;\r
+}\r
+\r
+PyObject *\r
+PyObject_CallFunctionObjArgs(PyObject *callable, ...)\r
+{\r
+ PyObject *args, *tmp;\r
+ va_list vargs;\r
+\r
+ if (callable == NULL)\r
+ return null_error();\r
+\r
+ /* count the args */\r
+ va_start(vargs, callable);\r
+ args = objargs_mktuple(vargs);\r
+ va_end(vargs);\r
+ if (args == NULL)\r
+ return NULL;\r
+ tmp = PyObject_Call(callable, args, NULL);\r
+ Py_DECREF(args);\r
+\r
+ return tmp;\r
+}\r
+\r
+\r
+/* isinstance(), issubclass() */\r
+\r
+/* abstract_get_bases() has logically 4 return states, with a sort of 0th\r
+ * state that will almost never happen.\r
+ *\r
+ * 0. creating the __bases__ static string could get a MemoryError\r
+ * 1. getattr(cls, '__bases__') could raise an AttributeError\r
+ * 2. getattr(cls, '__bases__') could raise some other exception\r
+ * 3. getattr(cls, '__bases__') could return a tuple\r
+ * 4. getattr(cls, '__bases__') could return something other than a tuple\r
+ *\r
+ * Only state #3 is a non-error state and only it returns a non-NULL object\r
+ * (it returns the retrieved tuple).\r
+ *\r
+ * Any raised AttributeErrors are masked by clearing the exception and\r
+ * returning NULL. If an object other than a tuple comes out of __bases__,\r
+ * then again, the return value is NULL. So yes, these two situations\r
+ * produce exactly the same results: NULL is returned and no error is set.\r
+ *\r
+ * If some exception other than AttributeError is raised, then NULL is also\r
+ * returned, but the exception is not cleared. That's because we want the\r
+ * exception to be propagated along.\r
+ *\r
+ * Callers are expected to test for PyErr_Occurred() when the return value\r
+ * is NULL to decide whether a valid exception should be propagated or not.\r
+ * When there's no exception to propagate, it's customary for the caller to\r
+ * set a TypeError.\r
+ */\r
+static PyObject *\r
+abstract_get_bases(PyObject *cls)\r
+{\r
+ static PyObject *__bases__ = NULL;\r
+ PyObject *bases;\r
+\r
+ if (__bases__ == NULL) {\r
+ __bases__ = PyString_InternFromString("__bases__");\r
+ if (__bases__ == NULL)\r
+ return NULL;\r
+ }\r
+ bases = PyObject_GetAttr(cls, __bases__);\r
+ if (bases == NULL) {\r
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))\r
+ PyErr_Clear();\r
+ return NULL;\r
+ }\r
+ if (!PyTuple_Check(bases)) {\r
+ Py_DECREF(bases);\r
+ return NULL;\r
+ }\r
+ return bases;\r
+}\r
+\r
+\r
+static int\r
+abstract_issubclass(PyObject *derived, PyObject *cls)\r
+{\r
+ PyObject *bases = NULL;\r
+ Py_ssize_t i, n;\r
+ int r = 0;\r
+\r
+ while (1) {\r
+ if (derived == cls)\r
+ return 1;\r
+ bases = abstract_get_bases(derived);\r
+ if (bases == NULL) {\r
+ if (PyErr_Occurred())\r
+ return -1;\r
+ return 0;\r
+ }\r
+ n = PyTuple_GET_SIZE(bases);\r
+ if (n == 0) {\r
+ Py_DECREF(bases);\r
+ return 0;\r
+ }\r
+ /* Avoid recursivity in the single inheritance case */\r
+ if (n == 1) {\r
+ derived = PyTuple_GET_ITEM(bases, 0);\r
+ Py_DECREF(bases);\r
+ continue;\r
+ }\r
+ for (i = 0; i < n; i++) {\r
+ r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);\r
+ if (r != 0)\r
+ break;\r
+ }\r
+ Py_DECREF(bases);\r
+ return r;\r
+ }\r
+}\r
+\r
+static int\r
+check_class(PyObject *cls, const char *error)\r
+{\r
+ PyObject *bases = abstract_get_bases(cls);\r
+ if (bases == NULL) {\r
+ /* Do not mask errors. */\r
+ if (!PyErr_Occurred())\r
+ PyErr_SetString(PyExc_TypeError, error);\r
+ return 0;\r
+ }\r
+ Py_DECREF(bases);\r
+ return -1;\r
+}\r
+\r
+static int\r
+recursive_isinstance(PyObject *inst, PyObject *cls)\r
+{\r
+ PyObject *icls;\r
+ static PyObject *__class__ = NULL;\r
+ int retval = 0;\r
+\r
+ if (__class__ == NULL) {\r
+ __class__ = PyString_InternFromString("__class__");\r
+ if (__class__ == NULL)\r
+ return -1;\r
+ }\r
+\r
+ if (PyClass_Check(cls) && PyInstance_Check(inst)) {\r
+ PyObject *inclass =\r
+ (PyObject*)((PyInstanceObject*)inst)->in_class;\r
+ retval = PyClass_IsSubclass(inclass, cls);\r
+ }\r
+ else if (PyType_Check(cls)) {\r
+ retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);\r
+ if (retval == 0) {\r
+ PyObject *c = PyObject_GetAttr(inst, __class__);\r
+ if (c == NULL) {\r
+ PyErr_Clear();\r
+ }\r
+ else {\r
+ if (c != (PyObject *)(inst->ob_type) &&\r
+ PyType_Check(c))\r
+ retval = PyType_IsSubtype(\r
+ (PyTypeObject *)c,\r
+ (PyTypeObject *)cls);\r
+ Py_DECREF(c);\r
+ }\r
+ }\r
+ }\r
+ else {\r
+ if (!check_class(cls,\r
+ "isinstance() arg 2 must be a class, type,"\r
+ " or tuple of classes and types"))\r
+ return -1;\r
+ icls = PyObject_GetAttr(inst, __class__);\r
+ if (icls == NULL) {\r
+ PyErr_Clear();\r
+ retval = 0;\r
+ }\r
+ else {\r
+ retval = abstract_issubclass(icls, cls);\r
+ Py_DECREF(icls);\r
+ }\r
+ }\r
+\r
+ return retval;\r
+}\r
+\r
+int\r
+PyObject_IsInstance(PyObject *inst, PyObject *cls)\r
+{\r
+ static PyObject *name = NULL;\r
+\r
+ /* Quick test for an exact match */\r
+ if (Py_TYPE(inst) == (PyTypeObject *)cls)\r
+ return 1;\r
+\r
+ if (PyTuple_Check(cls)) {\r
+ Py_ssize_t i;\r
+ Py_ssize_t n;\r
+ int r = 0;\r
+\r
+ if (Py_EnterRecursiveCall(" in __instancecheck__"))\r
+ return -1;\r
+ n = PyTuple_GET_SIZE(cls);\r
+ for (i = 0; i < n; ++i) {\r
+ PyObject *item = PyTuple_GET_ITEM(cls, i);\r
+ r = PyObject_IsInstance(inst, item);\r
+ if (r != 0)\r
+ /* either found it, or got an error */\r
+ break;\r
+ }\r
+ Py_LeaveRecursiveCall();\r
+ return r;\r
+ }\r
+\r
+ if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {\r
+ PyObject *checker;\r
+ checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name);\r
+ if (checker != NULL) {\r
+ PyObject *res;\r
+ int ok = -1;\r
+ if (Py_EnterRecursiveCall(" in __instancecheck__")) {\r
+ Py_DECREF(checker);\r
+ return ok;\r
+ }\r
+ res = PyObject_CallFunctionObjArgs(checker, inst, NULL);\r
+ Py_LeaveRecursiveCall();\r
+ Py_DECREF(checker);\r
+ if (res != NULL) {\r
+ ok = PyObject_IsTrue(res);\r
+ Py_DECREF(res);\r
+ }\r
+ return ok;\r
+ }\r
+ else if (PyErr_Occurred())\r
+ return -1;\r
+ }\r
+ return recursive_isinstance(inst, cls);\r
+}\r
+\r
+static int\r
+recursive_issubclass(PyObject *derived, PyObject *cls)\r
+{\r
+ int retval;\r
+\r
+ if (PyType_Check(cls) && PyType_Check(derived)) {\r
+ /* Fast path (non-recursive) */\r
+ return PyType_IsSubtype(\r
+ (PyTypeObject *)derived, (PyTypeObject *)cls);\r
+ }\r
+ if (!PyClass_Check(derived) || !PyClass_Check(cls)) {\r
+ if (!check_class(derived,\r
+ "issubclass() arg 1 must be a class"))\r
+ return -1;\r
+\r
+ if (!check_class(cls,\r
+ "issubclass() arg 2 must be a class"\r
+ " or tuple of classes"))\r
+ return -1;\r
+ retval = abstract_issubclass(derived, cls);\r
+ }\r
+ else {\r
+ /* shortcut */\r
+ if (!(retval = (derived == cls)))\r
+ retval = PyClass_IsSubclass(derived, cls);\r
+ }\r
+\r
+ return retval;\r
+}\r
+\r
+int\r
+PyObject_IsSubclass(PyObject *derived, PyObject *cls)\r
+{\r
+ static PyObject *name = NULL;\r
+\r
+ if (PyTuple_Check(cls)) {\r
+ Py_ssize_t i;\r
+ Py_ssize_t n;\r
+ int r = 0;\r
+\r
+ if (Py_EnterRecursiveCall(" in __subclasscheck__"))\r
+ return -1;\r
+ n = PyTuple_GET_SIZE(cls);\r
+ for (i = 0; i < n; ++i) {\r
+ PyObject *item = PyTuple_GET_ITEM(cls, i);\r
+ r = PyObject_IsSubclass(derived, item);\r
+ if (r != 0)\r
+ /* either found it, or got an error */\r
+ break;\r
+ }\r
+ Py_LeaveRecursiveCall();\r
+ return r;\r
+ }\r
+ if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {\r
+ PyObject *checker;\r
+ checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name);\r
+ if (checker != NULL) {\r
+ PyObject *res;\r
+ int ok = -1;\r
+ if (Py_EnterRecursiveCall(" in __subclasscheck__")) {\r
+ Py_DECREF(checker);\r
+ return ok;\r
+ }\r
+ res = PyObject_CallFunctionObjArgs(checker, derived, NULL);\r
+ Py_LeaveRecursiveCall();\r
+ Py_DECREF(checker);\r
+ if (res != NULL) {\r
+ ok = PyObject_IsTrue(res);\r
+ Py_DECREF(res);\r
+ }\r
+ return ok;\r
+ }\r
+ else if (PyErr_Occurred()) {\r
+ return -1;\r
+ }\r
+ }\r
+ return recursive_issubclass(derived, cls);\r
+}\r
+\r
+int\r
+_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)\r
+{\r
+ return recursive_isinstance(inst, cls);\r
+}\r
+\r
+int\r
+_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)\r
+{\r
+ return recursive_issubclass(derived, cls);\r
+}\r
+\r
+\r
+PyObject *\r
+PyObject_GetIter(PyObject *o)\r
+{\r
+ PyTypeObject *t = o->ob_type;\r
+ getiterfunc f = NULL;\r
+ if (PyType_HasFeature(t, Py_TPFLAGS_HAVE_ITER))\r
+ f = t->tp_iter;\r
+ if (f == NULL) {\r
+ if (PySequence_Check(o))\r
+ return PySeqIter_New(o);\r
+ return type_error("'%.200s' object is not iterable", o);\r
+ }\r
+ else {\r
+ PyObject *res = (*f)(o);\r
+ if (res != NULL && !PyIter_Check(res)) {\r
+ PyErr_Format(PyExc_TypeError,\r
+ "iter() returned non-iterator "\r
+ "of type '%.100s'",\r
+ res->ob_type->tp_name);\r
+ Py_DECREF(res);\r
+ res = NULL;\r
+ }\r
+ return res;\r
+ }\r
+}\r
+\r
+/* Return next item.\r
+ * If an error occurs, return NULL. PyErr_Occurred() will be true.\r
+ * If the iteration terminates normally, return NULL and clear the\r
+ * PyExc_StopIteration exception (if it was set). PyErr_Occurred()\r
+ * will be false.\r
+ * Else return the next object. PyErr_Occurred() will be false.\r
+ */\r
+PyObject *\r
+PyIter_Next(PyObject *iter)\r
+{\r
+ PyObject *result;\r
+ result = (*iter->ob_type->tp_iternext)(iter);\r
+ if (result == NULL &&\r
+ PyErr_Occurred() &&\r
+ PyErr_ExceptionMatches(PyExc_StopIteration))\r
+ PyErr_Clear();\r
+ return result;\r
+}\r