blob: 7cb2b1478cf9c113e6f1ab0f486b3b8bbf1c54db [file] [log] [blame]
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001/* PyByteArray (bytearray) implementation */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02005#include "pycore_abstract.h" // _PyIndex_Check()
Victor Stinner45876a92020-02-12 22:32:34 +01006#include "pycore_bytes_methods.h"
Victor Stinnerbcda8f12018-11-21 22:27:47 +01007#include "pycore_object.h"
Ethan Furmanb95b5612015-01-23 20:05:18 -08008#include "bytesobject.h"
Gregory P. Smith8cb65692015-04-25 23:22:26 +00009#include "pystrhex.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +000010
Martin v. Löwis7252a6e2014-07-27 16:25:09 +020011/*[clinic input]
12class bytearray "PyByteArrayObject *" "&PyByteArray_Type"
13[clinic start generated code]*/
14/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5535b77c37a119e0]*/
15
Serhiy Storchaka2ad93822020-12-03 12:46:16 +020016/* For PyByteArray_AS_STRING(). */
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000017char _PyByteArray_empty_string[] = "";
Christian Heimes2c9c7a52008-05-26 13:42:13 +000018
Christian Heimes2c9c7a52008-05-26 13:42:13 +000019/* Helpers */
20
21static int
22_getbytevalue(PyObject* arg, int *value)
23{
Serhiy Storchakae67f7db2020-06-29 22:36:41 +030024 int overflow;
25 long face_value = PyLong_AsLongAndOverflow(arg, &overflow);
Christian Heimes2c9c7a52008-05-26 13:42:13 +000026
Serhiy Storchakae67f7db2020-06-29 22:36:41 +030027 if (face_value == -1 && PyErr_Occurred()) {
28 *value = -1;
29 return 0;
Georg Brandl9a54d7c2008-07-16 23:15:30 +000030 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +000031 if (face_value < 0 || face_value >= 256) {
Serhiy Storchakae67f7db2020-06-29 22:36:41 +030032 /* this includes an overflow in converting to C long */
Georg Brandl9a54d7c2008-07-16 23:15:30 +000033 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
Mark Dickinson10de93a2010-07-09 19:25:48 +000034 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000035 return 0;
36 }
37
38 *value = face_value;
39 return 1;
40}
41
42static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +000043bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000044{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000045 void *ptr;
46 if (view == NULL) {
Stefan Krah5178d912015-02-03 16:57:21 +010047 PyErr_SetString(PyExc_BufferError,
48 "bytearray_getbuffer: view==NULL argument is obsolete");
49 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000050 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000051 ptr = (void *) PyByteArray_AS_STRING(obj);
Stefan Krah5178d912015-02-03 16:57:21 +010052 /* cannot fail if view != NULL and readonly == 0 */
53 (void)PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
54 obj->ob_exports++;
55 return 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000056}
57
58static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +000059bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000060{
61 obj->ob_exports--;
62}
63
Antoine Pitrou5504e892008-12-06 21:27:53 +000064static int
65_canresize(PyByteArrayObject *self)
66{
67 if (self->ob_exports > 0) {
68 PyErr_SetString(PyExc_BufferError,
69 "Existing exports of data: object cannot be re-sized");
70 return 0;
71 }
72 return 1;
73}
74
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030075#include "clinic/bytearrayobject.c.h"
76
Christian Heimes2c9c7a52008-05-26 13:42:13 +000077/* Direct API functions */
78
79PyObject *
80PyByteArray_FromObject(PyObject *input)
81{
Petr Viktorinffd97532020-02-11 17:46:57 +010082 return PyObject_CallOneArg((PyObject *)&PyByteArray_Type, input);
Christian Heimes2c9c7a52008-05-26 13:42:13 +000083}
84
Serhiy Storchakaa2314282017-10-29 02:11:54 +030085static PyObject *
86_PyByteArray_FromBufferObject(PyObject *obj)
87{
88 PyObject *result;
89 Py_buffer view;
90
91 if (PyObject_GetBuffer(obj, &view, PyBUF_FULL_RO) < 0) {
92 return NULL;
93 }
94 result = PyByteArray_FromStringAndSize(NULL, view.len);
95 if (result != NULL &&
96 PyBuffer_ToContiguous(PyByteArray_AS_STRING(result),
97 &view, view.len, 'C') < 0)
98 {
99 Py_CLEAR(result);
100 }
101 PyBuffer_Release(&view);
102 return result;
103}
104
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000105PyObject *
106PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
107{
108 PyByteArrayObject *new;
109 Py_ssize_t alloc;
110
111 if (size < 0) {
112 PyErr_SetString(PyExc_SystemError,
113 "Negative size passed to PyByteArray_FromStringAndSize");
114 return NULL;
115 }
116
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000117 /* Prevent buffer overflow when setting alloc to size+1. */
118 if (size == PY_SSIZE_T_MAX) {
119 return PyErr_NoMemory();
120 }
121
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000122 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
123 if (new == NULL)
124 return NULL;
125
126 if (size == 0) {
127 new->ob_bytes = NULL;
128 alloc = 0;
129 }
130 else {
131 alloc = size + 1;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100132 new->ob_bytes = PyObject_Malloc(alloc);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000133 if (new->ob_bytes == NULL) {
134 Py_DECREF(new);
135 return PyErr_NoMemory();
136 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +0000137 if (bytes != NULL && size > 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000138 memcpy(new->ob_bytes, bytes, size);
139 new->ob_bytes[size] = '\0'; /* Trailing null byte */
140 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100141 Py_SET_SIZE(new, size);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000142 new->ob_alloc = alloc;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200143 new->ob_start = new->ob_bytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000144 new->ob_exports = 0;
145
146 return (PyObject *)new;
147}
148
149Py_ssize_t
150PyByteArray_Size(PyObject *self)
151{
152 assert(self != NULL);
153 assert(PyByteArray_Check(self));
154
155 return PyByteArray_GET_SIZE(self);
156}
157
158char *
159PyByteArray_AsString(PyObject *self)
160{
161 assert(self != NULL);
162 assert(PyByteArray_Check(self));
163
164 return PyByteArray_AS_STRING(self);
165}
166
167int
Antoine Pitroucc231542014-11-02 18:40:09 +0100168PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000169{
170 void *sval;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200171 PyByteArrayObject *obj = ((PyByteArrayObject *)self);
Antoine Pitroucc231542014-11-02 18:40:09 +0100172 /* All computations are done unsigned to avoid integer overflows
173 (see issue #22335). */
174 size_t alloc = (size_t) obj->ob_alloc;
175 size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes);
176 size_t size = (size_t) requested_size;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000177
178 assert(self != NULL);
179 assert(PyByteArray_Check(self));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200180 assert(logical_offset <= alloc);
Antoine Pitroucc231542014-11-02 18:40:09 +0100181 assert(requested_size >= 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000182
Antoine Pitroucc231542014-11-02 18:40:09 +0100183 if (requested_size == Py_SIZE(self)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000184 return 0;
185 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200186 if (!_canresize(obj)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000187 return -1;
188 }
189
Antoine Pitrou25454112015-05-19 20:52:27 +0200190 if (size + logical_offset + 1 <= alloc) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200191 /* Current buffer is large enough to host the requested size,
192 decide on a strategy. */
193 if (size < alloc / 2) {
194 /* Major downsize; resize down to exact size */
195 alloc = size + 1;
196 }
197 else {
198 /* Minor downsize; quick exit */
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100199 Py_SET_SIZE(self, size);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200200 PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */
201 return 0;
202 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000203 }
204 else {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200205 /* Need growing, decide on a strategy */
206 if (size <= alloc * 1.125) {
207 /* Moderate upsize; overallocate similar to list_resize() */
208 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
209 }
210 else {
211 /* Major upsize; resize up to exact size */
212 alloc = size + 1;
213 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000214 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100215 if (alloc > PY_SSIZE_T_MAX) {
216 PyErr_NoMemory();
217 return -1;
218 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000219
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200220 if (logical_offset > 0) {
221 sval = PyObject_Malloc(alloc);
222 if (sval == NULL) {
223 PyErr_NoMemory();
224 return -1;
225 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100226 memcpy(sval, PyByteArray_AS_STRING(self),
Stefan Krahdce65022017-08-25 20:12:05 +0200227 Py_MIN((size_t)requested_size, (size_t)Py_SIZE(self)));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200228 PyObject_Free(obj->ob_bytes);
229 }
230 else {
231 sval = PyObject_Realloc(obj->ob_bytes, alloc);
232 if (sval == NULL) {
233 PyErr_NoMemory();
234 return -1;
235 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000236 }
237
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200238 obj->ob_bytes = obj->ob_start = sval;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100239 Py_SET_SIZE(self, size);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200240 obj->ob_alloc = alloc;
241 obj->ob_bytes[size] = '\0'; /* Trailing null byte */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000242
243 return 0;
244}
245
246PyObject *
247PyByteArray_Concat(PyObject *a, PyObject *b)
248{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000249 Py_buffer va, vb;
250 PyByteArrayObject *result = NULL;
251
252 va.len = -1;
253 vb.len = -1;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200254 if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 ||
255 PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000256 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
Serhiy Storchaka6b5a9ec2017-03-19 19:47:02 +0200257 Py_TYPE(b)->tp_name, Py_TYPE(a)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000258 goto done;
259 }
260
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300261 if (va.len > PY_SSIZE_T_MAX - vb.len) {
262 PyErr_NoMemory();
263 goto done;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000264 }
265
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300266 result = (PyByteArrayObject *) \
267 PyByteArray_FromStringAndSize(NULL, va.len + vb.len);
Serhiy Storchaka2ad93822020-12-03 12:46:16 +0200268 // result->ob_bytes is NULL if result is an empty bytearray:
stratakis61fc23c2020-07-08 22:39:41 +0200269 // if va.len + vb.len equals zero.
270 if (result != NULL && result->ob_bytes != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000271 memcpy(result->ob_bytes, va.buf, va.len);
272 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
273 }
274
275 done:
276 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000277 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000278 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000279 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000280 return (PyObject *)result;
281}
282
283/* Functions stuffed into the type object */
284
285static Py_ssize_t
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000286bytearray_length(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000287{
288 return Py_SIZE(self);
289}
290
291static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000292bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000293{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000294 Py_ssize_t size;
295 Py_buffer vo;
296
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200297 if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000298 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
299 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
300 return NULL;
301 }
302
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300303 size = Py_SIZE(self);
304 if (size > PY_SSIZE_T_MAX - vo.len) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000305 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000306 return PyErr_NoMemory();
307 }
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300308 if (PyByteArray_Resize((PyObject *)self, size + vo.len) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000309 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000310 return NULL;
311 }
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300312 memcpy(PyByteArray_AS_STRING(self) + size, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000313 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000314 Py_INCREF(self);
315 return (PyObject *)self;
316}
317
318static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000319bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000320{
321 PyByteArrayObject *result;
322 Py_ssize_t mysize;
323 Py_ssize_t size;
324
325 if (count < 0)
326 count = 0;
327 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000328 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000329 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000330 size = mysize * count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000331 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
332 if (result != NULL && size != 0) {
333 if (mysize == 1)
334 memset(result->ob_bytes, self->ob_bytes[0], size);
335 else {
336 Py_ssize_t i;
337 for (i = 0; i < count; i++)
338 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
339 }
340 }
341 return (PyObject *)result;
342}
343
344static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000345bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000346{
347 Py_ssize_t mysize;
348 Py_ssize_t size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200349 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000350
351 if (count < 0)
352 count = 0;
353 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000354 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000355 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000356 size = mysize * count;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200357 if (PyByteArray_Resize((PyObject *)self, size) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000358 return NULL;
359
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200360 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000361 if (mysize == 1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200362 memset(buf, buf[0], size);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000363 else {
364 Py_ssize_t i;
365 for (i = 1; i < count; i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200366 memcpy(buf + i*mysize, buf, mysize);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000367 }
368
369 Py_INCREF(self);
370 return (PyObject *)self;
371}
372
373static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000374bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000375{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000376 if (i < 0 || i >= Py_SIZE(self)) {
377 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
378 return NULL;
379 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200380 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000381}
382
383static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000384bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000385{
Victor Stinnera15e2602020-04-08 02:01:56 +0200386 if (_PyIndex_Check(index)) {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000387 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000388
389 if (i == -1 && PyErr_Occurred())
390 return NULL;
391
392 if (i < 0)
393 i += PyByteArray_GET_SIZE(self);
394
395 if (i < 0 || i >= Py_SIZE(self)) {
396 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
397 return NULL;
398 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200399 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000400 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000401 else if (PySlice_Check(index)) {
Zackery Spytz14514d92019-05-17 01:13:03 -0600402 Py_ssize_t start, stop, step, slicelength, i;
403 size_t cur;
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300404 if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000405 return NULL;
406 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300407 slicelength = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self),
408 &start, &stop, step);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000409
410 if (slicelength <= 0)
411 return PyByteArray_FromStringAndSize("", 0);
412 else if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200413 return PyByteArray_FromStringAndSize(
414 PyByteArray_AS_STRING(self) + start, slicelength);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000415 }
416 else {
417 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000418 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000419 PyObject *result;
420
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000421 result = PyByteArray_FromStringAndSize(NULL, slicelength);
422 if (result == NULL)
423 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000424
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000425 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000426 for (cur = start, i = 0; i < slicelength;
427 cur += step, i++) {
428 result_buf[i] = source_buf[cur];
429 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000430 return result;
431 }
432 }
433 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400434 PyErr_Format(PyExc_TypeError,
435 "bytearray indices must be integers or slices, not %.200s",
436 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000437 return NULL;
438 }
439}
440
441static int
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200442bytearray_setslice_linear(PyByteArrayObject *self,
443 Py_ssize_t lo, Py_ssize_t hi,
444 char *bytes, Py_ssize_t bytes_len)
445{
446 Py_ssize_t avail = hi - lo;
447 char *buf = PyByteArray_AS_STRING(self);
448 Py_ssize_t growth = bytes_len - avail;
Victor Stinner84557232013-11-21 12:29:51 +0100449 int res = 0;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200450 assert(avail >= 0);
451
Victor Stinner84557232013-11-21 12:29:51 +0100452 if (growth < 0) {
453 if (!_canresize(self))
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200454 return -1;
Victor Stinner84557232013-11-21 12:29:51 +0100455
456 if (lo == 0) {
457 /* Shrink the buffer by advancing its logical start */
458 self->ob_start -= growth;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200459 /*
Victor Stinner84557232013-11-21 12:29:51 +0100460 0 lo hi old_size
461 | |<----avail----->|<-----tail------>|
462 | |<-bytes_len->|<-----tail------>|
463 0 new_lo new_hi new_size
464 */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200465 }
Victor Stinner84557232013-11-21 12:29:51 +0100466 else {
467 /*
468 0 lo hi old_size
469 | |<----avail----->|<-----tomove------>|
470 | |<-bytes_len->|<-----tomove------>|
471 0 lo new_hi new_size
472 */
473 memmove(buf + lo + bytes_len, buf + hi,
474 Py_SIZE(self) - hi);
475 }
476 if (PyByteArray_Resize((PyObject *)self,
477 Py_SIZE(self) + growth) < 0) {
478 /* Issue #19578: Handling the memory allocation failure here is
479 tricky here because the bytearray object has already been
480 modified. Depending on growth and lo, the behaviour is
481 different.
482
483 If growth < 0 and lo != 0, the operation is completed, but a
484 MemoryError is still raised and the memory block is not
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700485 shrunk. Otherwise, the bytearray is restored in its previous
Victor Stinner84557232013-11-21 12:29:51 +0100486 state and a MemoryError is raised. */
487 if (lo == 0) {
488 self->ob_start += growth;
489 return -1;
490 }
491 /* memmove() removed bytes, the bytearray object cannot be
492 restored in its previous state. */
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100493 Py_SET_SIZE(self, Py_SIZE(self) + growth);
Victor Stinner84557232013-11-21 12:29:51 +0100494 res = -1;
495 }
496 buf = PyByteArray_AS_STRING(self);
497 }
498 else if (growth > 0) {
499 if (Py_SIZE(self) > (Py_ssize_t)PY_SSIZE_T_MAX - growth) {
500 PyErr_NoMemory();
501 return -1;
502 }
503
504 if (PyByteArray_Resize((PyObject *)self,
505 Py_SIZE(self) + growth) < 0) {
506 return -1;
507 }
508 buf = PyByteArray_AS_STRING(self);
509 /* Make the place for the additional bytes */
510 /*
511 0 lo hi old_size
512 | |<-avail->|<-----tomove------>|
513 | |<---bytes_len-->|<-----tomove------>|
514 0 lo new_hi new_size
515 */
516 memmove(buf + lo + bytes_len, buf + hi,
517 Py_SIZE(self) - lo - bytes_len);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200518 }
519
520 if (bytes_len > 0)
521 memcpy(buf + lo, bytes, bytes_len);
Victor Stinner84557232013-11-21 12:29:51 +0100522 return res;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200523}
524
525static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000526bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000527 PyObject *values)
528{
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200529 Py_ssize_t needed;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000530 void *bytes;
531 Py_buffer vbytes;
532 int res = 0;
533
534 vbytes.len = -1;
535 if (values == (PyObject *)self) {
536 /* Make a copy and call this function recursively */
537 int err;
Serhiy Storchakaa2314282017-10-29 02:11:54 +0300538 values = PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(values),
539 PyByteArray_GET_SIZE(values));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000540 if (values == NULL)
541 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000542 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000543 Py_DECREF(values);
544 return err;
545 }
546 if (values == NULL) {
547 /* del b[lo:hi] */
548 bytes = NULL;
549 needed = 0;
550 }
551 else {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200552 if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) {
553 PyErr_Format(PyExc_TypeError,
554 "can't set bytearray slice from %.100s",
555 Py_TYPE(values)->tp_name);
556 return -1;
557 }
558 needed = vbytes.len;
559 bytes = vbytes.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000560 }
561
562 if (lo < 0)
563 lo = 0;
564 if (hi < lo)
565 hi = lo;
566 if (hi > Py_SIZE(self))
567 hi = Py_SIZE(self);
568
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200569 res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000570 if (vbytes.len != -1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200571 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000572 return res;
573}
574
575static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000576bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000577{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000578 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000579
580 if (i < 0)
581 i += Py_SIZE(self);
582
583 if (i < 0 || i >= Py_SIZE(self)) {
584 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
585 return -1;
586 }
587
588 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000589 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000590
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000591 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000592 return -1;
593
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200594 PyByteArray_AS_STRING(self)[i] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000595 return 0;
596}
597
598static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000599bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000600{
601 Py_ssize_t start, stop, step, slicelen, needed;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200602 char *buf, *bytes;
603 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000604
Victor Stinnera15e2602020-04-08 02:01:56 +0200605 if (_PyIndex_Check(index)) {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000606 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000607
608 if (i == -1 && PyErr_Occurred())
609 return -1;
610
611 if (i < 0)
612 i += PyByteArray_GET_SIZE(self);
613
614 if (i < 0 || i >= Py_SIZE(self)) {
615 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
616 return -1;
617 }
618
619 if (values == NULL) {
620 /* Fall through to slice assignment */
621 start = i;
622 stop = i + 1;
623 step = 1;
624 slicelen = 1;
625 }
626 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000627 int ival;
628 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000629 return -1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200630 buf[i] = (char)ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000631 return 0;
632 }
633 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000634 else if (PySlice_Check(index)) {
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300635 if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000636 return -1;
637 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300638 slicelen = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self), &start,
639 &stop, step);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000640 }
641 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400642 PyErr_Format(PyExc_TypeError,
643 "bytearray indices must be integers or slices, not %.200s",
644 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000645 return -1;
646 }
647
648 if (values == NULL) {
649 bytes = NULL;
650 needed = 0;
651 }
652 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
Christian Heimes6d26ade2012-11-03 23:07:59 +0100653 int err;
Ezio Melottic64bcbe2012-11-03 21:19:06 +0200654 if (PyNumber_Check(values) || PyUnicode_Check(values)) {
655 PyErr_SetString(PyExc_TypeError,
656 "can assign only bytes, buffers, or iterables "
657 "of ints in range(0, 256)");
658 return -1;
659 }
Georg Brandlf3fa5682010-12-04 17:09:30 +0000660 /* Make a copy and call this function recursively */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000661 values = PyByteArray_FromObject(values);
662 if (values == NULL)
663 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000664 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000665 Py_DECREF(values);
666 return err;
667 }
668 else {
669 assert(PyByteArray_Check(values));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200670 bytes = PyByteArray_AS_STRING(values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000671 needed = Py_SIZE(values);
672 }
673 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
674 if ((step < 0 && start < stop) ||
675 (step > 0 && start > stop))
676 stop = start;
677 if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200678 return bytearray_setslice_linear(self, start, stop, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000679 }
680 else {
681 if (needed == 0) {
682 /* Delete slice */
Mark Dickinsonbc099642010-01-29 17:27:24 +0000683 size_t cur;
684 Py_ssize_t i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000685
Antoine Pitrou5504e892008-12-06 21:27:53 +0000686 if (!_canresize(self))
687 return -1;
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000688
689 if (slicelen == 0)
690 /* Nothing to do here. */
691 return 0;
692
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000693 if (step < 0) {
694 stop = start + 1;
695 start = stop + step * (slicelen - 1) - 1;
696 step = -step;
697 }
698 for (cur = start, i = 0;
699 i < slicelen; cur += step, i++) {
700 Py_ssize_t lim = step - 1;
701
Mark Dickinson66f575b2010-02-14 12:53:32 +0000702 if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000703 lim = PyByteArray_GET_SIZE(self) - cur - 1;
704
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200705 memmove(buf + cur - i,
706 buf + cur + 1, lim);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000707 }
708 /* Move the tail of the bytes, in one chunk */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000709 cur = start + (size_t)slicelen*step;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000710 if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200711 memmove(buf + cur - slicelen,
712 buf + cur,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000713 PyByteArray_GET_SIZE(self) - cur);
714 }
715 if (PyByteArray_Resize((PyObject *)self,
716 PyByteArray_GET_SIZE(self) - slicelen) < 0)
717 return -1;
718
719 return 0;
720 }
721 else {
722 /* Assign slice */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000723 Py_ssize_t i;
724 size_t cur;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000725
726 if (needed != slicelen) {
727 PyErr_Format(PyExc_ValueError,
728 "attempt to assign bytes of size %zd "
729 "to extended slice of size %zd",
730 needed, slicelen);
731 return -1;
732 }
733 for (cur = start, i = 0; i < slicelen; cur += step, i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200734 buf[cur] = bytes[i];
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000735 return 0;
736 }
737 }
738}
739
Serhiy Storchaka12f43342020-07-20 15:53:55 +0300740/*[clinic input]
741bytearray.__init__
742
743 source as arg: object = NULL
744 encoding: str = NULL
745 errors: str = NULL
746
747[clinic start generated code]*/
748
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000749static int
Serhiy Storchaka12f43342020-07-20 15:53:55 +0300750bytearray___init___impl(PyByteArrayObject *self, PyObject *arg,
751 const char *encoding, const char *errors)
752/*[clinic end generated code: output=4ce1304649c2f8b3 input=1141a7122eefd7b9]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000753{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000754 Py_ssize_t count;
755 PyObject *it;
756 PyObject *(*iternext)(PyObject *);
757
758 if (Py_SIZE(self) != 0) {
759 /* Empty previous contents (yes, do this first of all!) */
760 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
761 return -1;
762 }
763
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000764 /* Make a quick exit if no first argument */
765 if (arg == NULL) {
766 if (encoding != NULL || errors != NULL) {
767 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300768 encoding != NULL ?
769 "encoding without a string argument" :
770 "errors without a string argument");
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000771 return -1;
772 }
773 return 0;
774 }
775
776 if (PyUnicode_Check(arg)) {
777 /* Encode via the codec registry */
778 PyObject *encoded, *new;
779 if (encoding == NULL) {
780 PyErr_SetString(PyExc_TypeError,
781 "string argument without an encoding");
782 return -1;
783 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000784 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000785 if (encoded == NULL)
786 return -1;
787 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000788 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000789 Py_DECREF(encoded);
790 if (new == NULL)
791 return -1;
792 Py_DECREF(new);
793 return 0;
794 }
795
796 /* If it's not unicode, there can't be encoding or errors */
797 if (encoding != NULL || errors != NULL) {
798 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300799 encoding != NULL ?
800 "encoding without a string argument" :
801 "errors without a string argument");
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000802 return -1;
803 }
804
805 /* Is it an int? */
Victor Stinnera15e2602020-04-08 02:01:56 +0200806 if (_PyIndex_Check(arg)) {
Serhiy Storchakaeb249882016-08-15 09:46:07 +0300807 count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
808 if (count == -1 && PyErr_Occurred()) {
Serhiy Storchakae8904212018-10-15 00:02:57 +0300809 if (!PyErr_ExceptionMatches(PyExc_TypeError))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000810 return -1;
INADA Naokia634e232017-01-06 17:32:01 +0900811 PyErr_Clear(); /* fall through */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000812 }
INADA Naokia634e232017-01-06 17:32:01 +0900813 else {
814 if (count < 0) {
815 PyErr_SetString(PyExc_ValueError, "negative count");
816 return -1;
817 }
818 if (count > 0) {
819 if (PyByteArray_Resize((PyObject *)self, count))
820 return -1;
821 memset(PyByteArray_AS_STRING(self), 0, count);
822 }
823 return 0;
824 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000825 }
826
827 /* Use the buffer API */
828 if (PyObject_CheckBuffer(arg)) {
829 Py_ssize_t size;
830 Py_buffer view;
831 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
832 return -1;
833 size = view.len;
834 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200835 if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
836 &view, size, 'C') < 0)
Stefan Krah7d12d9d2012-07-28 12:25:55 +0200837 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000838 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000839 return 0;
840 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000841 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000842 return -1;
843 }
844
845 /* XXX Optimize this if the arguments is a list, tuple */
846
847 /* Get the iterator */
848 it = PyObject_GetIter(arg);
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300849 if (it == NULL) {
850 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
851 PyErr_Format(PyExc_TypeError,
852 "cannot convert '%.200s' object to bytearray",
Victor Stinner58ac7002020-02-07 03:04:21 +0100853 Py_TYPE(arg)->tp_name);
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300854 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000855 return -1;
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +0300856 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000857 iternext = *Py_TYPE(it)->tp_iternext;
858
859 /* Run the iterator to exhaustion */
860 for (;;) {
861 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000862 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000863
864 /* Get the next item */
865 item = iternext(it);
866 if (item == NULL) {
867 if (PyErr_Occurred()) {
868 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
869 goto error;
870 PyErr_Clear();
871 }
872 break;
873 }
874
875 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000876 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000877 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000878 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000879 goto error;
880
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000881 /* Append the byte */
Serhiy Storchaka7b6e3b92015-06-29 21:14:06 +0300882 if (Py_SIZE(self) + 1 < self->ob_alloc) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100883 Py_SET_SIZE(self, Py_SIZE(self) + 1);
Serhiy Storchaka7b6e3b92015-06-29 21:14:06 +0300884 PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0';
885 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000886 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
887 goto error;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200888 PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000889 }
890
891 /* Clean up and return success */
892 Py_DECREF(it);
893 return 0;
894
895 error:
896 /* Error handling when it != NULL */
897 Py_DECREF(it);
898 return -1;
899}
900
901/* Mostly copied from string_repr, but without the
902 "smart quote" functionality. */
903static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000904bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000905{
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300906 const char *className = _PyType_Name(Py_TYPE(self));
907 const char *quote_prefix = "(b";
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000908 const char *quote_postfix = ")";
909 Py_ssize_t length = Py_SIZE(self);
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300910 /* 6 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */
911 Py_ssize_t newsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000912 PyObject *v;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200913 Py_ssize_t i;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200914 char *bytes;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200915 char c;
916 char *p;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200917 int quote;
918 char *test, *start;
919 char *buffer;
920
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300921 newsize = strlen(className);
922 if (length > (PY_SSIZE_T_MAX - 6 - newsize) / 4) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000923 PyErr_SetString(PyExc_OverflowError,
924 "bytearray object is too large to make repr");
925 return NULL;
926 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200927
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300928 newsize += 6 + length * 4;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100929 buffer = PyObject_Malloc(newsize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200930 if (buffer == NULL) {
931 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000932 return NULL;
933 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000934
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200935 /* Figure out which quote to use; single is preferred */
936 quote = '\'';
937 start = PyByteArray_AS_STRING(self);
938 for (test = start; test < start+length; ++test) {
939 if (*test == '"') {
940 quote = '\''; /* back to single */
941 break;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000942 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200943 else if (*test == '\'')
944 quote = '"';
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000945 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200946
947 p = buffer;
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300948 while (*className)
949 *p++ = *className++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200950 while (*quote_prefix)
951 *p++ = *quote_prefix++;
952 *p++ = quote;
953
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200954 bytes = PyByteArray_AS_STRING(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200955 for (i = 0; i < length; i++) {
956 /* There's at least enough room for a hex escape
957 and a closing quote. */
958 assert(newsize - (p - buffer) >= 5);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200959 c = bytes[i];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200960 if (c == '\'' || c == '\\')
961 *p++ = '\\', *p++ = c;
962 else if (c == '\t')
963 *p++ = '\\', *p++ = 't';
964 else if (c == '\n')
965 *p++ = '\\', *p++ = 'n';
966 else if (c == '\r')
967 *p++ = '\\', *p++ = 'r';
968 else if (c == 0)
969 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
970 else if (c < ' ' || c >= 0x7f) {
971 *p++ = '\\';
972 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +0200973 *p++ = Py_hexdigits[(c & 0xf0) >> 4];
974 *p++ = Py_hexdigits[c & 0xf];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975 }
976 else
977 *p++ = c;
978 }
979 assert(newsize - (p - buffer) >= 1);
980 *p++ = quote;
981 while (*quote_postfix) {
982 *p++ = *quote_postfix++;
983 }
984
Serhiy Storchakab3a77962017-09-21 14:24:13 +0300985 v = PyUnicode_FromStringAndSize(buffer, p - buffer);
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100986 PyObject_Free(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987 return v;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000988}
989
990static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000991bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000992{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200993 if (_Py_GetConfig()->bytes_warning) {
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200994 if (PyErr_WarnEx(PyExc_BytesWarning,
995 "str() on a bytearray instance", 1)) {
996 return NULL;
Alexander Belopolskyf0f45142010-08-11 17:31:17 +0000997 }
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200998 }
999 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001000}
1001
1002static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001003bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001004{
1005 Py_ssize_t self_size, other_size;
1006 Py_buffer self_bytes, other_bytes;
Serhiy Storchaka313467e2020-11-22 22:00:53 +02001007 int cmp;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001008
Serhiy Storchaka313467e2020-11-22 22:00:53 +02001009 if (!PyObject_CheckBuffer(self) || !PyObject_CheckBuffer(other)) {
1010 if (PyUnicode_Check(self) || PyUnicode_Check(other)) {
1011 if (_Py_GetConfig()->bytes_warning && (op == Py_EQ || op == Py_NE)) {
1012 if (PyErr_WarnEx(PyExc_BytesWarning,
1013 "Comparison between bytearray and string", 1))
1014 return NULL;
1015 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001016 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001017 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001018 }
1019
Serhiy Storchaka2ad93822020-12-03 12:46:16 +02001020 /* Bytearrays can be compared to anything that supports the buffer API. */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001021 if (PyObject_GetBuffer(self, &self_bytes, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001022 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05001023 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001024 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001025 self_size = self_bytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001026
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001027 if (PyObject_GetBuffer(other, &other_bytes, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001028 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +00001029 PyBuffer_Release(&self_bytes);
Brian Curtindfc80e32011-08-10 20:28:54 -05001030 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001031 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001032 other_size = other_bytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001033
1034 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
1035 /* Shortcut: if the lengths differ, the objects differ */
stratakise8b19652017-11-02 11:32:54 +01001036 PyBuffer_Release(&self_bytes);
1037 PyBuffer_Release(&other_bytes);
1038 return PyBool_FromLong((op == Py_NE));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001039 }
1040 else {
stratakise8b19652017-11-02 11:32:54 +01001041 cmp = memcmp(self_bytes.buf, other_bytes.buf,
1042 Py_MIN(self_size, other_size));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001043 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
1044
stratakise8b19652017-11-02 11:32:54 +01001045 PyBuffer_Release(&self_bytes);
1046 PyBuffer_Release(&other_bytes);
1047
1048 if (cmp != 0) {
1049 Py_RETURN_RICHCOMPARE(cmp, 0, op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001050 }
1051
stratakise8b19652017-11-02 11:32:54 +01001052 Py_RETURN_RICHCOMPARE(self_size, other_size, op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001053 }
1054
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001055}
1056
1057static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001058bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001059{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001060 if (self->ob_exports > 0) {
1061 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001062 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001063 PyErr_Print();
1064 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001065 if (self->ob_bytes != 0) {
Antoine Pitrou39aba4f2011-11-12 21:15:28 +01001066 PyObject_Free(self->ob_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001067 }
1068 Py_TYPE(self)->tp_free((PyObject *)self);
1069}
1070
1071
1072/* -------------------------------------------------------------------- */
1073/* Methods */
1074
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001075#define FASTSEARCH fastsearch
1076#define STRINGLIB(F) stringlib_##F
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001077#define STRINGLIB_CHAR char
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001078#define STRINGLIB_SIZEOF_CHAR 1
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001079#define STRINGLIB_LEN PyByteArray_GET_SIZE
1080#define STRINGLIB_STR PyByteArray_AS_STRING
1081#define STRINGLIB_NEW PyByteArray_FromStringAndSize
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001082#define STRINGLIB_ISSPACE Py_ISSPACE
1083#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001084#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1085#define STRINGLIB_MUTABLE 1
1086
1087#include "stringlib/fastsearch.h"
1088#include "stringlib/count.h"
1089#include "stringlib/find.h"
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001090#include "stringlib/join.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001091#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001092#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001093#include "stringlib/ctype.h"
1094#include "stringlib/transmogrify.h"
1095
1096
Serhiy Storchakae09132f2016-07-03 13:57:48 +03001097static PyObject *
1098bytearray_find(PyByteArrayObject *self, PyObject *args)
1099{
1100 return _Py_bytes_find(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1101}
1102
1103static PyObject *
1104bytearray_count(PyByteArrayObject *self, PyObject *args)
1105{
1106 return _Py_bytes_count(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1107}
1108
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001109/*[clinic input]
1110bytearray.clear
1111
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001112Remove all items from the bytearray.
1113[clinic start generated code]*/
1114
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001115static PyObject *
1116bytearray_clear_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001117/*[clinic end generated code: output=85c2fe6aede0956c input=ed6edae9de447ac4]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001118{
1119 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
1120 return NULL;
1121 Py_RETURN_NONE;
1122}
1123
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001124/*[clinic input]
1125bytearray.copy
1126
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001127Return a copy of B.
1128[clinic start generated code]*/
1129
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001130static PyObject *
1131bytearray_copy_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001132/*[clinic end generated code: output=68cfbcfed484c132 input=6597b0c01bccaa9e]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001133{
1134 return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
1135 PyByteArray_GET_SIZE(self));
1136}
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001137
Serhiy Storchakae09132f2016-07-03 13:57:48 +03001138static PyObject *
1139bytearray_index(PyByteArrayObject *self, PyObject *args)
1140{
1141 return _Py_bytes_index(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1142}
1143
1144static PyObject *
1145bytearray_rfind(PyByteArrayObject *self, PyObject *args)
1146{
1147 return _Py_bytes_rfind(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1148}
1149
1150static PyObject *
1151bytearray_rindex(PyByteArrayObject *self, PyObject *args)
1152{
1153 return _Py_bytes_rindex(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1154}
1155
1156static int
1157bytearray_contains(PyObject *self, PyObject *arg)
1158{
1159 return _Py_bytes_contains(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), arg);
1160}
1161
1162static PyObject *
1163bytearray_startswith(PyByteArrayObject *self, PyObject *args)
1164{
1165 return _Py_bytes_startswith(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1166}
1167
1168static PyObject *
1169bytearray_endswith(PyByteArrayObject *self, PyObject *args)
1170{
1171 return _Py_bytes_endswith(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args);
1172}
1173
sweeneydea81849b2020-04-22 17:05:48 -04001174/*[clinic input]
1175bytearray.removeprefix as bytearray_removeprefix
1176
1177 prefix: Py_buffer
1178 /
1179
1180Return a bytearray with the given prefix string removed if present.
1181
1182If the bytearray starts with the prefix string, return
1183bytearray[len(prefix):]. Otherwise, return a copy of the original
1184bytearray.
1185[clinic start generated code]*/
1186
1187static PyObject *
1188bytearray_removeprefix_impl(PyByteArrayObject *self, Py_buffer *prefix)
1189/*[clinic end generated code: output=6cabc585e7f502e0 input=968aada38aedd262]*/
1190{
1191 const char *self_start = PyByteArray_AS_STRING(self);
1192 Py_ssize_t self_len = PyByteArray_GET_SIZE(self);
1193 const char *prefix_start = prefix->buf;
1194 Py_ssize_t prefix_len = prefix->len;
1195
1196 if (self_len >= prefix_len
1197 && memcmp(self_start, prefix_start, prefix_len) == 0)
1198 {
1199 return PyByteArray_FromStringAndSize(self_start + prefix_len,
1200 self_len - prefix_len);
1201 }
1202
1203 return PyByteArray_FromStringAndSize(self_start, self_len);
1204}
1205
1206/*[clinic input]
1207bytearray.removesuffix as bytearray_removesuffix
1208
1209 suffix: Py_buffer
1210 /
1211
1212Return a bytearray with the given suffix string removed if present.
1213
1214If the bytearray ends with the suffix string and that suffix is not
1215empty, return bytearray[:-len(suffix)]. Otherwise, return a copy of
1216the original bytearray.
1217[clinic start generated code]*/
1218
1219static PyObject *
1220bytearray_removesuffix_impl(PyByteArrayObject *self, Py_buffer *suffix)
1221/*[clinic end generated code: output=2bc8cfb79de793d3 input=c1827e810b2f6b99]*/
1222{
1223 const char *self_start = PyByteArray_AS_STRING(self);
1224 Py_ssize_t self_len = PyByteArray_GET_SIZE(self);
1225 const char *suffix_start = suffix->buf;
1226 Py_ssize_t suffix_len = suffix->len;
1227
1228 if (self_len >= suffix_len
1229 && memcmp(self_start + self_len - suffix_len,
1230 suffix_start, suffix_len) == 0)
1231 {
1232 return PyByteArray_FromStringAndSize(self_start,
1233 self_len - suffix_len);
1234 }
1235
1236 return PyByteArray_FromStringAndSize(self_start, self_len);
1237}
1238
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001239
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001240/*[clinic input]
1241bytearray.translate
1242
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001243 table: object
1244 Translation table, which must be a bytes object of length 256.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001245 /
Martin Panter1b6c6da2016-08-27 08:35:02 +00001246 delete as deletechars: object(c_default="NULL") = b''
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001247
1248Return a copy with each character mapped by the given translation table.
1249
Martin Panter1b6c6da2016-08-27 08:35:02 +00001250All characters occurring in the optional argument delete are removed.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001251The remaining characters are mapped through the given translation table.
1252[clinic start generated code]*/
1253
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001254static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001255bytearray_translate_impl(PyByteArrayObject *self, PyObject *table,
Martin Panter1b6c6da2016-08-27 08:35:02 +00001256 PyObject *deletechars)
1257/*[clinic end generated code: output=b6a8f01c2a74e446 input=cfff956d4d127a9b]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001258{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001259 char *input, *output;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001260 const char *table_chars;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001261 Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001262 PyObject *input_obj = (PyObject*)self;
1263 const char *output_start;
1264 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001265 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001266 int trans_table[256];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001267 Py_buffer vtable, vdel;
1268
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001269 if (table == Py_None) {
1270 table_chars = NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001271 table = NULL;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001272 } else if (PyObject_GetBuffer(table, &vtable, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001273 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001274 } else {
1275 if (vtable.len != 256) {
1276 PyErr_SetString(PyExc_ValueError,
1277 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001278 PyBuffer_Release(&vtable);
1279 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001280 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001281 table_chars = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001282 }
1283
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001284 if (deletechars != NULL) {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001285 if (PyObject_GetBuffer(deletechars, &vdel, PyBUF_SIMPLE) != 0) {
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001286 if (table != NULL)
Georg Brandl953152f2009-07-22 12:03:59 +00001287 PyBuffer_Release(&vtable);
1288 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001289 }
1290 }
1291 else {
1292 vdel.buf = NULL;
1293 vdel.len = 0;
1294 }
1295
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001296 inlen = PyByteArray_GET_SIZE(input_obj);
1297 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1298 if (result == NULL)
1299 goto done;
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03001300 output_start = output = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001301 input = PyByteArray_AS_STRING(input_obj);
1302
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001303 if (vdel.len == 0 && table_chars != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001304 /* If no deletions are required, use faster code */
1305 for (i = inlen; --i >= 0; ) {
1306 c = Py_CHARMASK(*input++);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001307 *output++ = table_chars[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001308 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001309 goto done;
1310 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001311
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001312 if (table_chars == NULL) {
Georg Brandlccc47b62008-12-28 11:44:14 +00001313 for (i = 0; i < 256; i++)
1314 trans_table[i] = Py_CHARMASK(i);
1315 } else {
1316 for (i = 0; i < 256; i++)
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001317 trans_table[i] = Py_CHARMASK(table_chars[i]);
Georg Brandlccc47b62008-12-28 11:44:14 +00001318 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001319
1320 for (i = 0; i < vdel.len; i++)
1321 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1322
1323 for (i = inlen; --i >= 0; ) {
1324 c = Py_CHARMASK(*input++);
1325 if (trans_table[c] != -1)
Martin Panter1b6c6da2016-08-27 08:35:02 +00001326 *output++ = (char)trans_table[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001327 }
Serhiy Storchaka2ad93822020-12-03 12:46:16 +02001328 /* Fix the size of the resulting bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001329 if (inlen > 0)
Christian Heimesc731bbe2013-07-21 02:04:35 +02001330 if (PyByteArray_Resize(result, output - output_start) < 0) {
1331 Py_CLEAR(result);
1332 goto done;
1333 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001334
1335done:
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001336 if (table != NULL)
Georg Brandlccc47b62008-12-28 11:44:14 +00001337 PyBuffer_Release(&vtable);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001338 if (deletechars != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001339 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001340 return result;
1341}
1342
1343
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001344/*[clinic input]
1345
1346@staticmethod
1347bytearray.maketrans
1348
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001349 frm: Py_buffer
1350 to: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001351 /
1352
1353Return a translation table useable for the bytes or bytearray translate method.
1354
1355The returned table will be one where each byte in frm is mapped to the byte at
1356the same position in to.
1357
1358The bytes objects frm and to must be of the same length.
1359[clinic start generated code]*/
1360
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001361static PyObject *
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001362bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001363/*[clinic end generated code: output=1df267d99f56b15e input=5925a81d2fbbf151]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001364{
1365 return _Py_bytes_maketrans(frm, to);
Georg Brandlabc38772009-04-12 15:51:51 +00001366}
1367
1368
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001369/*[clinic input]
1370bytearray.replace
1371
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001372 old: Py_buffer
1373 new: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001374 count: Py_ssize_t = -1
1375 Maximum number of occurrences to replace.
1376 -1 (the default value) means replace all occurrences.
1377 /
1378
1379Return a copy with all occurrences of substring old replaced by new.
1380
1381If the optional argument count is given, only the first count occurrences are
1382replaced.
1383[clinic start generated code]*/
1384
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001385static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001386bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old,
1387 Py_buffer *new, Py_ssize_t count)
1388/*[clinic end generated code: output=d39884c4dc59412a input=aa379d988637c7fb]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001389{
Serhiy Storchakafb81d3c2016-05-05 09:26:07 +03001390 return stringlib_replace((PyObject *)self,
Serhiy Storchakae09132f2016-07-03 13:57:48 +03001391 (const char *)old->buf, old->len,
1392 (const char *)new->buf, new->len, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001393}
1394
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001395/*[clinic input]
1396bytearray.split
1397
1398 sep: object = None
1399 The delimiter according which to split the bytearray.
1400 None (the default value) means split on ASCII whitespace characters
1401 (space, tab, return, newline, formfeed, vertical tab).
1402 maxsplit: Py_ssize_t = -1
1403 Maximum number of splits to do.
1404 -1 (the default value) means no limit.
1405
1406Return a list of the sections in the bytearray, using sep as the delimiter.
1407[clinic start generated code]*/
1408
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001409static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001410bytearray_split_impl(PyByteArrayObject *self, PyObject *sep,
1411 Py_ssize_t maxsplit)
1412/*[clinic end generated code: output=833e2cf385d9a04d input=24f82669f41bf523]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001413{
1414 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001415 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001416 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001417 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001418
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001419 if (maxsplit < 0)
1420 maxsplit = PY_SSIZE_T_MAX;
1421
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001422 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001423 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001424
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001425 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001426 return NULL;
1427 sub = vsub.buf;
1428 n = vsub.len;
1429
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001430 list = stringlib_split(
1431 (PyObject*) self, s, len, sub, n, maxsplit
1432 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001433 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001434 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001435}
1436
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001437/*[clinic input]
1438bytearray.partition
1439
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001440 sep: object
1441 /
1442
1443Partition the bytearray into three parts using the given separator.
1444
1445This will search for the separator sep in the bytearray. If the separator is
1446found, returns a 3-tuple containing the part before the separator, the
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001447separator itself, and the part after it as new bytearray objects.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001448
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001449If the separator is not found, returns a 3-tuple containing the copy of the
1450original bytearray object and two empty bytearray objects.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001451[clinic start generated code]*/
1452
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001453static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001454bytearray_partition(PyByteArrayObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001455/*[clinic end generated code: output=45d2525ddd35f957 input=8f644749ee4fc83a]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001456{
1457 PyObject *bytesep, *result;
1458
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001459 bytesep = _PyByteArray_FromBufferObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001460 if (! bytesep)
1461 return NULL;
1462
1463 result = stringlib_partition(
1464 (PyObject*) self,
1465 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1466 bytesep,
1467 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
1468 );
1469
1470 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001471 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001472}
1473
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001474/*[clinic input]
1475bytearray.rpartition
1476
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001477 sep: object
1478 /
1479
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001480Partition the bytearray into three parts using the given separator.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001481
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001482This will search for the separator sep in the bytearray, starting at the end.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001483If the separator is found, returns a 3-tuple containing the part before the
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001484separator, the separator itself, and the part after it as new bytearray
1485objects.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001486
1487If the separator is not found, returns a 3-tuple containing two empty bytearray
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001488objects and the copy of the original bytearray object.
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001489[clinic start generated code]*/
1490
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001491static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001492bytearray_rpartition(PyByteArrayObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001493/*[clinic end generated code: output=440de3c9426115e8 input=7e3df3e6cb8fa0ac]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001494{
1495 PyObject *bytesep, *result;
1496
Serhiy Storchakaa2314282017-10-29 02:11:54 +03001497 bytesep = _PyByteArray_FromBufferObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001498 if (! bytesep)
1499 return NULL;
1500
1501 result = stringlib_rpartition(
1502 (PyObject*) self,
1503 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1504 bytesep,
1505 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
1506 );
1507
1508 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001509 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001510}
1511
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001512/*[clinic input]
1513bytearray.rsplit = bytearray.split
1514
1515Return a list of the sections in the bytearray, using sep as the delimiter.
1516
1517Splitting is done starting at the end of the bytearray and working to the front.
1518[clinic start generated code]*/
1519
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001520static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001521bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep,
1522 Py_ssize_t maxsplit)
1523/*[clinic end generated code: output=a55e0b5a03cb6190 input=a68286e4dd692ffe]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001524{
1525 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001526 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001527 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001528 Py_buffer vsub;
1529
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001530 if (maxsplit < 0)
1531 maxsplit = PY_SSIZE_T_MAX;
1532
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001533 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001534 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001535
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001536 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001537 return NULL;
1538 sub = vsub.buf;
1539 n = vsub.len;
1540
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001541 list = stringlib_rsplit(
1542 (PyObject*) self, s, len, sub, n, maxsplit
1543 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001544 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001545 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001546}
1547
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001548/*[clinic input]
1549bytearray.reverse
1550
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001551Reverse the order of the values in B in place.
1552[clinic start generated code]*/
1553
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001554static PyObject *
1555bytearray_reverse_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001556/*[clinic end generated code: output=9f7616f29ab309d3 input=543356319fc78557]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001557{
1558 char swap, *head, *tail;
1559 Py_ssize_t i, j, n = Py_SIZE(self);
1560
1561 j = n / 2;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001562 head = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001563 tail = head + n - 1;
1564 for (i = 0; i < j; i++) {
1565 swap = *head;
1566 *head++ = *tail;
1567 *tail-- = swap;
1568 }
1569
1570 Py_RETURN_NONE;
1571}
1572
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001573
1574/*[python input]
1575class bytesvalue_converter(CConverter):
1576 type = 'int'
1577 converter = '_getbytevalue'
1578[python start generated code]*/
1579/*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/
1580
1581
1582/*[clinic input]
1583bytearray.insert
1584
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001585 index: Py_ssize_t
1586 The index where the value is to be inserted.
1587 item: bytesvalue
1588 The item to be inserted.
1589 /
1590
1591Insert a single item into the bytearray before the given index.
1592[clinic start generated code]*/
1593
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001594static PyObject *
1595bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001596/*[clinic end generated code: output=76c775a70e7b07b7 input=b2b5d07e9de6c070]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001597{
1598 Py_ssize_t n = Py_SIZE(self);
1599 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001600
1601 if (n == PY_SSIZE_T_MAX) {
1602 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00001603 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001604 return NULL;
1605 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001606 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
1607 return NULL;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001608 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001609
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001610 if (index < 0) {
1611 index += n;
1612 if (index < 0)
1613 index = 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001614 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001615 if (index > n)
1616 index = n;
1617 memmove(buf + index + 1, buf + index, n - index);
1618 buf[index] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001619
1620 Py_RETURN_NONE;
1621}
1622
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001623/*[clinic input]
1624bytearray.append
1625
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001626 item: bytesvalue
1627 The item to be appended.
1628 /
1629
1630Append a single item to the end of the bytearray.
1631[clinic start generated code]*/
1632
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001633static PyObject *
1634bytearray_append_impl(PyByteArrayObject *self, int item)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001635/*[clinic end generated code: output=a154e19ed1886cb6 input=20d6bec3d1340593]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001636{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001637 Py_ssize_t n = Py_SIZE(self);
1638
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001639 if (n == PY_SSIZE_T_MAX) {
1640 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00001641 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001642 return NULL;
1643 }
1644 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
1645 return NULL;
1646
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001647 PyByteArray_AS_STRING(self)[n] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001648
1649 Py_RETURN_NONE;
1650}
1651
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001652/*[clinic input]
1653bytearray.extend
1654
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001655 iterable_of_ints: object
1656 The iterable of items to append.
1657 /
1658
1659Append all the items from the iterator or sequence to the end of the bytearray.
1660[clinic start generated code]*/
1661
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001662static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001663bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001664/*[clinic end generated code: output=98155dbe249170b1 input=c617b3a93249ba28]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001665{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001666 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001667 Py_ssize_t buf_size = 0, len = 0;
1668 int value;
1669 char *buf;
1670
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001671 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001672 if (PyObject_CheckBuffer(iterable_of_ints)) {
1673 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001674 return NULL;
1675
1676 Py_RETURN_NONE;
1677 }
1678
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001679 it = PyObject_GetIter(iterable_of_ints);
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +03001680 if (it == NULL) {
1681 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
1682 PyErr_Format(PyExc_TypeError,
1683 "can't extend bytearray with %.100s",
Victor Stinner58ac7002020-02-07 03:04:21 +01001684 Py_TYPE(iterable_of_ints)->tp_name);
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +03001685 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001686 return NULL;
Serhiy Storchaka2c2044e2018-10-21 15:29:12 +03001687 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001688
Ezio Melotti42da6632011-03-15 05:18:48 +02001689 /* Try to determine the length of the argument. 32 is arbitrary. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001690 buf_size = PyObject_LengthHint(iterable_of_ints, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001691 if (buf_size == -1) {
1692 Py_DECREF(it);
1693 return NULL;
1694 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001695
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001696 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02001697 if (bytearray_obj == NULL) {
1698 Py_DECREF(it);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001699 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02001700 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001701 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001702
1703 while ((item = PyIter_Next(it)) != NULL) {
1704 if (! _getbytevalue(item, &value)) {
1705 Py_DECREF(item);
1706 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001707 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001708 return NULL;
1709 }
1710 buf[len++] = value;
1711 Py_DECREF(item);
1712
1713 if (len >= buf_size) {
Martin Panter371731e2016-07-18 07:53:13 +00001714 Py_ssize_t addition;
1715 if (len == PY_SSIZE_T_MAX) {
1716 Py_DECREF(it);
1717 Py_DECREF(bytearray_obj);
1718 return PyErr_NoMemory();
1719 }
1720 addition = len >> 1;
1721 if (addition > PY_SSIZE_T_MAX - len - 1)
1722 buf_size = PY_SSIZE_T_MAX;
1723 else
1724 buf_size = len + addition + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001725 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001726 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001727 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001728 return NULL;
1729 }
1730 /* Recompute the `buf' pointer, since the resizing operation may
1731 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001732 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001733 }
1734 }
1735 Py_DECREF(it);
1736
1737 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001738 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
1739 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001740 return NULL;
1741 }
1742
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02001743 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
1744 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001745 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02001746 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001747 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001748
Brandt Bucher2a7d5962019-06-26 12:06:18 -07001749 if (PyErr_Occurred()) {
1750 return NULL;
1751 }
1752
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001753 Py_RETURN_NONE;
1754}
1755
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001756/*[clinic input]
1757bytearray.pop
1758
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001759 index: Py_ssize_t = -1
1760 The index from where to remove the item.
1761 -1 (the default value) means remove the last item.
1762 /
1763
1764Remove and return a single item from B.
1765
1766If no index argument is given, will pop the last item.
1767[clinic start generated code]*/
1768
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001769static PyObject *
1770bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001771/*[clinic end generated code: output=e0ccd401f8021da8 input=3591df2d06c0d237]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001772{
1773 int value;
1774 Py_ssize_t n = Py_SIZE(self);
1775 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001776
1777 if (n == 0) {
Eli Bendersky1bc4f192011-03-04 04:55:25 +00001778 PyErr_SetString(PyExc_IndexError,
1779 "pop from empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001780 return NULL;
1781 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001782 if (index < 0)
1783 index += Py_SIZE(self);
1784 if (index < 0 || index >= Py_SIZE(self)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001785 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1786 return NULL;
1787 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00001788 if (!_canresize(self))
1789 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001790
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001791 buf = PyByteArray_AS_STRING(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001792 value = buf[index];
1793 memmove(buf + index, buf + index + 1, n - index);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001794 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
1795 return NULL;
1796
Mark Dickinson54a3db92009-09-06 10:19:23 +00001797 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001798}
1799
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001800/*[clinic input]
1801bytearray.remove
1802
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001803 value: bytesvalue
1804 The value to remove.
1805 /
1806
1807Remove the first occurrence of a value in the bytearray.
1808[clinic start generated code]*/
1809
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001810static PyObject *
1811bytearray_remove_impl(PyByteArrayObject *self, int value)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03001812/*[clinic end generated code: output=d659e37866709c13 input=121831240cd51ddf]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001813{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001814 Py_ssize_t where, n = Py_SIZE(self);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001815 char *buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001816
Serhiy Storchaka4b234942016-05-16 22:24:03 +03001817 where = stringlib_find_char(buf, n, value);
1818 if (where < 0) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00001819 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001820 return NULL;
1821 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00001822 if (!_canresize(self))
1823 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001824
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001825 memmove(buf + where, buf + where + 1, n - where);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001826 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
1827 return NULL;
1828
1829 Py_RETURN_NONE;
1830}
1831
1832/* XXX These two helpers could be optimized if argsize == 1 */
1833
1834static Py_ssize_t
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001835lstrip_helper(const char *myptr, Py_ssize_t mysize,
1836 const void *argptr, Py_ssize_t argsize)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001837{
1838 Py_ssize_t i = 0;
Antoine Pitrou5b720752013-10-05 21:24:10 +02001839 while (i < mysize && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001840 i++;
1841 return i;
1842}
1843
1844static Py_ssize_t
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001845rstrip_helper(const char *myptr, Py_ssize_t mysize,
1846 const void *argptr, Py_ssize_t argsize)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001847{
1848 Py_ssize_t i = mysize - 1;
Antoine Pitrou5b720752013-10-05 21:24:10 +02001849 while (i >= 0 && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001850 i--;
1851 return i + 1;
1852}
1853
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001854/*[clinic input]
1855bytearray.strip
1856
1857 bytes: object = None
1858 /
1859
1860Strip leading and trailing bytes contained in the argument.
1861
1862If the argument is omitted or None, strip leading and trailing ASCII whitespace.
1863[clinic start generated code]*/
1864
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001865static PyObject *
1866bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001867/*[clinic end generated code: output=760412661a34ad5a input=ef7bb59b09c21d62]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001868{
1869 Py_ssize_t left, right, mysize, byteslen;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001870 char *myptr;
1871 const char *bytesptr;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001872 Py_buffer vbytes;
1873
1874 if (bytes == Py_None) {
1875 bytesptr = "\t\n\r\f\v ";
1876 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001877 }
1878 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001879 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001880 return NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001881 bytesptr = (const char *) vbytes.buf;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001882 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001883 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001884 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001885 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001886 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001887 if (left == mysize)
1888 right = left;
1889 else
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001890 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
1891 if (bytes != Py_None)
1892 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001893 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001894}
1895
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001896/*[clinic input]
1897bytearray.lstrip
1898
1899 bytes: object = None
1900 /
1901
1902Strip leading bytes contained in the argument.
1903
1904If the argument is omitted or None, strip leading ASCII whitespace.
1905[clinic start generated code]*/
1906
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001907static PyObject *
1908bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001909/*[clinic end generated code: output=d005c9d0ab909e66 input=80843f975dd7c480]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001910{
1911 Py_ssize_t left, right, mysize, byteslen;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001912 char *myptr;
1913 const char *bytesptr;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001914 Py_buffer vbytes;
1915
1916 if (bytes == Py_None) {
1917 bytesptr = "\t\n\r\f\v ";
1918 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001919 }
1920 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001921 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001922 return NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001923 bytesptr = (const char *) vbytes.buf;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001924 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001925 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001926 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001927 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001928 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001929 right = mysize;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001930 if (bytes != Py_None)
1931 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001932 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001933}
1934
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001935/*[clinic input]
1936bytearray.rstrip
1937
1938 bytes: object = None
1939 /
1940
1941Strip trailing bytes contained in the argument.
1942
1943If the argument is omitted or None, strip trailing ASCII whitespace.
1944[clinic start generated code]*/
1945
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001946static PyObject *
1947bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001948/*[clinic end generated code: output=030e2fbd2f7276bd input=e728b994954cfd91]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001949{
1950 Py_ssize_t right, mysize, byteslen;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001951 char *myptr;
1952 const char *bytesptr;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001953 Py_buffer vbytes;
1954
1955 if (bytes == Py_None) {
1956 bytesptr = "\t\n\r\f\v ";
1957 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001958 }
1959 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001960 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001961 return NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001962 bytesptr = (const char *) vbytes.buf;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001963 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001964 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001965 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001966 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001967 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
1968 if (bytes != Py_None)
1969 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02001970 return PyByteArray_FromStringAndSize(myptr, right);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001971}
1972
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001973/*[clinic input]
1974bytearray.decode
1975
1976 encoding: str(c_default="NULL") = 'utf-8'
1977 The encoding with which to decode the bytearray.
1978 errors: str(c_default="NULL") = 'strict'
1979 The error handling scheme to use for the handling of decoding errors.
1980 The default is 'strict' meaning that decoding errors raise a
1981 UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
1982 as well as any other name registered with codecs.register_error that
1983 can handle UnicodeDecodeErrors.
1984
1985Decode the bytearray using the codec registered for encoding.
1986[clinic start generated code]*/
1987
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001988static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001989bytearray_decode_impl(PyByteArrayObject *self, const char *encoding,
1990 const char *errors)
1991/*[clinic end generated code: output=f57d43f4a00b42c5 input=f28d8f903020257b]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001992{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001993 if (encoding == NULL)
1994 encoding = PyUnicode_GetDefaultEncoding();
Martin v. Löwis0efea322014-07-27 17:29:17 +02001995 return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001996}
1997
1998PyDoc_STRVAR(alloc_doc,
1999"B.__alloc__() -> int\n\
2000\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002001Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002002
2003static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302004bytearray_alloc(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002005{
2006 return PyLong_FromSsize_t(self->ob_alloc);
2007}
2008
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002009/*[clinic input]
2010bytearray.join
2011
2012 iterable_of_bytes: object
2013 /
2014
2015Concatenate any number of bytes/bytearray objects.
2016
2017The bytearray whose method is called is inserted in between each pair.
2018
2019The result is returned as a new bytearray object.
2020[clinic start generated code]*/
2021
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002022static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002023bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002024/*[clinic end generated code: output=a8516370bf68ae08 input=aba6b1f9b30fcb8e]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002025{
Martin v. Löwis0efea322014-07-27 17:29:17 +02002026 return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002027}
2028
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002029/*[clinic input]
2030bytearray.splitlines
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002031
Serhiy Storchaka202fda52017-03-12 10:10:47 +02002032 keepends: bool(accept={int}) = False
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002033
2034Return a list of the lines in the bytearray, breaking at line boundaries.
2035
2036Line breaks are not included in the resulting list unless keepends is given and
2037true.
2038[clinic start generated code]*/
2039
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002040static PyObject *
2041bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +02002042/*[clinic end generated code: output=4223c94b895f6ad9 input=99a27ad959b9cf6b]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002043{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002044 return stringlib_splitlines(
2045 (PyObject*) self, PyByteArray_AS_STRING(self),
2046 PyByteArray_GET_SIZE(self), keepends
2047 );
2048}
2049
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002050/*[clinic input]
2051@classmethod
2052bytearray.fromhex
2053
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002054 string: unicode
2055 /
2056
2057Create a bytearray object from a string of hexadecimal numbers.
2058
2059Spaces between two numbers are accepted.
2060Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
2061[clinic start generated code]*/
2062
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002063static PyObject *
Serhiy Storchaka0855e702016-07-01 17:22:31 +03002064bytearray_fromhex_impl(PyTypeObject *type, PyObject *string)
2065/*[clinic end generated code: output=8f0f0b6d30fb3ba0 input=f033a16d1fb21f48]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002066{
Serhiy Storchaka0855e702016-07-01 17:22:31 +03002067 PyObject *result = _PyBytes_FromHex(string, type == &PyByteArray_Type);
2068 if (type != &PyByteArray_Type && result != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01002069 Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
Serhiy Storchaka0855e702016-07-01 17:22:31 +03002070 }
2071 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002072}
2073
Gregory P. Smith0c2f9302019-05-29 11:46:58 -07002074/*[clinic input]
2075bytearray.hex
2076
2077 sep: object = NULL
2078 An optional single character or byte to separate hex bytes.
2079 bytes_per_sep: int = 1
2080 How many bytes between separators. Positive values count from the
2081 right, negative values count from the left.
2082
Serhiy Storchaka2ad93822020-12-03 12:46:16 +02002083Create a string of hexadecimal numbers from a bytearray object.
Gregory P. Smith0c2f9302019-05-29 11:46:58 -07002084
2085Example:
2086>>> value = bytearray([0xb9, 0x01, 0xef])
2087>>> value.hex()
2088'b901ef'
2089>>> value.hex(':')
2090'b9:01:ef'
2091>>> value.hex(':', 2)
2092'b9:01ef'
2093>>> value.hex(':', -2)
2094'b901:ef'
2095[clinic start generated code]*/
Gregory P. Smith8cb65692015-04-25 23:22:26 +00002096
2097static PyObject *
Gregory P. Smith0c2f9302019-05-29 11:46:58 -07002098bytearray_hex_impl(PyByteArrayObject *self, PyObject *sep, int bytes_per_sep)
Serhiy Storchaka2ad93822020-12-03 12:46:16 +02002099/*[clinic end generated code: output=29c4e5ef72c565a0 input=808667e49bcccb54]*/
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002100{
2101 char* argbuf = PyByteArray_AS_STRING(self);
2102 Py_ssize_t arglen = PyByteArray_GET_SIZE(self);
Gregory P. Smith0c2f9302019-05-29 11:46:58 -07002103 return _Py_strhex_with_sep(argbuf, arglen, sep, bytes_per_sep);
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002104}
2105
2106static PyObject *
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002107_common_reduce(PyByteArrayObject *self, int proto)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002108{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002109 PyObject *dict;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002110 _Py_IDENTIFIER(__dict__);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002111 char *buf;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002112
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002113 if (_PyObject_LookupAttrId((PyObject *)self, &PyId___dict__, &dict) < 0) {
2114 return NULL;
2115 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002116 if (dict == NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002117 dict = Py_None;
2118 Py_INCREF(dict);
2119 }
2120
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002121 buf = PyByteArray_AS_STRING(self);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002122 if (proto < 3) {
2123 /* use str based reduction for backwards compatibility with Python 2.x */
2124 PyObject *latin1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002125 if (Py_SIZE(self))
2126 latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002127 else
2128 latin1 = PyUnicode_FromString("");
2129 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
2130 }
2131 else {
2132 /* use more efficient byte based reduction */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002133 if (Py_SIZE(self)) {
2134 return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), dict);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002135 }
2136 else {
2137 return Py_BuildValue("(O()N)", Py_TYPE(self), dict);
2138 }
2139 }
2140}
2141
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002142/*[clinic input]
2143bytearray.__reduce__ as bytearray_reduce
2144
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002145Return state information for pickling.
2146[clinic start generated code]*/
2147
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002148static PyObject *
2149bytearray_reduce_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03002150/*[clinic end generated code: output=52bf304086464cab input=44b5737ada62dd3f]*/
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002151{
2152 return _common_reduce(self, 2);
2153}
2154
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002155/*[clinic input]
2156bytearray.__reduce_ex__ as bytearray_reduce_ex
2157
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002158 proto: int = 0
2159 /
2160
2161Return state information for pickling.
2162[clinic start generated code]*/
2163
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002164static PyObject *
2165bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03002166/*[clinic end generated code: output=52eac33377197520 input=f129bc1a1aa151ee]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002167{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002168 return _common_reduce(self, proto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002169}
2170
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002171/*[clinic input]
2172bytearray.__sizeof__ as bytearray_sizeof
2173
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002174Returns the size of the bytearray object in memory, in bytes.
2175[clinic start generated code]*/
2176
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002177static PyObject *
2178bytearray_sizeof_impl(PyByteArrayObject *self)
Serhiy Storchaka7a9579c2016-05-02 13:45:20 +03002179/*[clinic end generated code: output=738abdd17951c427 input=e27320fd98a4bc5a]*/
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002180{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002181 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002182
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002183 res = _PyObject_SIZE(Py_TYPE(self)) + self->ob_alloc * sizeof(char);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002184 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002185}
2186
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002187static PySequenceMethods bytearray_as_sequence = {
2188 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002189 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002190 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
2191 (ssizeargfunc)bytearray_getitem, /* sq_item */
2192 0, /* sq_slice */
2193 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
2194 0, /* sq_ass_slice */
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002195 (objobjproc)bytearray_contains, /* sq_contains */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002196 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
2197 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002198};
2199
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002200static PyMappingMethods bytearray_as_mapping = {
2201 (lenfunc)bytearray_length,
2202 (binaryfunc)bytearray_subscript,
2203 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002204};
2205
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002206static PyBufferProcs bytearray_as_buffer = {
2207 (getbufferproc)bytearray_getbuffer,
2208 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002209};
2210
2211static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002212bytearray_methods[] = {
2213 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002214 BYTEARRAY_REDUCE_METHODDEF
2215 BYTEARRAY_REDUCE_EX_METHODDEF
2216 BYTEARRAY_SIZEOF_METHODDEF
2217 BYTEARRAY_APPEND_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302218 {"capitalize", stringlib_capitalize, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002219 _Py_capitalize__doc__},
Tal Einatc929df32018-07-06 13:17:38 +03002220 STRINGLIB_CENTER_METHODDEF
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002221 BYTEARRAY_CLEAR_METHODDEF
2222 BYTEARRAY_COPY_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002223 {"count", (PyCFunction)bytearray_count, METH_VARARGS,
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03002224 _Py_count__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002225 BYTEARRAY_DECODE_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002226 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS,
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03002227 _Py_endswith__doc__},
Tal Einatc929df32018-07-06 13:17:38 +03002228 STRINGLIB_EXPANDTABS_METHODDEF
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002229 BYTEARRAY_EXTEND_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002230 {"find", (PyCFunction)bytearray_find, METH_VARARGS,
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03002231 _Py_find__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002232 BYTEARRAY_FROMHEX_METHODDEF
Gregory P. Smith0c2f9302019-05-29 11:46:58 -07002233 BYTEARRAY_HEX_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002234 {"index", (PyCFunction)bytearray_index, METH_VARARGS, _Py_index__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002235 BYTEARRAY_INSERT_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302236 {"isalnum", stringlib_isalnum, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002237 _Py_isalnum__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302238 {"isalpha", stringlib_isalpha, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002239 _Py_isalpha__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302240 {"isascii", stringlib_isascii, METH_NOARGS,
INADA Naokia49ac992018-01-27 14:06:21 +09002241 _Py_isascii__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302242 {"isdigit", stringlib_isdigit, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002243 _Py_isdigit__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302244 {"islower", stringlib_islower, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002245 _Py_islower__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302246 {"isspace", stringlib_isspace, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002247 _Py_isspace__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302248 {"istitle", stringlib_istitle, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002249 _Py_istitle__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302250 {"isupper", stringlib_isupper, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002251 _Py_isupper__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002252 BYTEARRAY_JOIN_METHODDEF
Tal Einatc929df32018-07-06 13:17:38 +03002253 STRINGLIB_LJUST_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302254 {"lower", stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002255 BYTEARRAY_LSTRIP_METHODDEF
2256 BYTEARRAY_MAKETRANS_METHODDEF
2257 BYTEARRAY_PARTITION_METHODDEF
2258 BYTEARRAY_POP_METHODDEF
2259 BYTEARRAY_REMOVE_METHODDEF
2260 BYTEARRAY_REPLACE_METHODDEF
sweeneydea81849b2020-04-22 17:05:48 -04002261 BYTEARRAY_REMOVEPREFIX_METHODDEF
2262 BYTEARRAY_REMOVESUFFIX_METHODDEF
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002263 BYTEARRAY_REVERSE_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002264 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, _Py_rfind__doc__},
2265 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, _Py_rindex__doc__},
Tal Einatc929df32018-07-06 13:17:38 +03002266 STRINGLIB_RJUST_METHODDEF
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002267 BYTEARRAY_RPARTITION_METHODDEF
2268 BYTEARRAY_RSPLIT_METHODDEF
2269 BYTEARRAY_RSTRIP_METHODDEF
2270 BYTEARRAY_SPLIT_METHODDEF
2271 BYTEARRAY_SPLITLINES_METHODDEF
Serhiy Storchakae09132f2016-07-03 13:57:48 +03002272 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Serhiy Storchakadd40fc32016-05-04 22:23:26 +03002273 _Py_startswith__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002274 BYTEARRAY_STRIP_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302275 {"swapcase", stringlib_swapcase, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002276 _Py_swapcase__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302277 {"title", stringlib_title, METH_NOARGS, _Py_title__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002278 BYTEARRAY_TRANSLATE_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302279 {"upper", stringlib_upper, METH_NOARGS, _Py_upper__doc__},
Tal Einatc929df32018-07-06 13:17:38 +03002280 STRINGLIB_ZFILL_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002281 {NULL}
2282};
2283
Ethan Furmanb95b5612015-01-23 20:05:18 -08002284static PyObject *
2285bytearray_mod(PyObject *v, PyObject *w)
2286{
2287 if (!PyByteArray_Check(v))
2288 Py_RETURN_NOTIMPLEMENTED;
Berker Peksag43de36d2016-04-16 01:20:47 +03002289 return _PyBytes_FormatEx(PyByteArray_AS_STRING(v), PyByteArray_GET_SIZE(v), w, 1);
Ethan Furmanb95b5612015-01-23 20:05:18 -08002290}
2291
2292static PyNumberMethods bytearray_as_number = {
2293 0, /*nb_add*/
2294 0, /*nb_subtract*/
2295 0, /*nb_multiply*/
2296 bytearray_mod, /*nb_remainder*/
2297};
2298
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002299PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002300"bytearray(iterable_of_ints) -> bytearray\n\
2301bytearray(string, encoding[, errors]) -> bytearray\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01002302bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
2303bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
2304bytearray() -> empty bytes array\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002305\n\
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03002306Construct a mutable bytearray object from:\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002307 - an iterable yielding integers in range(256)\n\
2308 - a text string encoded using the specified encoding\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01002309 - a bytes or a buffer object\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002310 - any object implementing the buffer API.\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01002311 - an integer");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002312
2313
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002314static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002315
2316PyTypeObject PyByteArray_Type = {
2317 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2318 "bytearray",
2319 sizeof(PyByteArrayObject),
2320 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002321 (destructor)bytearray_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002322 0, /* tp_vectorcall_offset */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002323 0, /* tp_getattr */
2324 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002325 0, /* tp_as_async */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002326 (reprfunc)bytearray_repr, /* tp_repr */
Ethan Furmanb95b5612015-01-23 20:05:18 -08002327 &bytearray_as_number, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002328 &bytearray_as_sequence, /* tp_as_sequence */
2329 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002330 0, /* tp_hash */
2331 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002332 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002333 PyObject_GenericGetAttr, /* tp_getattro */
2334 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002335 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002336 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002337 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002338 0, /* tp_traverse */
2339 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002340 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002341 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002342 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002343 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002344 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002345 0, /* tp_members */
2346 0, /* tp_getset */
2347 0, /* tp_base */
2348 0, /* tp_dict */
2349 0, /* tp_descr_get */
2350 0, /* tp_descr_set */
2351 0, /* tp_dictoffset */
Serhiy Storchaka12f43342020-07-20 15:53:55 +03002352 (initproc)bytearray___init__, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002353 PyType_GenericAlloc, /* tp_alloc */
2354 PyType_GenericNew, /* tp_new */
2355 PyObject_Del, /* tp_free */
2356};
2357
Serhiy Storchaka2ad93822020-12-03 12:46:16 +02002358/*********************** Bytearray Iterator ****************************/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002359
2360typedef struct {
2361 PyObject_HEAD
2362 Py_ssize_t it_index;
2363 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
2364} bytesiterobject;
2365
2366static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002367bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002368{
2369 _PyObject_GC_UNTRACK(it);
2370 Py_XDECREF(it->it_seq);
2371 PyObject_GC_Del(it);
2372}
2373
2374static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002375bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002376{
2377 Py_VISIT(it->it_seq);
2378 return 0;
2379}
2380
2381static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002382bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002383{
2384 PyByteArrayObject *seq;
2385 PyObject *item;
2386
2387 assert(it != NULL);
2388 seq = it->it_seq;
2389 if (seq == NULL)
2390 return NULL;
2391 assert(PyByteArray_Check(seq));
2392
2393 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
2394 item = PyLong_FromLong(
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002395 (unsigned char)PyByteArray_AS_STRING(seq)[it->it_index]);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002396 if (item != NULL)
2397 ++it->it_index;
2398 return item;
2399 }
2400
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002401 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002402 Py_DECREF(seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002403 return NULL;
2404}
2405
2406static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302407bytearrayiter_length_hint(bytesiterobject *it, PyObject *Py_UNUSED(ignored))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002408{
2409 Py_ssize_t len = 0;
Serhiy Storchakaaf658722016-07-03 14:41:36 +03002410 if (it->it_seq) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002411 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
Serhiy Storchakaaf658722016-07-03 14:41:36 +03002412 if (len < 0) {
2413 len = 0;
2414 }
2415 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002416 return PyLong_FromSsize_t(len);
2417}
2418
2419PyDoc_STRVAR(length_hint_doc,
2420 "Private method returning an estimate of len(list(it)).");
2421
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002422static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302423bytearrayiter_reduce(bytesiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002424{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02002425 _Py_IDENTIFIER(iter);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002426 if (it->it_seq != NULL) {
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02002427 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002428 it->it_seq, it->it_index);
2429 } else {
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02002430 return Py_BuildValue("N(())", _PyEval_GetBuiltinId(&PyId_iter));
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002431 }
2432}
2433
2434static PyObject *
2435bytearrayiter_setstate(bytesiterobject *it, PyObject *state)
2436{
2437 Py_ssize_t index = PyLong_AsSsize_t(state);
2438 if (index == -1 && PyErr_Occurred())
2439 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00002440 if (it->it_seq != NULL) {
2441 if (index < 0)
2442 index = 0;
2443 else if (index > PyByteArray_GET_SIZE(it->it_seq))
2444 index = PyByteArray_GET_SIZE(it->it_seq); /* iterator exhausted */
2445 it->it_index = index;
2446 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002447 Py_RETURN_NONE;
2448}
2449
2450PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2451
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002452static PyMethodDef bytearrayiter_methods[] = {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002453 {"__length_hint__", (PyCFunction)bytearrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002454 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002455 {"__reduce__", (PyCFunction)bytearrayiter_reduce, METH_NOARGS,
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002456 bytearray_reduce__doc__},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002457 {"__setstate__", (PyCFunction)bytearrayiter_setstate, METH_O,
2458 setstate_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002459 {NULL, NULL} /* sentinel */
2460};
2461
2462PyTypeObject PyByteArrayIter_Type = {
2463 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2464 "bytearray_iterator", /* tp_name */
2465 sizeof(bytesiterobject), /* tp_basicsize */
2466 0, /* tp_itemsize */
2467 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002468 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002469 0, /* tp_vectorcall_offset */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002470 0, /* tp_getattr */
2471 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002472 0, /* tp_as_async */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002473 0, /* tp_repr */
2474 0, /* tp_as_number */
2475 0, /* tp_as_sequence */
2476 0, /* tp_as_mapping */
2477 0, /* tp_hash */
2478 0, /* tp_call */
2479 0, /* tp_str */
2480 PyObject_GenericGetAttr, /* tp_getattro */
2481 0, /* tp_setattro */
2482 0, /* tp_as_buffer */
2483 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2484 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002485 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002486 0, /* tp_clear */
2487 0, /* tp_richcompare */
2488 0, /* tp_weaklistoffset */
2489 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002490 (iternextfunc)bytearrayiter_next, /* tp_iternext */
2491 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002492 0,
2493};
2494
2495static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002496bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002497{
2498 bytesiterobject *it;
2499
2500 if (!PyByteArray_Check(seq)) {
2501 PyErr_BadInternalCall();
2502 return NULL;
2503 }
2504 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
2505 if (it == NULL)
2506 return NULL;
2507 it->it_index = 0;
2508 Py_INCREF(seq);
2509 it->it_seq = (PyByteArrayObject *)seq;
2510 _PyObject_GC_TRACK(it);
2511 return (PyObject *)it;
2512}