blob: 8d5ba540120f4bc6655c9e233d51b95bd9184554 [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 Stinnerbcda8f12018-11-21 22:27:47 +01005#include "pycore_object.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01006#include "pycore_pymem.h"
7#include "pycore_pystate.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00008#include "structmember.h"
9#include "bytes_methods.h"
Ethan Furmanb95b5612015-01-23 20:05:18 -080010#include "bytesobject.h"
Gregory P. Smith8cb65692015-04-25 23:22:26 +000011#include "pystrhex.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +000012
Martin v. Löwis7252a6e2014-07-27 16:25:09 +020013/*[clinic input]
14class bytearray "PyByteArrayObject *" "&PyByteArray_Type"
15[clinic start generated code]*/
16/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5535b77c37a119e0]*/
17
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000018char _PyByteArray_empty_string[] = "";
Christian Heimes2c9c7a52008-05-26 13:42:13 +000019
Christian Heimes2c9c7a52008-05-26 13:42:13 +000020/* end nullbytes support */
21
22/* Helpers */
23
24static int
25_getbytevalue(PyObject* arg, int *value)
26{
27 long face_value;
28
29 if (PyLong_Check(arg)) {
30 face_value = PyLong_AsLong(arg);
Georg Brandl9a54d7c2008-07-16 23:15:30 +000031 } else {
32 PyObject *index = PyNumber_Index(arg);
33 if (index == NULL) {
Mark Dickinson10de93a2010-07-09 19:25:48 +000034 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000035 return 0;
36 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +000037 face_value = PyLong_AsLong(index);
38 Py_DECREF(index);
39 }
40
41 if (face_value < 0 || face_value >= 256) {
42 /* this includes the OverflowError in case the long is too large */
43 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
Mark Dickinson10de93a2010-07-09 19:25:48 +000044 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000045 return 0;
46 }
47
48 *value = face_value;
49 return 1;
50}
51
52static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +000053bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000054{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000055 void *ptr;
56 if (view == NULL) {
Stefan Krah5178d912015-02-03 16:57:21 +010057 PyErr_SetString(PyExc_BufferError,
58 "bytearray_getbuffer: view==NULL argument is obsolete");
59 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000060 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000061 ptr = (void *) PyByteArray_AS_STRING(obj);
Stefan Krah5178d912015-02-03 16:57:21 +010062 /* cannot fail if view != NULL and readonly == 0 */
63 (void)PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
64 obj->ob_exports++;
65 return 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000066}
67
68static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +000069bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000070{
71 obj->ob_exports--;
72}
73
Antoine Pitrou5504e892008-12-06 21:27:53 +000074static int
75_canresize(PyByteArrayObject *self)
76{
77 if (self->ob_exports > 0) {
78 PyErr_SetString(PyExc_BufferError,
79 "Existing exports of data: object cannot be re-sized");
80 return 0;
81 }
82 return 1;
83}
84
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030085#include "clinic/bytearrayobject.c.h"
86
Christian Heimes2c9c7a52008-05-26 13:42:13 +000087/* Direct API functions */
88
89PyObject *
90PyByteArray_FromObject(PyObject *input)
91{
Victor Stinnerde4ae3d2016-12-04 22:59:09 +010092 return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
93 input, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +000094}
95
Serhiy Storchakaa2314282017-10-29 02:11:54 +030096static PyObject *
97_PyByteArray_FromBufferObject(PyObject *obj)
98{
99 PyObject *result;
100 Py_buffer view;
101
102 if (PyObject_GetBuffer(obj, &view, PyBUF_FULL_RO) < 0) {
103 return NULL;
104 }
105 result = PyByteArray_FromStringAndSize(NULL, view.len);
106 if (result != NULL &&
107 PyBuffer_ToContiguous(PyByteArray_AS_STRING(result),
108 &view, view.len, 'C') < 0)
109 {
110 Py_CLEAR(result);
111 }
112 PyBuffer_Release(&view);
113 return result;
114}
115
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000116PyObject *
117PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
118{
119 PyByteArrayObject *new;
120 Py_ssize_t alloc;
121
122 if (size < 0) {
123 PyErr_SetString(PyExc_SystemError,
124 "Negative size passed to PyByteArray_FromStringAndSize");
125 return NULL;
126 }
127
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000128 /* Prevent buffer overflow when setting alloc to size+1. */
129 if (size == PY_SSIZE_T_MAX) {
130 return PyErr_NoMemory();
131 }
132
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000133 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
134 if (new == NULL)
135 return NULL;
136
137 if (size == 0) {
138 new->ob_bytes = NULL;
139 alloc = 0;
140 }
141 else {
142 alloc = size + 1;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100143 new->ob_bytes = PyObject_Malloc(alloc);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000144 if (new->ob_bytes == NULL) {
145 Py_DECREF(new);
146 return PyErr_NoMemory();
147 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +0000148 if (bytes != NULL && size > 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000149 memcpy(new->ob_bytes, bytes, size);
150 new->ob_bytes[size] = '\0'; /* Trailing null byte */
151 }
152 Py_SIZE(new) = size;
153 new->ob_alloc = alloc;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200154 new->ob_start = new->ob_bytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000155 new->ob_exports = 0;
156
157 return (PyObject *)new;
158}
159
160Py_ssize_t
161PyByteArray_Size(PyObject *self)
162{
163 assert(self != NULL);
164 assert(PyByteArray_Check(self));
165
166 return PyByteArray_GET_SIZE(self);
167}
168
169char *
170PyByteArray_AsString(PyObject *self)
171{
172 assert(self != NULL);
173 assert(PyByteArray_Check(self));
174
175 return PyByteArray_AS_STRING(self);
176}
177
178int
Antoine Pitroucc231542014-11-02 18:40:09 +0100179PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000180{
181 void *sval;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200182 PyByteArrayObject *obj = ((PyByteArrayObject *)self);
Antoine Pitroucc231542014-11-02 18:40:09 +0100183 /* All computations are done unsigned to avoid integer overflows
184 (see issue #22335). */
185 size_t alloc = (size_t) obj->ob_alloc;
186 size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes);
187 size_t size = (size_t) requested_size;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000188
189 assert(self != NULL);
190 assert(PyByteArray_Check(self));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200191 assert(logical_offset <= alloc);
Antoine Pitroucc231542014-11-02 18:40:09 +0100192 assert(requested_size >= 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000193
Antoine Pitroucc231542014-11-02 18:40:09 +0100194 if (requested_size == Py_SIZE(self)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000195 return 0;
196 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200197 if (!_canresize(obj)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000198 return -1;
199 }
200
Antoine Pitrou25454112015-05-19 20:52:27 +0200201 if (size + logical_offset + 1 <= alloc) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200202 /* Current buffer is large enough to host the requested size,
203 decide on a strategy. */
204 if (size < alloc / 2) {
205 /* Major downsize; resize down to exact size */
206 alloc = size + 1;
207 }
208 else {
209 /* Minor downsize; quick exit */
210 Py_SIZE(self) = size;
211 PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */
212 return 0;
213 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000214 }
215 else {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200216 /* Need growing, decide on a strategy */
217 if (size <= alloc * 1.125) {
218 /* Moderate upsize; overallocate similar to list_resize() */
219 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
220 }
221 else {
222 /* Major upsize; resize up to exact size */
223 alloc = size + 1;
224 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000225 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100226 if (alloc > PY_SSIZE_T_MAX) {
227 PyErr_NoMemory();
228 return -1;
229 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000230
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200231 if (logical_offset > 0) {
232 sval = PyObject_Malloc(alloc);
233 if (sval == NULL) {
234 PyErr_NoMemory();
235 return -1;
236 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100237 memcpy(sval, PyByteArray_AS_STRING(self),
Stefan Krahdce65022017-08-25 20:12:05 +0200238 Py_MIN((size_t)requested_size, (size_t)Py_SIZE(self)));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200239 PyObject_Free(obj->ob_bytes);
240 }
241 else {
242 sval = PyObject_Realloc(obj->ob_bytes, alloc);
243 if (sval == NULL) {
244 PyErr_NoMemory();
245 return -1;
246 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000247 }
248
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200249 obj->ob_bytes = obj->ob_start = sval;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000250 Py_SIZE(self) = size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200251 obj->ob_alloc = alloc;
252 obj->ob_bytes[size] = '\0'; /* Trailing null byte */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000253
254 return 0;
255}
256
257PyObject *
258PyByteArray_Concat(PyObject *a, PyObject *b)
259{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000260 Py_buffer va, vb;
261 PyByteArrayObject *result = NULL;
262
263 va.len = -1;
264 vb.len = -1;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200265 if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 ||
266 PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000267 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
Serhiy Storchaka6b5a9ec2017-03-19 19:47:02 +0200268 Py_TYPE(b)->tp_name, Py_TYPE(a)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000269 goto done;
270 }
271
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300272 if (va.len > PY_SSIZE_T_MAX - vb.len) {
273 PyErr_NoMemory();
274 goto done;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000275 }
276
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300277 result = (PyByteArrayObject *) \
278 PyByteArray_FromStringAndSize(NULL, va.len + vb.len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000279 if (result != NULL) {
280 memcpy(result->ob_bytes, va.buf, va.len);
281 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
282 }
283
284 done:
285 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000286 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000287 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000288 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000289 return (PyObject *)result;
290}
291
292/* Functions stuffed into the type object */
293
294static Py_ssize_t
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000295bytearray_length(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000296{
297 return Py_SIZE(self);
298}
299
300static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000301bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000302{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000303 Py_ssize_t size;
304 Py_buffer vo;
305
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200306 if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000307 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
308 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
309 return NULL;
310 }
311
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300312 size = Py_SIZE(self);
313 if (size > PY_SSIZE_T_MAX - vo.len) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000314 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000315 return PyErr_NoMemory();
316 }
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300317 if (PyByteArray_Resize((PyObject *)self, size + vo.len) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000318 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000319 return NULL;
320 }
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300321 memcpy(PyByteArray_AS_STRING(self) + size, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000322 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000323 Py_INCREF(self);
324 return (PyObject *)self;
325}
326
327static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000328bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000329{
330 PyByteArrayObject *result;
331 Py_ssize_t mysize;
332 Py_ssize_t size;
333
334 if (count < 0)
335 count = 0;
336 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000337 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000338 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000339 size = mysize * count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000340 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
341 if (result != NULL && size != 0) {
342 if (mysize == 1)
343 memset(result->ob_bytes, self->ob_bytes[0], size);
344 else {
345 Py_ssize_t i;
346 for (i = 0; i < count; i++)
347 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
348 }
349 }
350 return (PyObject *)result;
351}
352
353static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000354bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000355{
356 Py_ssize_t mysize;
357 Py_ssize_t size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200358 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000359
360 if (count < 0)
361 count = 0;
362 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000363 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000364 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000365 size = mysize * count;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200366 if (PyByteArray_Resize((PyObject *)self, size) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000367 return NULL;
368
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200369 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000370 if (mysize == 1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200371 memset(buf, buf[0], size);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000372 else {
373 Py_ssize_t i;
374 for (i = 1; i < count; i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200375 memcpy(buf + i*mysize, buf, mysize);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000376 }
377
378 Py_INCREF(self);
379 return (PyObject *)self;
380}
381
382static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000383bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000384{
385 if (i < 0)
386 i += Py_SIZE(self);
387 if (i < 0 || i >= Py_SIZE(self)) {
388 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
389 return NULL;
390 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200391 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000392}
393
394static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000395bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000396{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000397 if (PyIndex_Check(index)) {
398 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000399
400 if (i == -1 && PyErr_Occurred())
401 return NULL;
402
403 if (i < 0)
404 i += PyByteArray_GET_SIZE(self);
405
406 if (i < 0 || i >= Py_SIZE(self)) {
407 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
408 return NULL;
409 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200410 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000411 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000412 else if (PySlice_Check(index)) {
Zackery Spytz14514d92019-05-17 01:13:03 -0600413 Py_ssize_t start, stop, step, slicelength, i;
414 size_t cur;
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300415 if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000416 return NULL;
417 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300418 slicelength = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self),
419 &start, &stop, step);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000420
421 if (slicelength <= 0)
422 return PyByteArray_FromStringAndSize("", 0);
423 else if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200424 return PyByteArray_FromStringAndSize(
425 PyByteArray_AS_STRING(self) + start, slicelength);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000426 }
427 else {
428 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000429 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000430 PyObject *result;
431
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000432 result = PyByteArray_FromStringAndSize(NULL, slicelength);
433 if (result == NULL)
434 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000435
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000436 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000437 for (cur = start, i = 0; i < slicelength;
438 cur += step, i++) {
439 result_buf[i] = source_buf[cur];
440 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000441 return result;
442 }
443 }
444 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400445 PyErr_Format(PyExc_TypeError,
446 "bytearray indices must be integers or slices, not %.200s",
447 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000448 return NULL;
449 }
450}
451
452static int
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200453bytearray_setslice_linear(PyByteArrayObject *self,
454 Py_ssize_t lo, Py_ssize_t hi,
455 char *bytes, Py_ssize_t bytes_len)
456{
457 Py_ssize_t avail = hi - lo;
458 char *buf = PyByteArray_AS_STRING(self);
459 Py_ssize_t growth = bytes_len - avail;
Victor Stinner84557232013-11-21 12:29:51 +0100460 int res = 0;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200461 assert(avail >= 0);
462
Victor Stinner84557232013-11-21 12:29:51 +0100463 if (growth < 0) {
464 if (!_canresize(self))
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200465 return -1;
Victor Stinner84557232013-11-21 12:29:51 +0100466
467 if (lo == 0) {
468 /* Shrink the buffer by advancing its logical start */
469 self->ob_start -= growth;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200470 /*
Victor Stinner84557232013-11-21 12:29:51 +0100471 0 lo hi old_size
472 | |<----avail----->|<-----tail------>|
473 | |<-bytes_len->|<-----tail------>|
474 0 new_lo new_hi new_size
475 */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200476 }
Victor Stinner84557232013-11-21 12:29:51 +0100477 else {
478 /*
479 0 lo hi old_size
480 | |<----avail----->|<-----tomove------>|
481 | |<-bytes_len->|<-----tomove------>|
482 0 lo new_hi new_size
483 */
484 memmove(buf + lo + bytes_len, buf + hi,
485 Py_SIZE(self) - hi);
486 }
487 if (PyByteArray_Resize((PyObject *)self,
488 Py_SIZE(self) + growth) < 0) {
489 /* Issue #19578: Handling the memory allocation failure here is
490 tricky here because the bytearray object has already been
491 modified. Depending on growth and lo, the behaviour is
492 different.
493
494 If growth < 0 and lo != 0, the operation is completed, but a
495 MemoryError is still raised and the memory block is not
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700496 shrunk. Otherwise, the bytearray is restored in its previous
Victor Stinner84557232013-11-21 12:29:51 +0100497 state and a MemoryError is raised. */
498 if (lo == 0) {
499 self->ob_start += growth;
500 return -1;
501 }
502 /* memmove() removed bytes, the bytearray object cannot be
503 restored in its previous state. */
504 Py_SIZE(self) += growth;
505 res = -1;
506 }
507 buf = PyByteArray_AS_STRING(self);
508 }
509 else if (growth > 0) {
510 if (Py_SIZE(self) > (Py_ssize_t)PY_SSIZE_T_MAX - growth) {
511 PyErr_NoMemory();
512 return -1;
513 }
514
515 if (PyByteArray_Resize((PyObject *)self,
516 Py_SIZE(self) + growth) < 0) {
517 return -1;
518 }
519 buf = PyByteArray_AS_STRING(self);
520 /* Make the place for the additional bytes */
521 /*
522 0 lo hi old_size
523 | |<-avail->|<-----tomove------>|
524 | |<---bytes_len-->|<-----tomove------>|
525 0 lo new_hi new_size
526 */
527 memmove(buf + lo + bytes_len, buf + hi,
528 Py_SIZE(self) - lo - bytes_len);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200529 }
530
531 if (bytes_len > 0)
532 memcpy(buf + lo, bytes, bytes_len);
Victor Stinner84557232013-11-21 12:29:51 +0100533 return res;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200534}
535
536static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000537bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000538 PyObject *values)
539{
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200540 Py_ssize_t needed;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000541 void *bytes;
542 Py_buffer vbytes;
543 int res = 0;
544
545 vbytes.len = -1;
546 if (values == (PyObject *)self) {
547 /* Make a copy and call this function recursively */
548 int err;
Serhiy Storchakaa2314282017-10-29 02:11:54 +0300549 values = PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(values),
550 PyByteArray_GET_SIZE(values));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000551 if (values == NULL)
552 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000553 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000554 Py_DECREF(values);
555 return err;
556 }
557 if (values == NULL) {
558 /* del b[lo:hi] */
559 bytes = NULL;
560 needed = 0;
561 }
562 else {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200563 if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) {
564 PyErr_Format(PyExc_TypeError,
565 "can't set bytearray slice from %.100s",
566 Py_TYPE(values)->tp_name);
567 return -1;
568 }
569 needed = vbytes.len;
570 bytes = vbytes.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000571 }
572
573 if (lo < 0)
574 lo = 0;
575 if (hi < lo)
576 hi = lo;
577 if (hi > Py_SIZE(self))
578 hi = Py_SIZE(self);
579
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200580 res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000581 if (vbytes.len != -1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200582 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000583 return res;
584}
585
586static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000587bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000588{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000589 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000590
591 if (i < 0)
592 i += Py_SIZE(self);
593
594 if (i < 0 || i >= Py_SIZE(self)) {
595 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
596 return -1;
597 }
598
599 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000600 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000601
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000602 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000603 return -1;
604
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200605 PyByteArray_AS_STRING(self)[i] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000606 return 0;
607}
608
609static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000610bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000611{
612 Py_ssize_t start, stop, step, slicelen, needed;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200613 char *buf, *bytes;
614 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000615
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000616 if (PyIndex_Check(index)) {
617 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000618
619 if (i == -1 && PyErr_Occurred())
620 return -1;
621
622 if (i < 0)
623 i += PyByteArray_GET_SIZE(self);
624
625 if (i < 0 || i >= Py_SIZE(self)) {
626 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
627 return -1;
628 }
629
630 if (values == NULL) {
631 /* Fall through to slice assignment */
632 start = i;
633 stop = i + 1;
634 step = 1;
635 slicelen = 1;
636 }
637 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000638 int ival;
639 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000640 return -1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200641 buf[i] = (char)ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000642 return 0;
643 }
644 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000645 else if (PySlice_Check(index)) {
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300646 if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000647 return -1;
648 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300649 slicelen = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self), &start,
650 &stop, step);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000651 }
652 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400653 PyErr_Format(PyExc_TypeError,
654 "bytearray indices must be integers or slices, not %.200s",
655 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000656 return -1;
657 }
658
659 if (values == NULL) {
660 bytes = NULL;
661 needed = 0;
662 }
663 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
Christian Heimes6d26ade2012-11-03 23:07:59 +0100664 int err;
Ezio Melottic64bcbe2012-11-03 21:19:06 +0200665 if (PyNumber_Check(values) || PyUnicode_Check(values)) {
666 PyErr_SetString(PyExc_TypeError,
667 "can assign only bytes, buffers, or iterables "
668 "of ints in range(0, 256)");
669 return -1;
670 }
Georg Brandlf3fa5682010-12-04 17:09:30 +0000671 /* Make a copy and call this function recursively */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000672 values = PyByteArray_FromObject(values);
673 if (values == NULL)
674 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000675 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000676 Py_DECREF(values);
677 return err;
678 }
679 else {
680 assert(PyByteArray_Check(values));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200681 bytes = PyByteArray_AS_STRING(values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000682 needed = Py_SIZE(values);
683 }
684 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
685 if ((step < 0 && start < stop) ||
686 (step > 0 && start > stop))
687 stop = start;
688 if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200689 return bytearray_setslice_linear(self, start, stop, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000690 }
691 else {
692 if (needed == 0) {
693 /* Delete slice */
Mark Dickinsonbc099642010-01-29 17:27:24 +0000694 size_t cur;
695 Py_ssize_t i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000696
Antoine Pitrou5504e892008-12-06 21:27:53 +0000697 if (!_canresize(self))
698 return -1;
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000699
700 if (slicelen == 0)
701 /* Nothing to do here. */
702 return 0;
703
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000704 if (step < 0) {
705 stop = start + 1;
706 start = stop + step * (slicelen - 1) - 1;
707 step = -step;
708 }
709 for (cur = start, i = 0;
710 i < slicelen; cur += step, i++) {
711 Py_ssize_t lim = step - 1;
712
Mark Dickinson66f575b2010-02-14 12:53:32 +0000713 if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000714 lim = PyByteArray_GET_SIZE(self) - cur - 1;
715
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200716 memmove(buf + cur - i,
717 buf + cur + 1, lim);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000718 }
719 /* Move the tail of the bytes, in one chunk */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000720 cur = start + (size_t)slicelen*step;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000721 if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200722 memmove(buf + cur - slicelen,
723 buf + cur,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000724 PyByteArray_GET_SIZE(self) - cur);
725 }
726 if (PyByteArray_Resize((PyObject *)self,
727 PyByteArray_GET_SIZE(self) - slicelen) < 0)
728 return -1;
729
730 return 0;
731 }
732 else {
733 /* Assign slice */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000734 Py_ssize_t i;
735 size_t cur;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000736
737 if (needed != slicelen) {
738 PyErr_Format(PyExc_ValueError,
739 "attempt to assign bytes of size %zd "
740 "to extended slice of size %zd",
741 needed, slicelen);
742 return -1;
743 }
744 for (cur = start, i = 0; i < slicelen; cur += step, i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200745 buf[cur] = bytes[i];
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000746 return 0;
747 }
748 }
749}
750
751static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000752bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000753{
754 static char *kwlist[] = {"source", "encoding", "errors", 0};
755 PyObject *arg = NULL;
756 const char *encoding = NULL;
757 const char *errors = NULL;
758 Py_ssize_t count;
759 PyObject *it;
760 PyObject *(*iternext)(PyObject *);
761
762 if (Py_SIZE(self) != 0) {
763 /* Empty previous contents (yes, do this first of all!) */
764 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
765 return -1;
766 }
767
768 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000769 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000770 &arg, &encoding, &errors))
771 return -1;
772
773 /* Make a quick exit if no first argument */
774 if (arg == NULL) {
775 if (encoding != NULL || errors != NULL) {
776 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300777 encoding != NULL ?
778 "encoding without a string argument" :
779 "errors without a string argument");
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000780 return -1;
781 }
782 return 0;
783 }
784
785 if (PyUnicode_Check(arg)) {
786 /* Encode via the codec registry */
787 PyObject *encoded, *new;
788 if (encoding == NULL) {
789 PyErr_SetString(PyExc_TypeError,
790 "string argument without an encoding");
791 return -1;
792 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000793 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000794 if (encoded == NULL)
795 return -1;
796 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000797 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000798 Py_DECREF(encoded);
799 if (new == NULL)
800 return -1;
801 Py_DECREF(new);
802 return 0;
803 }
804
805 /* If it's not unicode, there can't be encoding or errors */
806 if (encoding != NULL || errors != NULL) {
807 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300808 encoding != NULL ?
809 "encoding without a string argument" :
810 "errors without a string argument");
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000811 return -1;
812 }
813
814 /* Is it an int? */
Serhiy Storchakaeb249882016-08-15 09:46:07 +0300815 if (PyIndex_Check(arg)) {
816 count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
817 if (count == -1 && PyErr_Occurred()) {
Serhiy Storchakae8904212018-10-15 00:02:57 +0300818 if (!PyErr_ExceptionMatches(PyExc_TypeError))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000819 return -1;
INADA Naokia634e232017-01-06 17:32:01 +0900820 PyErr_Clear(); /* fall through */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000821 }
INADA Naokia634e232017-01-06 17:32:01 +0900822 else {
823 if (count < 0) {
824 PyErr_SetString(PyExc_ValueError, "negative count");
825 return -1;
826 }
827 if (count > 0) {
828 if (PyByteArray_Resize((PyObject *)self, count))
829 return -1;
830 memset(PyByteArray_AS_STRING(self), 0, count);
831 }
832 return 0;
833 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000834 }
835
836 /* Use the buffer API */
837 if (PyObject_CheckBuffer(arg)) {
838 Py_ssize_t size;
839 Py_buffer view;
840 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
841 return -1;
842 size = view.len;
843 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200844 if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
845 &view, size, 'C') < 0)
Stefan Krah7d12d9d2012-07-28 12:25:55 +0200846 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000847 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000848 return 0;
849 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000850 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000851 return -1;
852 }
853
854 /* XXX Optimize this if the arguments is a list, tuple */
855
856 /* Get the iterator */
857 it = PyObject_GetIter(arg);
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300858 if (it == NULL) {
859 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
860 PyErr_Format(PyExc_TypeError,
861 "cannot convert '%.200s' object to bytearray",
862 arg->ob_type->tp_name);
863 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000864 return -1;
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300865 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000866 iternext = *Py_TYPE(it)->tp_iternext;
867
868 /* Run the iterator to exhaustion */
869 for (;;) {
870 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000871 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000872
873 /* Get the next item */
874 item = iternext(it);
875 if (item == NULL) {
876 if (PyErr_Occurred()) {
877 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
878 goto error;
879 PyErr_Clear();
880 }
881 break;
882 }
883
884 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000885 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000886 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000887 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000888 goto error;
889
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000890 /* Append the byte */
Serhiy Storchaka7b6e3b92015-06-29 21:14:06 +0300891 if (Py_SIZE(self) + 1 < self->ob_alloc) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000892 Py_SIZE(self)++;
Serhiy Storchaka7b6e3b92015-06-29 21:14:06 +0300893 PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0';
894 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000895 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
896 goto error;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200897 PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000898 }
899
900 /* Clean up and return success */
901 Py_DECREF(it);
902 return 0;
903
904 error:
905 /* Error handling when it != NULL */
906 Py_DECREF(it);
907 return -1;
908}
909
910/* Mostly copied from string_repr, but without the
911 "smart quote" functionality. */
912static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000913bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000914{
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300915 const char *className = _PyType_Name(Py_TYPE(self));
916 const char *quote_prefix = "(b";
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000917 const char *quote_postfix = ")";
918 Py_ssize_t length = Py_SIZE(self);
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300919 /* 6 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */
920 Py_ssize_t newsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000921 PyObject *v;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200922 Py_ssize_t i;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200923 char *bytes;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200924 char c;
925 char *p;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200926 int quote;
927 char *test, *start;
928 char *buffer;
929
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300930 newsize = strlen(className);
931 if (length > (PY_SSIZE_T_MAX - 6 - newsize) / 4) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000932 PyErr_SetString(PyExc_OverflowError,
933 "bytearray object is too large to make repr");
934 return NULL;
935 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200936
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300937 newsize += 6 + length * 4;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100938 buffer = PyObject_Malloc(newsize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200939 if (buffer == NULL) {
940 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000941 return NULL;
942 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000943
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200944 /* Figure out which quote to use; single is preferred */
945 quote = '\'';
946 start = PyByteArray_AS_STRING(self);
947 for (test = start; test < start+length; ++test) {
948 if (*test == '"') {
949 quote = '\''; /* back to single */
950 break;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000951 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200952 else if (*test == '\'')
953 quote = '"';
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000954 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200955
956 p = buffer;
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300957 while (*className)
958 *p++ = *className++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200959 while (*quote_prefix)
960 *p++ = *quote_prefix++;
961 *p++ = quote;
962
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200963 bytes = PyByteArray_AS_STRING(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200964 for (i = 0; i < length; i++) {
965 /* There's at least enough room for a hex escape
966 and a closing quote. */
967 assert(newsize - (p - buffer) >= 5);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200968 c = bytes[i];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200969 if (c == '\'' || c == '\\')
970 *p++ = '\\', *p++ = c;
971 else if (c == '\t')
972 *p++ = '\\', *p++ = 't';
973 else if (c == '\n')
974 *p++ = '\\', *p++ = 'n';
975 else if (c == '\r')
976 *p++ = '\\', *p++ = 'r';
977 else if (c == 0)
978 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
979 else if (c < ' ' || c >= 0x7f) {
980 *p++ = '\\';
981 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +0200982 *p++ = Py_hexdigits[(c & 0xf0) >> 4];
983 *p++ = Py_hexdigits[c & 0xf];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200984 }
985 else
986 *p++ = c;
987 }
988 assert(newsize - (p - buffer) >= 1);
989 *p++ = quote;
990 while (*quote_postfix) {
991 *p++ = *quote_postfix++;
992 }
993
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300994 v = PyUnicode_FromStringAndSize(buffer, p - buffer);
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100995 PyObject_Free(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200996 return v;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000997}
998
999static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001000bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001001{
Victor Stinnerc96be812019-05-14 17:34:56 +02001002 _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
1003 if (config->bytes_warning) {
Victor Stinner53b7d4e2018-07-25 01:37:05 +02001004 if (PyErr_WarnEx(PyExc_BytesWarning,
1005 "str() on a bytearray instance", 1)) {
1006 return NULL;
Alexander Belopolskyf0f45142010-08-11 17:31:17 +00001007 }
Victor Stinner53b7d4e2018-07-25 01:37:05 +02001008 }
1009 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001010}
1011
1012static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001013bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001014{
1015 Py_ssize_t self_size, other_size;
1016 Py_buffer self_bytes, other_bytes;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001017 int cmp, rc;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001018
1019 /* Bytes can be compared to anything that supports the (binary)
1020 buffer API. Except that a comparison with Unicode is always an
1021 error, even if the comparison is for equality. */
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001022 rc = PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type);
1023 if (!rc)
1024 rc = PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type);
1025 if (rc < 0)
1026 return NULL;
1027 if (rc) {
Victor Stinnerc96be812019-05-14 17:34:56 +02001028 _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
1029 if (config->bytes_warning && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001030 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +00001031 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001032 return NULL;
1033 }
1034
Brian Curtindfc80e32011-08-10 20:28:54 -05001035 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001036 }
1037
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001038 if (PyObject_GetBuffer(self, &self_bytes, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001039 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05001040 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001041 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001042 self_size = self_bytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001043
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001044 if (PyObject_GetBuffer(other, &other_bytes, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001045 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +00001046 PyBuffer_Release(&self_bytes);
Brian Curtindfc80e32011-08-10 20:28:54 -05001047 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001048 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001049 other_size = other_bytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001050
1051 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
1052 /* Shortcut: if the lengths differ, the objects differ */
stratakise8b19652017-11-02 11:32:54 +01001053 PyBuffer_Release(&self_bytes);
1054 PyBuffer_Release(&other_bytes);
1055 return PyBool_FromLong((op == Py_NE));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001056 }
1057 else {
stratakise8b19652017-11-02 11:32:54 +01001058 cmp = memcmp(self_bytes.buf, other_bytes.buf,
1059 Py_MIN(self_size, other_size));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001060 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
1061
stratakise8b19652017-11-02 11:32:54 +01001062 PyBuffer_Release(&self_bytes);
1063 PyBuffer_Release(&other_bytes);
1064
1065 if (cmp != 0) {
1066 Py_RETURN_RICHCOMPARE(cmp, 0, op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001067 }
1068
stratakise8b19652017-11-02 11:32:54 +01001069 Py_RETURN_RICHCOMPARE(self_size, other_size, op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001070 }
1071
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001072}
1073
1074static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001075bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001076{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001077 if (self->ob_exports > 0) {
1078 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001079 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001080 PyErr_Print();
1081 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001082 if (self->ob_bytes != 0) {
Antoine Pitrou39aba4f2011-11-12 21:15:28 +01001083 PyObject_Free(self->ob_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001084 }
1085 Py_TYPE(self)->tp_free((PyObject *)self);
1086}
1087
1088
1089/* -------------------------------------------------------------------- */
1090/* Methods */
1091
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001092#define FASTSEARCH fastsearch
1093#define STRINGLIB(F) stringlib_##F
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001094#define STRINGLIB_CHAR char
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001095#define STRINGLIB_SIZEOF_CHAR 1
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001096#define STRINGLIB_LEN PyByteArray_GET_SIZE
1097#define STRINGLIB_STR PyByteArray_AS_STRING
1098#define STRINGLIB_NEW PyByteArray_FromStringAndSize
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001099#define STRINGLIB_ISSPACE Py_ISSPACE
1100#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001101#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1102#define STRINGLIB_MUTABLE 1
1103
1104#include "stringlib/fastsearch.h"
1105#include "stringlib/count.h"
1106#include "stringlib/find.h"
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001107#include "stringlib/join.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001108#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001109#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001110#include "stringlib/ctype.h"
1111#include "stringlib/transmogrify.h"
1112
1113
Serhiy Storchakae09132f2016-07-03 13:57:48 +03001114static PyObject *
1115bytearray_find(PyByteArrayObject *self, PyObject *args)
1116{
1117 return _Py_bytes_find(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1118}
1119
1120static PyObject *
1121bytearray_count(PyByteArrayObject *self, PyObject *args)
1122{
1123 return _Py_bytes_count(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1124}
1125
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001126/*[clinic input]
1127bytearray.clear
1128
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001129Remove all items from the bytearray.
1130[clinic start generated code]*/
1131
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001132static PyObject *
1133bytearray_clear_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001134/*[clinic end generated code: output=85c2fe6aede0956c input=ed6edae9de447ac4]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001135{
1136 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
1137 return NULL;
1138 Py_RETURN_NONE;
1139}
1140
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001141/*[clinic input]
1142bytearray.copy
1143
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001144Return a copy of B.
1145[clinic start generated code]*/
1146
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001147static PyObject *
1148bytearray_copy_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001149/*[clinic end generated code: output=68cfbcfed484c132 input=6597b0c01bccaa9e]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001150{
1151 return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
1152 PyByteArray_GET_SIZE(self));
1153}
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001154
Serhiy Storchakae09132f2016-07-03 13:57:48 +03001155static PyObject *
1156bytearray_index(PyByteArrayObject *self, PyObject *args)
1157{
1158 return _Py_bytes_index(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1159}
1160
1161static PyObject *
1162bytearray_rfind(PyByteArrayObject *self, PyObject *args)
1163{
1164 return _Py_bytes_rfind(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1165}
1166
1167static PyObject *
1168bytearray_rindex(PyByteArrayObject *self, PyObject *args)
1169{
1170 return _Py_bytes_rindex(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1171}
1172
1173static int
1174bytearray_contains(PyObject *self, PyObject *arg)
1175{
1176 return _Py_bytes_contains(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), arg);
1177}
1178
1179static PyObject *
1180bytearray_startswith(PyByteArrayObject *self, PyObject *args)
1181{
1182 return _Py_bytes_startswith(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1183}
1184
1185static PyObject *
1186bytearray_endswith(PyByteArrayObject *self, PyObject *args)
1187{
1188 return _Py_bytes_endswith(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1189}
1190
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001191
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001192/*[clinic input]
1193bytearray.translate
1194
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001195 table: object
1196 Translation table, which must be a bytes object of length 256.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001197 /
Martin Panter1b6c6da2016-08-27 08:35:02 +00001198 delete as deletechars: object(c_default="NULL") = b''
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001199
1200Return a copy with each character mapped by the given translation table.
1201
Martin Panter1b6c6da2016-08-27 08:35:02 +00001202All characters occurring in the optional argument delete are removed.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001203The remaining characters are mapped through the given translation table.
1204[clinic start generated code]*/
1205
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001206static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001207bytearray_translate_impl(PyByteArrayObject *self, PyObject *table,
Martin Panter1b6c6da2016-08-27 08:35:02 +00001208 PyObject *deletechars)
1209/*[clinic end generated code: output=b6a8f01c2a74e446 input=cfff956d4d127a9b]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001210{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001211 char *input, *output;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001212 const char *table_chars;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001213 Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001214 PyObject *input_obj = (PyObject*)self;
1215 const char *output_start;
1216 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001217 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001218 int trans_table[256];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001219 Py_buffer vtable, vdel;
1220
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001221 if (table == Py_None) {
1222 table_chars = NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001223 table = NULL;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001224 } else if (PyObject_GetBuffer(table, &vtable, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001225 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001226 } else {
1227 if (vtable.len != 256) {
1228 PyErr_SetString(PyExc_ValueError,
1229 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001230 PyBuffer_Release(&vtable);
1231 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001232 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001233 table_chars = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001234 }
1235
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001236 if (deletechars != NULL) {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001237 if (PyObject_GetBuffer(deletechars, &vdel, PyBUF_SIMPLE) != 0) {
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001238 if (table != NULL)
Georg Brandl953152f2009-07-22 12:03:59 +00001239 PyBuffer_Release(&vtable);
1240 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001241 }
1242 }
1243 else {
1244 vdel.buf = NULL;
1245 vdel.len = 0;
1246 }
1247
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001248 inlen = PyByteArray_GET_SIZE(input_obj);
1249 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1250 if (result == NULL)
1251 goto done;
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03001252 output_start = output = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001253 input = PyByteArray_AS_STRING(input_obj);
1254
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001255 if (vdel.len == 0 && table_chars != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001256 /* If no deletions are required, use faster code */
1257 for (i = inlen; --i >= 0; ) {
1258 c = Py_CHARMASK(*input++);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001259 *output++ = table_chars[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001260 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001261 goto done;
1262 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001263
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001264 if (table_chars == NULL) {
Georg Brandlccc47b62008-12-28 11:44:14 +00001265 for (i = 0; i < 256; i++)
1266 trans_table[i] = Py_CHARMASK(i);
1267 } else {
1268 for (i = 0; i < 256; i++)
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001269 trans_table[i] = Py_CHARMASK(table_chars[i]);
Georg Brandlccc47b62008-12-28 11:44:14 +00001270 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001271
1272 for (i = 0; i < vdel.len; i++)
1273 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1274
1275 for (i = inlen; --i >= 0; ) {
1276 c = Py_CHARMASK(*input++);
1277 if (trans_table[c] != -1)
Martin Panter1b6c6da2016-08-27 08:35:02 +00001278 *output++ = (char)trans_table[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001279 }
1280 /* Fix the size of the resulting string */
1281 if (inlen > 0)
Christian Heimesc731bbe2013-07-21 02:04:35 +02001282 if (PyByteArray_Resize(result, output - output_start) < 0) {
1283 Py_CLEAR(result);
1284 goto done;
1285 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001286
1287done:
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001288 if (table != NULL)
Georg Brandlccc47b62008-12-28 11:44:14 +00001289 PyBuffer_Release(&vtable);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001290 if (deletechars != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001291 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001292 return result;
1293}
1294
1295
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001296/*[clinic input]
1297
1298@staticmethod
1299bytearray.maketrans
1300
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001301 frm: Py_buffer
1302 to: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001303 /
1304
1305Return a translation table useable for the bytes or bytearray translate method.
1306
1307The returned table will be one where each byte in frm is mapped to the byte at
1308the same position in to.
1309
1310The bytes objects frm and to must be of the same length.
1311[clinic start generated code]*/
1312
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001313static PyObject *
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001314bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001315/*[clinic end generated code: output=1df267d99f56b15e input=5925a81d2fbbf151]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001316{
1317 return _Py_bytes_maketrans(frm, to);
Georg Brandlabc38772009-04-12 15:51:51 +00001318}
1319
1320
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001321/*[clinic input]
1322bytearray.replace
1323
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001324 old: Py_buffer
1325 new: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001326 count: Py_ssize_t = -1
1327 Maximum number of occurrences to replace.
1328 -1 (the default value) means replace all occurrences.
1329 /
1330
1331Return a copy with all occurrences of substring old replaced by new.
1332
1333If the optional argument count is given, only the first count occurrences are
1334replaced.
1335[clinic start generated code]*/
1336
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001337static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001338bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old,
1339 Py_buffer *new, Py_ssize_t count)
1340/*[clinic end generated code: output=d39884c4dc59412a input=aa379d988637c7fb]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001341{
Serhiy Storchakafb81d3c2016-05-05 09:26:07 +03001342 return stringlib_replace((PyObject *)self,
Serhiy Storchakae09132f2016-07-03 13:57:48 +03001343 (const char *)old->buf, old->len,
1344 (const char *)new->buf, new->len, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001345}
1346
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001347/*[clinic input]
1348bytearray.split
1349
1350 sep: object = None
1351 The delimiter according which to split the bytearray.
1352 None (the default value) means split on ASCII whitespace characters
1353 (space, tab, return, newline, formfeed, vertical tab).
1354 maxsplit: Py_ssize_t = -1
1355 Maximum number of splits to do.
1356 -1 (the default value) means no limit.
1357
1358Return a list of the sections in the bytearray, using sep as the delimiter.
1359[clinic start generated code]*/
1360
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001361static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001362bytearray_split_impl(PyByteArrayObject *self, PyObject *sep,
1363 Py_ssize_t maxsplit)
1364/*[clinic end generated code: output=833e2cf385d9a04d input=24f82669f41bf523]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001365{
1366 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001367 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001368 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001369 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001370
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001371 if (maxsplit < 0)
1372 maxsplit = PY_SSIZE_T_MAX;
1373
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001374 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001375 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001376
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001377 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001378 return NULL;
1379 sub = vsub.buf;
1380 n = vsub.len;
1381
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001382 list = stringlib_split(
1383 (PyObject*) self, s, len, sub, n, maxsplit
1384 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001385 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001386 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001387}
1388
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001389/*[clinic input]
1390bytearray.partition
1391
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001392 sep: object
1393 /
1394
1395Partition the bytearray into three parts using the given separator.
1396
1397This will search for the separator sep in the bytearray. If the separator is
1398found, returns a 3-tuple containing the part before the separator, the
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001399separator itself, and the part after it as new bytearray objects.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001400
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001401If the separator is not found, returns a 3-tuple containing the copy of the
1402original bytearray object and two empty bytearray objects.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001403[clinic start generated code]*/
1404
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001405static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001406bytearray_partition(PyByteArrayObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001407/*[clinic end generated code: output=45d2525ddd35f957 input=8f644749ee4fc83a]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001408{
1409 PyObject *bytesep, *result;
1410
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001411 bytesep = _PyByteArray_FromBufferObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001412 if (! bytesep)
1413 return NULL;
1414
1415 result = stringlib_partition(
1416 (PyObject*) self,
1417 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1418 bytesep,
1419 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
1420 );
1421
1422 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001423 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001424}
1425
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001426/*[clinic input]
1427bytearray.rpartition
1428
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001429 sep: object
1430 /
1431
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001432Partition the bytearray into three parts using the given separator.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001433
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001434This will search for the separator sep in the bytearray, starting at the end.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001435If the separator is found, returns a 3-tuple containing the part before the
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001436separator, the separator itself, and the part after it as new bytearray
1437objects.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001438
1439If the separator is not found, returns a 3-tuple containing two empty bytearray
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001440objects and the copy of the original bytearray object.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001441[clinic start generated code]*/
1442
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001443static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001444bytearray_rpartition(PyByteArrayObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001445/*[clinic end generated code: output=440de3c9426115e8 input=7e3df3e6cb8fa0ac]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001446{
1447 PyObject *bytesep, *result;
1448
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001449 bytesep = _PyByteArray_FromBufferObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001450 if (! bytesep)
1451 return NULL;
1452
1453 result = stringlib_rpartition(
1454 (PyObject*) self,
1455 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1456 bytesep,
1457 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
1458 );
1459
1460 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001461 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001462}
1463
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001464/*[clinic input]
1465bytearray.rsplit = bytearray.split
1466
1467Return a list of the sections in the bytearray, using sep as the delimiter.
1468
1469Splitting is done starting at the end of the bytearray and working to the front.
1470[clinic start generated code]*/
1471
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001472static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001473bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep,
1474 Py_ssize_t maxsplit)
1475/*[clinic end generated code: output=a55e0b5a03cb6190 input=a68286e4dd692ffe]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001476{
1477 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001478 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001479 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001480 Py_buffer vsub;
1481
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001482 if (maxsplit < 0)
1483 maxsplit = PY_SSIZE_T_MAX;
1484
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001485 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001486 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001487
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001488 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001489 return NULL;
1490 sub = vsub.buf;
1491 n = vsub.len;
1492
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001493 list = stringlib_rsplit(
1494 (PyObject*) self, s, len, sub, n, maxsplit
1495 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001496 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001497 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001498}
1499
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001500/*[clinic input]
1501bytearray.reverse
1502
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001503Reverse the order of the values in B in place.
1504[clinic start generated code]*/
1505
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001506static PyObject *
1507bytearray_reverse_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001508/*[clinic end generated code: output=9f7616f29ab309d3 input=543356319fc78557]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001509{
1510 char swap, *head, *tail;
1511 Py_ssize_t i, j, n = Py_SIZE(self);
1512
1513 j = n / 2;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001514 head = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001515 tail = head + n - 1;
1516 for (i = 0; i < j; i++) {
1517 swap = *head;
1518 *head++ = *tail;
1519 *tail-- = swap;
1520 }
1521
1522 Py_RETURN_NONE;
1523}
1524
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001525
1526/*[python input]
1527class bytesvalue_converter(CConverter):
1528 type = 'int'
1529 converter = '_getbytevalue'
1530[python start generated code]*/
1531/*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/
1532
1533
1534/*[clinic input]
1535bytearray.insert
1536
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001537 index: Py_ssize_t
1538 The index where the value is to be inserted.
1539 item: bytesvalue
1540 The item to be inserted.
1541 /
1542
1543Insert a single item into the bytearray before the given index.
1544[clinic start generated code]*/
1545
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001546static PyObject *
1547bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001548/*[clinic end generated code: output=76c775a70e7b07b7 input=b2b5d07e9de6c070]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001549{
1550 Py_ssize_t n = Py_SIZE(self);
1551 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001552
1553 if (n == PY_SSIZE_T_MAX) {
1554 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00001555 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001556 return NULL;
1557 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001558 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
1559 return NULL;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001560 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001561
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001562 if (index < 0) {
1563 index += n;
1564 if (index < 0)
1565 index = 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001566 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001567 if (index > n)
1568 index = n;
1569 memmove(buf + index + 1, buf + index, n - index);
1570 buf[index] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001571
1572 Py_RETURN_NONE;
1573}
1574
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001575/*[clinic input]
1576bytearray.append
1577
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001578 item: bytesvalue
1579 The item to be appended.
1580 /
1581
1582Append a single item to the end of the bytearray.
1583[clinic start generated code]*/
1584
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001585static PyObject *
1586bytearray_append_impl(PyByteArrayObject *self, int item)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001587/*[clinic end generated code: output=a154e19ed1886cb6 input=20d6bec3d1340593]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001588{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001589 Py_ssize_t n = Py_SIZE(self);
1590
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001591 if (n == PY_SSIZE_T_MAX) {
1592 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00001593 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001594 return NULL;
1595 }
1596 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
1597 return NULL;
1598
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001599 PyByteArray_AS_STRING(self)[n] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001600
1601 Py_RETURN_NONE;
1602}
1603
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001604/*[clinic input]
1605bytearray.extend
1606
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001607 iterable_of_ints: object
1608 The iterable of items to append.
1609 /
1610
1611Append all the items from the iterator or sequence to the end of the bytearray.
1612[clinic start generated code]*/
1613
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001614static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001615bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001616/*[clinic end generated code: output=98155dbe249170b1 input=c617b3a93249ba28]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001617{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001618 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001619 Py_ssize_t buf_size = 0, len = 0;
1620 int value;
1621 char *buf;
1622
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001623 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001624 if (PyObject_CheckBuffer(iterable_of_ints)) {
1625 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001626 return NULL;
1627
1628 Py_RETURN_NONE;
1629 }
1630
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001631 it = PyObject_GetIter(iterable_of_ints);
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +03001632 if (it == NULL) {
1633 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
1634 PyErr_Format(PyExc_TypeError,
1635 "can't extend bytearray with %.100s",
1636 iterable_of_ints->ob_type->tp_name);
1637 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001638 return NULL;
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +03001639 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001640
Ezio Melotti42da6632011-03-15 05:18:48 +02001641 /* Try to determine the length of the argument. 32 is arbitrary. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001642 buf_size = PyObject_LengthHint(iterable_of_ints, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001643 if (buf_size == -1) {
1644 Py_DECREF(it);
1645 return NULL;
1646 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001647
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001648 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02001649 if (bytearray_obj == NULL) {
1650 Py_DECREF(it);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001651 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02001652 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001653 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001654
1655 while ((item = PyIter_Next(it)) != NULL) {
1656 if (! _getbytevalue(item, &value)) {
1657 Py_DECREF(item);
1658 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001659 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001660 return NULL;
1661 }
1662 buf[len++] = value;
1663 Py_DECREF(item);
1664
1665 if (len >= buf_size) {
Martin Panter371731e2016-07-18 07:53:13 +00001666 Py_ssize_t addition;
1667 if (len == PY_SSIZE_T_MAX) {
1668 Py_DECREF(it);
1669 Py_DECREF(bytearray_obj);
1670 return PyErr_NoMemory();
1671 }
1672 addition = len >> 1;
1673 if (addition > PY_SSIZE_T_MAX - len - 1)
1674 buf_size = PY_SSIZE_T_MAX;
1675 else
1676 buf_size = len + addition + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001677 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001678 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001679 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001680 return NULL;
1681 }
1682 /* Recompute the `buf' pointer, since the resizing operation may
1683 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001684 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001685 }
1686 }
1687 Py_DECREF(it);
1688
1689 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001690 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
1691 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001692 return NULL;
1693 }
1694
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02001695 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
1696 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001697 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02001698 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001699 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001700
1701 Py_RETURN_NONE;
1702}
1703
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001704/*[clinic input]
1705bytearray.pop
1706
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001707 index: Py_ssize_t = -1
1708 The index from where to remove the item.
1709 -1 (the default value) means remove the last item.
1710 /
1711
1712Remove and return a single item from B.
1713
1714If no index argument is given, will pop the last item.
1715[clinic start generated code]*/
1716
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001717static PyObject *
1718bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001719/*[clinic end generated code: output=e0ccd401f8021da8 input=3591df2d06c0d237]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001720{
1721 int value;
1722 Py_ssize_t n = Py_SIZE(self);
1723 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001724
1725 if (n == 0) {
Eli Bendersky1bc4f192011-03-04 04:55:25 +00001726 PyErr_SetString(PyExc_IndexError,
1727 "pop from empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001728 return NULL;
1729 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001730 if (index < 0)
1731 index += Py_SIZE(self);
1732 if (index < 0 || index >= Py_SIZE(self)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001733 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1734 return NULL;
1735 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00001736 if (!_canresize(self))
1737 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001738
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001739 buf = PyByteArray_AS_STRING(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001740 value = buf[index];
1741 memmove(buf + index, buf + index + 1, n - index);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001742 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
1743 return NULL;
1744
Mark Dickinson54a3db92009-09-06 10:19:23 +00001745 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001746}
1747
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001748/*[clinic input]
1749bytearray.remove
1750
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001751 value: bytesvalue
1752 The value to remove.
1753 /
1754
1755Remove the first occurrence of a value in the bytearray.
1756[clinic start generated code]*/
1757
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001758static PyObject *
1759bytearray_remove_impl(PyByteArrayObject *self, int value)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001760/*[clinic end generated code: output=d659e37866709c13 input=121831240cd51ddf]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001761{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001762 Py_ssize_t where, n = Py_SIZE(self);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001763 char *buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001764
Serhiy Storchaka4b234942016-05-16 22:24:03 +03001765 where = stringlib_find_char(buf, n, value);
1766 if (where < 0) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00001767 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001768 return NULL;
1769 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00001770 if (!_canresize(self))
1771 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001772
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001773 memmove(buf + where, buf + where + 1, n - where);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001774 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
1775 return NULL;
1776
1777 Py_RETURN_NONE;
1778}
1779
1780/* XXX These two helpers could be optimized if argsize == 1 */
1781
1782static Py_ssize_t
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001783lstrip_helper(const char *myptr, Py_ssize_t mysize,
1784 const void *argptr, Py_ssize_t argsize)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001785{
1786 Py_ssize_t i = 0;
Antoine Pitrou5b720752013-10-05 21:24:10 +02001787 while (i < mysize && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001788 i++;
1789 return i;
1790}
1791
1792static Py_ssize_t
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001793rstrip_helper(const char *myptr, Py_ssize_t mysize,
1794 const void *argptr, Py_ssize_t argsize)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001795{
1796 Py_ssize_t i = mysize - 1;
Antoine Pitrou5b720752013-10-05 21:24:10 +02001797 while (i >= 0 && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001798 i--;
1799 return i + 1;
1800}
1801
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001802/*[clinic input]
1803bytearray.strip
1804
1805 bytes: object = None
1806 /
1807
1808Strip leading and trailing bytes contained in the argument.
1809
1810If the argument is omitted or None, strip leading and trailing ASCII whitespace.
1811[clinic start generated code]*/
1812
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001813static PyObject *
1814bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001815/*[clinic end generated code: output=760412661a34ad5a input=ef7bb59b09c21d62]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001816{
1817 Py_ssize_t left, right, mysize, byteslen;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001818 char *myptr;
1819 const char *bytesptr;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001820 Py_buffer vbytes;
1821
1822 if (bytes == Py_None) {
1823 bytesptr = "\t\n\r\f\v ";
1824 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001825 }
1826 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001827 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001828 return NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001829 bytesptr = (const char *) vbytes.buf;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001830 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001831 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001832 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001833 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001834 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001835 if (left == mysize)
1836 right = left;
1837 else
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001838 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
1839 if (bytes != Py_None)
1840 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001841 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001842}
1843
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001844/*[clinic input]
1845bytearray.lstrip
1846
1847 bytes: object = None
1848 /
1849
1850Strip leading bytes contained in the argument.
1851
1852If the argument is omitted or None, strip leading ASCII whitespace.
1853[clinic start generated code]*/
1854
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001855static PyObject *
1856bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001857/*[clinic end generated code: output=d005c9d0ab909e66 input=80843f975dd7c480]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001858{
1859 Py_ssize_t left, right, mysize, byteslen;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001860 char *myptr;
1861 const char *bytesptr;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001862 Py_buffer vbytes;
1863
1864 if (bytes == Py_None) {
1865 bytesptr = "\t\n\r\f\v ";
1866 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001867 }
1868 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001869 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001870 return NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001871 bytesptr = (const char *) vbytes.buf;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001872 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001873 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001874 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001875 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001876 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001877 right = mysize;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001878 if (bytes != Py_None)
1879 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001880 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001881}
1882
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001883/*[clinic input]
1884bytearray.rstrip
1885
1886 bytes: object = None
1887 /
1888
1889Strip trailing bytes contained in the argument.
1890
1891If the argument is omitted or None, strip trailing ASCII whitespace.
1892[clinic start generated code]*/
1893
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001894static PyObject *
1895bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001896/*[clinic end generated code: output=030e2fbd2f7276bd input=e728b994954cfd91]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001897{
1898 Py_ssize_t right, mysize, byteslen;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001899 char *myptr;
1900 const char *bytesptr;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001901 Py_buffer vbytes;
1902
1903 if (bytes == Py_None) {
1904 bytesptr = "\t\n\r\f\v ";
1905 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001906 }
1907 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001908 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001909 return NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001910 bytesptr = (const char *) vbytes.buf;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001911 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001912 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001913 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001914 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001915 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
1916 if (bytes != Py_None)
1917 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001918 return PyByteArray_FromStringAndSize(myptr, right);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001919}
1920
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001921/*[clinic input]
1922bytearray.decode
1923
1924 encoding: str(c_default="NULL") = 'utf-8'
1925 The encoding with which to decode the bytearray.
1926 errors: str(c_default="NULL") = 'strict'
1927 The error handling scheme to use for the handling of decoding errors.
1928 The default is 'strict' meaning that decoding errors raise a
1929 UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
1930 as well as any other name registered with codecs.register_error that
1931 can handle UnicodeDecodeErrors.
1932
1933Decode the bytearray using the codec registered for encoding.
1934[clinic start generated code]*/
1935
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001936static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001937bytearray_decode_impl(PyByteArrayObject *self, const char *encoding,
1938 const char *errors)
1939/*[clinic end generated code: output=f57d43f4a00b42c5 input=f28d8f903020257b]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001940{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001941 if (encoding == NULL)
1942 encoding = PyUnicode_GetDefaultEncoding();
Martin v. Löwis0efea322014-07-27 17:29:17 +02001943 return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001944}
1945
1946PyDoc_STRVAR(alloc_doc,
1947"B.__alloc__() -> int\n\
1948\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00001949Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001950
1951static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301952bytearray_alloc(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001953{
1954 return PyLong_FromSsize_t(self->ob_alloc);
1955}
1956
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001957/*[clinic input]
1958bytearray.join
1959
1960 iterable_of_bytes: object
1961 /
1962
1963Concatenate any number of bytes/bytearray objects.
1964
1965The bytearray whose method is called is inserted in between each pair.
1966
1967The result is returned as a new bytearray object.
1968[clinic start generated code]*/
1969
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001970static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001971bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001972/*[clinic end generated code: output=a8516370bf68ae08 input=aba6b1f9b30fcb8e]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001973{
Martin v. Löwis0efea322014-07-27 17:29:17 +02001974 return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001975}
1976
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001977/*[clinic input]
1978bytearray.splitlines
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001979
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001980 keepends: bool(accept={int}) = False
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001981
1982Return a list of the lines in the bytearray, breaking at line boundaries.
1983
1984Line breaks are not included in the resulting list unless keepends is given and
1985true.
1986[clinic start generated code]*/
1987
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001988static PyObject *
1989bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001990/*[clinic end generated code: output=4223c94b895f6ad9 input=99a27ad959b9cf6b]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001991{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001992 return stringlib_splitlines(
1993 (PyObject*) self, PyByteArray_AS_STRING(self),
1994 PyByteArray_GET_SIZE(self), keepends
1995 );
1996}
1997
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001998/*[clinic input]
1999@classmethod
2000bytearray.fromhex
2001
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002002 string: unicode
2003 /
2004
2005Create a bytearray object from a string of hexadecimal numbers.
2006
2007Spaces between two numbers are accepted.
2008Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
2009[clinic start generated code]*/
2010
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002011static PyObject *
Serhiy Storchaka0855e702016-07-01 17:22:31 +03002012bytearray_fromhex_impl(PyTypeObject *type, PyObject *string)
2013/*[clinic end generated code: output=8f0f0b6d30fb3ba0 input=f033a16d1fb21f48]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002014{
Serhiy Storchaka0855e702016-07-01 17:22:31 +03002015 PyObject *result = _PyBytes_FromHex(string, type == &PyByteArray_Type);
2016 if (type != &PyByteArray_Type && result != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002017 Py_SETREF(result, PyObject_CallFunctionObjArgs((PyObject *)type,
2018 result, NULL));
Serhiy Storchaka0855e702016-07-01 17:22:31 +03002019 }
2020 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002021}
2022
Gregory P. Smith8cb65692015-04-25 23:22:26 +00002023PyDoc_STRVAR(hex__doc__,
2024"B.hex() -> string\n\
2025\n\
2026Create a string of hexadecimal numbers from a bytearray object.\n\
2027Example: bytearray([0xb9, 0x01, 0xef]).hex() -> 'b901ef'.");
2028
2029static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302030bytearray_hex(PyBytesObject *self, PyObject *Py_UNUSED(ignored))
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002031{
2032 char* argbuf = PyByteArray_AS_STRING(self);
2033 Py_ssize_t arglen = PyByteArray_GET_SIZE(self);
2034 return _Py_strhex(argbuf, arglen);
2035}
2036
2037static PyObject *
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002038_common_reduce(PyByteArrayObject *self, int proto)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002039{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002040 PyObject *dict;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002041 _Py_IDENTIFIER(__dict__);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002042 char *buf;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002043
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002044 dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002045 if (dict == NULL) {
2046 PyErr_Clear();
2047 dict = Py_None;
2048 Py_INCREF(dict);
2049 }
2050
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002051 buf = PyByteArray_AS_STRING(self);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002052 if (proto < 3) {
2053 /* use str based reduction for backwards compatibility with Python 2.x */
2054 PyObject *latin1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002055 if (Py_SIZE(self))
2056 latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002057 else
2058 latin1 = PyUnicode_FromString("");
2059 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
2060 }
2061 else {
2062 /* use more efficient byte based reduction */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002063 if (Py_SIZE(self)) {
2064 return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), dict);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002065 }
2066 else {
2067 return Py_BuildValue("(O()N)", Py_TYPE(self), dict);
2068 }
2069 }
2070}
2071
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002072/*[clinic input]
2073bytearray.__reduce__ as bytearray_reduce
2074
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002075Return state information for pickling.
2076[clinic start generated code]*/
2077
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002078static PyObject *
2079bytearray_reduce_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03002080/*[clinic end generated code: output=52bf304086464cab input=44b5737ada62dd3f]*/
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002081{
2082 return _common_reduce(self, 2);
2083}
2084
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002085/*[clinic input]
2086bytearray.__reduce_ex__ as bytearray_reduce_ex
2087
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002088 proto: int = 0
2089 /
2090
2091Return state information for pickling.
2092[clinic start generated code]*/
2093
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002094static PyObject *
2095bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03002096/*[clinic end generated code: output=52eac33377197520 input=f129bc1a1aa151ee]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002097{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002098 return _common_reduce(self, proto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002099}
2100
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002101/*[clinic input]
2102bytearray.__sizeof__ as bytearray_sizeof
2103
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002104Returns the size of the bytearray object in memory, in bytes.
2105[clinic start generated code]*/
2106
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002107static PyObject *
2108bytearray_sizeof_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03002109/*[clinic end generated code: output=738abdd17951c427 input=e27320fd98a4bc5a]*/
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002110{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002111 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002112
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002113 res = _PyObject_SIZE(Py_TYPE(self)) + self->ob_alloc * sizeof(char);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002114 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002115}
2116
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002117static PySequenceMethods bytearray_as_sequence = {
2118 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002119 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002120 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
2121 (ssizeargfunc)bytearray_getitem, /* sq_item */
2122 0, /* sq_slice */
2123 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
2124 0, /* sq_ass_slice */
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002125 (objobjproc)bytearray_contains, /* sq_contains */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002126 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
2127 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002128};
2129
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002130static PyMappingMethods bytearray_as_mapping = {
2131 (lenfunc)bytearray_length,
2132 (binaryfunc)bytearray_subscript,
2133 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002134};
2135
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002136static PyBufferProcs bytearray_as_buffer = {
2137 (getbufferproc)bytearray_getbuffer,
2138 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002139};
2140
2141static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002142bytearray_methods[] = {
2143 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002144 BYTEARRAY_REDUCE_METHODDEF
2145 BYTEARRAY_REDUCE_EX_METHODDEF
2146 BYTEARRAY_SIZEOF_METHODDEF
2147 BYTEARRAY_APPEND_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302148 {"capitalize", stringlib_capitalize, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002149 _Py_capitalize__doc__},
Tal Einatc929df32018-07-06 13:17:38 +03002150 STRINGLIB_CENTER_METHODDEF
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002151 BYTEARRAY_CLEAR_METHODDEF
2152 BYTEARRAY_COPY_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002153 {"count", (PyCFunction)bytearray_count, METH_VARARGS,
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03002154 _Py_count__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002155 BYTEARRAY_DECODE_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002156 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS,
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03002157 _Py_endswith__doc__},
Tal Einatc929df32018-07-06 13:17:38 +03002158 STRINGLIB_EXPANDTABS_METHODDEF
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002159 BYTEARRAY_EXTEND_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002160 {"find", (PyCFunction)bytearray_find, METH_VARARGS,
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03002161 _Py_find__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002162 BYTEARRAY_FROMHEX_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002163 {"hex", (PyCFunction)bytearray_hex, METH_NOARGS, hex__doc__},
2164 {"index", (PyCFunction)bytearray_index, METH_VARARGS, _Py_index__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002165 BYTEARRAY_INSERT_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302166 {"isalnum", stringlib_isalnum, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002167 _Py_isalnum__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302168 {"isalpha", stringlib_isalpha, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002169 _Py_isalpha__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302170 {"isascii", stringlib_isascii, METH_NOARGS,
INADA Naokia49ac992018-01-27 14:06:21 +09002171 _Py_isascii__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302172 {"isdigit", stringlib_isdigit, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002173 _Py_isdigit__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302174 {"islower", stringlib_islower, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002175 _Py_islower__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302176 {"isspace", stringlib_isspace, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002177 _Py_isspace__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302178 {"istitle", stringlib_istitle, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002179 _Py_istitle__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302180 {"isupper", stringlib_isupper, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002181 _Py_isupper__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002182 BYTEARRAY_JOIN_METHODDEF
Tal Einatc929df32018-07-06 13:17:38 +03002183 STRINGLIB_LJUST_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302184 {"lower", stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002185 BYTEARRAY_LSTRIP_METHODDEF
2186 BYTEARRAY_MAKETRANS_METHODDEF
2187 BYTEARRAY_PARTITION_METHODDEF
2188 BYTEARRAY_POP_METHODDEF
2189 BYTEARRAY_REMOVE_METHODDEF
2190 BYTEARRAY_REPLACE_METHODDEF
2191 BYTEARRAY_REVERSE_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002192 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, _Py_rfind__doc__},
2193 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, _Py_rindex__doc__},
Tal Einatc929df32018-07-06 13:17:38 +03002194 STRINGLIB_RJUST_METHODDEF
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002195 BYTEARRAY_RPARTITION_METHODDEF
2196 BYTEARRAY_RSPLIT_METHODDEF
2197 BYTEARRAY_RSTRIP_METHODDEF
2198 BYTEARRAY_SPLIT_METHODDEF
2199 BYTEARRAY_SPLITLINES_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002200 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03002201 _Py_startswith__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002202 BYTEARRAY_STRIP_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302203 {"swapcase", stringlib_swapcase, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002204 _Py_swapcase__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302205 {"title", stringlib_title, METH_NOARGS, _Py_title__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002206 BYTEARRAY_TRANSLATE_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302207 {"upper", stringlib_upper, METH_NOARGS, _Py_upper__doc__},
Tal Einatc929df32018-07-06 13:17:38 +03002208 STRINGLIB_ZFILL_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002209 {NULL}
2210};
2211
Ethan Furmanb95b5612015-01-23 20:05:18 -08002212static PyObject *
2213bytearray_mod(PyObject *v, PyObject *w)
2214{
2215 if (!PyByteArray_Check(v))
2216 Py_RETURN_NOTIMPLEMENTED;
Berker Peksag43de36d2016-04-16 01:20:47 +03002217 return _PyBytes_FormatEx(PyByteArray_AS_STRING(v), PyByteArray_GET_SIZE(v), w, 1);
Ethan Furmanb95b5612015-01-23 20:05:18 -08002218}
2219
2220static PyNumberMethods bytearray_as_number = {
2221 0, /*nb_add*/
2222 0, /*nb_subtract*/
2223 0, /*nb_multiply*/
2224 bytearray_mod, /*nb_remainder*/
2225};
2226
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002227PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002228"bytearray(iterable_of_ints) -> bytearray\n\
2229bytearray(string, encoding[, errors]) -> bytearray\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01002230bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
2231bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
2232bytearray() -> empty bytes array\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002233\n\
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03002234Construct a mutable bytearray object from:\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002235 - an iterable yielding integers in range(256)\n\
2236 - a text string encoded using the specified encoding\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01002237 - a bytes or a buffer object\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002238 - any object implementing the buffer API.\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01002239 - an integer");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002240
2241
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002242static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002243
2244PyTypeObject PyByteArray_Type = {
2245 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2246 "bytearray",
2247 sizeof(PyByteArrayObject),
2248 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002249 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002250 0, /* tp_print */
2251 0, /* tp_getattr */
2252 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002253 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002254 (reprfunc)bytearray_repr, /* tp_repr */
Ethan Furmanb95b5612015-01-23 20:05:18 -08002255 &bytearray_as_number, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002256 &bytearray_as_sequence, /* tp_as_sequence */
2257 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002258 0, /* tp_hash */
2259 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002260 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002261 PyObject_GenericGetAttr, /* tp_getattro */
2262 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002263 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002264 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002265 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002266 0, /* tp_traverse */
2267 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002268 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002269 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002270 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002271 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002272 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002273 0, /* tp_members */
2274 0, /* tp_getset */
2275 0, /* tp_base */
2276 0, /* tp_dict */
2277 0, /* tp_descr_get */
2278 0, /* tp_descr_set */
2279 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002280 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002281 PyType_GenericAlloc, /* tp_alloc */
2282 PyType_GenericNew, /* tp_new */
2283 PyObject_Del, /* tp_free */
2284};
2285
2286/*********************** Bytes Iterator ****************************/
2287
2288typedef struct {
2289 PyObject_HEAD
2290 Py_ssize_t it_index;
2291 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
2292} bytesiterobject;
2293
2294static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002295bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002296{
2297 _PyObject_GC_UNTRACK(it);
2298 Py_XDECREF(it->it_seq);
2299 PyObject_GC_Del(it);
2300}
2301
2302static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002303bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002304{
2305 Py_VISIT(it->it_seq);
2306 return 0;
2307}
2308
2309static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002310bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002311{
2312 PyByteArrayObject *seq;
2313 PyObject *item;
2314
2315 assert(it != NULL);
2316 seq = it->it_seq;
2317 if (seq == NULL)
2318 return NULL;
2319 assert(PyByteArray_Check(seq));
2320
2321 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
2322 item = PyLong_FromLong(
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002323 (unsigned char)PyByteArray_AS_STRING(seq)[it->it_index]);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002324 if (item != NULL)
2325 ++it->it_index;
2326 return item;
2327 }
2328
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002329 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002330 Py_DECREF(seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002331 return NULL;
2332}
2333
2334static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302335bytearrayiter_length_hint(bytesiterobject *it, PyObject *Py_UNUSED(ignored))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002336{
2337 Py_ssize_t len = 0;
Serhiy Storchakaaf658722016-07-03 14:41:36 +03002338 if (it->it_seq) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002339 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
Serhiy Storchakaaf658722016-07-03 14:41:36 +03002340 if (len < 0) {
2341 len = 0;
2342 }
2343 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002344 return PyLong_FromSsize_t(len);
2345}
2346
2347PyDoc_STRVAR(length_hint_doc,
2348 "Private method returning an estimate of len(list(it)).");
2349
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002350static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302351bytearrayiter_reduce(bytesiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002352{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02002353 _Py_IDENTIFIER(iter);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002354 if (it->it_seq != NULL) {
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02002355 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002356 it->it_seq, it->it_index);
2357 } else {
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02002358 return Py_BuildValue("N(())", _PyEval_GetBuiltinId(&PyId_iter));
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002359 }
2360}
2361
2362static PyObject *
2363bytearrayiter_setstate(bytesiterobject *it, PyObject *state)
2364{
2365 Py_ssize_t index = PyLong_AsSsize_t(state);
2366 if (index == -1 && PyErr_Occurred())
2367 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00002368 if (it->it_seq != NULL) {
2369 if (index < 0)
2370 index = 0;
2371 else if (index > PyByteArray_GET_SIZE(it->it_seq))
2372 index = PyByteArray_GET_SIZE(it->it_seq); /* iterator exhausted */
2373 it->it_index = index;
2374 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002375 Py_RETURN_NONE;
2376}
2377
2378PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2379
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002380static PyMethodDef bytearrayiter_methods[] = {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002381 {"__length_hint__", (PyCFunction)bytearrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002382 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002383 {"__reduce__", (PyCFunction)bytearrayiter_reduce, METH_NOARGS,
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002384 bytearray_reduce__doc__},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002385 {"__setstate__", (PyCFunction)bytearrayiter_setstate, METH_O,
2386 setstate_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002387 {NULL, NULL} /* sentinel */
2388};
2389
2390PyTypeObject PyByteArrayIter_Type = {
2391 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2392 "bytearray_iterator", /* tp_name */
2393 sizeof(bytesiterobject), /* tp_basicsize */
2394 0, /* tp_itemsize */
2395 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002396 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002397 0, /* tp_print */
2398 0, /* tp_getattr */
2399 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002400 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002401 0, /* tp_repr */
2402 0, /* tp_as_number */
2403 0, /* tp_as_sequence */
2404 0, /* tp_as_mapping */
2405 0, /* tp_hash */
2406 0, /* tp_call */
2407 0, /* tp_str */
2408 PyObject_GenericGetAttr, /* tp_getattro */
2409 0, /* tp_setattro */
2410 0, /* tp_as_buffer */
2411 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2412 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002413 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002414 0, /* tp_clear */
2415 0, /* tp_richcompare */
2416 0, /* tp_weaklistoffset */
2417 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002418 (iternextfunc)bytearrayiter_next, /* tp_iternext */
2419 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002420 0,
2421};
2422
2423static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002424bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002425{
2426 bytesiterobject *it;
2427
2428 if (!PyByteArray_Check(seq)) {
2429 PyErr_BadInternalCall();
2430 return NULL;
2431 }
2432 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
2433 if (it == NULL)
2434 return NULL;
2435 it->it_index = 0;
2436 Py_INCREF(seq);
2437 it->it_seq = (PyByteArrayObject *)seq;
2438 _PyObject_GC_TRACK(it);
2439 return (PyObject *)it;
2440}