+++ /dev/null
-/* PyBytes (bytearray) implementation */\r
-\r
-#define PY_SSIZE_T_CLEAN\r
-#include "Python.h"\r
-#include "structmember.h"\r
-#include "bytes_methods.h"\r
-\r
-char _PyByteArray_empty_string[] = "";\r
-\r
-void\r
-PyByteArray_Fini(void)\r
-{\r
-}\r
-\r
-int\r
-PyByteArray_Init(void)\r
-{\r
- return 1;\r
-}\r
-\r
-/* end nullbytes support */\r
-\r
-/* Helpers */\r
-\r
-static int\r
-_getbytevalue(PyObject* arg, int *value)\r
-{\r
- long face_value;\r
-\r
- if (PyBytes_CheckExact(arg)) {\r
- if (Py_SIZE(arg) != 1) {\r
- PyErr_SetString(PyExc_ValueError, "string must be of size 1");\r
- return 0;\r
- }\r
- *value = Py_CHARMASK(((PyBytesObject*)arg)->ob_sval[0]);\r
- return 1;\r
- }\r
- else if (PyInt_Check(arg) || PyLong_Check(arg)) {\r
- face_value = PyLong_AsLong(arg);\r
- }\r
- else {\r
- PyObject *index = PyNumber_Index(arg);\r
- if (index == NULL) {\r
- PyErr_Format(PyExc_TypeError,\r
- "an integer or string of size 1 is required");\r
- return 0;\r
- }\r
- face_value = PyLong_AsLong(index);\r
- Py_DECREF(index);\r
- }\r
-\r
- if (face_value < 0 || face_value >= 256) {\r
- /* this includes the OverflowError in case the long is too large */\r
- PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");\r
- return 0;\r
- }\r
-\r
- *value = face_value;\r
- return 1;\r
-}\r
-\r
-static Py_ssize_t\r
-bytearray_buffer_getreadbuf(PyByteArrayObject *self, Py_ssize_t index, const void **ptr)\r
-{\r
- if ( index != 0 ) {\r
- PyErr_SetString(PyExc_SystemError,\r
- "accessing non-existent bytes segment");\r
- return -1;\r
- }\r
- *ptr = (void *)PyByteArray_AS_STRING(self);\r
- return Py_SIZE(self);\r
-}\r
-\r
-static Py_ssize_t\r
-bytearray_buffer_getwritebuf(PyByteArrayObject *self, Py_ssize_t index, const void **ptr)\r
-{\r
- if ( index != 0 ) {\r
- PyErr_SetString(PyExc_SystemError,\r
- "accessing non-existent bytes segment");\r
- return -1;\r
- }\r
- *ptr = (void *)PyByteArray_AS_STRING(self);\r
- return Py_SIZE(self);\r
-}\r
-\r
-static Py_ssize_t\r
-bytearray_buffer_getsegcount(PyByteArrayObject *self, Py_ssize_t *lenp)\r
-{\r
- if ( lenp )\r
- *lenp = Py_SIZE(self);\r
- return 1;\r
-}\r
-\r
-static Py_ssize_t\r
-bytearray_buffer_getcharbuf(PyByteArrayObject *self, Py_ssize_t index, const char **ptr)\r
-{\r
- if ( index != 0 ) {\r
- PyErr_SetString(PyExc_SystemError,\r
- "accessing non-existent bytes segment");\r
- return -1;\r
- }\r
- *ptr = PyByteArray_AS_STRING(self);\r
- return Py_SIZE(self);\r
-}\r
-\r
-static int\r
-bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)\r
-{\r
- int ret;\r
- void *ptr;\r
- if (view == NULL) {\r
- obj->ob_exports++;\r
- return 0;\r
- }\r
- ptr = (void *) PyByteArray_AS_STRING(obj);\r
- ret = PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);\r
- if (ret >= 0) {\r
- obj->ob_exports++;\r
- }\r
- return ret;\r
-}\r
-\r
-static void\r
-bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)\r
-{\r
- obj->ob_exports--;\r
-}\r
-\r
-static Py_ssize_t\r
-_getbuffer(PyObject *obj, Py_buffer *view)\r
-{\r
- PyBufferProcs *buffer = Py_TYPE(obj)->tp_as_buffer;\r
-\r
- if (buffer == NULL || buffer->bf_getbuffer == NULL)\r
- {\r
- PyErr_Format(PyExc_TypeError,\r
- "Type %.100s doesn't support the buffer API",\r
- Py_TYPE(obj)->tp_name);\r
- return -1;\r
- }\r
-\r
- if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0)\r
- return -1;\r
- return view->len;\r
-}\r
-\r
-static int\r
-_canresize(PyByteArrayObject *self)\r
-{\r
- if (self->ob_exports > 0) {\r
- PyErr_SetString(PyExc_BufferError,\r
- "Existing exports of data: object cannot be re-sized");\r
- return 0;\r
- }\r
- return 1;\r
-}\r
-\r
-/* Direct API functions */\r
-\r
-PyObject *\r
-PyByteArray_FromObject(PyObject *input)\r
-{\r
- return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,\r
- input, NULL);\r
-}\r
-\r
-PyObject *\r
-PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)\r
-{\r
- PyByteArrayObject *new;\r
- Py_ssize_t alloc;\r
-\r
- if (size < 0) {\r
- PyErr_SetString(PyExc_SystemError,\r
- "Negative size passed to PyByteArray_FromStringAndSize");\r
- return NULL;\r
- }\r
-\r
- new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);\r
- if (new == NULL)\r
- return NULL;\r
-\r
- if (size == 0) {\r
- new->ob_bytes = NULL;\r
- alloc = 0;\r
- }\r
- else {\r
- alloc = size + 1;\r
- new->ob_bytes = PyMem_Malloc(alloc);\r
- if (new->ob_bytes == NULL) {\r
- Py_DECREF(new);\r
- return PyErr_NoMemory();\r
- }\r
- if (bytes != NULL && size > 0)\r
- memcpy(new->ob_bytes, bytes, size);\r
- new->ob_bytes[size] = '\0'; /* Trailing null byte */\r
- }\r
- Py_SIZE(new) = size;\r
- new->ob_alloc = alloc;\r
- new->ob_exports = 0;\r
-\r
- return (PyObject *)new;\r
-}\r
-\r
-Py_ssize_t\r
-PyByteArray_Size(PyObject *self)\r
-{\r
- assert(self != NULL);\r
- assert(PyByteArray_Check(self));\r
-\r
- return PyByteArray_GET_SIZE(self);\r
-}\r
-\r
-char *\r
-PyByteArray_AsString(PyObject *self)\r
-{\r
- assert(self != NULL);\r
- assert(PyByteArray_Check(self));\r
-\r
- return PyByteArray_AS_STRING(self);\r
-}\r
-\r
-int\r
-PyByteArray_Resize(PyObject *self, Py_ssize_t size)\r
-{\r
- void *sval;\r
- Py_ssize_t alloc = ((PyByteArrayObject *)self)->ob_alloc;\r
-\r
- assert(self != NULL);\r
- assert(PyByteArray_Check(self));\r
- assert(size >= 0);\r
-\r
- if (size == Py_SIZE(self)) {\r
- return 0;\r
- }\r
- if (!_canresize((PyByteArrayObject *)self)) {\r
- return -1;\r
- }\r
-\r
- if (size < alloc / 2) {\r
- /* Major downsize; resize down to exact size */\r
- alloc = size + 1;\r
- }\r
- else if (size < alloc) {\r
- /* Within allocated size; quick exit */\r
- Py_SIZE(self) = size;\r
- ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null */\r
- return 0;\r
- }\r
- else if (size <= alloc * 1.125) {\r
- /* Moderate upsize; overallocate similar to list_resize() */\r
- alloc = size + (size >> 3) + (size < 9 ? 3 : 6);\r
- }\r
- else {\r
- /* Major upsize; resize up to exact size */\r
- alloc = size + 1;\r
- }\r
-\r
- sval = PyMem_Realloc(((PyByteArrayObject *)self)->ob_bytes, alloc);\r
- if (sval == NULL) {\r
- PyErr_NoMemory();\r
- return -1;\r
- }\r
-\r
- ((PyByteArrayObject *)self)->ob_bytes = sval;\r
- Py_SIZE(self) = size;\r
- ((PyByteArrayObject *)self)->ob_alloc = alloc;\r
- ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null byte */\r
-\r
- return 0;\r
-}\r
-\r
-PyObject *\r
-PyByteArray_Concat(PyObject *a, PyObject *b)\r
-{\r
- Py_ssize_t size;\r
- Py_buffer va, vb;\r
- PyByteArrayObject *result = NULL;\r
-\r
- va.len = -1;\r
- vb.len = -1;\r
- if (_getbuffer(a, &va) < 0 ||\r
- _getbuffer(b, &vb) < 0) {\r
- PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",\r
- Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);\r
- goto done;\r
- }\r
-\r
- size = va.len + vb.len;\r
- if (size < 0) {\r
- PyErr_NoMemory();\r
- goto done;\r
- }\r
-\r
- result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);\r
- if (result != NULL) {\r
- memcpy(result->ob_bytes, va.buf, va.len);\r
- memcpy(result->ob_bytes + va.len, vb.buf, vb.len);\r
- }\r
-\r
- done:\r
- if (va.len != -1)\r
- PyBuffer_Release(&va);\r
- if (vb.len != -1)\r
- PyBuffer_Release(&vb);\r
- return (PyObject *)result;\r
-}\r
-\r
-/* Functions stuffed into the type object */\r
-\r
-static Py_ssize_t\r
-bytearray_length(PyByteArrayObject *self)\r
-{\r
- return Py_SIZE(self);\r
-}\r
-\r
-static PyObject *\r
-bytearray_iconcat(PyByteArrayObject *self, PyObject *other)\r
-{\r
- Py_ssize_t mysize;\r
- Py_ssize_t size;\r
- Py_buffer vo;\r
-\r
- if (_getbuffer(other, &vo) < 0) {\r
- PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",\r
- Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);\r
- return NULL;\r
- }\r
-\r
- mysize = Py_SIZE(self);\r
- size = mysize + vo.len;\r
- if (size < 0) {\r
- PyBuffer_Release(&vo);\r
- return PyErr_NoMemory();\r
- }\r
- if (size < self->ob_alloc) {\r
- Py_SIZE(self) = size;\r
- self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */\r
- }\r
- else if (PyByteArray_Resize((PyObject *)self, size) < 0) {\r
- PyBuffer_Release(&vo);\r
- return NULL;\r
- }\r
- memcpy(self->ob_bytes + mysize, vo.buf, vo.len);\r
- PyBuffer_Release(&vo);\r
- Py_INCREF(self);\r
- return (PyObject *)self;\r
-}\r
-\r
-static PyObject *\r
-bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)\r
-{\r
- PyByteArrayObject *result;\r
- Py_ssize_t mysize;\r
- Py_ssize_t size;\r
-\r
- if (count < 0)\r
- count = 0;\r
- mysize = Py_SIZE(self);\r
- size = mysize * count;\r
- if (count != 0 && size / count != mysize)\r
- return PyErr_NoMemory();\r
- result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);\r
- if (result != NULL && size != 0) {\r
- if (mysize == 1)\r
- memset(result->ob_bytes, self->ob_bytes[0], size);\r
- else {\r
- Py_ssize_t i;\r
- for (i = 0; i < count; i++)\r
- memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);\r
- }\r
- }\r
- return (PyObject *)result;\r
-}\r
-\r
-static PyObject *\r
-bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)\r
-{\r
- Py_ssize_t mysize;\r
- Py_ssize_t size;\r
-\r
- if (count < 0)\r
- count = 0;\r
- mysize = Py_SIZE(self);\r
- size = mysize * count;\r
- if (count != 0 && size / count != mysize)\r
- return PyErr_NoMemory();\r
- if (size < self->ob_alloc) {\r
- Py_SIZE(self) = size;\r
- self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */\r
- }\r
- else if (PyByteArray_Resize((PyObject *)self, size) < 0)\r
- return NULL;\r
-\r
- if (mysize == 1)\r
- memset(self->ob_bytes, self->ob_bytes[0], size);\r
- else {\r
- Py_ssize_t i;\r
- for (i = 1; i < count; i++)\r
- memcpy(self->ob_bytes + i*mysize, self->ob_bytes, mysize);\r
- }\r
-\r
- Py_INCREF(self);\r
- return (PyObject *)self;\r
-}\r
-\r
-static PyObject *\r
-bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)\r
-{\r
- if (i < 0)\r
- i += Py_SIZE(self);\r
- if (i < 0 || i >= Py_SIZE(self)) {\r
- PyErr_SetString(PyExc_IndexError, "bytearray index out of range");\r
- return NULL;\r
- }\r
- return PyInt_FromLong((unsigned char)(self->ob_bytes[i]));\r
-}\r
-\r
-static PyObject *\r
-bytearray_subscript(PyByteArrayObject *self, PyObject *index)\r
-{\r
- if (PyIndex_Check(index)) {\r
- Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);\r
-\r
- if (i == -1 && PyErr_Occurred())\r
- return NULL;\r
-\r
- if (i < 0)\r
- i += PyByteArray_GET_SIZE(self);\r
-\r
- if (i < 0 || i >= Py_SIZE(self)) {\r
- PyErr_SetString(PyExc_IndexError, "bytearray index out of range");\r
- return NULL;\r
- }\r
- return PyInt_FromLong((unsigned char)(self->ob_bytes[i]));\r
- }\r
- else if (PySlice_Check(index)) {\r
- Py_ssize_t start, stop, step, slicelength, cur, i;\r
- if (PySlice_GetIndicesEx((PySliceObject *)index,\r
- PyByteArray_GET_SIZE(self),\r
- &start, &stop, &step, &slicelength) < 0) {\r
- return NULL;\r
- }\r
-\r
- if (slicelength <= 0)\r
- return PyByteArray_FromStringAndSize("", 0);\r
- else if (step == 1) {\r
- return PyByteArray_FromStringAndSize(self->ob_bytes + start,\r
- slicelength);\r
- }\r
- else {\r
- char *source_buf = PyByteArray_AS_STRING(self);\r
- char *result_buf = (char *)PyMem_Malloc(slicelength);\r
- PyObject *result;\r
-\r
- if (result_buf == NULL)\r
- return PyErr_NoMemory();\r
-\r
- for (cur = start, i = 0; i < slicelength;\r
- cur += step, i++) {\r
- result_buf[i] = source_buf[cur];\r
- }\r
- result = PyByteArray_FromStringAndSize(result_buf, slicelength);\r
- PyMem_Free(result_buf);\r
- return result;\r
- }\r
- }\r
- else {\r
- PyErr_SetString(PyExc_TypeError, "bytearray indices must be integers");\r
- return NULL;\r
- }\r
-}\r
-\r
-static int\r
-bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,\r
- PyObject *values)\r
-{\r
- Py_ssize_t avail, needed;\r
- void *bytes;\r
- Py_buffer vbytes;\r
- int res = 0;\r
-\r
- vbytes.len = -1;\r
- if (values == (PyObject *)self) {\r
- /* Make a copy and call this function recursively */\r
- int err;\r
- values = PyByteArray_FromObject(values);\r
- if (values == NULL)\r
- return -1;\r
- err = bytearray_setslice(self, lo, hi, values);\r
- Py_DECREF(values);\r
- return err;\r
- }\r
- if (values == NULL) {\r
- /* del b[lo:hi] */\r
- bytes = NULL;\r
- needed = 0;\r
- }\r
- else {\r
- if (_getbuffer(values, &vbytes) < 0) {\r
- PyErr_Format(PyExc_TypeError,\r
- "can't set bytearray slice from %.100s",\r
- Py_TYPE(values)->tp_name);\r
- return -1;\r
- }\r
- needed = vbytes.len;\r
- bytes = vbytes.buf;\r
- }\r
-\r
- if (lo < 0)\r
- lo = 0;\r
- if (hi < lo)\r
- hi = lo;\r
- if (hi > Py_SIZE(self))\r
- hi = Py_SIZE(self);\r
-\r
- avail = hi - lo;\r
- if (avail < 0)\r
- lo = hi = avail = 0;\r
-\r
- if (avail != needed) {\r
- if (avail > needed) {\r
- if (!_canresize(self)) {\r
- res = -1;\r
- goto finish;\r
- }\r
- /*\r
- 0 lo hi old_size\r
- | |<----avail----->|<-----tomove------>|\r
- | |<-needed->|<-----tomove------>|\r
- 0 lo new_hi new_size\r
- */\r
- memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,\r
- Py_SIZE(self) - hi);\r
- }\r
- /* XXX(nnorwitz): need to verify this can't overflow! */\r
- if (PyByteArray_Resize((PyObject *)self,\r
- Py_SIZE(self) + needed - avail) < 0) {\r
- res = -1;\r
- goto finish;\r
- }\r
- if (avail < needed) {\r
- /*\r
- 0 lo hi old_size\r
- | |<-avail->|<-----tomove------>|\r
- | |<----needed---->|<-----tomove------>|\r
- 0 lo new_hi new_size\r
- */\r
- memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,\r
- Py_SIZE(self) - lo - needed);\r
- }\r
- }\r
-\r
- if (needed > 0)\r
- memcpy(self->ob_bytes + lo, bytes, needed);\r
-\r
-\r
- finish:\r
- if (vbytes.len != -1)\r
- PyBuffer_Release(&vbytes);\r
- return res;\r
-}\r
-\r
-static int\r
-bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)\r
-{\r
- int ival;\r
-\r
- if (i < 0)\r
- i += Py_SIZE(self);\r
-\r
- if (i < 0 || i >= Py_SIZE(self)) {\r
- PyErr_SetString(PyExc_IndexError, "bytearray index out of range");\r
- return -1;\r
- }\r
-\r
- if (value == NULL)\r
- return bytearray_setslice(self, i, i+1, NULL);\r
-\r
- if (!_getbytevalue(value, &ival))\r
- return -1;\r
-\r
- self->ob_bytes[i] = ival;\r
- return 0;\r
-}\r
-\r
-static int\r
-bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)\r
-{\r
- Py_ssize_t start, stop, step, slicelen, needed;\r
- char *bytes;\r
-\r
- if (PyIndex_Check(index)) {\r
- Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);\r
-\r
- if (i == -1 && PyErr_Occurred())\r
- return -1;\r
-\r
- if (i < 0)\r
- i += PyByteArray_GET_SIZE(self);\r
-\r
- if (i < 0 || i >= Py_SIZE(self)) {\r
- PyErr_SetString(PyExc_IndexError, "bytearray index out of range");\r
- return -1;\r
- }\r
-\r
- if (values == NULL) {\r
- /* Fall through to slice assignment */\r
- start = i;\r
- stop = i + 1;\r
- step = 1;\r
- slicelen = 1;\r
- }\r
- else {\r
- int ival;\r
- if (!_getbytevalue(values, &ival))\r
- return -1;\r
- self->ob_bytes[i] = (char)ival;\r
- return 0;\r
- }\r
- }\r
- else if (PySlice_Check(index)) {\r
- if (PySlice_GetIndicesEx((PySliceObject *)index,\r
- PyByteArray_GET_SIZE(self),\r
- &start, &stop, &step, &slicelen) < 0) {\r
- return -1;\r
- }\r
- }\r
- else {\r
- PyErr_SetString(PyExc_TypeError, "bytearray indices must be integer");\r
- return -1;\r
- }\r
-\r
- if (values == NULL) {\r
- bytes = NULL;\r
- needed = 0;\r
- }\r
- else if (values == (PyObject *)self || !PyByteArray_Check(values)) {\r
- int err;\r
- if (PyNumber_Check(values) || PyUnicode_Check(values)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "can assign only bytes, buffers, or iterables "\r
- "of ints in range(0, 256)");\r
- return -1;\r
- }\r
- /* Make a copy and call this function recursively */\r
- values = PyByteArray_FromObject(values);\r
- if (values == NULL)\r
- return -1;\r
- err = bytearray_ass_subscript(self, index, values);\r
- Py_DECREF(values);\r
- return err;\r
- }\r
- else {\r
- assert(PyByteArray_Check(values));\r
- bytes = ((PyByteArrayObject *)values)->ob_bytes;\r
- needed = Py_SIZE(values);\r
- }\r
- /* Make sure b[5:2] = ... inserts before 5, not before 2. */\r
- if ((step < 0 && start < stop) ||\r
- (step > 0 && start > stop))\r
- stop = start;\r
- if (step == 1) {\r
- if (slicelen != needed) {\r
- if (!_canresize(self))\r
- return -1;\r
- if (slicelen > needed) {\r
- /*\r
- 0 start stop old_size\r
- | |<---slicelen--->|<-----tomove------>|\r
- | |<-needed->|<-----tomove------>|\r
- 0 lo new_hi new_size\r
- */\r
- memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,\r
- Py_SIZE(self) - stop);\r
- }\r
- if (PyByteArray_Resize((PyObject *)self,\r
- Py_SIZE(self) + needed - slicelen) < 0)\r
- return -1;\r
- if (slicelen < needed) {\r
- /*\r
- 0 lo hi old_size\r
- | |<-avail->|<-----tomove------>|\r
- | |<----needed---->|<-----tomove------>|\r
- 0 lo new_hi new_size\r
- */\r
- memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,\r
- Py_SIZE(self) - start - needed);\r
- }\r
- }\r
-\r
- if (needed > 0)\r
- memcpy(self->ob_bytes + start, bytes, needed);\r
-\r
- return 0;\r
- }\r
- else {\r
- if (needed == 0) {\r
- /* Delete slice */\r
- size_t cur;\r
- Py_ssize_t i;\r
-\r
- if (!_canresize(self))\r
- return -1;\r
- if (step < 0) {\r
- stop = start + 1;\r
- start = stop + step * (slicelen - 1) - 1;\r
- step = -step;\r
- }\r
- for (cur = start, i = 0;\r
- i < slicelen; cur += step, i++) {\r
- Py_ssize_t lim = step - 1;\r
-\r
- if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))\r
- lim = PyByteArray_GET_SIZE(self) - cur - 1;\r
-\r
- memmove(self->ob_bytes + cur - i,\r
- self->ob_bytes + cur + 1, lim);\r
- }\r
- /* Move the tail of the bytes, in one chunk */\r
- cur = start + slicelen*step;\r
- if (cur < (size_t)PyByteArray_GET_SIZE(self)) {\r
- memmove(self->ob_bytes + cur - slicelen,\r
- self->ob_bytes + cur,\r
- PyByteArray_GET_SIZE(self) - cur);\r
- }\r
- if (PyByteArray_Resize((PyObject *)self,\r
- PyByteArray_GET_SIZE(self) - slicelen) < 0)\r
- return -1;\r
-\r
- return 0;\r
- }\r
- else {\r
- /* Assign slice */\r
- Py_ssize_t cur, i;\r
-\r
- if (needed != slicelen) {\r
- PyErr_Format(PyExc_ValueError,\r
- "attempt to assign bytes of size %zd "\r
- "to extended slice of size %zd",\r
- needed, slicelen);\r
- return -1;\r
- }\r
- for (cur = start, i = 0; i < slicelen; cur += step, i++)\r
- self->ob_bytes[cur] = bytes[i];\r
- return 0;\r
- }\r
- }\r
-}\r
-\r
-static int\r
-bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)\r
-{\r
- static char *kwlist[] = {"source", "encoding", "errors", 0};\r
- PyObject *arg = NULL;\r
- const char *encoding = NULL;\r
- const char *errors = NULL;\r
- Py_ssize_t count;\r
- PyObject *it;\r
- PyObject *(*iternext)(PyObject *);\r
-\r
- if (Py_SIZE(self) != 0) {\r
- /* Empty previous contents (yes, do this first of all!) */\r
- if (PyByteArray_Resize((PyObject *)self, 0) < 0)\r
- return -1;\r
- }\r
-\r
- /* Parse arguments */\r
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,\r
- &arg, &encoding, &errors))\r
- return -1;\r
-\r
- /* Make a quick exit if no first argument */\r
- if (arg == NULL) {\r
- if (encoding != NULL || errors != NULL) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "encoding or errors without sequence argument");\r
- return -1;\r
- }\r
- return 0;\r
- }\r
-\r
- if (PyBytes_Check(arg)) {\r
- PyObject *new, *encoded;\r
- if (encoding != NULL) {\r
- encoded = PyCodec_Encode(arg, encoding, errors);\r
- if (encoded == NULL)\r
- return -1;\r
- assert(PyBytes_Check(encoded));\r
- }\r
- else {\r
- encoded = arg;\r
- Py_INCREF(arg);\r
- }\r
- new = bytearray_iconcat(self, arg);\r
- Py_DECREF(encoded);\r
- if (new == NULL)\r
- return -1;\r
- Py_DECREF(new);\r
- return 0;\r
- }\r
-\r
-#ifdef Py_USING_UNICODE\r
- if (PyUnicode_Check(arg)) {\r
- /* Encode via the codec registry */\r
- PyObject *encoded, *new;\r
- if (encoding == NULL) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "unicode argument without an encoding");\r
- return -1;\r
- }\r
- encoded = PyCodec_Encode(arg, encoding, errors);\r
- if (encoded == NULL)\r
- return -1;\r
- assert(PyBytes_Check(encoded));\r
- new = bytearray_iconcat(self, encoded);\r
- Py_DECREF(encoded);\r
- if (new == NULL)\r
- return -1;\r
- Py_DECREF(new);\r
- return 0;\r
- }\r
-#endif\r
-\r
- /* If it's not unicode, there can't be encoding or errors */\r
- if (encoding != NULL || errors != NULL) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "encoding or errors without a string argument");\r
- return -1;\r
- }\r
-\r
- /* Is it an int? */\r
- count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);\r
- if (count == -1 && PyErr_Occurred()) {\r
- if (PyErr_ExceptionMatches(PyExc_OverflowError))\r
- return -1;\r
- PyErr_Clear();\r
- }\r
- else if (count < 0) {\r
- PyErr_SetString(PyExc_ValueError, "negative count");\r
- return -1;\r
- }\r
- else {\r
- if (count > 0) {\r
- if (PyByteArray_Resize((PyObject *)self, count))\r
- return -1;\r
- memset(self->ob_bytes, 0, count);\r
- }\r
- return 0;\r
- }\r
-\r
- /* Use the buffer API */\r
- if (PyObject_CheckBuffer(arg)) {\r
- Py_ssize_t size;\r
- Py_buffer view;\r
- if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)\r
- return -1;\r
- size = view.len;\r
- if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;\r
- if (PyBuffer_ToContiguous(self->ob_bytes, &view, size, 'C') < 0)\r
- goto fail;\r
- PyBuffer_Release(&view);\r
- return 0;\r
- fail:\r
- PyBuffer_Release(&view);\r
- return -1;\r
- }\r
-\r
- /* XXX Optimize this if the arguments is a list, tuple */\r
-\r
- /* Get the iterator */\r
- it = PyObject_GetIter(arg);\r
- if (it == NULL)\r
- return -1;\r
- iternext = *Py_TYPE(it)->tp_iternext;\r
-\r
- /* Run the iterator to exhaustion */\r
- for (;;) {\r
- PyObject *item;\r
- int rc, value;\r
-\r
- /* Get the next item */\r
- item = iternext(it);\r
- if (item == NULL) {\r
- if (PyErr_Occurred()) {\r
- if (!PyErr_ExceptionMatches(PyExc_StopIteration))\r
- goto error;\r
- PyErr_Clear();\r
- }\r
- break;\r
- }\r
-\r
- /* Interpret it as an int (__index__) */\r
- rc = _getbytevalue(item, &value);\r
- Py_DECREF(item);\r
- if (!rc)\r
- goto error;\r
-\r
- /* Append the byte */\r
- if (Py_SIZE(self) < self->ob_alloc)\r
- Py_SIZE(self)++;\r
- else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)\r
- goto error;\r
- self->ob_bytes[Py_SIZE(self)-1] = value;\r
- }\r
-\r
- /* Clean up and return success */\r
- Py_DECREF(it);\r
- return 0;\r
-\r
- error:\r
- /* Error handling when it != NULL */\r
- Py_DECREF(it);\r
- return -1;\r
-}\r
-\r
-/* Mostly copied from string_repr, but without the\r
- "smart quote" functionality. */\r
-static PyObject *\r
-bytearray_repr(PyByteArrayObject *self)\r
-{\r
- static const char *hexdigits = "0123456789abcdef";\r
- const char *quote_prefix = "bytearray(b";\r
- const char *quote_postfix = ")";\r
- Py_ssize_t length = Py_SIZE(self);\r
- /* 14 == strlen(quote_prefix) + 2 + strlen(quote_postfix) */\r
- size_t newsize;\r
- PyObject *v;\r
- if (length > (PY_SSIZE_T_MAX - 14) / 4) {\r
- PyErr_SetString(PyExc_OverflowError,\r
- "bytearray object is too large to make repr");\r
- return NULL;\r
- }\r
- newsize = 14 + 4 * length;\r
- v = PyString_FromStringAndSize(NULL, newsize);\r
- if (v == NULL) {\r
- return NULL;\r
- }\r
- else {\r
- register Py_ssize_t i;\r
- register char c;\r
- register char *p;\r
- int quote;\r
-\r
- /* Figure out which quote to use; single is preferred */\r
- quote = '\'';\r
- {\r
- char *test, *start;\r
- start = PyByteArray_AS_STRING(self);\r
- for (test = start; test < start+length; ++test) {\r
- if (*test == '"') {\r
- quote = '\''; /* back to single */\r
- goto decided;\r
- }\r
- else if (*test == '\'')\r
- quote = '"';\r
- }\r
- decided:\r
- ;\r
- }\r
-\r
- p = PyString_AS_STRING(v);\r
- while (*quote_prefix)\r
- *p++ = *quote_prefix++;\r
- *p++ = quote;\r
-\r
- for (i = 0; i < length; i++) {\r
- /* There's at least enough room for a hex escape\r
- and a closing quote. */\r
- assert(newsize - (p - PyString_AS_STRING(v)) >= 5);\r
- c = self->ob_bytes[i];\r
- if (c == '\'' || c == '\\')\r
- *p++ = '\\', *p++ = c;\r
- else if (c == '\t')\r
- *p++ = '\\', *p++ = 't';\r
- else if (c == '\n')\r
- *p++ = '\\', *p++ = 'n';\r
- else if (c == '\r')\r
- *p++ = '\\', *p++ = 'r';\r
- else if (c == 0)\r
- *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';\r
- else if (c < ' ' || c >= 0x7f) {\r
- *p++ = '\\';\r
- *p++ = 'x';\r
- *p++ = hexdigits[(c & 0xf0) >> 4];\r
- *p++ = hexdigits[c & 0xf];\r
- }\r
- else\r
- *p++ = c;\r
- }\r
- assert(newsize - (p - PyString_AS_STRING(v)) >= 1);\r
- *p++ = quote;\r
- while (*quote_postfix) {\r
- *p++ = *quote_postfix++;\r
- }\r
- *p = '\0';\r
- /* v is cleared on error */\r
- (void)_PyString_Resize(&v, (p - PyString_AS_STRING(v)));\r
- return v;\r
- }\r
-}\r
-\r
-static PyObject *\r
-bytearray_str(PyObject *op)\r
-{\r
-#if 0\r
- if (Py_BytesWarningFlag) {\r
- if (PyErr_WarnEx(PyExc_BytesWarning,\r
- "str() on a bytearray instance", 1))\r
- return NULL;\r
- }\r
- return bytearray_repr((PyByteArrayObject*)op);\r
-#endif\r
- return PyBytes_FromStringAndSize(((PyByteArrayObject*)op)->ob_bytes, Py_SIZE(op));\r
-}\r
-\r
-static PyObject *\r
-bytearray_richcompare(PyObject *self, PyObject *other, int op)\r
-{\r
- Py_ssize_t self_size, other_size;\r
- Py_buffer self_bytes, other_bytes;\r
- PyObject *res;\r
- Py_ssize_t minsize;\r
- int cmp;\r
-\r
- /* Bytes can be compared to anything that supports the (binary)\r
- buffer API. Except that a comparison with Unicode is always an\r
- error, even if the comparison is for equality. */\r
-#ifdef Py_USING_UNICODE\r
- if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||\r
- PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {\r
- if (Py_BytesWarningFlag && op == Py_EQ) {\r
- if (PyErr_WarnEx(PyExc_BytesWarning,\r
- "Comparison between bytearray and string", 1))\r
- return NULL;\r
- }\r
-\r
- Py_INCREF(Py_NotImplemented);\r
- return Py_NotImplemented;\r
- }\r
-#endif\r
-\r
- self_size = _getbuffer(self, &self_bytes);\r
- if (self_size < 0) {\r
- PyErr_Clear();\r
- Py_INCREF(Py_NotImplemented);\r
- return Py_NotImplemented;\r
- }\r
-\r
- other_size = _getbuffer(other, &other_bytes);\r
- if (other_size < 0) {\r
- PyErr_Clear();\r
- PyBuffer_Release(&self_bytes);\r
- Py_INCREF(Py_NotImplemented);\r
- return Py_NotImplemented;\r
- }\r
-\r
- if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {\r
- /* Shortcut: if the lengths differ, the objects differ */\r
- cmp = (op == Py_NE);\r
- }\r
- else {\r
- minsize = self_size;\r
- if (other_size < minsize)\r
- minsize = other_size;\r
-\r
- cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);\r
- /* In ISO C, memcmp() guarantees to use unsigned bytes! */\r
-\r
- if (cmp == 0) {\r
- if (self_size < other_size)\r
- cmp = -1;\r
- else if (self_size > other_size)\r
- cmp = 1;\r
- }\r
-\r
- switch (op) {\r
- case Py_LT: cmp = cmp < 0; break;\r
- case Py_LE: cmp = cmp <= 0; break;\r
- case Py_EQ: cmp = cmp == 0; break;\r
- case Py_NE: cmp = cmp != 0; break;\r
- case Py_GT: cmp = cmp > 0; break;\r
- case Py_GE: cmp = cmp >= 0; break;\r
- }\r
- }\r
-\r
- res = cmp ? Py_True : Py_False;\r
- PyBuffer_Release(&self_bytes);\r
- PyBuffer_Release(&other_bytes);\r
- Py_INCREF(res);\r
- return res;\r
-}\r
-\r
-static void\r
-bytearray_dealloc(PyByteArrayObject *self)\r
-{\r
- if (self->ob_exports > 0) {\r
- PyErr_SetString(PyExc_SystemError,\r
- "deallocated bytearray object has exported buffers");\r
- PyErr_Print();\r
- }\r
- if (self->ob_bytes != 0) {\r
- PyMem_Free(self->ob_bytes);\r
- }\r
- Py_TYPE(self)->tp_free((PyObject *)self);\r
-}\r
-\r
-\r
-/* -------------------------------------------------------------------- */\r
-/* Methods */\r
-\r
-#define STRINGLIB_CHAR char\r
-#define STRINGLIB_LEN PyByteArray_GET_SIZE\r
-#define STRINGLIB_STR PyByteArray_AS_STRING\r
-#define STRINGLIB_NEW PyByteArray_FromStringAndSize\r
-#define STRINGLIB_ISSPACE Py_ISSPACE\r
-#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))\r
-#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact\r
-#define STRINGLIB_MUTABLE 1\r
-\r
-#include "stringlib/fastsearch.h"\r
-#include "stringlib/count.h"\r
-#include "stringlib/find.h"\r
-#include "stringlib/partition.h"\r
-#include "stringlib/split.h"\r
-#include "stringlib/ctype.h"\r
-#include "stringlib/transmogrify.h"\r
-\r
-\r
-/* The following Py_LOCAL_INLINE and Py_LOCAL functions\r
-were copied from the old char* style string object. */\r
-\r
-/* helper macro to fixup start/end slice values */\r
-#define ADJUST_INDICES(start, end, len) \\r
- if (end > len) \\r
- end = len; \\r
- else if (end < 0) { \\r
- end += len; \\r
- if (end < 0) \\r
- end = 0; \\r
- } \\r
- if (start < 0) { \\r
- start += len; \\r
- if (start < 0) \\r
- start = 0; \\r
- }\r
-\r
-Py_LOCAL_INLINE(Py_ssize_t)\r
-bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)\r
-{\r
- PyObject *subobj;\r
- Py_buffer subbuf;\r
- Py_ssize_t start=0, end=PY_SSIZE_T_MAX;\r
- Py_ssize_t res;\r
-\r
- if (!stringlib_parse_args_finds("find/rfind/index/rindex",\r
- args, &subobj, &start, &end))\r
- return -2;\r
- if (_getbuffer(subobj, &subbuf) < 0)\r
- return -2;\r
- if (dir > 0)\r
- res = stringlib_find_slice(\r
- PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),\r
- subbuf.buf, subbuf.len, start, end);\r
- else\r
- res = stringlib_rfind_slice(\r
- PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),\r
- subbuf.buf, subbuf.len, start, end);\r
- PyBuffer_Release(&subbuf);\r
- return res;\r
-}\r
-\r
-PyDoc_STRVAR(find__doc__,\r
-"B.find(sub [,start [,end]]) -> int\n\\r
-\n\\r
-Return the lowest index in B where subsection sub is found,\n\\r
-such that sub is contained within B[start,end]. Optional\n\\r
-arguments start and end are interpreted as in slice notation.\n\\r
-\n\\r
-Return -1 on failure.");\r
-\r
-static PyObject *\r
-bytearray_find(PyByteArrayObject *self, PyObject *args)\r
-{\r
- Py_ssize_t result = bytearray_find_internal(self, args, +1);\r
- if (result == -2)\r
- return NULL;\r
- return PyInt_FromSsize_t(result);\r
-}\r
-\r
-PyDoc_STRVAR(count__doc__,\r
-"B.count(sub [,start [,end]]) -> int\n\\r
-\n\\r
-Return the number of non-overlapping occurrences of subsection sub in\n\\r
-bytes B[start:end]. Optional arguments start and end are interpreted\n\\r
-as in slice notation.");\r
-\r
-static PyObject *\r
-bytearray_count(PyByteArrayObject *self, PyObject *args)\r
-{\r
- PyObject *sub_obj;\r
- const char *str = PyByteArray_AS_STRING(self);\r
- Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;\r
- Py_buffer vsub;\r
- PyObject *count_obj;\r
-\r
- if (!stringlib_parse_args_finds("count", args, &sub_obj, &start, &end))\r
- return NULL;\r
-\r
- if (_getbuffer(sub_obj, &vsub) < 0)\r
- return NULL;\r
-\r
- ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));\r
-\r
- count_obj = PyInt_FromSsize_t(\r
- stringlib_count(str + start, end - start, vsub.buf, vsub.len, PY_SSIZE_T_MAX)\r
- );\r
- PyBuffer_Release(&vsub);\r
- return count_obj;\r
-}\r
-\r
-\r
-PyDoc_STRVAR(index__doc__,\r
-"B.index(sub [,start [,end]]) -> int\n\\r
-\n\\r
-Like B.find() but raise ValueError when the subsection is not found.");\r
-\r
-static PyObject *\r
-bytearray_index(PyByteArrayObject *self, PyObject *args)\r
-{\r
- Py_ssize_t result = bytearray_find_internal(self, args, +1);\r
- if (result == -2)\r
- return NULL;\r
- if (result == -1) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "subsection not found");\r
- return NULL;\r
- }\r
- return PyInt_FromSsize_t(result);\r
-}\r
-\r
-\r
-PyDoc_STRVAR(rfind__doc__,\r
-"B.rfind(sub [,start [,end]]) -> int\n\\r
-\n\\r
-Return the highest index in B where subsection sub is found,\n\\r
-such that sub is contained within B[start,end]. Optional\n\\r
-arguments start and end are interpreted as in slice notation.\n\\r
-\n\\r
-Return -1 on failure.");\r
-\r
-static PyObject *\r
-bytearray_rfind(PyByteArrayObject *self, PyObject *args)\r
-{\r
- Py_ssize_t result = bytearray_find_internal(self, args, -1);\r
- if (result == -2)\r
- return NULL;\r
- return PyInt_FromSsize_t(result);\r
-}\r
-\r
-\r
-PyDoc_STRVAR(rindex__doc__,\r
-"B.rindex(sub [,start [,end]]) -> int\n\\r
-\n\\r
-Like B.rfind() but raise ValueError when the subsection is not found.");\r
-\r
-static PyObject *\r
-bytearray_rindex(PyByteArrayObject *self, PyObject *args)\r
-{\r
- Py_ssize_t result = bytearray_find_internal(self, args, -1);\r
- if (result == -2)\r
- return NULL;\r
- if (result == -1) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "subsection not found");\r
- return NULL;\r
- }\r
- return PyInt_FromSsize_t(result);\r
-}\r
-\r
-\r
-static int\r
-bytearray_contains(PyObject *self, PyObject *arg)\r
-{\r
- Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);\r
- if (ival == -1 && PyErr_Occurred()) {\r
- Py_buffer varg;\r
- int pos;\r
- PyErr_Clear();\r
- if (_getbuffer(arg, &varg) < 0)\r
- return -1;\r
- pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),\r
- varg.buf, varg.len, 0);\r
- PyBuffer_Release(&varg);\r
- return pos >= 0;\r
- }\r
- if (ival < 0 || ival >= 256) {\r
- PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");\r
- return -1;\r
- }\r
-\r
- return memchr(PyByteArray_AS_STRING(self), ival, Py_SIZE(self)) != NULL;\r
-}\r
-\r
-\r
-/* Matches the end (direction >= 0) or start (direction < 0) of self\r
- * against substr, using the start and end arguments. Returns\r
- * -1 on error, 0 if not found and 1 if found.\r
- */\r
-Py_LOCAL(int)\r
-_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,\r
- Py_ssize_t end, int direction)\r
-{\r
- Py_ssize_t len = PyByteArray_GET_SIZE(self);\r
- const char* str;\r
- Py_buffer vsubstr;\r
- int rv = 0;\r
-\r
- str = PyByteArray_AS_STRING(self);\r
-\r
- if (_getbuffer(substr, &vsubstr) < 0)\r
- return -1;\r
-\r
- ADJUST_INDICES(start, end, len);\r
-\r
- if (direction < 0) {\r
- /* startswith */\r
- if (start+vsubstr.len > len) {\r
- goto done;\r
- }\r
- } else {\r
- /* endswith */\r
- if (end-start < vsubstr.len || start > len) {\r
- goto done;\r
- }\r
-\r
- if (end-vsubstr.len > start)\r
- start = end - vsubstr.len;\r
- }\r
- if (end-start >= vsubstr.len)\r
- rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);\r
-\r
-done:\r
- PyBuffer_Release(&vsubstr);\r
- return rv;\r
-}\r
-\r
-\r
-PyDoc_STRVAR(startswith__doc__,\r
-"B.startswith(prefix [,start [,end]]) -> bool\n\\r
-\n\\r
-Return True if B starts with the specified prefix, False otherwise.\n\\r
-With optional start, test B beginning at that position.\n\\r
-With optional end, stop comparing B at that position.\n\\r
-prefix can also be a tuple of strings to try.");\r
-\r
-static PyObject *\r
-bytearray_startswith(PyByteArrayObject *self, PyObject *args)\r
-{\r
- Py_ssize_t start = 0;\r
- Py_ssize_t end = PY_SSIZE_T_MAX;\r
- PyObject *subobj;\r
- int result;\r
-\r
- if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))\r
- return NULL;\r
- if (PyTuple_Check(subobj)) {\r
- Py_ssize_t i;\r
- for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {\r
- result = _bytearray_tailmatch(self,\r
- PyTuple_GET_ITEM(subobj, i),\r
- start, end, -1);\r
- if (result == -1)\r
- return NULL;\r
- else if (result) {\r
- Py_RETURN_TRUE;\r
- }\r
- }\r
- Py_RETURN_FALSE;\r
- }\r
- result = _bytearray_tailmatch(self, subobj, start, end, -1);\r
- if (result == -1)\r
- return NULL;\r
- else\r
- return PyBool_FromLong(result);\r
-}\r
-\r
-PyDoc_STRVAR(endswith__doc__,\r
-"B.endswith(suffix [,start [,end]]) -> bool\n\\r
-\n\\r
-Return True if B ends with the specified suffix, False otherwise.\n\\r
-With optional start, test B beginning at that position.\n\\r
-With optional end, stop comparing B at that position.\n\\r
-suffix can also be a tuple of strings to try.");\r
-\r
-static PyObject *\r
-bytearray_endswith(PyByteArrayObject *self, PyObject *args)\r
-{\r
- Py_ssize_t start = 0;\r
- Py_ssize_t end = PY_SSIZE_T_MAX;\r
- PyObject *subobj;\r
- int result;\r
-\r
- if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))\r
- return NULL;\r
- if (PyTuple_Check(subobj)) {\r
- Py_ssize_t i;\r
- for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {\r
- result = _bytearray_tailmatch(self,\r
- PyTuple_GET_ITEM(subobj, i),\r
- start, end, +1);\r
- if (result == -1)\r
- return NULL;\r
- else if (result) {\r
- Py_RETURN_TRUE;\r
- }\r
- }\r
- Py_RETURN_FALSE;\r
- }\r
- result = _bytearray_tailmatch(self, subobj, start, end, +1);\r
- if (result == -1)\r
- return NULL;\r
- else\r
- return PyBool_FromLong(result);\r
-}\r
-\r
-\r
-PyDoc_STRVAR(translate__doc__,\r
-"B.translate(table[, deletechars]) -> bytearray\n\\r
-\n\\r
-Return a copy of B, where all characters occurring in the\n\\r
-optional argument deletechars are removed, and the remaining\n\\r
-characters have been mapped through the given translation\n\\r
-table, which must be a bytes object of length 256.");\r
-\r
-static PyObject *\r
-bytearray_translate(PyByteArrayObject *self, PyObject *args)\r
-{\r
- register char *input, *output;\r
- register const char *table;\r
- register Py_ssize_t i, c;\r
- PyObject *input_obj = (PyObject*)self;\r
- const char *output_start;\r
- Py_ssize_t inlen;\r
- PyObject *result = NULL;\r
- int trans_table[256];\r
- PyObject *tableobj = NULL, *delobj = NULL;\r
- Py_buffer vtable, vdel;\r
-\r
- if (!PyArg_UnpackTuple(args, "translate", 1, 2,\r
- &tableobj, &delobj))\r
- return NULL;\r
-\r
- if (tableobj == Py_None) {\r
- table = NULL;\r
- tableobj = NULL;\r
- } else if (_getbuffer(tableobj, &vtable) < 0) {\r
- return NULL;\r
- } else {\r
- if (vtable.len != 256) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "translation table must be 256 characters long");\r
- PyBuffer_Release(&vtable);\r
- return NULL;\r
- }\r
- table = (const char*)vtable.buf;\r
- }\r
-\r
- if (delobj != NULL) {\r
- if (_getbuffer(delobj, &vdel) < 0) {\r
- if (tableobj != NULL)\r
- PyBuffer_Release(&vtable);\r
- return NULL;\r
- }\r
- }\r
- else {\r
- vdel.buf = NULL;\r
- vdel.len = 0;\r
- }\r
-\r
- inlen = PyByteArray_GET_SIZE(input_obj);\r
- result = PyByteArray_FromStringAndSize((char *)NULL, inlen);\r
- if (result == NULL)\r
- goto done;\r
- output_start = output = PyByteArray_AsString(result);\r
- input = PyByteArray_AS_STRING(input_obj);\r
-\r
- if (vdel.len == 0 && table != NULL) {\r
- /* If no deletions are required, use faster code */\r
- for (i = inlen; --i >= 0; ) {\r
- c = Py_CHARMASK(*input++);\r
- *output++ = table[c];\r
- }\r
- goto done;\r
- }\r
-\r
- if (table == NULL) {\r
- for (i = 0; i < 256; i++)\r
- trans_table[i] = Py_CHARMASK(i);\r
- } else {\r
- for (i = 0; i < 256; i++)\r
- trans_table[i] = Py_CHARMASK(table[i]);\r
- }\r
-\r
- for (i = 0; i < vdel.len; i++)\r
- trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;\r
-\r
- for (i = inlen; --i >= 0; ) {\r
- c = Py_CHARMASK(*input++);\r
- if (trans_table[c] != -1)\r
- if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)\r
- continue;\r
- }\r
- /* Fix the size of the resulting string */\r
- if (inlen > 0)\r
- PyByteArray_Resize(result, output - output_start);\r
-\r
-done:\r
- if (tableobj != NULL)\r
- PyBuffer_Release(&vtable);\r
- if (delobj != NULL)\r
- PyBuffer_Release(&vdel);\r
- return result;\r
-}\r
-\r
-\r
-/* find and count characters and substrings */\r
-\r
-#define findchar(target, target_len, c) \\r
- ((char *)memchr((const void *)(target), c, target_len))\r
-\r
-\r
-/* Bytes ops must return a string, create a copy */\r
-Py_LOCAL(PyByteArrayObject *)\r
-return_self(PyByteArrayObject *self)\r
-{\r
- return (PyByteArrayObject *)PyByteArray_FromStringAndSize(\r
- PyByteArray_AS_STRING(self),\r
- PyByteArray_GET_SIZE(self));\r
-}\r
-\r
-Py_LOCAL_INLINE(Py_ssize_t)\r
-countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)\r
-{\r
- Py_ssize_t count=0;\r
- const char *start=target;\r
- const char *end=target+target_len;\r
-\r
- while ( (start=findchar(start, end-start, c)) != NULL ) {\r
- count++;\r
- if (count >= maxcount)\r
- break;\r
- start += 1;\r
- }\r
- return count;\r
-}\r
-\r
-\r
-/* Algorithms for different cases of string replacement */\r
-\r
-/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */\r
-Py_LOCAL(PyByteArrayObject *)\r
-replace_interleave(PyByteArrayObject *self,\r
- const char *to_s, Py_ssize_t to_len,\r
- Py_ssize_t maxcount)\r
-{\r
- char *self_s, *result_s;\r
- Py_ssize_t self_len, result_len;\r
- Py_ssize_t count, i, product;\r
- PyByteArrayObject *result;\r
-\r
- self_len = PyByteArray_GET_SIZE(self);\r
-\r
- /* 1 at the end plus 1 after every character */\r
- count = self_len+1;\r
- if (maxcount < count)\r
- count = maxcount;\r
-\r
- /* Check for overflow */\r
- /* result_len = count * to_len + self_len; */\r
- product = count * to_len;\r
- if (product / to_len != count) {\r
- PyErr_SetString(PyExc_OverflowError,\r
- "replace string is too long");\r
- return NULL;\r
- }\r
- result_len = product + self_len;\r
- if (result_len < 0) {\r
- PyErr_SetString(PyExc_OverflowError,\r
- "replace string is too long");\r
- return NULL;\r
- }\r
-\r
- if (! (result = (PyByteArrayObject *)\r
- PyByteArray_FromStringAndSize(NULL, result_len)) )\r
- return NULL;\r
-\r
- self_s = PyByteArray_AS_STRING(self);\r
- result_s = PyByteArray_AS_STRING(result);\r
-\r
- /* TODO: special case single character, which doesn't need memcpy */\r
-\r
- /* Lay the first one down (guaranteed this will occur) */\r
- Py_MEMCPY(result_s, to_s, to_len);\r
- result_s += to_len;\r
- count -= 1;\r
-\r
- for (i=0; i<count; i++) {\r
- *result_s++ = *self_s++;\r
- Py_MEMCPY(result_s, to_s, to_len);\r
- result_s += to_len;\r
- }\r
-\r
- /* Copy the rest of the original string */\r
- Py_MEMCPY(result_s, self_s, self_len-i);\r
-\r
- return result;\r
-}\r
-\r
-/* Special case for deleting a single character */\r
-/* len(self)>=1, len(from)==1, to="", maxcount>=1 */\r
-Py_LOCAL(PyByteArrayObject *)\r
-replace_delete_single_character(PyByteArrayObject *self,\r
- char from_c, Py_ssize_t maxcount)\r
-{\r
- char *self_s, *result_s;\r
- char *start, *next, *end;\r
- Py_ssize_t self_len, result_len;\r
- Py_ssize_t count;\r
- PyByteArrayObject *result;\r
-\r
- self_len = PyByteArray_GET_SIZE(self);\r
- self_s = PyByteArray_AS_STRING(self);\r
-\r
- count = countchar(self_s, self_len, from_c, maxcount);\r
- if (count == 0) {\r
- return return_self(self);\r
- }\r
-\r
- result_len = self_len - count; /* from_len == 1 */\r
- assert(result_len>=0);\r
-\r
- if ( (result = (PyByteArrayObject *)\r
- PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)\r
- return NULL;\r
- result_s = PyByteArray_AS_STRING(result);\r
-\r
- start = self_s;\r
- end = self_s + self_len;\r
- while (count-- > 0) {\r
- next = findchar(start, end-start, from_c);\r
- if (next == NULL)\r
- break;\r
- Py_MEMCPY(result_s, start, next-start);\r
- result_s += (next-start);\r
- start = next+1;\r
- }\r
- Py_MEMCPY(result_s, start, end-start);\r
-\r
- return result;\r
-}\r
-\r
-/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */\r
-\r
-Py_LOCAL(PyByteArrayObject *)\r
-replace_delete_substring(PyByteArrayObject *self,\r
- const char *from_s, Py_ssize_t from_len,\r
- Py_ssize_t maxcount)\r
-{\r
- char *self_s, *result_s;\r
- char *start, *next, *end;\r
- Py_ssize_t self_len, result_len;\r
- Py_ssize_t count, offset;\r
- PyByteArrayObject *result;\r
-\r
- self_len = PyByteArray_GET_SIZE(self);\r
- self_s = PyByteArray_AS_STRING(self);\r
-\r
- count = stringlib_count(self_s, self_len,\r
- from_s, from_len,\r
- maxcount);\r
-\r
- if (count == 0) {\r
- /* no matches */\r
- return return_self(self);\r
- }\r
-\r
- result_len = self_len - (count * from_len);\r
- assert (result_len>=0);\r
-\r
- if ( (result = (PyByteArrayObject *)\r
- PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )\r
- return NULL;\r
-\r
- result_s = PyByteArray_AS_STRING(result);\r
-\r
- start = self_s;\r
- end = self_s + self_len;\r
- while (count-- > 0) {\r
- offset = stringlib_find(start, end-start,\r
- from_s, from_len,\r
- 0);\r
- if (offset == -1)\r
- break;\r
- next = start + offset;\r
-\r
- Py_MEMCPY(result_s, start, next-start);\r
-\r
- result_s += (next-start);\r
- start = next+from_len;\r
- }\r
- Py_MEMCPY(result_s, start, end-start);\r
- return result;\r
-}\r
-\r
-/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */\r
-Py_LOCAL(PyByteArrayObject *)\r
-replace_single_character_in_place(PyByteArrayObject *self,\r
- char from_c, char to_c,\r
- Py_ssize_t maxcount)\r
-{\r
- char *self_s, *result_s, *start, *end, *next;\r
- Py_ssize_t self_len;\r
- PyByteArrayObject *result;\r
-\r
- /* The result string will be the same size */\r
- self_s = PyByteArray_AS_STRING(self);\r
- self_len = PyByteArray_GET_SIZE(self);\r
-\r
- next = findchar(self_s, self_len, from_c);\r
-\r
- if (next == NULL) {\r
- /* No matches; return the original bytes */\r
- return return_self(self);\r
- }\r
-\r
- /* Need to make a new bytes */\r
- result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);\r
- if (result == NULL)\r
- return NULL;\r
- result_s = PyByteArray_AS_STRING(result);\r
- Py_MEMCPY(result_s, self_s, self_len);\r
-\r
- /* change everything in-place, starting with this one */\r
- start = result_s + (next-self_s);\r
- *start = to_c;\r
- start++;\r
- end = result_s + self_len;\r
-\r
- while (--maxcount > 0) {\r
- next = findchar(start, end-start, from_c);\r
- if (next == NULL)\r
- break;\r
- *next = to_c;\r
- start = next+1;\r
- }\r
-\r
- return result;\r
-}\r
-\r
-/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */\r
-Py_LOCAL(PyByteArrayObject *)\r
-replace_substring_in_place(PyByteArrayObject *self,\r
- const char *from_s, Py_ssize_t from_len,\r
- const char *to_s, Py_ssize_t to_len,\r
- Py_ssize_t maxcount)\r
-{\r
- char *result_s, *start, *end;\r
- char *self_s;\r
- Py_ssize_t self_len, offset;\r
- PyByteArrayObject *result;\r
-\r
- /* The result bytes will be the same size */\r
-\r
- self_s = PyByteArray_AS_STRING(self);\r
- self_len = PyByteArray_GET_SIZE(self);\r
-\r
- offset = stringlib_find(self_s, self_len,\r
- from_s, from_len,\r
- 0);\r
- if (offset == -1) {\r
- /* No matches; return the original bytes */\r
- return return_self(self);\r
- }\r
-\r
- /* Need to make a new bytes */\r
- result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);\r
- if (result == NULL)\r
- return NULL;\r
- result_s = PyByteArray_AS_STRING(result);\r
- Py_MEMCPY(result_s, self_s, self_len);\r
-\r
- /* change everything in-place, starting with this one */\r
- start = result_s + offset;\r
- Py_MEMCPY(start, to_s, from_len);\r
- start += from_len;\r
- end = result_s + self_len;\r
-\r
- while ( --maxcount > 0) {\r
- offset = stringlib_find(start, end-start,\r
- from_s, from_len,\r
- 0);\r
- if (offset==-1)\r
- break;\r
- Py_MEMCPY(start+offset, to_s, from_len);\r
- start += offset+from_len;\r
- }\r
-\r
- return result;\r
-}\r
-\r
-/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */\r
-Py_LOCAL(PyByteArrayObject *)\r
-replace_single_character(PyByteArrayObject *self,\r
- char from_c,\r
- const char *to_s, Py_ssize_t to_len,\r
- Py_ssize_t maxcount)\r
-{\r
- char *self_s, *result_s;\r
- char *start, *next, *end;\r
- Py_ssize_t self_len, result_len;\r
- Py_ssize_t count, product;\r
- PyByteArrayObject *result;\r
-\r
- self_s = PyByteArray_AS_STRING(self);\r
- self_len = PyByteArray_GET_SIZE(self);\r
-\r
- count = countchar(self_s, self_len, from_c, maxcount);\r
- if (count == 0) {\r
- /* no matches, return unchanged */\r
- return return_self(self);\r
- }\r
-\r
- /* use the difference between current and new, hence the "-1" */\r
- /* result_len = self_len + count * (to_len-1) */\r
- product = count * (to_len-1);\r
- if (product / (to_len-1) != count) {\r
- PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");\r
- return NULL;\r
- }\r
- result_len = self_len + product;\r
- if (result_len < 0) {\r
- PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");\r
- return NULL;\r
- }\r
-\r
- if ( (result = (PyByteArrayObject *)\r
- PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)\r
- return NULL;\r
- result_s = PyByteArray_AS_STRING(result);\r
-\r
- start = self_s;\r
- end = self_s + self_len;\r
- while (count-- > 0) {\r
- next = findchar(start, end-start, from_c);\r
- if (next == NULL)\r
- break;\r
-\r
- if (next == start) {\r
- /* replace with the 'to' */\r
- Py_MEMCPY(result_s, to_s, to_len);\r
- result_s += to_len;\r
- start += 1;\r
- } else {\r
- /* copy the unchanged old then the 'to' */\r
- Py_MEMCPY(result_s, start, next-start);\r
- result_s += (next-start);\r
- Py_MEMCPY(result_s, to_s, to_len);\r
- result_s += to_len;\r
- start = next+1;\r
- }\r
- }\r
- /* Copy the remainder of the remaining bytes */\r
- Py_MEMCPY(result_s, start, end-start);\r
-\r
- return result;\r
-}\r
-\r
-/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */\r
-Py_LOCAL(PyByteArrayObject *)\r
-replace_substring(PyByteArrayObject *self,\r
- const char *from_s, Py_ssize_t from_len,\r
- const char *to_s, Py_ssize_t to_len,\r
- Py_ssize_t maxcount)\r
-{\r
- char *self_s, *result_s;\r
- char *start, *next, *end;\r
- Py_ssize_t self_len, result_len;\r
- Py_ssize_t count, offset, product;\r
- PyByteArrayObject *result;\r
-\r
- self_s = PyByteArray_AS_STRING(self);\r
- self_len = PyByteArray_GET_SIZE(self);\r
-\r
- count = stringlib_count(self_s, self_len,\r
- from_s, from_len,\r
- maxcount);\r
-\r
- if (count == 0) {\r
- /* no matches, return unchanged */\r
- return return_self(self);\r
- }\r
-\r
- /* Check for overflow */\r
- /* result_len = self_len + count * (to_len-from_len) */\r
- product = count * (to_len-from_len);\r
- if (product / (to_len-from_len) != count) {\r
- PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");\r
- return NULL;\r
- }\r
- result_len = self_len + product;\r
- if (result_len < 0) {\r
- PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");\r
- return NULL;\r
- }\r
-\r
- if ( (result = (PyByteArrayObject *)\r
- PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)\r
- return NULL;\r
- result_s = PyByteArray_AS_STRING(result);\r
-\r
- start = self_s;\r
- end = self_s + self_len;\r
- while (count-- > 0) {\r
- offset = stringlib_find(start, end-start,\r
- from_s, from_len,\r
- 0);\r
- if (offset == -1)\r
- break;\r
- next = start+offset;\r
- if (next == start) {\r
- /* replace with the 'to' */\r
- Py_MEMCPY(result_s, to_s, to_len);\r
- result_s += to_len;\r
- start += from_len;\r
- } else {\r
- /* copy the unchanged old then the 'to' */\r
- Py_MEMCPY(result_s, start, next-start);\r
- result_s += (next-start);\r
- Py_MEMCPY(result_s, to_s, to_len);\r
- result_s += to_len;\r
- start = next+from_len;\r
- }\r
- }\r
- /* Copy the remainder of the remaining bytes */\r
- Py_MEMCPY(result_s, start, end-start);\r
-\r
- return result;\r
-}\r
-\r
-\r
-Py_LOCAL(PyByteArrayObject *)\r
-replace(PyByteArrayObject *self,\r
- const char *from_s, Py_ssize_t from_len,\r
- const char *to_s, Py_ssize_t to_len,\r
- Py_ssize_t maxcount)\r
-{\r
- if (maxcount < 0) {\r
- maxcount = PY_SSIZE_T_MAX;\r
- } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {\r
- /* nothing to do; return the original bytes */\r
- return return_self(self);\r
- }\r
-\r
- if (maxcount == 0 ||\r
- (from_len == 0 && to_len == 0)) {\r
- /* nothing to do; return the original bytes */\r
- return return_self(self);\r
- }\r
-\r
- /* Handle zero-length special cases */\r
-\r
- if (from_len == 0) {\r
- /* insert the 'to' bytes everywhere. */\r
- /* >>> "Python".replace("", ".") */\r
- /* '.P.y.t.h.o.n.' */\r
- return replace_interleave(self, to_s, to_len, maxcount);\r
- }\r
-\r
- /* Except for "".replace("", "A") == "A" there is no way beyond this */\r
- /* point for an empty self bytes to generate a non-empty bytes */\r
- /* Special case so the remaining code always gets a non-empty bytes */\r
- if (PyByteArray_GET_SIZE(self) == 0) {\r
- return return_self(self);\r
- }\r
-\r
- if (to_len == 0) {\r
- /* delete all occurances of 'from' bytes */\r
- if (from_len == 1) {\r
- return replace_delete_single_character(\r
- self, from_s[0], maxcount);\r
- } else {\r
- return replace_delete_substring(self, from_s, from_len, maxcount);\r
- }\r
- }\r
-\r
- /* Handle special case where both bytes have the same length */\r
-\r
- if (from_len == to_len) {\r
- if (from_len == 1) {\r
- return replace_single_character_in_place(\r
- self,\r
- from_s[0],\r
- to_s[0],\r
- maxcount);\r
- } else {\r
- return replace_substring_in_place(\r
- self, from_s, from_len, to_s, to_len, maxcount);\r
- }\r
- }\r
-\r
- /* Otherwise use the more generic algorithms */\r
- if (from_len == 1) {\r
- return replace_single_character(self, from_s[0],\r
- to_s, to_len, maxcount);\r
- } else {\r
- /* len('from')>=2, len('to')>=1 */\r
- return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);\r
- }\r
-}\r
-\r
-\r
-PyDoc_STRVAR(replace__doc__,\r
-"B.replace(old, new[, count]) -> bytes\n\\r
-\n\\r
-Return a copy of B with all occurrences of subsection\n\\r
-old replaced by new. If the optional argument count is\n\\r
-given, only the first count occurrences are replaced.");\r
-\r
-static PyObject *\r
-bytearray_replace(PyByteArrayObject *self, PyObject *args)\r
-{\r
- Py_ssize_t count = -1;\r
- PyObject *from, *to, *res;\r
- Py_buffer vfrom, vto;\r
-\r
- if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))\r
- return NULL;\r
-\r
- if (_getbuffer(from, &vfrom) < 0)\r
- return NULL;\r
- if (_getbuffer(to, &vto) < 0) {\r
- PyBuffer_Release(&vfrom);\r
- return NULL;\r
- }\r
-\r
- res = (PyObject *)replace((PyByteArrayObject *) self,\r
- vfrom.buf, vfrom.len,\r
- vto.buf, vto.len, count);\r
-\r
- PyBuffer_Release(&vfrom);\r
- PyBuffer_Release(&vto);\r
- return res;\r
-}\r
-\r
-PyDoc_STRVAR(split__doc__,\r
-"B.split([sep[, maxsplit]]) -> list of bytearray\n\\r
-\n\\r
-Return a list of the sections in B, using sep as the delimiter.\n\\r
-If sep is not given, B is split on ASCII whitespace characters\n\\r
-(space, tab, return, newline, formfeed, vertical tab).\n\\r
-If maxsplit is given, at most maxsplit splits are done.");\r
-\r
-static PyObject *\r
-bytearray_split(PyByteArrayObject *self, PyObject *args)\r
-{\r
- Py_ssize_t len = PyByteArray_GET_SIZE(self), n;\r
- Py_ssize_t maxsplit = -1;\r
- const char *s = PyByteArray_AS_STRING(self), *sub;\r
- PyObject *list, *subobj = Py_None;\r
- Py_buffer vsub;\r
-\r
- if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))\r
- return NULL;\r
- if (maxsplit < 0)\r
- maxsplit = PY_SSIZE_T_MAX;\r
-\r
- if (subobj == Py_None)\r
- return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);\r
-\r
- if (_getbuffer(subobj, &vsub) < 0)\r
- return NULL;\r
- sub = vsub.buf;\r
- n = vsub.len;\r
-\r
- list = stringlib_split(\r
- (PyObject*) self, s, len, sub, n, maxsplit\r
- );\r
- PyBuffer_Release(&vsub);\r
- return list;\r
-}\r
-\r
-PyDoc_STRVAR(partition__doc__,\r
-"B.partition(sep) -> (head, sep, tail)\n\\r
-\n\\r
-Searches for the separator sep in B, and returns the part before it,\n\\r
-the separator itself, and the part after it. If the separator is not\n\\r
-found, returns B and two empty bytearray objects.");\r
-\r
-static PyObject *\r
-bytearray_partition(PyByteArrayObject *self, PyObject *sep_obj)\r
-{\r
- PyObject *bytesep, *result;\r
-\r
- bytesep = PyByteArray_FromObject(sep_obj);\r
- if (! bytesep)\r
- return NULL;\r
-\r
- result = stringlib_partition(\r
- (PyObject*) self,\r
- PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),\r
- bytesep,\r
- PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)\r
- );\r
-\r
- Py_DECREF(bytesep);\r
- return result;\r
-}\r
-\r
-PyDoc_STRVAR(rpartition__doc__,\r
-"B.rpartition(sep) -> (head, sep, tail)\n\\r
-\n\\r
-Searches for the separator sep in B, starting at the end of B,\n\\r
-and returns the part before it, the separator itself, and the\n\\r
-part after it. If the separator is not found, returns two empty\n\\r
-bytearray objects and B.");\r
-\r
-static PyObject *\r
-bytearray_rpartition(PyByteArrayObject *self, PyObject *sep_obj)\r
-{\r
- PyObject *bytesep, *result;\r
-\r
- bytesep = PyByteArray_FromObject(sep_obj);\r
- if (! bytesep)\r
- return NULL;\r
-\r
- result = stringlib_rpartition(\r
- (PyObject*) self,\r
- PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),\r
- bytesep,\r
- PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)\r
- );\r
-\r
- Py_DECREF(bytesep);\r
- return result;\r
-}\r
-\r
-PyDoc_STRVAR(rsplit__doc__,\r
-"B.rsplit(sep[, maxsplit]) -> list of bytearray\n\\r
-\n\\r
-Return a list of the sections in B, using sep as the delimiter,\n\\r
-starting at the end of B and working to the front.\n\\r
-If sep is not given, B is split on ASCII whitespace characters\n\\r
-(space, tab, return, newline, formfeed, vertical tab).\n\\r
-If maxsplit is given, at most maxsplit splits are done.");\r
-\r
-static PyObject *\r
-bytearray_rsplit(PyByteArrayObject *self, PyObject *args)\r
-{\r
- Py_ssize_t len = PyByteArray_GET_SIZE(self), n;\r
- Py_ssize_t maxsplit = -1;\r
- const char *s = PyByteArray_AS_STRING(self), *sub;\r
- PyObject *list, *subobj = Py_None;\r
- Py_buffer vsub;\r
-\r
- if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))\r
- return NULL;\r
- if (maxsplit < 0)\r
- maxsplit = PY_SSIZE_T_MAX;\r
-\r
- if (subobj == Py_None)\r
- return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);\r
-\r
- if (_getbuffer(subobj, &vsub) < 0)\r
- return NULL;\r
- sub = vsub.buf;\r
- n = vsub.len;\r
-\r
- list = stringlib_rsplit(\r
- (PyObject*) self, s, len, sub, n, maxsplit\r
- );\r
- PyBuffer_Release(&vsub);\r
- return list;\r
-}\r
-\r
-PyDoc_STRVAR(reverse__doc__,\r
-"B.reverse() -> None\n\\r
-\n\\r
-Reverse the order of the values in B in place.");\r
-static PyObject *\r
-bytearray_reverse(PyByteArrayObject *self, PyObject *unused)\r
-{\r
- char swap, *head, *tail;\r
- Py_ssize_t i, j, n = Py_SIZE(self);\r
-\r
- j = n / 2;\r
- head = self->ob_bytes;\r
- tail = head + n - 1;\r
- for (i = 0; i < j; i++) {\r
- swap = *head;\r
- *head++ = *tail;\r
- *tail-- = swap;\r
- }\r
-\r
- Py_RETURN_NONE;\r
-}\r
-\r
-PyDoc_STRVAR(insert__doc__,\r
-"B.insert(index, int) -> None\n\\r
-\n\\r
-Insert a single item into the bytearray before the given index.");\r
-static PyObject *\r
-bytearray_insert(PyByteArrayObject *self, PyObject *args)\r
-{\r
- PyObject *value;\r
- int ival;\r
- Py_ssize_t where, n = Py_SIZE(self);\r
-\r
- if (!PyArg_ParseTuple(args, "nO:insert", &where, &value))\r
- return NULL;\r
-\r
- if (n == PY_SSIZE_T_MAX) {\r
- PyErr_SetString(PyExc_OverflowError,\r
- "cannot add more objects to bytearray");\r
- return NULL;\r
- }\r
- if (!_getbytevalue(value, &ival))\r
- return NULL;\r
- if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)\r
- return NULL;\r
-\r
- if (where < 0) {\r
- where += n;\r
- if (where < 0)\r
- where = 0;\r
- }\r
- if (where > n)\r
- where = n;\r
- memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where);\r
- self->ob_bytes[where] = ival;\r
-\r
- Py_RETURN_NONE;\r
-}\r
-\r
-PyDoc_STRVAR(append__doc__,\r
-"B.append(int) -> None\n\\r
-\n\\r
-Append a single item to the end of B.");\r
-static PyObject *\r
-bytearray_append(PyByteArrayObject *self, PyObject *arg)\r
-{\r
- int value;\r
- Py_ssize_t n = Py_SIZE(self);\r
-\r
- if (! _getbytevalue(arg, &value))\r
- return NULL;\r
- if (n == PY_SSIZE_T_MAX) {\r
- PyErr_SetString(PyExc_OverflowError,\r
- "cannot add more objects to bytearray");\r
- return NULL;\r
- }\r
- if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)\r
- return NULL;\r
-\r
- self->ob_bytes[n] = value;\r
-\r
- Py_RETURN_NONE;\r
-}\r
-\r
-PyDoc_STRVAR(extend__doc__,\r
-"B.extend(iterable int) -> None\n\\r
-\n\\r
-Append all the elements from the iterator or sequence to the\n\\r
-end of B.");\r
-static PyObject *\r
-bytearray_extend(PyByteArrayObject *self, PyObject *arg)\r
-{\r
- PyObject *it, *item, *bytearray_obj;\r
- Py_ssize_t buf_size = 0, len = 0;\r
- int value;\r
- char *buf;\r
-\r
- /* bytearray_setslice code only accepts something supporting PEP 3118. */\r
- if (PyObject_CheckBuffer(arg)) {\r
- if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), arg) == -1)\r
- return NULL;\r
-\r
- Py_RETURN_NONE;\r
- }\r
-\r
- it = PyObject_GetIter(arg);\r
- if (it == NULL)\r
- return NULL;\r
-\r
- /* Try to determine the length of the argument. 32 is arbitrary. */\r
- buf_size = _PyObject_LengthHint(arg, 32);\r
- if (buf_size == -1) {\r
- Py_DECREF(it);\r
- return NULL;\r
- }\r
-\r
- bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);\r
- if (bytearray_obj == NULL) {\r
- Py_DECREF(it);\r
- return NULL;\r
- }\r
- buf = PyByteArray_AS_STRING(bytearray_obj);\r
-\r
- while ((item = PyIter_Next(it)) != NULL) {\r
- if (! _getbytevalue(item, &value)) {\r
- Py_DECREF(item);\r
- Py_DECREF(it);\r
- Py_DECREF(bytearray_obj);\r
- return NULL;\r
- }\r
- buf[len++] = value;\r
- Py_DECREF(item);\r
-\r
- if (len >= buf_size) {\r
- buf_size = len + (len >> 1) + 1;\r
- if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {\r
- Py_DECREF(it);\r
- Py_DECREF(bytearray_obj);\r
- return NULL;\r
- }\r
- /* Recompute the `buf' pointer, since the resizing operation may\r
- have invalidated it. */\r
- buf = PyByteArray_AS_STRING(bytearray_obj);\r
- }\r
- }\r
- Py_DECREF(it);\r
-\r
- /* Resize down to exact size. */\r
- if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {\r
- Py_DECREF(bytearray_obj);\r
- return NULL;\r
- }\r
-\r
- if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {\r
- Py_DECREF(bytearray_obj);\r
- return NULL;\r
- }\r
- Py_DECREF(bytearray_obj);\r
-\r
- Py_RETURN_NONE;\r
-}\r
-\r
-PyDoc_STRVAR(pop__doc__,\r
-"B.pop([index]) -> int\n\\r
-\n\\r
-Remove and return a single item from B. If no index\n\\r
-argument is given, will pop the last value.");\r
-static PyObject *\r
-bytearray_pop(PyByteArrayObject *self, PyObject *args)\r
-{\r
- int value;\r
- Py_ssize_t where = -1, n = Py_SIZE(self);\r
-\r
- if (!PyArg_ParseTuple(args, "|n:pop", &where))\r
- return NULL;\r
-\r
- if (n == 0) {\r
- PyErr_SetString(PyExc_IndexError,\r
- "pop from empty bytearray");\r
- return NULL;\r
- }\r
- if (where < 0)\r
- where += Py_SIZE(self);\r
- if (where < 0 || where >= Py_SIZE(self)) {\r
- PyErr_SetString(PyExc_IndexError, "pop index out of range");\r
- return NULL;\r
- }\r
- if (!_canresize(self))\r
- return NULL;\r
-\r
- value = self->ob_bytes[where];\r
- memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);\r
- if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)\r
- return NULL;\r
-\r
- return PyInt_FromLong((unsigned char)value);\r
-}\r
-\r
-PyDoc_STRVAR(remove__doc__,\r
-"B.remove(int) -> None\n\\r
-\n\\r
-Remove the first occurance of a value in B.");\r
-static PyObject *\r
-bytearray_remove(PyByteArrayObject *self, PyObject *arg)\r
-{\r
- int value;\r
- Py_ssize_t where, n = Py_SIZE(self);\r
-\r
- if (! _getbytevalue(arg, &value))\r
- return NULL;\r
-\r
- for (where = 0; where < n; where++) {\r
- if (self->ob_bytes[where] == value)\r
- break;\r
- }\r
- if (where == n) {\r
- PyErr_SetString(PyExc_ValueError, "value not found in bytearray");\r
- return NULL;\r
- }\r
- if (!_canresize(self))\r
- return NULL;\r
-\r
- memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);\r
- if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)\r
- return NULL;\r
-\r
- Py_RETURN_NONE;\r
-}\r
-\r
-/* XXX These two helpers could be optimized if argsize == 1 */\r
-\r
-static Py_ssize_t\r
-lstrip_helper(unsigned char *myptr, Py_ssize_t mysize,\r
- void *argptr, Py_ssize_t argsize)\r
-{\r
- Py_ssize_t i = 0;\r
- while (i < mysize && memchr(argptr, myptr[i], argsize))\r
- i++;\r
- return i;\r
-}\r
-\r
-static Py_ssize_t\r
-rstrip_helper(unsigned char *myptr, Py_ssize_t mysize,\r
- void *argptr, Py_ssize_t argsize)\r
-{\r
- Py_ssize_t i = mysize - 1;\r
- while (i >= 0 && memchr(argptr, myptr[i], argsize))\r
- i--;\r
- return i + 1;\r
-}\r
-\r
-PyDoc_STRVAR(strip__doc__,\r
-"B.strip([bytes]) -> bytearray\n\\r
-\n\\r
-Strip leading and trailing bytes contained in the argument.\n\\r
-If the argument is omitted, strip ASCII whitespace.");\r
-static PyObject *\r
-bytearray_strip(PyByteArrayObject *self, PyObject *args)\r
-{\r
- Py_ssize_t left, right, mysize, argsize;\r
- void *myptr, *argptr;\r
- PyObject *arg = Py_None;\r
- Py_buffer varg;\r
- if (!PyArg_ParseTuple(args, "|O:strip", &arg))\r
- return NULL;\r
- if (arg == Py_None) {\r
- argptr = "\t\n\r\f\v ";\r
- argsize = 6;\r
- }\r
- else {\r
- if (_getbuffer(arg, &varg) < 0)\r
- return NULL;\r
- argptr = varg.buf;\r
- argsize = varg.len;\r
- }\r
- myptr = self->ob_bytes;\r
- mysize = Py_SIZE(self);\r
- left = lstrip_helper(myptr, mysize, argptr, argsize);\r
- if (left == mysize)\r
- right = left;\r
- else\r
- right = rstrip_helper(myptr, mysize, argptr, argsize);\r
- if (arg != Py_None)\r
- PyBuffer_Release(&varg);\r
- return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);\r
-}\r
-\r
-PyDoc_STRVAR(lstrip__doc__,\r
-"B.lstrip([bytes]) -> bytearray\n\\r
-\n\\r
-Strip leading bytes contained in the argument.\n\\r
-If the argument is omitted, strip leading ASCII whitespace.");\r
-static PyObject *\r
-bytearray_lstrip(PyByteArrayObject *self, PyObject *args)\r
-{\r
- Py_ssize_t left, right, mysize, argsize;\r
- void *myptr, *argptr;\r
- PyObject *arg = Py_None;\r
- Py_buffer varg;\r
- if (!PyArg_ParseTuple(args, "|O:lstrip", &arg))\r
- return NULL;\r
- if (arg == Py_None) {\r
- argptr = "\t\n\r\f\v ";\r
- argsize = 6;\r
- }\r
- else {\r
- if (_getbuffer(arg, &varg) < 0)\r
- return NULL;\r
- argptr = varg.buf;\r
- argsize = varg.len;\r
- }\r
- myptr = self->ob_bytes;\r
- mysize = Py_SIZE(self);\r
- left = lstrip_helper(myptr, mysize, argptr, argsize);\r
- right = mysize;\r
- if (arg != Py_None)\r
- PyBuffer_Release(&varg);\r
- return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);\r
-}\r
-\r
-PyDoc_STRVAR(rstrip__doc__,\r
-"B.rstrip([bytes]) -> bytearray\n\\r
-\n\\r
-Strip trailing bytes contained in the argument.\n\\r
-If the argument is omitted, strip trailing ASCII whitespace.");\r
-static PyObject *\r
-bytearray_rstrip(PyByteArrayObject *self, PyObject *args)\r
-{\r
- Py_ssize_t left, right, mysize, argsize;\r
- void *myptr, *argptr;\r
- PyObject *arg = Py_None;\r
- Py_buffer varg;\r
- if (!PyArg_ParseTuple(args, "|O:rstrip", &arg))\r
- return NULL;\r
- if (arg == Py_None) {\r
- argptr = "\t\n\r\f\v ";\r
- argsize = 6;\r
- }\r
- else {\r
- if (_getbuffer(arg, &varg) < 0)\r
- return NULL;\r
- argptr = varg.buf;\r
- argsize = varg.len;\r
- }\r
- myptr = self->ob_bytes;\r
- mysize = Py_SIZE(self);\r
- left = 0;\r
- right = rstrip_helper(myptr, mysize, argptr, argsize);\r
- if (arg != Py_None)\r
- PyBuffer_Release(&varg);\r
- return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);\r
-}\r
-\r
-PyDoc_STRVAR(decode_doc,\r
-"B.decode([encoding[, errors]]) -> unicode object.\n\\r
-\n\\r
-Decodes B using the codec registered for encoding. encoding defaults\n\\r
-to the default encoding. errors may be given to set a different error\n\\r
-handling scheme. Default is 'strict' meaning that encoding errors raise\n\\r
-a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\\r
-as well as any other name registered with codecs.register_error that is\n\\r
-able to handle UnicodeDecodeErrors.");\r
-\r
-static PyObject *\r
-bytearray_decode(PyObject *self, PyObject *args, PyObject *kwargs)\r
-{\r
- const char *encoding = NULL;\r
- const char *errors = NULL;\r
- static char *kwlist[] = {"encoding", "errors", 0};\r
-\r
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode", kwlist, &encoding, &errors))\r
- return NULL;\r
- if (encoding == NULL) {\r
-#ifdef Py_USING_UNICODE\r
- encoding = PyUnicode_GetDefaultEncoding();\r
-#else\r
- PyErr_SetString(PyExc_ValueError, "no encoding specified");\r
- return NULL;\r
-#endif\r
- }\r
- return PyCodec_Decode(self, encoding, errors);\r
-}\r
-\r
-PyDoc_STRVAR(alloc_doc,\r
-"B.__alloc__() -> int\n\\r
-\n\\r
-Returns the number of bytes actually allocated.");\r
-\r
-static PyObject *\r
-bytearray_alloc(PyByteArrayObject *self)\r
-{\r
- return PyInt_FromSsize_t(self->ob_alloc);\r
-}\r
-\r
-PyDoc_STRVAR(join_doc,\r
-"B.join(iterable_of_bytes) -> bytes\n\\r
-\n\\r
-Concatenates any number of bytearray objects, with B in between each pair.");\r
-\r
-static PyObject *\r
-bytearray_join(PyByteArrayObject *self, PyObject *it)\r
-{\r
- PyObject *seq;\r
- Py_ssize_t mysize = Py_SIZE(self);\r
- Py_ssize_t i;\r
- Py_ssize_t n;\r
- PyObject **items;\r
- Py_ssize_t totalsize = 0;\r
- PyObject *result;\r
- char *dest;\r
-\r
- seq = PySequence_Fast(it, "can only join an iterable");\r
- if (seq == NULL)\r
- return NULL;\r
- n = PySequence_Fast_GET_SIZE(seq);\r
- items = PySequence_Fast_ITEMS(seq);\r
-\r
- /* Compute the total size, and check that they are all bytes */\r
- /* XXX Shouldn't we use _getbuffer() on these items instead? */\r
- for (i = 0; i < n; i++) {\r
- PyObject *obj = items[i];\r
- if (!PyByteArray_Check(obj) && !PyBytes_Check(obj)) {\r
- PyErr_Format(PyExc_TypeError,\r
- "can only join an iterable of bytes "\r
- "(item %ld has type '%.100s')",\r
- /* XXX %ld isn't right on Win64 */\r
- (long)i, Py_TYPE(obj)->tp_name);\r
- goto error;\r
- }\r
- if (i > 0)\r
- totalsize += mysize;\r
- totalsize += Py_SIZE(obj);\r
- if (totalsize < 0) {\r
- PyErr_NoMemory();\r
- goto error;\r
- }\r
- }\r
-\r
- /* Allocate the result, and copy the bytes */\r
- result = PyByteArray_FromStringAndSize(NULL, totalsize);\r
- if (result == NULL)\r
- goto error;\r
- dest = PyByteArray_AS_STRING(result);\r
- for (i = 0; i < n; i++) {\r
- PyObject *obj = items[i];\r
- Py_ssize_t size = Py_SIZE(obj);\r
- char *buf;\r
- if (PyByteArray_Check(obj))\r
- buf = PyByteArray_AS_STRING(obj);\r
- else\r
- buf = PyBytes_AS_STRING(obj);\r
- if (i) {\r
- memcpy(dest, self->ob_bytes, mysize);\r
- dest += mysize;\r
- }\r
- memcpy(dest, buf, size);\r
- dest += size;\r
- }\r
-\r
- /* Done */\r
- Py_DECREF(seq);\r
- return result;\r
-\r
- /* Error handling */\r
- error:\r
- Py_DECREF(seq);\r
- return NULL;\r
-}\r
-\r
-PyDoc_STRVAR(splitlines__doc__,\r
-"B.splitlines(keepends=False) -> list of lines\n\\r
-\n\\r
-Return a list of the lines in B, breaking at line boundaries.\n\\r
-Line breaks are not included in the resulting list unless keepends\n\\r
-is given and true.");\r
-\r
-static PyObject*\r
-bytearray_splitlines(PyObject *self, PyObject *args)\r
-{\r
- int keepends = 0;\r
-\r
- if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))\r
- return NULL;\r
-\r
- return stringlib_splitlines(\r
- (PyObject*) self, PyByteArray_AS_STRING(self),\r
- PyByteArray_GET_SIZE(self), keepends\r
- );\r
-}\r
-\r
-PyDoc_STRVAR(fromhex_doc,\r
-"bytearray.fromhex(string) -> bytearray\n\\r
-\n\\r
-Create a bytearray object from a string of hexadecimal numbers.\n\\r
-Spaces between two numbers are accepted.\n\\r
-Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef').");\r
-\r
-static int\r
-hex_digit_to_int(char c)\r
-{\r
- if (Py_ISDIGIT(c))\r
- return c - '0';\r
- else {\r
- if (Py_ISUPPER(c))\r
- c = Py_TOLOWER(c);\r
- if (c >= 'a' && c <= 'f')\r
- return c - 'a' + 10;\r
- }\r
- return -1;\r
-}\r
-\r
-static PyObject *\r
-bytearray_fromhex(PyObject *cls, PyObject *args)\r
-{\r
- PyObject *newbytes;\r
- char *buf;\r
- char *hex;\r
- Py_ssize_t hexlen, byteslen, i, j;\r
- int top, bot;\r
-\r
- if (!PyArg_ParseTuple(args, "s#:fromhex", &hex, &hexlen))\r
- return NULL;\r
- byteslen = hexlen/2; /* This overestimates if there are spaces */\r
- newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);\r
- if (!newbytes)\r
- return NULL;\r
- buf = PyByteArray_AS_STRING(newbytes);\r
- for (i = j = 0; i < hexlen; i += 2) {\r
- /* skip over spaces in the input */\r
- while (hex[i] == ' ')\r
- i++;\r
- if (i >= hexlen)\r
- break;\r
- top = hex_digit_to_int(hex[i]);\r
- bot = hex_digit_to_int(hex[i+1]);\r
- if (top == -1 || bot == -1) {\r
- PyErr_Format(PyExc_ValueError,\r
- "non-hexadecimal number found in "\r
- "fromhex() arg at position %zd", i);\r
- goto error;\r
- }\r
- buf[j++] = (top << 4) + bot;\r
- }\r
- if (PyByteArray_Resize(newbytes, j) < 0)\r
- goto error;\r
- return newbytes;\r
-\r
- error:\r
- Py_DECREF(newbytes);\r
- return NULL;\r
-}\r
-\r
-PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");\r
-\r
-static PyObject *\r
-bytearray_reduce(PyByteArrayObject *self)\r
-{\r
- PyObject *latin1, *dict;\r
- if (self->ob_bytes)\r
-#ifdef Py_USING_UNICODE\r
- latin1 = PyUnicode_DecodeLatin1(self->ob_bytes,\r
- Py_SIZE(self), NULL);\r
-#else\r
- latin1 = PyString_FromStringAndSize(self->ob_bytes, Py_SIZE(self));\r
-#endif\r
- else\r
-#ifdef Py_USING_UNICODE\r
- latin1 = PyUnicode_FromString("");\r
-#else\r
- latin1 = PyString_FromString("");\r
-#endif\r
-\r
- dict = PyObject_GetAttrString((PyObject *)self, "__dict__");\r
- if (dict == NULL) {\r
- PyErr_Clear();\r
- dict = Py_None;\r
- Py_INCREF(dict);\r
- }\r
-\r
- return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);\r
-}\r
-\r
-PyDoc_STRVAR(sizeof_doc,\r
-"B.__sizeof__() -> int\n\\r
- \n\\r
-Returns the size of B in memory, in bytes");\r
-static PyObject *\r
-bytearray_sizeof(PyByteArrayObject *self)\r
-{\r
- Py_ssize_t res;\r
-\r
- res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);\r
- return PyInt_FromSsize_t(res);\r
-}\r
-\r
-static PySequenceMethods bytearray_as_sequence = {\r
- (lenfunc)bytearray_length, /* sq_length */\r
- (binaryfunc)PyByteArray_Concat, /* sq_concat */\r
- (ssizeargfunc)bytearray_repeat, /* sq_repeat */\r
- (ssizeargfunc)bytearray_getitem, /* sq_item */\r
- 0, /* sq_slice */\r
- (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */\r
- 0, /* sq_ass_slice */\r
- (objobjproc)bytearray_contains, /* sq_contains */\r
- (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */\r
- (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */\r
-};\r
-\r
-static PyMappingMethods bytearray_as_mapping = {\r
- (lenfunc)bytearray_length,\r
- (binaryfunc)bytearray_subscript,\r
- (objobjargproc)bytearray_ass_subscript,\r
-};\r
-\r
-static PyBufferProcs bytearray_as_buffer = {\r
- (readbufferproc)bytearray_buffer_getreadbuf,\r
- (writebufferproc)bytearray_buffer_getwritebuf,\r
- (segcountproc)bytearray_buffer_getsegcount,\r
- (charbufferproc)bytearray_buffer_getcharbuf,\r
- (getbufferproc)bytearray_getbuffer,\r
- (releasebufferproc)bytearray_releasebuffer,\r
-};\r
-\r
-static PyMethodDef\r
-bytearray_methods[] = {\r
- {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},\r
- {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, reduce_doc},\r
- {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, sizeof_doc},\r
- {"append", (PyCFunction)bytearray_append, METH_O, append__doc__},\r
- {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,\r
- _Py_capitalize__doc__},\r
- {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},\r
- {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},\r
- {"decode", (PyCFunction)bytearray_decode, METH_VARARGS | METH_KEYWORDS, decode_doc},\r
- {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},\r
- {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS,\r
- expandtabs__doc__},\r
- {"extend", (PyCFunction)bytearray_extend, METH_O, extend__doc__},\r
- {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},\r
- {"fromhex", (PyCFunction)bytearray_fromhex, METH_VARARGS|METH_CLASS,\r
- fromhex_doc},\r
- {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},\r
- {"insert", (PyCFunction)bytearray_insert, METH_VARARGS, insert__doc__},\r
- {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,\r
- _Py_isalnum__doc__},\r
- {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,\r
- _Py_isalpha__doc__},\r
- {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,\r
- _Py_isdigit__doc__},\r
- {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,\r
- _Py_islower__doc__},\r
- {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,\r
- _Py_isspace__doc__},\r
- {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,\r
- _Py_istitle__doc__},\r
- {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,\r
- _Py_isupper__doc__},\r
- {"join", (PyCFunction)bytearray_join, METH_O, join_doc},\r
- {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},\r
- {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},\r
- {"lstrip", (PyCFunction)bytearray_lstrip, METH_VARARGS, lstrip__doc__},\r
- {"partition", (PyCFunction)bytearray_partition, METH_O, partition__doc__},\r
- {"pop", (PyCFunction)bytearray_pop, METH_VARARGS, pop__doc__},\r
- {"remove", (PyCFunction)bytearray_remove, METH_O, remove__doc__},\r
- {"replace", (PyCFunction)bytearray_replace, METH_VARARGS, replace__doc__},\r
- {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, reverse__doc__},\r
- {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},\r
- {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},\r
- {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},\r
- {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, rpartition__doc__},\r
- {"rsplit", (PyCFunction)bytearray_rsplit, METH_VARARGS, rsplit__doc__},\r
- {"rstrip", (PyCFunction)bytearray_rstrip, METH_VARARGS, rstrip__doc__},\r
- {"split", (PyCFunction)bytearray_split, METH_VARARGS, split__doc__},\r
- {"splitlines", (PyCFunction)bytearray_splitlines, METH_VARARGS,\r
- splitlines__doc__},\r
- {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,\r
- startswith__doc__},\r
- {"strip", (PyCFunction)bytearray_strip, METH_VARARGS, strip__doc__},\r
- {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,\r
- _Py_swapcase__doc__},\r
- {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},\r
- {"translate", (PyCFunction)bytearray_translate, METH_VARARGS,\r
- translate__doc__},\r
- {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},\r
- {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},\r
- {NULL}\r
-};\r
-\r
-PyDoc_STRVAR(bytearray_doc,\r
-"bytearray(iterable_of_ints) -> bytearray.\n\\r
-bytearray(string, encoding[, errors]) -> bytearray.\n\\r
-bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray.\n\\r
-bytearray(memory_view) -> bytearray.\n\\r
-\n\\r
-Construct an mutable bytearray object from:\n\\r
- - an iterable yielding integers in range(256)\n\\r
- - a text string encoded using the specified encoding\n\\r
- - a bytes or a bytearray object\n\\r
- - any object implementing the buffer API.\n\\r
-\n\\r
-bytearray(int) -> bytearray.\n\\r
-\n\\r
-Construct a zero-initialized bytearray of the given length.");\r
-\r
-\r
-static PyObject *bytearray_iter(PyObject *seq);\r
-\r
-PyTypeObject PyByteArray_Type = {\r
- PyVarObject_HEAD_INIT(&PyType_Type, 0)\r
- "bytearray",\r
- sizeof(PyByteArrayObject),\r
- 0,\r
- (destructor)bytearray_dealloc, /* tp_dealloc */\r
- 0, /* tp_print */\r
- 0, /* tp_getattr */\r
- 0, /* tp_setattr */\r
- 0, /* tp_compare */\r
- (reprfunc)bytearray_repr, /* tp_repr */\r
- 0, /* tp_as_number */\r
- &bytearray_as_sequence, /* tp_as_sequence */\r
- &bytearray_as_mapping, /* tp_as_mapping */\r
- 0, /* tp_hash */\r
- 0, /* tp_call */\r
- bytearray_str, /* tp_str */\r
- PyObject_GenericGetAttr, /* tp_getattro */\r
- 0, /* tp_setattro */\r
- &bytearray_as_buffer, /* tp_as_buffer */\r
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |\r
- Py_TPFLAGS_HAVE_NEWBUFFER, /* tp_flags */\r
- bytearray_doc, /* tp_doc */\r
- 0, /* tp_traverse */\r
- 0, /* tp_clear */\r
- (richcmpfunc)bytearray_richcompare, /* tp_richcompare */\r
- 0, /* tp_weaklistoffset */\r
- bytearray_iter, /* tp_iter */\r
- 0, /* tp_iternext */\r
- bytearray_methods, /* tp_methods */\r
- 0, /* tp_members */\r
- 0, /* tp_getset */\r
- 0, /* tp_base */\r
- 0, /* tp_dict */\r
- 0, /* tp_descr_get */\r
- 0, /* tp_descr_set */\r
- 0, /* tp_dictoffset */\r
- (initproc)bytearray_init, /* tp_init */\r
- PyType_GenericAlloc, /* tp_alloc */\r
- PyType_GenericNew, /* tp_new */\r
- PyObject_Del, /* tp_free */\r
-};\r
-\r
-/*********************** Bytes Iterator ****************************/\r
-\r
-typedef struct {\r
- PyObject_HEAD\r
- Py_ssize_t it_index;\r
- PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */\r
-} bytesiterobject;\r
-\r
-static void\r
-bytearrayiter_dealloc(bytesiterobject *it)\r
-{\r
- _PyObject_GC_UNTRACK(it);\r
- Py_XDECREF(it->it_seq);\r
- PyObject_GC_Del(it);\r
-}\r
-\r
-static int\r
-bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)\r
-{\r
- Py_VISIT(it->it_seq);\r
- return 0;\r
-}\r
-\r
-static PyObject *\r
-bytearrayiter_next(bytesiterobject *it)\r
-{\r
- PyByteArrayObject *seq;\r
- PyObject *item;\r
-\r
- assert(it != NULL);\r
- seq = it->it_seq;\r
- if (seq == NULL)\r
- return NULL;\r
- assert(PyByteArray_Check(seq));\r
-\r
- if (it->it_index < PyByteArray_GET_SIZE(seq)) {\r
- item = PyInt_FromLong(\r
- (unsigned char)seq->ob_bytes[it->it_index]);\r
- if (item != NULL)\r
- ++it->it_index;\r
- return item;\r
- }\r
-\r
- Py_DECREF(seq);\r
- it->it_seq = NULL;\r
- return NULL;\r
-}\r
-\r
-static PyObject *\r
-bytesarrayiter_length_hint(bytesiterobject *it)\r
-{\r
- Py_ssize_t len = 0;\r
- if (it->it_seq)\r
- len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;\r
- return PyInt_FromSsize_t(len);\r
-}\r
-\r
-PyDoc_STRVAR(length_hint_doc,\r
- "Private method returning an estimate of len(list(it)).");\r
-\r
-static PyMethodDef bytearrayiter_methods[] = {\r
- {"__length_hint__", (PyCFunction)bytesarrayiter_length_hint, METH_NOARGS,\r
- length_hint_doc},\r
- {NULL, NULL} /* sentinel */\r
-};\r
-\r
-PyTypeObject PyByteArrayIter_Type = {\r
- PyVarObject_HEAD_INIT(&PyType_Type, 0)\r
- "bytearray_iterator", /* tp_name */\r
- sizeof(bytesiterobject), /* tp_basicsize */\r
- 0, /* tp_itemsize */\r
- /* methods */\r
- (destructor)bytearrayiter_dealloc, /* tp_dealloc */\r
- 0, /* tp_print */\r
- 0, /* tp_getattr */\r
- 0, /* tp_setattr */\r
- 0, /* tp_compare */\r
- 0, /* tp_repr */\r
- 0, /* tp_as_number */\r
- 0, /* tp_as_sequence */\r
- 0, /* tp_as_mapping */\r
- 0, /* tp_hash */\r
- 0, /* tp_call */\r
- 0, /* tp_str */\r
- PyObject_GenericGetAttr, /* tp_getattro */\r
- 0, /* tp_setattro */\r
- 0, /* tp_as_buffer */\r
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */\r
- 0, /* tp_doc */\r
- (traverseproc)bytearrayiter_traverse, /* tp_traverse */\r
- 0, /* tp_clear */\r
- 0, /* tp_richcompare */\r
- 0, /* tp_weaklistoffset */\r
- PyObject_SelfIter, /* tp_iter */\r
- (iternextfunc)bytearrayiter_next, /* tp_iternext */\r
- bytearrayiter_methods, /* tp_methods */\r
- 0,\r
-};\r
-\r
-static PyObject *\r
-bytearray_iter(PyObject *seq)\r
-{\r
- bytesiterobject *it;\r
-\r
- if (!PyByteArray_Check(seq)) {\r
- PyErr_BadInternalCall();\r
- return NULL;\r
- }\r
- it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);\r
- if (it == NULL)\r
- return NULL;\r
- it->it_index = 0;\r
- Py_INCREF(seq);\r
- it->it_seq = (PyByteArrayObject *)seq;\r
- _PyObject_GC_TRACK(it);\r
- return (PyObject *)it;\r
-}\r