blob: 83c79b200a0a130a579335bc6ec212df5361002f [file] [log] [blame]
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001/* PyByteArray (bytearray) implementation */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02005#include "pycore_abstract.h" // _PyIndex_Check()
Victor Stinner45876a92020-02-12 22:32:34 +01006#include "pycore_bytes_methods.h"
Victor Stinnerbcda8f12018-11-21 22:27:47 +01007#include "pycore_object.h"
Ethan Furmanb95b5612015-01-23 20:05:18 -08008#include "bytesobject.h"
Gregory P. Smith8cb65692015-04-25 23:22:26 +00009#include "pystrhex.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +000010
Martin v. Löwis7252a6e2014-07-27 16:25:09 +020011/*[clinic input]
12class bytearray "PyByteArrayObject *" "&PyByteArray_Type"
13[clinic start generated code]*/
14/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5535b77c37a119e0]*/
15
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000016char _PyByteArray_empty_string[] = "";
Christian Heimes2c9c7a52008-05-26 13:42:13 +000017
Christian Heimes2c9c7a52008-05-26 13:42:13 +000018/* end nullbytes support */
19
20/* Helpers */
21
22static int
23_getbytevalue(PyObject* arg, int *value)
24{
Serhiy Storchakae67f7db2020-06-29 22:36:41 +030025 int overflow;
26 long face_value = PyLong_AsLongAndOverflow(arg, &overflow);
Christian Heimes2c9c7a52008-05-26 13:42:13 +000027
Serhiy Storchakae67f7db2020-06-29 22:36:41 +030028 if (face_value == -1 && PyErr_Occurred()) {
29 *value = -1;
30 return 0;
Georg Brandl9a54d7c2008-07-16 23:15:30 +000031 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +000032 if (face_value < 0 || face_value >= 256) {
Serhiy Storchakae67f7db2020-06-29 22:36:41 +030033 /* this includes an overflow in converting to C long */
Georg Brandl9a54d7c2008-07-16 23:15:30 +000034 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
Mark Dickinson10de93a2010-07-09 19:25:48 +000035 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000036 return 0;
37 }
38
39 *value = face_value;
40 return 1;
41}
42
43static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +000044bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000045{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000046 void *ptr;
47 if (view == NULL) {
Stefan Krah5178d912015-02-03 16:57:21 +010048 PyErr_SetString(PyExc_BufferError,
49 "bytearray_getbuffer: view==NULL argument is obsolete");
50 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000051 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000052 ptr = (void *) PyByteArray_AS_STRING(obj);
Stefan Krah5178d912015-02-03 16:57:21 +010053 /* cannot fail if view != NULL and readonly == 0 */
54 (void)PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
55 obj->ob_exports++;
56 return 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000057}
58
59static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +000060bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000061{
62 obj->ob_exports--;
63}
64
Antoine Pitrou5504e892008-12-06 21:27:53 +000065static int
66_canresize(PyByteArrayObject *self)
67{
68 if (self->ob_exports > 0) {
69 PyErr_SetString(PyExc_BufferError,
70 "Existing exports of data: object cannot be re-sized");
71 return 0;
72 }
73 return 1;
74}
75
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030076#include "clinic/bytearrayobject.c.h"
77
Christian Heimes2c9c7a52008-05-26 13:42:13 +000078/* Direct API functions */
79
80PyObject *
81PyByteArray_FromObject(PyObject *input)
82{
Petr Viktorinffd97532020-02-11 17:46:57 +010083 return PyObject_CallOneArg((PyObject *)&PyByteArray_Type, input);
Christian Heimes2c9c7a52008-05-26 13:42:13 +000084}
85
Serhiy Storchakaa2314282017-10-29 02:11:54 +030086static PyObject *
87_PyByteArray_FromBufferObject(PyObject *obj)
88{
89 PyObject *result;
90 Py_buffer view;
91
92 if (PyObject_GetBuffer(obj, &view, PyBUF_FULL_RO) < 0) {
93 return NULL;
94 }
95 result = PyByteArray_FromStringAndSize(NULL, view.len);
96 if (result != NULL &&
97 PyBuffer_ToContiguous(PyByteArray_AS_STRING(result),
98 &view, view.len, 'C') < 0)
99 {
100 Py_CLEAR(result);
101 }
102 PyBuffer_Release(&view);
103 return result;
104}
105
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000106PyObject *
107PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
108{
109 PyByteArrayObject *new;
110 Py_ssize_t alloc;
111
112 if (size < 0) {
113 PyErr_SetString(PyExc_SystemError,
114 "Negative size passed to PyByteArray_FromStringAndSize");
115 return NULL;
116 }
117
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000118 /* Prevent buffer overflow when setting alloc to size+1. */
119 if (size == PY_SSIZE_T_MAX) {
120 return PyErr_NoMemory();
121 }
122
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000123 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
124 if (new == NULL)
125 return NULL;
126
127 if (size == 0) {
128 new->ob_bytes = NULL;
129 alloc = 0;
130 }
131 else {
132 alloc = size + 1;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100133 new->ob_bytes = PyObject_Malloc(alloc);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000134 if (new->ob_bytes == NULL) {
135 Py_DECREF(new);
136 return PyErr_NoMemory();
137 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +0000138 if (bytes != NULL && size > 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000139 memcpy(new->ob_bytes, bytes, size);
140 new->ob_bytes[size] = '\0'; /* Trailing null byte */
141 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100142 Py_SET_SIZE(new, size);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000143 new->ob_alloc = alloc;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200144 new->ob_start = new->ob_bytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000145 new->ob_exports = 0;
146
147 return (PyObject *)new;
148}
149
150Py_ssize_t
151PyByteArray_Size(PyObject *self)
152{
153 assert(self != NULL);
154 assert(PyByteArray_Check(self));
155
156 return PyByteArray_GET_SIZE(self);
157}
158
159char *
160PyByteArray_AsString(PyObject *self)
161{
162 assert(self != NULL);
163 assert(PyByteArray_Check(self));
164
165 return PyByteArray_AS_STRING(self);
166}
167
168int
Antoine Pitroucc231542014-11-02 18:40:09 +0100169PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000170{
171 void *sval;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200172 PyByteArrayObject *obj = ((PyByteArrayObject *)self);
Antoine Pitroucc231542014-11-02 18:40:09 +0100173 /* All computations are done unsigned to avoid integer overflows
174 (see issue #22335). */
175 size_t alloc = (size_t) obj->ob_alloc;
176 size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes);
177 size_t size = (size_t) requested_size;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000178
179 assert(self != NULL);
180 assert(PyByteArray_Check(self));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200181 assert(logical_offset <= alloc);
Antoine Pitroucc231542014-11-02 18:40:09 +0100182 assert(requested_size >= 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000183
Antoine Pitroucc231542014-11-02 18:40:09 +0100184 if (requested_size == Py_SIZE(self)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000185 return 0;
186 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200187 if (!_canresize(obj)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000188 return -1;
189 }
190
Antoine Pitrou25454112015-05-19 20:52:27 +0200191 if (size + logical_offset + 1 <= alloc) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200192 /* Current buffer is large enough to host the requested size,
193 decide on a strategy. */
194 if (size < alloc / 2) {
195 /* Major downsize; resize down to exact size */
196 alloc = size + 1;
197 }
198 else {
199 /* Minor downsize; quick exit */
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100200 Py_SET_SIZE(self, size);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200201 PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */
202 return 0;
203 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000204 }
205 else {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200206 /* Need growing, decide on a strategy */
207 if (size <= alloc * 1.125) {
208 /* Moderate upsize; overallocate similar to list_resize() */
209 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
210 }
211 else {
212 /* Major upsize; resize up to exact size */
213 alloc = size + 1;
214 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000215 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100216 if (alloc > PY_SSIZE_T_MAX) {
217 PyErr_NoMemory();
218 return -1;
219 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000220
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200221 if (logical_offset > 0) {
222 sval = PyObject_Malloc(alloc);
223 if (sval == NULL) {
224 PyErr_NoMemory();
225 return -1;
226 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100227 memcpy(sval, PyByteArray_AS_STRING(self),
Stefan Krahdce65022017-08-25 20:12:05 +0200228 Py_MIN((size_t)requested_size, (size_t)Py_SIZE(self)));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200229 PyObject_Free(obj->ob_bytes);
230 }
231 else {
232 sval = PyObject_Realloc(obj->ob_bytes, alloc);
233 if (sval == NULL) {
234 PyErr_NoMemory();
235 return -1;
236 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000237 }
238
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200239 obj->ob_bytes = obj->ob_start = sval;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100240 Py_SET_SIZE(self, size);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200241 obj->ob_alloc = alloc;
242 obj->ob_bytes[size] = '\0'; /* Trailing null byte */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000243
244 return 0;
245}
246
247PyObject *
248PyByteArray_Concat(PyObject *a, PyObject *b)
249{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000250 Py_buffer va, vb;
251 PyByteArrayObject *result = NULL;
252
253 va.len = -1;
254 vb.len = -1;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200255 if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 ||
256 PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000257 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
Serhiy Storchaka6b5a9ec2017-03-19 19:47:02 +0200258 Py_TYPE(b)->tp_name, Py_TYPE(a)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000259 goto done;
260 }
261
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300262 if (va.len > PY_SSIZE_T_MAX - vb.len) {
263 PyErr_NoMemory();
264 goto done;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000265 }
266
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300267 result = (PyByteArrayObject *) \
268 PyByteArray_FromStringAndSize(NULL, va.len + vb.len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000269 if (result != NULL) {
270 memcpy(result->ob_bytes, va.buf, va.len);
271 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
272 }
273
274 done:
275 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000276 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000277 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000278 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000279 return (PyObject *)result;
280}
281
282/* Functions stuffed into the type object */
283
284static Py_ssize_t
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000285bytearray_length(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000286{
287 return Py_SIZE(self);
288}
289
290static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000291bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000292{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000293 Py_ssize_t size;
294 Py_buffer vo;
295
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200296 if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000297 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
298 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
299 return NULL;
300 }
301
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300302 size = Py_SIZE(self);
303 if (size > PY_SSIZE_T_MAX - vo.len) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000304 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000305 return PyErr_NoMemory();
306 }
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300307 if (PyByteArray_Resize((PyObject *)self, size + vo.len) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000308 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000309 return NULL;
310 }
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300311 memcpy(PyByteArray_AS_STRING(self) + size, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000312 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000313 Py_INCREF(self);
314 return (PyObject *)self;
315}
316
317static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000318bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000319{
320 PyByteArrayObject *result;
321 Py_ssize_t mysize;
322 Py_ssize_t size;
323
324 if (count < 0)
325 count = 0;
326 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000327 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000328 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000329 size = mysize * count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000330 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
331 if (result != NULL && size != 0) {
332 if (mysize == 1)
333 memset(result->ob_bytes, self->ob_bytes[0], size);
334 else {
335 Py_ssize_t i;
336 for (i = 0; i < count; i++)
337 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
338 }
339 }
340 return (PyObject *)result;
341}
342
343static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000344bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000345{
346 Py_ssize_t mysize;
347 Py_ssize_t size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200348 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000349
350 if (count < 0)
351 count = 0;
352 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000353 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000354 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000355 size = mysize * count;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200356 if (PyByteArray_Resize((PyObject *)self, size) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000357 return NULL;
358
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200359 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000360 if (mysize == 1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200361 memset(buf, buf[0], size);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000362 else {
363 Py_ssize_t i;
364 for (i = 1; i < count; i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200365 memcpy(buf + i*mysize, buf, mysize);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000366 }
367
368 Py_INCREF(self);
369 return (PyObject *)self;
370}
371
372static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000373bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000374{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000375 if (i < 0 || i >= Py_SIZE(self)) {
376 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
377 return NULL;
378 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200379 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000380}
381
382static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000383bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000384{
Victor Stinnera15e2602020-04-08 02:01:56 +0200385 if (_PyIndex_Check(index)) {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000386 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000387
388 if (i == -1 && PyErr_Occurred())
389 return NULL;
390
391 if (i < 0)
392 i += PyByteArray_GET_SIZE(self);
393
394 if (i < 0 || i >= Py_SIZE(self)) {
395 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
396 return NULL;
397 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200398 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000399 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000400 else if (PySlice_Check(index)) {
Zackery Spytz14514d92019-05-17 01:13:03 -0600401 Py_ssize_t start, stop, step, slicelength, i;
402 size_t cur;
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300403 if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000404 return NULL;
405 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300406 slicelength = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self),
407 &start, &stop, step);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000408
409 if (slicelength <= 0)
410 return PyByteArray_FromStringAndSize("", 0);
411 else if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200412 return PyByteArray_FromStringAndSize(
413 PyByteArray_AS_STRING(self) + start, slicelength);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000414 }
415 else {
416 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000417 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000418 PyObject *result;
419
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000420 result = PyByteArray_FromStringAndSize(NULL, slicelength);
421 if (result == NULL)
422 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000423
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000424 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000425 for (cur = start, i = 0; i < slicelength;
426 cur += step, i++) {
427 result_buf[i] = source_buf[cur];
428 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000429 return result;
430 }
431 }
432 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400433 PyErr_Format(PyExc_TypeError,
434 "bytearray indices must be integers or slices, not %.200s",
435 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000436 return NULL;
437 }
438}
439
440static int
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200441bytearray_setslice_linear(PyByteArrayObject *self,
442 Py_ssize_t lo, Py_ssize_t hi,
443 char *bytes, Py_ssize_t bytes_len)
444{
445 Py_ssize_t avail = hi - lo;
446 char *buf = PyByteArray_AS_STRING(self);
447 Py_ssize_t growth = bytes_len - avail;
Victor Stinner84557232013-11-21 12:29:51 +0100448 int res = 0;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200449 assert(avail >= 0);
450
Victor Stinner84557232013-11-21 12:29:51 +0100451 if (growth < 0) {
452 if (!_canresize(self))
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200453 return -1;
Victor Stinner84557232013-11-21 12:29:51 +0100454
455 if (lo == 0) {
456 /* Shrink the buffer by advancing its logical start */
457 self->ob_start -= growth;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200458 /*
Victor Stinner84557232013-11-21 12:29:51 +0100459 0 lo hi old_size
460 | |<----avail----->|<-----tail------>|
461 | |<-bytes_len->|<-----tail------>|
462 0 new_lo new_hi new_size
463 */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200464 }
Victor Stinner84557232013-11-21 12:29:51 +0100465 else {
466 /*
467 0 lo hi old_size
468 | |<----avail----->|<-----tomove------>|
469 | |<-bytes_len->|<-----tomove------>|
470 0 lo new_hi new_size
471 */
472 memmove(buf + lo + bytes_len, buf + hi,
473 Py_SIZE(self) - hi);
474 }
475 if (PyByteArray_Resize((PyObject *)self,
476 Py_SIZE(self) + growth) < 0) {
477 /* Issue #19578: Handling the memory allocation failure here is
478 tricky here because the bytearray object has already been
479 modified. Depending on growth and lo, the behaviour is
480 different.
481
482 If growth < 0 and lo != 0, the operation is completed, but a
483 MemoryError is still raised and the memory block is not
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700484 shrunk. Otherwise, the bytearray is restored in its previous
Victor Stinner84557232013-11-21 12:29:51 +0100485 state and a MemoryError is raised. */
486 if (lo == 0) {
487 self->ob_start += growth;
488 return -1;
489 }
490 /* memmove() removed bytes, the bytearray object cannot be
491 restored in its previous state. */
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100492 Py_SET_SIZE(self, Py_SIZE(self) + growth);
Victor Stinner84557232013-11-21 12:29:51 +0100493 res = -1;
494 }
495 buf = PyByteArray_AS_STRING(self);
496 }
497 else if (growth > 0) {
498 if (Py_SIZE(self) > (Py_ssize_t)PY_SSIZE_T_MAX - growth) {
499 PyErr_NoMemory();
500 return -1;
501 }
502
503 if (PyByteArray_Resize((PyObject *)self,
504 Py_SIZE(self) + growth) < 0) {
505 return -1;
506 }
507 buf = PyByteArray_AS_STRING(self);
508 /* Make the place for the additional bytes */
509 /*
510 0 lo hi old_size
511 | |<-avail->|<-----tomove------>|
512 | |<---bytes_len-->|<-----tomove------>|
513 0 lo new_hi new_size
514 */
515 memmove(buf + lo + bytes_len, buf + hi,
516 Py_SIZE(self) - lo - bytes_len);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200517 }
518
519 if (bytes_len > 0)
520 memcpy(buf + lo, bytes, bytes_len);
Victor Stinner84557232013-11-21 12:29:51 +0100521 return res;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200522}
523
524static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000525bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000526 PyObject *values)
527{
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200528 Py_ssize_t needed;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000529 void *bytes;
530 Py_buffer vbytes;
531 int res = 0;
532
533 vbytes.len = -1;
534 if (values == (PyObject *)self) {
535 /* Make a copy and call this function recursively */
536 int err;
Serhiy Storchakaa2314282017-10-29 02:11:54 +0300537 values = PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(values),
538 PyByteArray_GET_SIZE(values));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000539 if (values == NULL)
540 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000541 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000542 Py_DECREF(values);
543 return err;
544 }
545 if (values == NULL) {
546 /* del b[lo:hi] */
547 bytes = NULL;
548 needed = 0;
549 }
550 else {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200551 if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) {
552 PyErr_Format(PyExc_TypeError,
553 "can't set bytearray slice from %.100s",
554 Py_TYPE(values)->tp_name);
555 return -1;
556 }
557 needed = vbytes.len;
558 bytes = vbytes.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000559 }
560
561 if (lo < 0)
562 lo = 0;
563 if (hi < lo)
564 hi = lo;
565 if (hi > Py_SIZE(self))
566 hi = Py_SIZE(self);
567
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200568 res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000569 if (vbytes.len != -1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200570 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000571 return res;
572}
573
574static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000575bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000576{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000577 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000578
579 if (i < 0)
580 i += Py_SIZE(self);
581
582 if (i < 0 || i >= Py_SIZE(self)) {
583 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
584 return -1;
585 }
586
587 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000588 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000589
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000590 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000591 return -1;
592
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200593 PyByteArray_AS_STRING(self)[i] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000594 return 0;
595}
596
597static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000598bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000599{
600 Py_ssize_t start, stop, step, slicelen, needed;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200601 char *buf, *bytes;
602 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000603
Victor Stinnera15e2602020-04-08 02:01:56 +0200604 if (_PyIndex_Check(index)) {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000605 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000606
607 if (i == -1 && PyErr_Occurred())
608 return -1;
609
610 if (i < 0)
611 i += PyByteArray_GET_SIZE(self);
612
613 if (i < 0 || i >= Py_SIZE(self)) {
614 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
615 return -1;
616 }
617
618 if (values == NULL) {
619 /* Fall through to slice assignment */
620 start = i;
621 stop = i + 1;
622 step = 1;
623 slicelen = 1;
624 }
625 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000626 int ival;
627 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000628 return -1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200629 buf[i] = (char)ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000630 return 0;
631 }
632 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000633 else if (PySlice_Check(index)) {
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300634 if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000635 return -1;
636 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300637 slicelen = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self), &start,
638 &stop, step);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000639 }
640 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400641 PyErr_Format(PyExc_TypeError,
642 "bytearray indices must be integers or slices, not %.200s",
643 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000644 return -1;
645 }
646
647 if (values == NULL) {
648 bytes = NULL;
649 needed = 0;
650 }
651 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
Christian Heimes6d26ade2012-11-03 23:07:59 +0100652 int err;
Ezio Melottic64bcbe2012-11-03 21:19:06 +0200653 if (PyNumber_Check(values) || PyUnicode_Check(values)) {
654 PyErr_SetString(PyExc_TypeError,
655 "can assign only bytes, buffers, or iterables "
656 "of ints in range(0, 256)");
657 return -1;
658 }
Georg Brandlf3fa5682010-12-04 17:09:30 +0000659 /* Make a copy and call this function recursively */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000660 values = PyByteArray_FromObject(values);
661 if (values == NULL)
662 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000663 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000664 Py_DECREF(values);
665 return err;
666 }
667 else {
668 assert(PyByteArray_Check(values));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200669 bytes = PyByteArray_AS_STRING(values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000670 needed = Py_SIZE(values);
671 }
672 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
673 if ((step < 0 && start < stop) ||
674 (step > 0 && start > stop))
675 stop = start;
676 if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200677 return bytearray_setslice_linear(self, start, stop, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000678 }
679 else {
680 if (needed == 0) {
681 /* Delete slice */
Mark Dickinsonbc099642010-01-29 17:27:24 +0000682 size_t cur;
683 Py_ssize_t i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000684
Antoine Pitrou5504e892008-12-06 21:27:53 +0000685 if (!_canresize(self))
686 return -1;
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000687
688 if (slicelen == 0)
689 /* Nothing to do here. */
690 return 0;
691
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000692 if (step < 0) {
693 stop = start + 1;
694 start = stop + step * (slicelen - 1) - 1;
695 step = -step;
696 }
697 for (cur = start, i = 0;
698 i < slicelen; cur += step, i++) {
699 Py_ssize_t lim = step - 1;
700
Mark Dickinson66f575b2010-02-14 12:53:32 +0000701 if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000702 lim = PyByteArray_GET_SIZE(self) - cur - 1;
703
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200704 memmove(buf + cur - i,
705 buf + cur + 1, lim);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000706 }
707 /* Move the tail of the bytes, in one chunk */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000708 cur = start + (size_t)slicelen*step;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000709 if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200710 memmove(buf + cur - slicelen,
711 buf + cur,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000712 PyByteArray_GET_SIZE(self) - cur);
713 }
714 if (PyByteArray_Resize((PyObject *)self,
715 PyByteArray_GET_SIZE(self) - slicelen) < 0)
716 return -1;
717
718 return 0;
719 }
720 else {
721 /* Assign slice */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000722 Py_ssize_t i;
723 size_t cur;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000724
725 if (needed != slicelen) {
726 PyErr_Format(PyExc_ValueError,
727 "attempt to assign bytes of size %zd "
728 "to extended slice of size %zd",
729 needed, slicelen);
730 return -1;
731 }
732 for (cur = start, i = 0; i < slicelen; cur += step, i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200733 buf[cur] = bytes[i];
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000734 return 0;
735 }
736 }
737}
738
739static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000740bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000741{
742 static char *kwlist[] = {"source", "encoding", "errors", 0};
743 PyObject *arg = NULL;
744 const char *encoding = NULL;
745 const char *errors = NULL;
746 Py_ssize_t count;
747 PyObject *it;
748 PyObject *(*iternext)(PyObject *);
749
750 if (Py_SIZE(self) != 0) {
751 /* Empty previous contents (yes, do this first of all!) */
752 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
753 return -1;
754 }
755
756 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000757 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000758 &arg, &encoding, &errors))
759 return -1;
760
761 /* Make a quick exit if no first argument */
762 if (arg == NULL) {
763 if (encoding != NULL || errors != NULL) {
764 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300765 encoding != NULL ?
766 "encoding without a string argument" :
767 "errors without a string argument");
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000768 return -1;
769 }
770 return 0;
771 }
772
773 if (PyUnicode_Check(arg)) {
774 /* Encode via the codec registry */
775 PyObject *encoded, *new;
776 if (encoding == NULL) {
777 PyErr_SetString(PyExc_TypeError,
778 "string argument without an encoding");
779 return -1;
780 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000781 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000782 if (encoded == NULL)
783 return -1;
784 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000785 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000786 Py_DECREF(encoded);
787 if (new == NULL)
788 return -1;
789 Py_DECREF(new);
790 return 0;
791 }
792
793 /* If it's not unicode, there can't be encoding or errors */
794 if (encoding != NULL || errors != NULL) {
795 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300796 encoding != NULL ?
797 "encoding without a string argument" :
798 "errors without a string argument");
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000799 return -1;
800 }
801
802 /* Is it an int? */
Victor Stinnera15e2602020-04-08 02:01:56 +0200803 if (_PyIndex_Check(arg)) {
Serhiy Storchakaeb249882016-08-15 09:46:07 +0300804 count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
805 if (count == -1 && PyErr_Occurred()) {
Serhiy Storchakae8904212018-10-15 00:02:57 +0300806 if (!PyErr_ExceptionMatches(PyExc_TypeError))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000807 return -1;
INADA Naokia634e232017-01-06 17:32:01 +0900808 PyErr_Clear(); /* fall through */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000809 }
INADA Naokia634e232017-01-06 17:32:01 +0900810 else {
811 if (count < 0) {
812 PyErr_SetString(PyExc_ValueError, "negative count");
813 return -1;
814 }
815 if (count > 0) {
816 if (PyByteArray_Resize((PyObject *)self, count))
817 return -1;
818 memset(PyByteArray_AS_STRING(self), 0, count);
819 }
820 return 0;
821 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000822 }
823
824 /* Use the buffer API */
825 if (PyObject_CheckBuffer(arg)) {
826 Py_ssize_t size;
827 Py_buffer view;
828 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
829 return -1;
830 size = view.len;
831 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200832 if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
833 &view, size, 'C') < 0)
Stefan Krah7d12d9d2012-07-28 12:25:55 +0200834 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000835 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000836 return 0;
837 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000838 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000839 return -1;
840 }
841
842 /* XXX Optimize this if the arguments is a list, tuple */
843
844 /* Get the iterator */
845 it = PyObject_GetIter(arg);
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300846 if (it == NULL) {
847 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
848 PyErr_Format(PyExc_TypeError,
849 "cannot convert '%.200s' object to bytearray",
Victor Stinner58ac7002020-02-07 03:04:21 +0100850 Py_TYPE(arg)->tp_name);
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300851 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000852 return -1;
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300853 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000854 iternext = *Py_TYPE(it)->tp_iternext;
855
856 /* Run the iterator to exhaustion */
857 for (;;) {
858 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000859 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000860
861 /* Get the next item */
862 item = iternext(it);
863 if (item == NULL) {
864 if (PyErr_Occurred()) {
865 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
866 goto error;
867 PyErr_Clear();
868 }
869 break;
870 }
871
872 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000873 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000874 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000875 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000876 goto error;
877
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000878 /* Append the byte */
Serhiy Storchaka7b6e3b92015-06-29 21:14:06 +0300879 if (Py_SIZE(self) + 1 < self->ob_alloc) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100880 Py_SET_SIZE(self, Py_SIZE(self) + 1);
Serhiy Storchaka7b6e3b92015-06-29 21:14:06 +0300881 PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0';
882 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000883 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
884 goto error;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200885 PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000886 }
887
888 /* Clean up and return success */
889 Py_DECREF(it);
890 return 0;
891
892 error:
893 /* Error handling when it != NULL */
894 Py_DECREF(it);
895 return -1;
896}
897
898/* Mostly copied from string_repr, but without the
899 "smart quote" functionality. */
900static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000901bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000902{
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300903 const char *className = _PyType_Name(Py_TYPE(self));
904 const char *quote_prefix = "(b";
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000905 const char *quote_postfix = ")";
906 Py_ssize_t length = Py_SIZE(self);
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300907 /* 6 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */
908 Py_ssize_t newsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000909 PyObject *v;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200910 Py_ssize_t i;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200911 char *bytes;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200912 char c;
913 char *p;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200914 int quote;
915 char *test, *start;
916 char *buffer;
917
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300918 newsize = strlen(className);
919 if (length > (PY_SSIZE_T_MAX - 6 - newsize) / 4) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000920 PyErr_SetString(PyExc_OverflowError,
921 "bytearray object is too large to make repr");
922 return NULL;
923 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200924
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300925 newsize += 6 + length * 4;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100926 buffer = PyObject_Malloc(newsize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200927 if (buffer == NULL) {
928 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000929 return NULL;
930 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000931
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200932 /* Figure out which quote to use; single is preferred */
933 quote = '\'';
934 start = PyByteArray_AS_STRING(self);
935 for (test = start; test < start+length; ++test) {
936 if (*test == '"') {
937 quote = '\''; /* back to single */
938 break;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000939 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200940 else if (*test == '\'')
941 quote = '"';
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000942 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200943
944 p = buffer;
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300945 while (*className)
946 *p++ = *className++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200947 while (*quote_prefix)
948 *p++ = *quote_prefix++;
949 *p++ = quote;
950
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200951 bytes = PyByteArray_AS_STRING(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200952 for (i = 0; i < length; i++) {
953 /* There's at least enough room for a hex escape
954 and a closing quote. */
955 assert(newsize - (p - buffer) >= 5);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200956 c = bytes[i];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200957 if (c == '\'' || c == '\\')
958 *p++ = '\\', *p++ = c;
959 else if (c == '\t')
960 *p++ = '\\', *p++ = 't';
961 else if (c == '\n')
962 *p++ = '\\', *p++ = 'n';
963 else if (c == '\r')
964 *p++ = '\\', *p++ = 'r';
965 else if (c == 0)
966 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
967 else if (c < ' ' || c >= 0x7f) {
968 *p++ = '\\';
969 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +0200970 *p++ = Py_hexdigits[(c & 0xf0) >> 4];
971 *p++ = Py_hexdigits[c & 0xf];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200972 }
973 else
974 *p++ = c;
975 }
976 assert(newsize - (p - buffer) >= 1);
977 *p++ = quote;
978 while (*quote_postfix) {
979 *p++ = *quote_postfix++;
980 }
981
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300982 v = PyUnicode_FromStringAndSize(buffer, p - buffer);
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100983 PyObject_Free(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200984 return v;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000985}
986
987static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000988bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000989{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200990 if (_Py_GetConfig()->bytes_warning) {
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200991 if (PyErr_WarnEx(PyExc_BytesWarning,
992 "str() on a bytearray instance", 1)) {
993 return NULL;
Alexander Belopolskyf0f45142010-08-11 17:31:17 +0000994 }
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200995 }
996 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000997}
998
999static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001000bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001001{
1002 Py_ssize_t self_size, other_size;
1003 Py_buffer self_bytes, other_bytes;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001004 int cmp, rc;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001005
1006 /* Bytes can be compared to anything that supports the (binary)
1007 buffer API. Except that a comparison with Unicode is always an
1008 error, even if the comparison is for equality. */
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001009 rc = PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type);
1010 if (!rc)
1011 rc = PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type);
1012 if (rc < 0)
1013 return NULL;
1014 if (rc) {
Victor Stinnerda7933e2020-04-13 03:04:28 +02001015 if (_Py_GetConfig()->bytes_warning && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001016 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +00001017 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001018 return NULL;
1019 }
1020
Brian Curtindfc80e32011-08-10 20:28:54 -05001021 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001022 }
1023
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001024 if (PyObject_GetBuffer(self, &self_bytes, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001025 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05001026 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001027 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001028 self_size = self_bytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001029
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001030 if (PyObject_GetBuffer(other, &other_bytes, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001031 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +00001032 PyBuffer_Release(&self_bytes);
Brian Curtindfc80e32011-08-10 20:28:54 -05001033 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001034 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001035 other_size = other_bytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001036
1037 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
1038 /* Shortcut: if the lengths differ, the objects differ */
stratakise8b19652017-11-02 11:32:54 +01001039 PyBuffer_Release(&self_bytes);
1040 PyBuffer_Release(&other_bytes);
1041 return PyBool_FromLong((op == Py_NE));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001042 }
1043 else {
stratakise8b19652017-11-02 11:32:54 +01001044 cmp = memcmp(self_bytes.buf, other_bytes.buf,
1045 Py_MIN(self_size, other_size));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001046 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
1047
stratakise8b19652017-11-02 11:32:54 +01001048 PyBuffer_Release(&self_bytes);
1049 PyBuffer_Release(&other_bytes);
1050
1051 if (cmp != 0) {
1052 Py_RETURN_RICHCOMPARE(cmp, 0, op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001053 }
1054
stratakise8b19652017-11-02 11:32:54 +01001055 Py_RETURN_RICHCOMPARE(self_size, other_size, op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001056 }
1057
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001058}
1059
1060static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001061bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001062{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001063 if (self->ob_exports > 0) {
1064 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001065 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001066 PyErr_Print();
1067 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001068 if (self->ob_bytes != 0) {
Antoine Pitrou39aba4f2011-11-12 21:15:28 +01001069 PyObject_Free(self->ob_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001070 }
1071 Py_TYPE(self)->tp_free((PyObject *)self);
1072}
1073
1074
1075/* -------------------------------------------------------------------- */
1076/* Methods */
1077
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001078#define FASTSEARCH fastsearch
1079#define STRINGLIB(F) stringlib_##F
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001080#define STRINGLIB_CHAR char
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001081#define STRINGLIB_SIZEOF_CHAR 1
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001082#define STRINGLIB_LEN PyByteArray_GET_SIZE
1083#define STRINGLIB_STR PyByteArray_AS_STRING
1084#define STRINGLIB_NEW PyByteArray_FromStringAndSize
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001085#define STRINGLIB_ISSPACE Py_ISSPACE
1086#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001087#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1088#define STRINGLIB_MUTABLE 1
1089
1090#include "stringlib/fastsearch.h"
1091#include "stringlib/count.h"
1092#include "stringlib/find.h"
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001093#include "stringlib/join.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001094#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001095#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001096#include "stringlib/ctype.h"
1097#include "stringlib/transmogrify.h"
1098
1099
Serhiy Storchakae09132f2016-07-03 13:57:48 +03001100static PyObject *
1101bytearray_find(PyByteArrayObject *self, PyObject *args)
1102{
1103 return _Py_bytes_find(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1104}
1105
1106static PyObject *
1107bytearray_count(PyByteArrayObject *self, PyObject *args)
1108{
1109 return _Py_bytes_count(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1110}
1111
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001112/*[clinic input]
1113bytearray.clear
1114
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001115Remove all items from the bytearray.
1116[clinic start generated code]*/
1117
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001118static PyObject *
1119bytearray_clear_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001120/*[clinic end generated code: output=85c2fe6aede0956c input=ed6edae9de447ac4]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001121{
1122 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
1123 return NULL;
1124 Py_RETURN_NONE;
1125}
1126
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001127/*[clinic input]
1128bytearray.copy
1129
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001130Return a copy of B.
1131[clinic start generated code]*/
1132
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001133static PyObject *
1134bytearray_copy_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001135/*[clinic end generated code: output=68cfbcfed484c132 input=6597b0c01bccaa9e]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001136{
1137 return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
1138 PyByteArray_GET_SIZE(self));
1139}
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001140
Serhiy Storchakae09132f2016-07-03 13:57:48 +03001141static PyObject *
1142bytearray_index(PyByteArrayObject *self, PyObject *args)
1143{
1144 return _Py_bytes_index(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1145}
1146
1147static PyObject *
1148bytearray_rfind(PyByteArrayObject *self, PyObject *args)
1149{
1150 return _Py_bytes_rfind(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1151}
1152
1153static PyObject *
1154bytearray_rindex(PyByteArrayObject *self, PyObject *args)
1155{
1156 return _Py_bytes_rindex(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1157}
1158
1159static int
1160bytearray_contains(PyObject *self, PyObject *arg)
1161{
1162 return _Py_bytes_contains(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), arg);
1163}
1164
1165static PyObject *
1166bytearray_startswith(PyByteArrayObject *self, PyObject *args)
1167{
1168 return _Py_bytes_startswith(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1169}
1170
1171static PyObject *
1172bytearray_endswith(PyByteArrayObject *self, PyObject *args)
1173{
1174 return _Py_bytes_endswith(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1175}
1176
sweeneydea81849b2020-04-22 17:05:48 -04001177/*[clinic input]
1178bytearray.removeprefix as bytearray_removeprefix
1179
1180 prefix: Py_buffer
1181 /
1182
1183Return a bytearray with the given prefix string removed if present.
1184
1185If the bytearray starts with the prefix string, return
1186bytearray[len(prefix):]. Otherwise, return a copy of the original
1187bytearray.
1188[clinic start generated code]*/
1189
1190static PyObject *
1191bytearray_removeprefix_impl(PyByteArrayObject *self, Py_buffer *prefix)
1192/*[clinic end generated code: output=6cabc585e7f502e0 input=968aada38aedd262]*/
1193{
1194 const char *self_start = PyByteArray_AS_STRING(self);
1195 Py_ssize_t self_len = PyByteArray_GET_SIZE(self);
1196 const char *prefix_start = prefix->buf;
1197 Py_ssize_t prefix_len = prefix->len;
1198
1199 if (self_len >= prefix_len
1200 && memcmp(self_start, prefix_start, prefix_len) == 0)
1201 {
1202 return PyByteArray_FromStringAndSize(self_start + prefix_len,
1203 self_len - prefix_len);
1204 }
1205
1206 return PyByteArray_FromStringAndSize(self_start, self_len);
1207}
1208
1209/*[clinic input]
1210bytearray.removesuffix as bytearray_removesuffix
1211
1212 suffix: Py_buffer
1213 /
1214
1215Return a bytearray with the given suffix string removed if present.
1216
1217If the bytearray ends with the suffix string and that suffix is not
1218empty, return bytearray[:-len(suffix)]. Otherwise, return a copy of
1219the original bytearray.
1220[clinic start generated code]*/
1221
1222static PyObject *
1223bytearray_removesuffix_impl(PyByteArrayObject *self, Py_buffer *suffix)
1224/*[clinic end generated code: output=2bc8cfb79de793d3 input=c1827e810b2f6b99]*/
1225{
1226 const char *self_start = PyByteArray_AS_STRING(self);
1227 Py_ssize_t self_len = PyByteArray_GET_SIZE(self);
1228 const char *suffix_start = suffix->buf;
1229 Py_ssize_t suffix_len = suffix->len;
1230
1231 if (self_len >= suffix_len
1232 && memcmp(self_start + self_len - suffix_len,
1233 suffix_start, suffix_len) == 0)
1234 {
1235 return PyByteArray_FromStringAndSize(self_start,
1236 self_len - suffix_len);
1237 }
1238
1239 return PyByteArray_FromStringAndSize(self_start, self_len);
1240}
1241
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001242
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001243/*[clinic input]
1244bytearray.translate
1245
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001246 table: object
1247 Translation table, which must be a bytes object of length 256.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001248 /
Martin Panter1b6c6da2016-08-27 08:35:02 +00001249 delete as deletechars: object(c_default="NULL") = b''
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001250
1251Return a copy with each character mapped by the given translation table.
1252
Martin Panter1b6c6da2016-08-27 08:35:02 +00001253All characters occurring in the optional argument delete are removed.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001254The remaining characters are mapped through the given translation table.
1255[clinic start generated code]*/
1256
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001257static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001258bytearray_translate_impl(PyByteArrayObject *self, PyObject *table,
Martin Panter1b6c6da2016-08-27 08:35:02 +00001259 PyObject *deletechars)
1260/*[clinic end generated code: output=b6a8f01c2a74e446 input=cfff956d4d127a9b]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001261{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001262 char *input, *output;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001263 const char *table_chars;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001264 Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001265 PyObject *input_obj = (PyObject*)self;
1266 const char *output_start;
1267 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001268 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001269 int trans_table[256];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001270 Py_buffer vtable, vdel;
1271
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001272 if (table == Py_None) {
1273 table_chars = NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001274 table = NULL;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001275 } else if (PyObject_GetBuffer(table, &vtable, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001276 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001277 } else {
1278 if (vtable.len != 256) {
1279 PyErr_SetString(PyExc_ValueError,
1280 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001281 PyBuffer_Release(&vtable);
1282 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001283 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001284 table_chars = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001285 }
1286
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001287 if (deletechars != NULL) {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001288 if (PyObject_GetBuffer(deletechars, &vdel, PyBUF_SIMPLE) != 0) {
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001289 if (table != NULL)
Georg Brandl953152f2009-07-22 12:03:59 +00001290 PyBuffer_Release(&vtable);
1291 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001292 }
1293 }
1294 else {
1295 vdel.buf = NULL;
1296 vdel.len = 0;
1297 }
1298
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001299 inlen = PyByteArray_GET_SIZE(input_obj);
1300 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1301 if (result == NULL)
1302 goto done;
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03001303 output_start = output = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001304 input = PyByteArray_AS_STRING(input_obj);
1305
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001306 if (vdel.len == 0 && table_chars != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001307 /* If no deletions are required, use faster code */
1308 for (i = inlen; --i >= 0; ) {
1309 c = Py_CHARMASK(*input++);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001310 *output++ = table_chars[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001311 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001312 goto done;
1313 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001314
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001315 if (table_chars == NULL) {
Georg Brandlccc47b62008-12-28 11:44:14 +00001316 for (i = 0; i < 256; i++)
1317 trans_table[i] = Py_CHARMASK(i);
1318 } else {
1319 for (i = 0; i < 256; i++)
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001320 trans_table[i] = Py_CHARMASK(table_chars[i]);
Georg Brandlccc47b62008-12-28 11:44:14 +00001321 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001322
1323 for (i = 0; i < vdel.len; i++)
1324 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1325
1326 for (i = inlen; --i >= 0; ) {
1327 c = Py_CHARMASK(*input++);
1328 if (trans_table[c] != -1)
Martin Panter1b6c6da2016-08-27 08:35:02 +00001329 *output++ = (char)trans_table[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001330 }
1331 /* Fix the size of the resulting string */
1332 if (inlen > 0)
Christian Heimesc731bbe2013-07-21 02:04:35 +02001333 if (PyByteArray_Resize(result, output - output_start) < 0) {
1334 Py_CLEAR(result);
1335 goto done;
1336 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001337
1338done:
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001339 if (table != NULL)
Georg Brandlccc47b62008-12-28 11:44:14 +00001340 PyBuffer_Release(&vtable);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001341 if (deletechars != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001342 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001343 return result;
1344}
1345
1346
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001347/*[clinic input]
1348
1349@staticmethod
1350bytearray.maketrans
1351
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001352 frm: Py_buffer
1353 to: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001354 /
1355
1356Return a translation table useable for the bytes or bytearray translate method.
1357
1358The returned table will be one where each byte in frm is mapped to the byte at
1359the same position in to.
1360
1361The bytes objects frm and to must be of the same length.
1362[clinic start generated code]*/
1363
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001364static PyObject *
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001365bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001366/*[clinic end generated code: output=1df267d99f56b15e input=5925a81d2fbbf151]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001367{
1368 return _Py_bytes_maketrans(frm, to);
Georg Brandlabc38772009-04-12 15:51:51 +00001369}
1370
1371
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001372/*[clinic input]
1373bytearray.replace
1374
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001375 old: Py_buffer
1376 new: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001377 count: Py_ssize_t = -1
1378 Maximum number of occurrences to replace.
1379 -1 (the default value) means replace all occurrences.
1380 /
1381
1382Return a copy with all occurrences of substring old replaced by new.
1383
1384If the optional argument count is given, only the first count occurrences are
1385replaced.
1386[clinic start generated code]*/
1387
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001388static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001389bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old,
1390 Py_buffer *new, Py_ssize_t count)
1391/*[clinic end generated code: output=d39884c4dc59412a input=aa379d988637c7fb]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001392{
Serhiy Storchakafb81d3c2016-05-05 09:26:07 +03001393 return stringlib_replace((PyObject *)self,
Serhiy Storchakae09132f2016-07-03 13:57:48 +03001394 (const char *)old->buf, old->len,
1395 (const char *)new->buf, new->len, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001396}
1397
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001398/*[clinic input]
1399bytearray.split
1400
1401 sep: object = None
1402 The delimiter according which to split the bytearray.
1403 None (the default value) means split on ASCII whitespace characters
1404 (space, tab, return, newline, formfeed, vertical tab).
1405 maxsplit: Py_ssize_t = -1
1406 Maximum number of splits to do.
1407 -1 (the default value) means no limit.
1408
1409Return a list of the sections in the bytearray, using sep as the delimiter.
1410[clinic start generated code]*/
1411
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001412static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001413bytearray_split_impl(PyByteArrayObject *self, PyObject *sep,
1414 Py_ssize_t maxsplit)
1415/*[clinic end generated code: output=833e2cf385d9a04d input=24f82669f41bf523]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001416{
1417 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001418 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001419 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001420 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001421
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001422 if (maxsplit < 0)
1423 maxsplit = PY_SSIZE_T_MAX;
1424
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001425 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001426 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001427
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001428 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001429 return NULL;
1430 sub = vsub.buf;
1431 n = vsub.len;
1432
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001433 list = stringlib_split(
1434 (PyObject*) self, s, len, sub, n, maxsplit
1435 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001436 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001437 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001438}
1439
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001440/*[clinic input]
1441bytearray.partition
1442
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001443 sep: object
1444 /
1445
1446Partition the bytearray into three parts using the given separator.
1447
1448This will search for the separator sep in the bytearray. If the separator is
1449found, returns a 3-tuple containing the part before the separator, the
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001450separator itself, and the part after it as new bytearray objects.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001451
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001452If the separator is not found, returns a 3-tuple containing the copy of the
1453original bytearray object and two empty bytearray objects.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001454[clinic start generated code]*/
1455
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001456static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001457bytearray_partition(PyByteArrayObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001458/*[clinic end generated code: output=45d2525ddd35f957 input=8f644749ee4fc83a]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001459{
1460 PyObject *bytesep, *result;
1461
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001462 bytesep = _PyByteArray_FromBufferObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001463 if (! bytesep)
1464 return NULL;
1465
1466 result = stringlib_partition(
1467 (PyObject*) self,
1468 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1469 bytesep,
1470 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
1471 );
1472
1473 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001474 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001475}
1476
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001477/*[clinic input]
1478bytearray.rpartition
1479
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001480 sep: object
1481 /
1482
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001483Partition the bytearray into three parts using the given separator.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001484
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001485This will search for the separator sep in the bytearray, starting at the end.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001486If the separator is found, returns a 3-tuple containing the part before the
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001487separator, the separator itself, and the part after it as new bytearray
1488objects.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001489
1490If the separator is not found, returns a 3-tuple containing two empty bytearray
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001491objects and the copy of the original bytearray object.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001492[clinic start generated code]*/
1493
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001494static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001495bytearray_rpartition(PyByteArrayObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001496/*[clinic end generated code: output=440de3c9426115e8 input=7e3df3e6cb8fa0ac]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001497{
1498 PyObject *bytesep, *result;
1499
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001500 bytesep = _PyByteArray_FromBufferObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001501 if (! bytesep)
1502 return NULL;
1503
1504 result = stringlib_rpartition(
1505 (PyObject*) self,
1506 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1507 bytesep,
1508 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
1509 );
1510
1511 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001512 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001513}
1514
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001515/*[clinic input]
1516bytearray.rsplit = bytearray.split
1517
1518Return a list of the sections in the bytearray, using sep as the delimiter.
1519
1520Splitting is done starting at the end of the bytearray and working to the front.
1521[clinic start generated code]*/
1522
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001523static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001524bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep,
1525 Py_ssize_t maxsplit)
1526/*[clinic end generated code: output=a55e0b5a03cb6190 input=a68286e4dd692ffe]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001527{
1528 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001529 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001530 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001531 Py_buffer vsub;
1532
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001533 if (maxsplit < 0)
1534 maxsplit = PY_SSIZE_T_MAX;
1535
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001536 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001537 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001538
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001539 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001540 return NULL;
1541 sub = vsub.buf;
1542 n = vsub.len;
1543
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001544 list = stringlib_rsplit(
1545 (PyObject*) self, s, len, sub, n, maxsplit
1546 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001547 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001548 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001549}
1550
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001551/*[clinic input]
1552bytearray.reverse
1553
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001554Reverse the order of the values in B in place.
1555[clinic start generated code]*/
1556
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001557static PyObject *
1558bytearray_reverse_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001559/*[clinic end generated code: output=9f7616f29ab309d3 input=543356319fc78557]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001560{
1561 char swap, *head, *tail;
1562 Py_ssize_t i, j, n = Py_SIZE(self);
1563
1564 j = n / 2;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001565 head = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001566 tail = head + n - 1;
1567 for (i = 0; i < j; i++) {
1568 swap = *head;
1569 *head++ = *tail;
1570 *tail-- = swap;
1571 }
1572
1573 Py_RETURN_NONE;
1574}
1575
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001576
1577/*[python input]
1578class bytesvalue_converter(CConverter):
1579 type = 'int'
1580 converter = '_getbytevalue'
1581[python start generated code]*/
1582/*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/
1583
1584
1585/*[clinic input]
1586bytearray.insert
1587
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001588 index: Py_ssize_t
1589 The index where the value is to be inserted.
1590 item: bytesvalue
1591 The item to be inserted.
1592 /
1593
1594Insert a single item into the bytearray before the given index.
1595[clinic start generated code]*/
1596
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001597static PyObject *
1598bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001599/*[clinic end generated code: output=76c775a70e7b07b7 input=b2b5d07e9de6c070]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001600{
1601 Py_ssize_t n = Py_SIZE(self);
1602 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001603
1604 if (n == PY_SSIZE_T_MAX) {
1605 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00001606 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001607 return NULL;
1608 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001609 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
1610 return NULL;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001611 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001612
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001613 if (index < 0) {
1614 index += n;
1615 if (index < 0)
1616 index = 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001617 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001618 if (index > n)
1619 index = n;
1620 memmove(buf + index + 1, buf + index, n - index);
1621 buf[index] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001622
1623 Py_RETURN_NONE;
1624}
1625
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001626/*[clinic input]
1627bytearray.append
1628
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001629 item: bytesvalue
1630 The item to be appended.
1631 /
1632
1633Append a single item to the end of the bytearray.
1634[clinic start generated code]*/
1635
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001636static PyObject *
1637bytearray_append_impl(PyByteArrayObject *self, int item)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001638/*[clinic end generated code: output=a154e19ed1886cb6 input=20d6bec3d1340593]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001639{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001640 Py_ssize_t n = Py_SIZE(self);
1641
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001642 if (n == PY_SSIZE_T_MAX) {
1643 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00001644 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001645 return NULL;
1646 }
1647 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
1648 return NULL;
1649
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001650 PyByteArray_AS_STRING(self)[n] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001651
1652 Py_RETURN_NONE;
1653}
1654
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001655/*[clinic input]
1656bytearray.extend
1657
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001658 iterable_of_ints: object
1659 The iterable of items to append.
1660 /
1661
1662Append all the items from the iterator or sequence to the end of the bytearray.
1663[clinic start generated code]*/
1664
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001665static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001666bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001667/*[clinic end generated code: output=98155dbe249170b1 input=c617b3a93249ba28]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001668{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001669 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001670 Py_ssize_t buf_size = 0, len = 0;
1671 int value;
1672 char *buf;
1673
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001674 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001675 if (PyObject_CheckBuffer(iterable_of_ints)) {
1676 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001677 return NULL;
1678
1679 Py_RETURN_NONE;
1680 }
1681
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001682 it = PyObject_GetIter(iterable_of_ints);
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +03001683 if (it == NULL) {
1684 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
1685 PyErr_Format(PyExc_TypeError,
1686 "can't extend bytearray with %.100s",
Victor Stinner58ac7002020-02-07 03:04:21 +01001687 Py_TYPE(iterable_of_ints)->tp_name);
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +03001688 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001689 return NULL;
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +03001690 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001691
Ezio Melotti42da6632011-03-15 05:18:48 +02001692 /* Try to determine the length of the argument. 32 is arbitrary. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001693 buf_size = PyObject_LengthHint(iterable_of_ints, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001694 if (buf_size == -1) {
1695 Py_DECREF(it);
1696 return NULL;
1697 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001698
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001699 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02001700 if (bytearray_obj == NULL) {
1701 Py_DECREF(it);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001702 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02001703 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001704 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001705
1706 while ((item = PyIter_Next(it)) != NULL) {
1707 if (! _getbytevalue(item, &value)) {
1708 Py_DECREF(item);
1709 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001710 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001711 return NULL;
1712 }
1713 buf[len++] = value;
1714 Py_DECREF(item);
1715
1716 if (len >= buf_size) {
Martin Panter371731e2016-07-18 07:53:13 +00001717 Py_ssize_t addition;
1718 if (len == PY_SSIZE_T_MAX) {
1719 Py_DECREF(it);
1720 Py_DECREF(bytearray_obj);
1721 return PyErr_NoMemory();
1722 }
1723 addition = len >> 1;
1724 if (addition > PY_SSIZE_T_MAX - len - 1)
1725 buf_size = PY_SSIZE_T_MAX;
1726 else
1727 buf_size = len + addition + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001728 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001729 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001730 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001731 return NULL;
1732 }
1733 /* Recompute the `buf' pointer, since the resizing operation may
1734 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001735 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001736 }
1737 }
1738 Py_DECREF(it);
1739
1740 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001741 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
1742 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001743 return NULL;
1744 }
1745
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02001746 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
1747 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001748 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02001749 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001750 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001751
Brandt Bucher2a7d5962019-06-26 12:06:18 -07001752 if (PyErr_Occurred()) {
1753 return NULL;
1754 }
1755
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001756 Py_RETURN_NONE;
1757}
1758
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001759/*[clinic input]
1760bytearray.pop
1761
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001762 index: Py_ssize_t = -1
1763 The index from where to remove the item.
1764 -1 (the default value) means remove the last item.
1765 /
1766
1767Remove and return a single item from B.
1768
1769If no index argument is given, will pop the last item.
1770[clinic start generated code]*/
1771
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001772static PyObject *
1773bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001774/*[clinic end generated code: output=e0ccd401f8021da8 input=3591df2d06c0d237]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001775{
1776 int value;
1777 Py_ssize_t n = Py_SIZE(self);
1778 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001779
1780 if (n == 0) {
Eli Bendersky1bc4f192011-03-04 04:55:25 +00001781 PyErr_SetString(PyExc_IndexError,
1782 "pop from empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001783 return NULL;
1784 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001785 if (index < 0)
1786 index += Py_SIZE(self);
1787 if (index < 0 || index >= Py_SIZE(self)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001788 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1789 return NULL;
1790 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00001791 if (!_canresize(self))
1792 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001793
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001794 buf = PyByteArray_AS_STRING(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001795 value = buf[index];
1796 memmove(buf + index, buf + index + 1, n - index);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001797 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
1798 return NULL;
1799
Mark Dickinson54a3db92009-09-06 10:19:23 +00001800 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001801}
1802
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001803/*[clinic input]
1804bytearray.remove
1805
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001806 value: bytesvalue
1807 The value to remove.
1808 /
1809
1810Remove the first occurrence of a value in the bytearray.
1811[clinic start generated code]*/
1812
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001813static PyObject *
1814bytearray_remove_impl(PyByteArrayObject *self, int value)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001815/*[clinic end generated code: output=d659e37866709c13 input=121831240cd51ddf]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001816{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001817 Py_ssize_t where, n = Py_SIZE(self);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001818 char *buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001819
Serhiy Storchaka4b234942016-05-16 22:24:03 +03001820 where = stringlib_find_char(buf, n, value);
1821 if (where < 0) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00001822 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001823 return NULL;
1824 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00001825 if (!_canresize(self))
1826 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001827
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001828 memmove(buf + where, buf + where + 1, n - where);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001829 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
1830 return NULL;
1831
1832 Py_RETURN_NONE;
1833}
1834
1835/* XXX These two helpers could be optimized if argsize == 1 */
1836
1837static Py_ssize_t
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001838lstrip_helper(const char *myptr, Py_ssize_t mysize,
1839 const void *argptr, Py_ssize_t argsize)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001840{
1841 Py_ssize_t i = 0;
Antoine Pitrou5b720752013-10-05 21:24:10 +02001842 while (i < mysize && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001843 i++;
1844 return i;
1845}
1846
1847static Py_ssize_t
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001848rstrip_helper(const char *myptr, Py_ssize_t mysize,
1849 const void *argptr, Py_ssize_t argsize)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001850{
1851 Py_ssize_t i = mysize - 1;
Antoine Pitrou5b720752013-10-05 21:24:10 +02001852 while (i >= 0 && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001853 i--;
1854 return i + 1;
1855}
1856
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001857/*[clinic input]
1858bytearray.strip
1859
1860 bytes: object = None
1861 /
1862
1863Strip leading and trailing bytes contained in the argument.
1864
1865If the argument is omitted or None, strip leading and trailing ASCII whitespace.
1866[clinic start generated code]*/
1867
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001868static PyObject *
1869bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001870/*[clinic end generated code: output=760412661a34ad5a input=ef7bb59b09c21d62]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001871{
1872 Py_ssize_t left, right, mysize, byteslen;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001873 char *myptr;
1874 const char *bytesptr;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001875 Py_buffer vbytes;
1876
1877 if (bytes == Py_None) {
1878 bytesptr = "\t\n\r\f\v ";
1879 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001880 }
1881 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001882 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001883 return NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001884 bytesptr = (const char *) vbytes.buf;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001885 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001886 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001887 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001888 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001889 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001890 if (left == mysize)
1891 right = left;
1892 else
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001893 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
1894 if (bytes != Py_None)
1895 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001896 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001897}
1898
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001899/*[clinic input]
1900bytearray.lstrip
1901
1902 bytes: object = None
1903 /
1904
1905Strip leading bytes contained in the argument.
1906
1907If the argument is omitted or None, strip leading ASCII whitespace.
1908[clinic start generated code]*/
1909
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001910static PyObject *
1911bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001912/*[clinic end generated code: output=d005c9d0ab909e66 input=80843f975dd7c480]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001913{
1914 Py_ssize_t left, right, mysize, byteslen;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001915 char *myptr;
1916 const char *bytesptr;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001917 Py_buffer vbytes;
1918
1919 if (bytes == Py_None) {
1920 bytesptr = "\t\n\r\f\v ";
1921 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001922 }
1923 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001924 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001925 return NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001926 bytesptr = (const char *) vbytes.buf;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001927 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001928 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001929 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001930 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001931 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001932 right = mysize;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001933 if (bytes != Py_None)
1934 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001935 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001936}
1937
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001938/*[clinic input]
1939bytearray.rstrip
1940
1941 bytes: object = None
1942 /
1943
1944Strip trailing bytes contained in the argument.
1945
1946If the argument is omitted or None, strip trailing ASCII whitespace.
1947[clinic start generated code]*/
1948
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001949static PyObject *
1950bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001951/*[clinic end generated code: output=030e2fbd2f7276bd input=e728b994954cfd91]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001952{
1953 Py_ssize_t right, mysize, byteslen;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001954 char *myptr;
1955 const char *bytesptr;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001956 Py_buffer vbytes;
1957
1958 if (bytes == Py_None) {
1959 bytesptr = "\t\n\r\f\v ";
1960 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001961 }
1962 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001963 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001964 return NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001965 bytesptr = (const char *) vbytes.buf;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001966 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001967 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001968 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001969 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001970 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
1971 if (bytes != Py_None)
1972 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001973 return PyByteArray_FromStringAndSize(myptr, right);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001974}
1975
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001976/*[clinic input]
1977bytearray.decode
1978
1979 encoding: str(c_default="NULL") = 'utf-8'
1980 The encoding with which to decode the bytearray.
1981 errors: str(c_default="NULL") = 'strict'
1982 The error handling scheme to use for the handling of decoding errors.
1983 The default is 'strict' meaning that decoding errors raise a
1984 UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
1985 as well as any other name registered with codecs.register_error that
1986 can handle UnicodeDecodeErrors.
1987
1988Decode the bytearray using the codec registered for encoding.
1989[clinic start generated code]*/
1990
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001991static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001992bytearray_decode_impl(PyByteArrayObject *self, const char *encoding,
1993 const char *errors)
1994/*[clinic end generated code: output=f57d43f4a00b42c5 input=f28d8f903020257b]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001995{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001996 if (encoding == NULL)
1997 encoding = PyUnicode_GetDefaultEncoding();
Martin v. Löwis0efea322014-07-27 17:29:17 +02001998 return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001999}
2000
2001PyDoc_STRVAR(alloc_doc,
2002"B.__alloc__() -> int\n\
2003\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002004Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002005
2006static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302007bytearray_alloc(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002008{
2009 return PyLong_FromSsize_t(self->ob_alloc);
2010}
2011
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002012/*[clinic input]
2013bytearray.join
2014
2015 iterable_of_bytes: object
2016 /
2017
2018Concatenate any number of bytes/bytearray objects.
2019
2020The bytearray whose method is called is inserted in between each pair.
2021
2022The result is returned as a new bytearray object.
2023[clinic start generated code]*/
2024
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002025static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002026bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002027/*[clinic end generated code: output=a8516370bf68ae08 input=aba6b1f9b30fcb8e]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002028{
Martin v. Löwis0efea322014-07-27 17:29:17 +02002029 return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002030}
2031
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002032/*[clinic input]
2033bytearray.splitlines
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002034
Serhiy Storchaka202fda52017-03-12 10:10:47 +02002035 keepends: bool(accept={int}) = False
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002036
2037Return a list of the lines in the bytearray, breaking at line boundaries.
2038
2039Line breaks are not included in the resulting list unless keepends is given and
2040true.
2041[clinic start generated code]*/
2042
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002043static PyObject *
2044bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +02002045/*[clinic end generated code: output=4223c94b895f6ad9 input=99a27ad959b9cf6b]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002046{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002047 return stringlib_splitlines(
2048 (PyObject*) self, PyByteArray_AS_STRING(self),
2049 PyByteArray_GET_SIZE(self), keepends
2050 );
2051}
2052
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002053/*[clinic input]
2054@classmethod
2055bytearray.fromhex
2056
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002057 string: unicode
2058 /
2059
2060Create a bytearray object from a string of hexadecimal numbers.
2061
2062Spaces between two numbers are accepted.
2063Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
2064[clinic start generated code]*/
2065
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002066static PyObject *
Serhiy Storchaka0855e702016-07-01 17:22:31 +03002067bytearray_fromhex_impl(PyTypeObject *type, PyObject *string)
2068/*[clinic end generated code: output=8f0f0b6d30fb3ba0 input=f033a16d1fb21f48]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002069{
Serhiy Storchaka0855e702016-07-01 17:22:31 +03002070 PyObject *result = _PyBytes_FromHex(string, type == &PyByteArray_Type);
2071 if (type != &PyByteArray_Type && result != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01002072 Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
Serhiy Storchaka0855e702016-07-01 17:22:31 +03002073 }
2074 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002075}
2076
Gregory P. Smith0c2f9302019-05-29 11:46:58 -07002077/*[clinic input]
2078bytearray.hex
2079
2080 sep: object = NULL
2081 An optional single character or byte to separate hex bytes.
2082 bytes_per_sep: int = 1
2083 How many bytes between separators. Positive values count from the
2084 right, negative values count from the left.
2085
2086Create a str of hexadecimal numbers from a bytearray object.
2087
2088Example:
2089>>> value = bytearray([0xb9, 0x01, 0xef])
2090>>> value.hex()
2091'b901ef'
2092>>> value.hex(':')
2093'b9:01:ef'
2094>>> value.hex(':', 2)
2095'b9:01ef'
2096>>> value.hex(':', -2)
2097'b901:ef'
2098[clinic start generated code]*/
Gregory P. Smith8cb65692015-04-25 23:22:26 +00002099
2100static PyObject *
Gregory P. Smith0c2f9302019-05-29 11:46:58 -07002101bytearray_hex_impl(PyByteArrayObject *self, PyObject *sep, int bytes_per_sep)
2102/*[clinic end generated code: output=29c4e5ef72c565a0 input=814c15830ac8c4b5]*/
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002103{
2104 char* argbuf = PyByteArray_AS_STRING(self);
2105 Py_ssize_t arglen = PyByteArray_GET_SIZE(self);
Gregory P. Smith0c2f9302019-05-29 11:46:58 -07002106 return _Py_strhex_with_sep(argbuf, arglen, sep, bytes_per_sep);
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002107}
2108
2109static PyObject *
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002110_common_reduce(PyByteArrayObject *self, int proto)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002111{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002112 PyObject *dict;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002113 _Py_IDENTIFIER(__dict__);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002114 char *buf;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002115
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002116 if (_PyObject_LookupAttrId((PyObject *)self, &PyId___dict__, &dict) < 0) {
2117 return NULL;
2118 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002119 if (dict == NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002120 dict = Py_None;
2121 Py_INCREF(dict);
2122 }
2123
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002124 buf = PyByteArray_AS_STRING(self);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002125 if (proto < 3) {
2126 /* use str based reduction for backwards compatibility with Python 2.x */
2127 PyObject *latin1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002128 if (Py_SIZE(self))
2129 latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002130 else
2131 latin1 = PyUnicode_FromString("");
2132 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
2133 }
2134 else {
2135 /* use more efficient byte based reduction */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002136 if (Py_SIZE(self)) {
2137 return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), dict);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002138 }
2139 else {
2140 return Py_BuildValue("(O()N)", Py_TYPE(self), dict);
2141 }
2142 }
2143}
2144
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002145/*[clinic input]
2146bytearray.__reduce__ as bytearray_reduce
2147
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002148Return state information for pickling.
2149[clinic start generated code]*/
2150
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002151static PyObject *
2152bytearray_reduce_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03002153/*[clinic end generated code: output=52bf304086464cab input=44b5737ada62dd3f]*/
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002154{
2155 return _common_reduce(self, 2);
2156}
2157
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002158/*[clinic input]
2159bytearray.__reduce_ex__ as bytearray_reduce_ex
2160
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002161 proto: int = 0
2162 /
2163
2164Return state information for pickling.
2165[clinic start generated code]*/
2166
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002167static PyObject *
2168bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03002169/*[clinic end generated code: output=52eac33377197520 input=f129bc1a1aa151ee]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002170{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002171 return _common_reduce(self, proto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002172}
2173
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002174/*[clinic input]
2175bytearray.__sizeof__ as bytearray_sizeof
2176
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002177Returns the size of the bytearray object in memory, in bytes.
2178[clinic start generated code]*/
2179
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002180static PyObject *
2181bytearray_sizeof_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03002182/*[clinic end generated code: output=738abdd17951c427 input=e27320fd98a4bc5a]*/
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002183{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002184 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002185
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002186 res = _PyObject_SIZE(Py_TYPE(self)) + self->ob_alloc * sizeof(char);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002187 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002188}
2189
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002190static PySequenceMethods bytearray_as_sequence = {
2191 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002192 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002193 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
2194 (ssizeargfunc)bytearray_getitem, /* sq_item */
2195 0, /* sq_slice */
2196 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
2197 0, /* sq_ass_slice */
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002198 (objobjproc)bytearray_contains, /* sq_contains */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002199 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
2200 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002201};
2202
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002203static PyMappingMethods bytearray_as_mapping = {
2204 (lenfunc)bytearray_length,
2205 (binaryfunc)bytearray_subscript,
2206 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002207};
2208
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002209static PyBufferProcs bytearray_as_buffer = {
2210 (getbufferproc)bytearray_getbuffer,
2211 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002212};
2213
2214static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002215bytearray_methods[] = {
2216 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002217 BYTEARRAY_REDUCE_METHODDEF
2218 BYTEARRAY_REDUCE_EX_METHODDEF
2219 BYTEARRAY_SIZEOF_METHODDEF
2220 BYTEARRAY_APPEND_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302221 {"capitalize", stringlib_capitalize, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002222 _Py_capitalize__doc__},
Tal Einatc929df32018-07-06 13:17:38 +03002223 STRINGLIB_CENTER_METHODDEF
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002224 BYTEARRAY_CLEAR_METHODDEF
2225 BYTEARRAY_COPY_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002226 {"count", (PyCFunction)bytearray_count, METH_VARARGS,
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03002227 _Py_count__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002228 BYTEARRAY_DECODE_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002229 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS,
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03002230 _Py_endswith__doc__},
Tal Einatc929df32018-07-06 13:17:38 +03002231 STRINGLIB_EXPANDTABS_METHODDEF
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002232 BYTEARRAY_EXTEND_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002233 {"find", (PyCFunction)bytearray_find, METH_VARARGS,
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03002234 _Py_find__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002235 BYTEARRAY_FROMHEX_METHODDEF
Gregory P. Smith0c2f9302019-05-29 11:46:58 -07002236 BYTEARRAY_HEX_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002237 {"index", (PyCFunction)bytearray_index, METH_VARARGS, _Py_index__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002238 BYTEARRAY_INSERT_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302239 {"isalnum", stringlib_isalnum, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002240 _Py_isalnum__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302241 {"isalpha", stringlib_isalpha, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002242 _Py_isalpha__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302243 {"isascii", stringlib_isascii, METH_NOARGS,
INADA Naokia49ac992018-01-27 14:06:21 +09002244 _Py_isascii__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302245 {"isdigit", stringlib_isdigit, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002246 _Py_isdigit__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302247 {"islower", stringlib_islower, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002248 _Py_islower__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302249 {"isspace", stringlib_isspace, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002250 _Py_isspace__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302251 {"istitle", stringlib_istitle, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002252 _Py_istitle__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302253 {"isupper", stringlib_isupper, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002254 _Py_isupper__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002255 BYTEARRAY_JOIN_METHODDEF
Tal Einatc929df32018-07-06 13:17:38 +03002256 STRINGLIB_LJUST_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302257 {"lower", stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002258 BYTEARRAY_LSTRIP_METHODDEF
2259 BYTEARRAY_MAKETRANS_METHODDEF
2260 BYTEARRAY_PARTITION_METHODDEF
2261 BYTEARRAY_POP_METHODDEF
2262 BYTEARRAY_REMOVE_METHODDEF
2263 BYTEARRAY_REPLACE_METHODDEF
sweeneydea81849b2020-04-22 17:05:48 -04002264 BYTEARRAY_REMOVEPREFIX_METHODDEF
2265 BYTEARRAY_REMOVESUFFIX_METHODDEF
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002266 BYTEARRAY_REVERSE_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002267 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, _Py_rfind__doc__},
2268 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, _Py_rindex__doc__},
Tal Einatc929df32018-07-06 13:17:38 +03002269 STRINGLIB_RJUST_METHODDEF
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002270 BYTEARRAY_RPARTITION_METHODDEF
2271 BYTEARRAY_RSPLIT_METHODDEF
2272 BYTEARRAY_RSTRIP_METHODDEF
2273 BYTEARRAY_SPLIT_METHODDEF
2274 BYTEARRAY_SPLITLINES_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002275 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03002276 _Py_startswith__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002277 BYTEARRAY_STRIP_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302278 {"swapcase", stringlib_swapcase, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002279 _Py_swapcase__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302280 {"title", stringlib_title, METH_NOARGS, _Py_title__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002281 BYTEARRAY_TRANSLATE_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302282 {"upper", stringlib_upper, METH_NOARGS, _Py_upper__doc__},
Tal Einatc929df32018-07-06 13:17:38 +03002283 STRINGLIB_ZFILL_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002284 {NULL}
2285};
2286
Ethan Furmanb95b5612015-01-23 20:05:18 -08002287static PyObject *
2288bytearray_mod(PyObject *v, PyObject *w)
2289{
2290 if (!PyByteArray_Check(v))
2291 Py_RETURN_NOTIMPLEMENTED;
Berker Peksag43de36d2016-04-16 01:20:47 +03002292 return _PyBytes_FormatEx(PyByteArray_AS_STRING(v), PyByteArray_GET_SIZE(v), w, 1);
Ethan Furmanb95b5612015-01-23 20:05:18 -08002293}
2294
2295static PyNumberMethods bytearray_as_number = {
2296 0, /*nb_add*/
2297 0, /*nb_subtract*/
2298 0, /*nb_multiply*/
2299 bytearray_mod, /*nb_remainder*/
2300};
2301
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002302PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002303"bytearray(iterable_of_ints) -> bytearray\n\
2304bytearray(string, encoding[, errors]) -> bytearray\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01002305bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
2306bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
2307bytearray() -> empty bytes array\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002308\n\
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03002309Construct a mutable bytearray object from:\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002310 - an iterable yielding integers in range(256)\n\
2311 - a text string encoded using the specified encoding\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01002312 - a bytes or a buffer object\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002313 - any object implementing the buffer API.\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01002314 - an integer");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002315
2316
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002317static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002318
2319PyTypeObject PyByteArray_Type = {
2320 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2321 "bytearray",
2322 sizeof(PyByteArrayObject),
2323 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002324 (destructor)bytearray_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002325 0, /* tp_vectorcall_offset */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002326 0, /* tp_getattr */
2327 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002328 0, /* tp_as_async */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002329 (reprfunc)bytearray_repr, /* tp_repr */
Ethan Furmanb95b5612015-01-23 20:05:18 -08002330 &bytearray_as_number, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002331 &bytearray_as_sequence, /* tp_as_sequence */
2332 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002333 0, /* tp_hash */
2334 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002335 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002336 PyObject_GenericGetAttr, /* tp_getattro */
2337 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002338 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002339 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002340 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002341 0, /* tp_traverse */
2342 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002343 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002344 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002345 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002346 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002347 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002348 0, /* tp_members */
2349 0, /* tp_getset */
2350 0, /* tp_base */
2351 0, /* tp_dict */
2352 0, /* tp_descr_get */
2353 0, /* tp_descr_set */
2354 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002355 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002356 PyType_GenericAlloc, /* tp_alloc */
2357 PyType_GenericNew, /* tp_new */
2358 PyObject_Del, /* tp_free */
2359};
2360
2361/*********************** Bytes Iterator ****************************/
2362
2363typedef struct {
2364 PyObject_HEAD
2365 Py_ssize_t it_index;
2366 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
2367} bytesiterobject;
2368
2369static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002370bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002371{
2372 _PyObject_GC_UNTRACK(it);
2373 Py_XDECREF(it->it_seq);
2374 PyObject_GC_Del(it);
2375}
2376
2377static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002378bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002379{
2380 Py_VISIT(it->it_seq);
2381 return 0;
2382}
2383
2384static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002385bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002386{
2387 PyByteArrayObject *seq;
2388 PyObject *item;
2389
2390 assert(it != NULL);
2391 seq = it->it_seq;
2392 if (seq == NULL)
2393 return NULL;
2394 assert(PyByteArray_Check(seq));
2395
2396 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
2397 item = PyLong_FromLong(
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002398 (unsigned char)PyByteArray_AS_STRING(seq)[it->it_index]);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002399 if (item != NULL)
2400 ++it->it_index;
2401 return item;
2402 }
2403
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002404 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002405 Py_DECREF(seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002406 return NULL;
2407}
2408
2409static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302410bytearrayiter_length_hint(bytesiterobject *it, PyObject *Py_UNUSED(ignored))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002411{
2412 Py_ssize_t len = 0;
Serhiy Storchakaaf658722016-07-03 14:41:36 +03002413 if (it->it_seq) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002414 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
Serhiy Storchakaaf658722016-07-03 14:41:36 +03002415 if (len < 0) {
2416 len = 0;
2417 }
2418 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002419 return PyLong_FromSsize_t(len);
2420}
2421
2422PyDoc_STRVAR(length_hint_doc,
2423 "Private method returning an estimate of len(list(it)).");
2424
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002425static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302426bytearrayiter_reduce(bytesiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002427{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02002428 _Py_IDENTIFIER(iter);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002429 if (it->it_seq != NULL) {
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02002430 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002431 it->it_seq, it->it_index);
2432 } else {
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02002433 return Py_BuildValue("N(())", _PyEval_GetBuiltinId(&PyId_iter));
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002434 }
2435}
2436
2437static PyObject *
2438bytearrayiter_setstate(bytesiterobject *it, PyObject *state)
2439{
2440 Py_ssize_t index = PyLong_AsSsize_t(state);
2441 if (index == -1 && PyErr_Occurred())
2442 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00002443 if (it->it_seq != NULL) {
2444 if (index < 0)
2445 index = 0;
2446 else if (index > PyByteArray_GET_SIZE(it->it_seq))
2447 index = PyByteArray_GET_SIZE(it->it_seq); /* iterator exhausted */
2448 it->it_index = index;
2449 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002450 Py_RETURN_NONE;
2451}
2452
2453PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2454
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002455static PyMethodDef bytearrayiter_methods[] = {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002456 {"__length_hint__", (PyCFunction)bytearrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002457 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002458 {"__reduce__", (PyCFunction)bytearrayiter_reduce, METH_NOARGS,
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002459 bytearray_reduce__doc__},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002460 {"__setstate__", (PyCFunction)bytearrayiter_setstate, METH_O,
2461 setstate_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002462 {NULL, NULL} /* sentinel */
2463};
2464
2465PyTypeObject PyByteArrayIter_Type = {
2466 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2467 "bytearray_iterator", /* tp_name */
2468 sizeof(bytesiterobject), /* tp_basicsize */
2469 0, /* tp_itemsize */
2470 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002471 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002472 0, /* tp_vectorcall_offset */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002473 0, /* tp_getattr */
2474 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002475 0, /* tp_as_async */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002476 0, /* tp_repr */
2477 0, /* tp_as_number */
2478 0, /* tp_as_sequence */
2479 0, /* tp_as_mapping */
2480 0, /* tp_hash */
2481 0, /* tp_call */
2482 0, /* tp_str */
2483 PyObject_GenericGetAttr, /* tp_getattro */
2484 0, /* tp_setattro */
2485 0, /* tp_as_buffer */
2486 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2487 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002488 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002489 0, /* tp_clear */
2490 0, /* tp_richcompare */
2491 0, /* tp_weaklistoffset */
2492 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002493 (iternextfunc)bytearrayiter_next, /* tp_iternext */
2494 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002495 0,
2496};
2497
2498static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002499bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002500{
2501 bytesiterobject *it;
2502
2503 if (!PyByteArray_Check(seq)) {
2504 PyErr_BadInternalCall();
2505 return NULL;
2506 }
2507 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
2508 if (it == NULL)
2509 return NULL;
2510 it->it_index = 0;
2511 Py_INCREF(seq);
2512 it->it_seq = (PyByteArrayObject *)seq;
2513 _PyObject_GC_TRACK(it);
2514 return (PyObject *)it;
2515}