blob: 145863575f2445d3971d14db518e19681057c709 [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"
5#include "structmember.h"
6#include "bytes_methods.h"
Ethan Furmanb95b5612015-01-23 20:05:18 -08007#include "bytesobject.h"
Gregory P. Smith8cb65692015-04-25 23:22:26 +00008#include "pystrhex.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00009
Martin v. Löwis7252a6e2014-07-27 16:25:09 +020010/*[clinic input]
11class bytearray "PyByteArrayObject *" "&PyByteArray_Type"
12[clinic start generated code]*/
13/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5535b77c37a119e0]*/
14
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000015char _PyByteArray_empty_string[] = "";
Christian Heimes2c9c7a52008-05-26 13:42:13 +000016
17void
18PyByteArray_Fini(void)
19{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000020}
21
22int
23PyByteArray_Init(void)
24{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000025 return 1;
26}
27
28/* end nullbytes support */
29
30/* Helpers */
31
32static int
33_getbytevalue(PyObject* arg, int *value)
34{
35 long face_value;
36
37 if (PyLong_Check(arg)) {
38 face_value = PyLong_AsLong(arg);
Georg Brandl9a54d7c2008-07-16 23:15:30 +000039 } else {
40 PyObject *index = PyNumber_Index(arg);
41 if (index == NULL) {
42 PyErr_Format(PyExc_TypeError, "an integer is required");
Mark Dickinson10de93a2010-07-09 19:25:48 +000043 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000044 return 0;
45 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +000046 face_value = PyLong_AsLong(index);
47 Py_DECREF(index);
48 }
49
50 if (face_value < 0 || face_value >= 256) {
51 /* this includes the OverflowError in case the long is too large */
52 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
Mark Dickinson10de93a2010-07-09 19:25:48 +000053 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000054 return 0;
55 }
56
57 *value = face_value;
58 return 1;
59}
60
61static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +000062bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000063{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000064 void *ptr;
65 if (view == NULL) {
Stefan Krah5178d912015-02-03 16:57:21 +010066 PyErr_SetString(PyExc_BufferError,
67 "bytearray_getbuffer: view==NULL argument is obsolete");
68 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000069 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000070 ptr = (void *) PyByteArray_AS_STRING(obj);
Stefan Krah5178d912015-02-03 16:57:21 +010071 /* cannot fail if view != NULL and readonly == 0 */
72 (void)PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
73 obj->ob_exports++;
74 return 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000075}
76
77static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +000078bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000079{
80 obj->ob_exports--;
81}
82
Antoine Pitrou5504e892008-12-06 21:27:53 +000083static int
84_canresize(PyByteArrayObject *self)
85{
86 if (self->ob_exports > 0) {
87 PyErr_SetString(PyExc_BufferError,
88 "Existing exports of data: object cannot be re-sized");
89 return 0;
90 }
91 return 1;
92}
93
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030094#include "clinic/bytearrayobject.c.h"
95
Christian Heimes2c9c7a52008-05-26 13:42:13 +000096/* Direct API functions */
97
98PyObject *
99PyByteArray_FromObject(PyObject *input)
100{
101 return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
102 input, NULL);
103}
104
105PyObject *
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 }
141 Py_SIZE(new) = size;
142 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 */
199 Py_SIZE(self) = size;
200 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),
227 Py_MIN(requested_size, 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;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000239 Py_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",
257 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
258 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);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000268 if (result != NULL) {
269 memcpy(result->ob_bytes, va.buf, va.len);
270 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
271 }
272
273 done:
274 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000275 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000276 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000277 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000278 return (PyObject *)result;
279}
280
Ethan Furmanb95b5612015-01-23 20:05:18 -0800281static PyObject *
282bytearray_format(PyByteArrayObject *self, PyObject *args)
283{
284 PyObject *bytes_in, *bytes_out, *res;
285 char *bytestring;
286
287 if (self == NULL || !PyByteArray_Check(self) || args == NULL) {
288 PyErr_BadInternalCall();
289 return NULL;
290 }
291 bytestring = PyByteArray_AS_STRING(self);
292 bytes_in = PyBytes_FromString(bytestring);
293 if (bytes_in == NULL)
294 return NULL;
295 bytes_out = _PyBytes_Format(bytes_in, args);
296 Py_DECREF(bytes_in);
297 if (bytes_out == NULL)
298 return NULL;
299 res = PyByteArray_FromObject(bytes_out);
300 Py_DECREF(bytes_out);
301 if (res == NULL)
302 return NULL;
303 return res;
304}
305
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000306/* Functions stuffed into the type object */
307
308static Py_ssize_t
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000309bytearray_length(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000310{
311 return Py_SIZE(self);
312}
313
314static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000315bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000316{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000317 Py_ssize_t size;
318 Py_buffer vo;
319
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200320 if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000321 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
322 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
323 return NULL;
324 }
325
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300326 size = Py_SIZE(self);
327 if (size > PY_SSIZE_T_MAX - vo.len) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000328 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000329 return PyErr_NoMemory();
330 }
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300331 if (PyByteArray_Resize((PyObject *)self, size + vo.len) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000332 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000333 return NULL;
334 }
Serhiy Storchaka06cfb0c2016-07-10 20:48:43 +0300335 memcpy(PyByteArray_AS_STRING(self) + size, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000336 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000337 Py_INCREF(self);
338 return (PyObject *)self;
339}
340
341static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000342bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000343{
344 PyByteArrayObject *result;
345 Py_ssize_t mysize;
346 Py_ssize_t size;
347
348 if (count < 0)
349 count = 0;
350 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000351 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000352 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000353 size = mysize * count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000354 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
355 if (result != NULL && size != 0) {
356 if (mysize == 1)
357 memset(result->ob_bytes, self->ob_bytes[0], size);
358 else {
359 Py_ssize_t i;
360 for (i = 0; i < count; i++)
361 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
362 }
363 }
364 return (PyObject *)result;
365}
366
367static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000368bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000369{
370 Py_ssize_t mysize;
371 Py_ssize_t size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200372 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000373
374 if (count < 0)
375 count = 0;
376 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000377 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000378 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000379 size = mysize * count;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200380 if (PyByteArray_Resize((PyObject *)self, size) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000381 return NULL;
382
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200383 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000384 if (mysize == 1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200385 memset(buf, buf[0], size);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000386 else {
387 Py_ssize_t i;
388 for (i = 1; i < count; i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200389 memcpy(buf + i*mysize, buf, mysize);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000390 }
391
392 Py_INCREF(self);
393 return (PyObject *)self;
394}
395
396static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000397bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000398{
399 if (i < 0)
400 i += Py_SIZE(self);
401 if (i < 0 || i >= Py_SIZE(self)) {
402 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
403 return NULL;
404 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200405 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000406}
407
408static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000409bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000410{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000411 if (PyIndex_Check(index)) {
412 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000413
414 if (i == -1 && PyErr_Occurred())
415 return NULL;
416
417 if (i < 0)
418 i += PyByteArray_GET_SIZE(self);
419
420 if (i < 0 || i >= Py_SIZE(self)) {
421 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
422 return NULL;
423 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200424 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000425 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000426 else if (PySlice_Check(index)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000427 Py_ssize_t start, stop, step, slicelength, cur, i;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000428 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000429 PyByteArray_GET_SIZE(self),
430 &start, &stop, &step, &slicelength) < 0) {
431 return NULL;
432 }
433
434 if (slicelength <= 0)
435 return PyByteArray_FromStringAndSize("", 0);
436 else if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200437 return PyByteArray_FromStringAndSize(
438 PyByteArray_AS_STRING(self) + start, slicelength);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000439 }
440 else {
441 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000442 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000443 PyObject *result;
444
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000445 result = PyByteArray_FromStringAndSize(NULL, slicelength);
446 if (result == NULL)
447 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000448
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000449 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000450 for (cur = start, i = 0; i < slicelength;
451 cur += step, i++) {
452 result_buf[i] = source_buf[cur];
453 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000454 return result;
455 }
456 }
457 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400458 PyErr_Format(PyExc_TypeError,
459 "bytearray indices must be integers or slices, not %.200s",
460 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000461 return NULL;
462 }
463}
464
465static int
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200466bytearray_setslice_linear(PyByteArrayObject *self,
467 Py_ssize_t lo, Py_ssize_t hi,
468 char *bytes, Py_ssize_t bytes_len)
469{
470 Py_ssize_t avail = hi - lo;
471 char *buf = PyByteArray_AS_STRING(self);
472 Py_ssize_t growth = bytes_len - avail;
Victor Stinner84557232013-11-21 12:29:51 +0100473 int res = 0;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200474 assert(avail >= 0);
475
Victor Stinner84557232013-11-21 12:29:51 +0100476 if (growth < 0) {
477 if (!_canresize(self))
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200478 return -1;
Victor Stinner84557232013-11-21 12:29:51 +0100479
480 if (lo == 0) {
481 /* Shrink the buffer by advancing its logical start */
482 self->ob_start -= growth;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200483 /*
Victor Stinner84557232013-11-21 12:29:51 +0100484 0 lo hi old_size
485 | |<----avail----->|<-----tail------>|
486 | |<-bytes_len->|<-----tail------>|
487 0 new_lo new_hi new_size
488 */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200489 }
Victor Stinner84557232013-11-21 12:29:51 +0100490 else {
491 /*
492 0 lo hi old_size
493 | |<----avail----->|<-----tomove------>|
494 | |<-bytes_len->|<-----tomove------>|
495 0 lo new_hi new_size
496 */
497 memmove(buf + lo + bytes_len, buf + hi,
498 Py_SIZE(self) - hi);
499 }
500 if (PyByteArray_Resize((PyObject *)self,
501 Py_SIZE(self) + growth) < 0) {
502 /* Issue #19578: Handling the memory allocation failure here is
503 tricky here because the bytearray object has already been
504 modified. Depending on growth and lo, the behaviour is
505 different.
506
507 If growth < 0 and lo != 0, the operation is completed, but a
508 MemoryError is still raised and the memory block is not
509 shrinked. Otherwise, the bytearray is restored in its previous
510 state and a MemoryError is raised. */
511 if (lo == 0) {
512 self->ob_start += growth;
513 return -1;
514 }
515 /* memmove() removed bytes, the bytearray object cannot be
516 restored in its previous state. */
517 Py_SIZE(self) += growth;
518 res = -1;
519 }
520 buf = PyByteArray_AS_STRING(self);
521 }
522 else if (growth > 0) {
523 if (Py_SIZE(self) > (Py_ssize_t)PY_SSIZE_T_MAX - growth) {
524 PyErr_NoMemory();
525 return -1;
526 }
527
528 if (PyByteArray_Resize((PyObject *)self,
529 Py_SIZE(self) + growth) < 0) {
530 return -1;
531 }
532 buf = PyByteArray_AS_STRING(self);
533 /* Make the place for the additional bytes */
534 /*
535 0 lo hi old_size
536 | |<-avail->|<-----tomove------>|
537 | |<---bytes_len-->|<-----tomove------>|
538 0 lo new_hi new_size
539 */
540 memmove(buf + lo + bytes_len, buf + hi,
541 Py_SIZE(self) - lo - bytes_len);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200542 }
543
544 if (bytes_len > 0)
545 memcpy(buf + lo, bytes, bytes_len);
Victor Stinner84557232013-11-21 12:29:51 +0100546 return res;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200547}
548
549static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000550bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000551 PyObject *values)
552{
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200553 Py_ssize_t needed;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000554 void *bytes;
555 Py_buffer vbytes;
556 int res = 0;
557
558 vbytes.len = -1;
559 if (values == (PyObject *)self) {
560 /* Make a copy and call this function recursively */
561 int err;
562 values = PyByteArray_FromObject(values);
563 if (values == NULL)
564 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000565 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000566 Py_DECREF(values);
567 return err;
568 }
569 if (values == NULL) {
570 /* del b[lo:hi] */
571 bytes = NULL;
572 needed = 0;
573 }
574 else {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200575 if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) {
576 PyErr_Format(PyExc_TypeError,
577 "can't set bytearray slice from %.100s",
578 Py_TYPE(values)->tp_name);
579 return -1;
580 }
581 needed = vbytes.len;
582 bytes = vbytes.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000583 }
584
585 if (lo < 0)
586 lo = 0;
587 if (hi < lo)
588 hi = lo;
589 if (hi > Py_SIZE(self))
590 hi = Py_SIZE(self);
591
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200592 res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000593 if (vbytes.len != -1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200594 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000595 return res;
596}
597
598static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000599bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000600{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000601 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000602
603 if (i < 0)
604 i += Py_SIZE(self);
605
606 if (i < 0 || i >= Py_SIZE(self)) {
607 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
608 return -1;
609 }
610
611 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000612 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000613
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000614 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000615 return -1;
616
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200617 PyByteArray_AS_STRING(self)[i] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000618 return 0;
619}
620
621static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000622bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000623{
624 Py_ssize_t start, stop, step, slicelen, needed;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200625 char *buf, *bytes;
626 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000627
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000628 if (PyIndex_Check(index)) {
629 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000630
631 if (i == -1 && PyErr_Occurred())
632 return -1;
633
634 if (i < 0)
635 i += PyByteArray_GET_SIZE(self);
636
637 if (i < 0 || i >= Py_SIZE(self)) {
638 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
639 return -1;
640 }
641
642 if (values == NULL) {
643 /* Fall through to slice assignment */
644 start = i;
645 stop = i + 1;
646 step = 1;
647 slicelen = 1;
648 }
649 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000650 int ival;
651 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000652 return -1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200653 buf[i] = (char)ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000654 return 0;
655 }
656 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000657 else if (PySlice_Check(index)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000658 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000659 PyByteArray_GET_SIZE(self),
660 &start, &stop, &step, &slicelen) < 0) {
661 return -1;
662 }
663 }
664 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400665 PyErr_Format(PyExc_TypeError,
666 "bytearray indices must be integers or slices, not %.200s",
667 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000668 return -1;
669 }
670
671 if (values == NULL) {
672 bytes = NULL;
673 needed = 0;
674 }
675 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
Christian Heimes6d26ade2012-11-03 23:07:59 +0100676 int err;
Ezio Melottic64bcbe2012-11-03 21:19:06 +0200677 if (PyNumber_Check(values) || PyUnicode_Check(values)) {
678 PyErr_SetString(PyExc_TypeError,
679 "can assign only bytes, buffers, or iterables "
680 "of ints in range(0, 256)");
681 return -1;
682 }
Georg Brandlf3fa5682010-12-04 17:09:30 +0000683 /* Make a copy and call this function recursively */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000684 values = PyByteArray_FromObject(values);
685 if (values == NULL)
686 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000687 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000688 Py_DECREF(values);
689 return err;
690 }
691 else {
692 assert(PyByteArray_Check(values));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200693 bytes = PyByteArray_AS_STRING(values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000694 needed = Py_SIZE(values);
695 }
696 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
697 if ((step < 0 && start < stop) ||
698 (step > 0 && start > stop))
699 stop = start;
700 if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200701 return bytearray_setslice_linear(self, start, stop, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000702 }
703 else {
704 if (needed == 0) {
705 /* Delete slice */
Mark Dickinsonbc099642010-01-29 17:27:24 +0000706 size_t cur;
707 Py_ssize_t i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000708
Antoine Pitrou5504e892008-12-06 21:27:53 +0000709 if (!_canresize(self))
710 return -1;
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000711
712 if (slicelen == 0)
713 /* Nothing to do here. */
714 return 0;
715
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000716 if (step < 0) {
717 stop = start + 1;
718 start = stop + step * (slicelen - 1) - 1;
719 step = -step;
720 }
721 for (cur = start, i = 0;
722 i < slicelen; cur += step, i++) {
723 Py_ssize_t lim = step - 1;
724
Mark Dickinson66f575b2010-02-14 12:53:32 +0000725 if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000726 lim = PyByteArray_GET_SIZE(self) - cur - 1;
727
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200728 memmove(buf + cur - i,
729 buf + cur + 1, lim);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000730 }
731 /* Move the tail of the bytes, in one chunk */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000732 cur = start + (size_t)slicelen*step;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000733 if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200734 memmove(buf + cur - slicelen,
735 buf + cur,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000736 PyByteArray_GET_SIZE(self) - cur);
737 }
738 if (PyByteArray_Resize((PyObject *)self,
739 PyByteArray_GET_SIZE(self) - slicelen) < 0)
740 return -1;
741
742 return 0;
743 }
744 else {
745 /* Assign slice */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000746 Py_ssize_t i;
747 size_t cur;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000748
749 if (needed != slicelen) {
750 PyErr_Format(PyExc_ValueError,
751 "attempt to assign bytes of size %zd "
752 "to extended slice of size %zd",
753 needed, slicelen);
754 return -1;
755 }
756 for (cur = start, i = 0; i < slicelen; cur += step, i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200757 buf[cur] = bytes[i];
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000758 return 0;
759 }
760 }
761}
762
763static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000764bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000765{
766 static char *kwlist[] = {"source", "encoding", "errors", 0};
767 PyObject *arg = NULL;
768 const char *encoding = NULL;
769 const char *errors = NULL;
770 Py_ssize_t count;
771 PyObject *it;
772 PyObject *(*iternext)(PyObject *);
773
774 if (Py_SIZE(self) != 0) {
775 /* Empty previous contents (yes, do this first of all!) */
776 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
777 return -1;
778 }
779
780 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000781 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000782 &arg, &encoding, &errors))
783 return -1;
784
785 /* Make a quick exit if no first argument */
786 if (arg == NULL) {
787 if (encoding != NULL || errors != NULL) {
788 PyErr_SetString(PyExc_TypeError,
789 "encoding or errors without sequence argument");
790 return -1;
791 }
792 return 0;
793 }
794
795 if (PyUnicode_Check(arg)) {
796 /* Encode via the codec registry */
797 PyObject *encoded, *new;
798 if (encoding == NULL) {
799 PyErr_SetString(PyExc_TypeError,
800 "string argument without an encoding");
801 return -1;
802 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000803 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000804 if (encoded == NULL)
805 return -1;
806 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000807 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000808 Py_DECREF(encoded);
809 if (new == NULL)
810 return -1;
811 Py_DECREF(new);
812 return 0;
813 }
814
815 /* If it's not unicode, there can't be encoding or errors */
816 if (encoding != NULL || errors != NULL) {
817 PyErr_SetString(PyExc_TypeError,
818 "encoding or errors without a string argument");
819 return -1;
820 }
821
822 /* Is it an int? */
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000823 count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
824 if (count == -1 && PyErr_Occurred()) {
825 if (PyErr_ExceptionMatches(PyExc_OverflowError))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000826 return -1;
Benjamin Peterson9c0e94f2010-04-16 23:00:53 +0000827 PyErr_Clear();
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000828 }
829 else if (count < 0) {
830 PyErr_SetString(PyExc_ValueError, "negative count");
831 return -1;
832 }
833 else {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000834 if (count > 0) {
Victor Stinner2bc4d952014-06-02 22:22:42 +0200835 if (PyByteArray_Resize((PyObject *)self, count))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000836 return -1;
Victor Stinner2bc4d952014-06-02 22:22:42 +0200837 memset(PyByteArray_AS_STRING(self), 0, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000838 }
839 return 0;
840 }
841
842 /* Use the buffer API */
843 if (PyObject_CheckBuffer(arg)) {
844 Py_ssize_t size;
845 Py_buffer view;
846 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
847 return -1;
848 size = view.len;
849 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200850 if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
851 &view, size, 'C') < 0)
Stefan Krah7d12d9d2012-07-28 12:25:55 +0200852 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000853 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000854 return 0;
855 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000856 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000857 return -1;
858 }
859
860 /* XXX Optimize this if the arguments is a list, tuple */
861
862 /* Get the iterator */
863 it = PyObject_GetIter(arg);
864 if (it == NULL)
865 return -1;
866 iternext = *Py_TYPE(it)->tp_iternext;
867
868 /* Run the iterator to exhaustion */
869 for (;;) {
870 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000871 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000872
873 /* Get the next item */
874 item = iternext(it);
875 if (item == NULL) {
876 if (PyErr_Occurred()) {
877 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
878 goto error;
879 PyErr_Clear();
880 }
881 break;
882 }
883
884 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000885 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000886 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000887 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000888 goto error;
889
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000890 /* Append the byte */
Serhiy Storchaka7b6e3b92015-06-29 21:14:06 +0300891 if (Py_SIZE(self) + 1 < self->ob_alloc) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000892 Py_SIZE(self)++;
Serhiy Storchaka7b6e3b92015-06-29 21:14:06 +0300893 PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0';
894 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000895 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
896 goto error;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200897 PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000898 }
899
900 /* Clean up and return success */
901 Py_DECREF(it);
902 return 0;
903
904 error:
905 /* Error handling when it != NULL */
906 Py_DECREF(it);
907 return -1;
908}
909
910/* Mostly copied from string_repr, but without the
911 "smart quote" functionality. */
912static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000913bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000914{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000915 const char *quote_prefix = "bytearray(b";
916 const char *quote_postfix = ")";
917 Py_ssize_t length = Py_SIZE(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200918 /* 15 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */
Mark Dickinson66f575b2010-02-14 12:53:32 +0000919 size_t newsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000920 PyObject *v;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200921 Py_ssize_t i;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200922 char *bytes;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200923 char c;
924 char *p;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200925 int quote;
926 char *test, *start;
927 char *buffer;
928
929 if (length > (PY_SSIZE_T_MAX - 15) / 4) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000930 PyErr_SetString(PyExc_OverflowError,
931 "bytearray object is too large to make repr");
932 return NULL;
933 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200934
935 newsize = 15 + length * 4;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100936 buffer = PyObject_Malloc(newsize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200937 if (buffer == NULL) {
938 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000939 return NULL;
940 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000941
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200942 /* Figure out which quote to use; single is preferred */
943 quote = '\'';
944 start = PyByteArray_AS_STRING(self);
945 for (test = start; test < start+length; ++test) {
946 if (*test == '"') {
947 quote = '\''; /* back to single */
948 break;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000949 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200950 else if (*test == '\'')
951 quote = '"';
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000952 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200953
954 p = buffer;
955 while (*quote_prefix)
956 *p++ = *quote_prefix++;
957 *p++ = quote;
958
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200959 bytes = PyByteArray_AS_STRING(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200960 for (i = 0; i < length; i++) {
961 /* There's at least enough room for a hex escape
962 and a closing quote. */
963 assert(newsize - (p - buffer) >= 5);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200964 c = bytes[i];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200965 if (c == '\'' || c == '\\')
966 *p++ = '\\', *p++ = c;
967 else if (c == '\t')
968 *p++ = '\\', *p++ = 't';
969 else if (c == '\n')
970 *p++ = '\\', *p++ = 'n';
971 else if (c == '\r')
972 *p++ = '\\', *p++ = 'r';
973 else if (c == 0)
974 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
975 else if (c < ' ' || c >= 0x7f) {
976 *p++ = '\\';
977 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +0200978 *p++ = Py_hexdigits[(c & 0xf0) >> 4];
979 *p++ = Py_hexdigits[c & 0xf];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200980 }
981 else
982 *p++ = c;
983 }
984 assert(newsize - (p - buffer) >= 1);
985 *p++ = quote;
986 while (*quote_postfix) {
987 *p++ = *quote_postfix++;
988 }
989
990 v = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100991 PyObject_Free(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200992 return v;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000993}
994
995static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000996bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000997{
Alexander Belopolskyf0f45142010-08-11 17:31:17 +0000998 if (Py_BytesWarningFlag) {
999 if (PyErr_WarnEx(PyExc_BytesWarning,
1000 "str() on a bytearray instance", 1))
1001 return NULL;
1002 }
1003 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001004}
1005
1006static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001007bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001008{
1009 Py_ssize_t self_size, other_size;
1010 Py_buffer self_bytes, other_bytes;
1011 PyObject *res;
1012 Py_ssize_t minsize;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001013 int cmp, rc;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001014
1015 /* Bytes can be compared to anything that supports the (binary)
1016 buffer API. Except that a comparison with Unicode is always an
1017 error, even if the comparison is for equality. */
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001018 rc = PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type);
1019 if (!rc)
1020 rc = PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type);
1021 if (rc < 0)
1022 return NULL;
1023 if (rc) {
Barry Warsaw9e9dcd62008-10-17 01:50:37 +00001024 if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001025 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +00001026 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001027 return NULL;
1028 }
1029
Brian Curtindfc80e32011-08-10 20:28:54 -05001030 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001031 }
1032
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001033 if (PyObject_GetBuffer(self, &self_bytes, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001034 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05001035 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001036 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001037 self_size = self_bytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001038
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001039 if (PyObject_GetBuffer(other, &other_bytes, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001040 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +00001041 PyBuffer_Release(&self_bytes);
Brian Curtindfc80e32011-08-10 20:28:54 -05001042 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001043 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001044 other_size = other_bytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001045
1046 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
1047 /* Shortcut: if the lengths differ, the objects differ */
1048 cmp = (op == Py_NE);
1049 }
1050 else {
1051 minsize = self_size;
1052 if (other_size < minsize)
1053 minsize = other_size;
1054
1055 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
1056 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
1057
1058 if (cmp == 0) {
1059 if (self_size < other_size)
1060 cmp = -1;
1061 else if (self_size > other_size)
1062 cmp = 1;
1063 }
1064
1065 switch (op) {
1066 case Py_LT: cmp = cmp < 0; break;
1067 case Py_LE: cmp = cmp <= 0; break;
1068 case Py_EQ: cmp = cmp == 0; break;
1069 case Py_NE: cmp = cmp != 0; break;
1070 case Py_GT: cmp = cmp > 0; break;
1071 case Py_GE: cmp = cmp >= 0; break;
1072 }
1073 }
1074
1075 res = cmp ? Py_True : Py_False;
Martin v. Löwis423be952008-08-13 15:53:07 +00001076 PyBuffer_Release(&self_bytes);
1077 PyBuffer_Release(&other_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001078 Py_INCREF(res);
1079 return res;
1080}
1081
1082static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001083bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001084{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001085 if (self->ob_exports > 0) {
1086 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001087 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001088 PyErr_Print();
1089 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001090 if (self->ob_bytes != 0) {
Antoine Pitrou39aba4f2011-11-12 21:15:28 +01001091 PyObject_Free(self->ob_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001092 }
1093 Py_TYPE(self)->tp_free((PyObject *)self);
1094}
1095
1096
1097/* -------------------------------------------------------------------- */
1098/* Methods */
1099
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100#define FASTSEARCH fastsearch
1101#define STRINGLIB(F) stringlib_##F
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001102#define STRINGLIB_CHAR char
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001103#define STRINGLIB_SIZEOF_CHAR 1
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001104#define STRINGLIB_LEN PyByteArray_GET_SIZE
1105#define STRINGLIB_STR PyByteArray_AS_STRING
1106#define STRINGLIB_NEW PyByteArray_FromStringAndSize
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001107#define STRINGLIB_ISSPACE Py_ISSPACE
1108#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001109#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1110#define STRINGLIB_MUTABLE 1
1111
1112#include "stringlib/fastsearch.h"
1113#include "stringlib/count.h"
1114#include "stringlib/find.h"
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001115#include "stringlib/join.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001116#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001117#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001118#include "stringlib/ctype.h"
1119#include "stringlib/transmogrify.h"
1120
1121
1122/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1123were copied from the old char* style string object. */
1124
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001125/* helper macro to fixup start/end slice values */
1126#define ADJUST_INDICES(start, end, len) \
1127 if (end > len) \
1128 end = len; \
1129 else if (end < 0) { \
1130 end += len; \
1131 if (end < 0) \
1132 end = 0; \
1133 } \
1134 if (start < 0) { \
1135 start += len; \
1136 if (start < 0) \
1137 start = 0; \
1138 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001139
1140Py_LOCAL_INLINE(Py_ssize_t)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001141bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001142{
1143 PyObject *subobj;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001144 char byte;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001145 Py_buffer subbuf;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001146 const char *sub;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02001147 Py_ssize_t len, sub_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001148 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1149 Py_ssize_t res;
1150
Antoine Pitrouac65d962011-10-20 23:54:17 +02001151 if (!stringlib_parse_args_finds_byte("find/rfind/index/rindex",
1152 args, &subobj, &byte, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001153 return -2;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001154
1155 if (subobj) {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001156 if (PyObject_GetBuffer(subobj, &subbuf, PyBUF_SIMPLE) != 0)
Antoine Pitrouac65d962011-10-20 23:54:17 +02001157 return -2;
1158
1159 sub = subbuf.buf;
1160 sub_len = subbuf.len;
1161 }
1162 else {
1163 sub = &byte;
1164 sub_len = 1;
1165 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02001166 len = PyByteArray_GET_SIZE(self);
Antoine Pitrouac65d962011-10-20 23:54:17 +02001167
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02001168 ADJUST_INDICES(start, end, len);
1169 if (end - start < sub_len)
1170 res = -1;
Serhiy Storchakad92d4ef2015-07-20 22:58:02 +03001171 else if (sub_len == 1
1172#ifndef HAVE_MEMRCHR
1173 && dir > 0
1174#endif
1175 ) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02001176 unsigned char needle = *sub;
Serhiy Storchakad92d4ef2015-07-20 22:58:02 +03001177 int mode = (dir > 0) ? FAST_SEARCH : FAST_RSEARCH;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02001178 res = stringlib_fastsearch_memchr_1char(
1179 PyByteArray_AS_STRING(self) + start, end - start,
Serhiy Storchakad92d4ef2015-07-20 22:58:02 +03001180 needle, needle, mode);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02001181 if (res >= 0)
1182 res += start;
1183 }
1184 else {
1185 if (dir > 0)
1186 res = stringlib_find_slice(
1187 PyByteArray_AS_STRING(self), len,
1188 sub, sub_len, start, end);
1189 else
1190 res = stringlib_rfind_slice(
1191 PyByteArray_AS_STRING(self), len,
1192 sub, sub_len, start, end);
1193 }
Antoine Pitrouac65d962011-10-20 23:54:17 +02001194
1195 if (subobj)
1196 PyBuffer_Release(&subbuf);
1197
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001198 return res;
1199}
1200
1201PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001202"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001203\n\
1204Return the lowest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001205such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001206arguments start and end are interpreted as in slice notation.\n\
1207\n\
1208Return -1 on failure.");
1209
1210static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001211bytearray_find(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001212{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001213 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001214 if (result == -2)
1215 return NULL;
1216 return PyLong_FromSsize_t(result);
1217}
1218
1219PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001220"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001221\n\
1222Return the number of non-overlapping occurrences of subsection sub in\n\
1223bytes B[start:end]. Optional arguments start and end are interpreted\n\
1224as in slice notation.");
1225
1226static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001227bytearray_count(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001228{
1229 PyObject *sub_obj;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001230 const char *str = PyByteArray_AS_STRING(self), *sub;
1231 Py_ssize_t sub_len;
1232 char byte;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001233 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001234
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001235 Py_buffer vsub;
1236 PyObject *count_obj;
1237
Antoine Pitrouac65d962011-10-20 23:54:17 +02001238 if (!stringlib_parse_args_finds_byte("count", args, &sub_obj, &byte,
1239 &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001240 return NULL;
1241
Antoine Pitrouac65d962011-10-20 23:54:17 +02001242 if (sub_obj) {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001243 if (PyObject_GetBuffer(sub_obj, &vsub, PyBUF_SIMPLE) != 0)
Antoine Pitrouac65d962011-10-20 23:54:17 +02001244 return NULL;
1245
1246 sub = vsub.buf;
1247 sub_len = vsub.len;
1248 }
1249 else {
1250 sub = &byte;
1251 sub_len = 1;
1252 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001253
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001254 ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001255
1256 count_obj = PyLong_FromSsize_t(
Antoine Pitrouac65d962011-10-20 23:54:17 +02001257 stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001258 );
Antoine Pitrouac65d962011-10-20 23:54:17 +02001259
1260 if (sub_obj)
1261 PyBuffer_Release(&vsub);
1262
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001263 return count_obj;
1264}
1265
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001266/*[clinic input]
1267bytearray.clear
1268
1269 self: self(type="PyByteArrayObject *")
1270
1271Remove all items from the bytearray.
1272[clinic start generated code]*/
1273
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001274static PyObject *
1275bytearray_clear_impl(PyByteArrayObject *self)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001276/*[clinic end generated code: output=85c2fe6aede0956c input=e524fd330abcdc18]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001277{
1278 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
1279 return NULL;
1280 Py_RETURN_NONE;
1281}
1282
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001283/*[clinic input]
1284bytearray.copy
1285
1286 self: self(type="PyByteArrayObject *")
1287
1288Return a copy of B.
1289[clinic start generated code]*/
1290
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001291static PyObject *
1292bytearray_copy_impl(PyByteArrayObject *self)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001293/*[clinic end generated code: output=68cfbcfed484c132 input=6d5d2975aa0f33f3]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001294{
1295 return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
1296 PyByteArray_GET_SIZE(self));
1297}
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001298
1299PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001300"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001301\n\
1302Like B.find() but raise ValueError when the subsection is not found.");
1303
1304static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001305bytearray_index(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001306{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001307 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001308 if (result == -2)
1309 return NULL;
1310 if (result == -1) {
1311 PyErr_SetString(PyExc_ValueError,
1312 "subsection not found");
1313 return NULL;
1314 }
1315 return PyLong_FromSsize_t(result);
1316}
1317
1318
1319PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001320"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001321\n\
1322Return the highest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001323such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001324arguments start and end are interpreted as in slice notation.\n\
1325\n\
1326Return -1 on failure.");
1327
1328static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001329bytearray_rfind(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001330{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001331 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001332 if (result == -2)
1333 return NULL;
1334 return PyLong_FromSsize_t(result);
1335}
1336
1337
1338PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001339"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001340\n\
1341Like B.rfind() but raise ValueError when the subsection is not found.");
1342
1343static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001344bytearray_rindex(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001345{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001346 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001347 if (result == -2)
1348 return NULL;
1349 if (result == -1) {
1350 PyErr_SetString(PyExc_ValueError,
1351 "subsection not found");
1352 return NULL;
1353 }
1354 return PyLong_FromSsize_t(result);
1355}
1356
1357
1358static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001359bytearray_contains(PyObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001360{
1361 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1362 if (ival == -1 && PyErr_Occurred()) {
1363 Py_buffer varg;
Antoine Pitrou0010d372010-08-15 17:12:55 +00001364 Py_ssize_t pos;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001365 PyErr_Clear();
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001366 if (PyObject_GetBuffer(arg, &varg, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001367 return -1;
1368 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1369 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001370 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001371 return pos >= 0;
1372 }
1373 if (ival < 0 || ival >= 256) {
1374 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1375 return -1;
1376 }
1377
Antoine Pitrou0010d372010-08-15 17:12:55 +00001378 return memchr(PyByteArray_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001379}
1380
1381
1382/* Matches the end (direction >= 0) or start (direction < 0) of self
1383 * against substr, using the start and end arguments. Returns
1384 * -1 on error, 0 if not found and 1 if found.
1385 */
1386Py_LOCAL(int)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001387_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001388 Py_ssize_t end, int direction)
1389{
1390 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1391 const char* str;
1392 Py_buffer vsubstr;
1393 int rv = 0;
1394
1395 str = PyByteArray_AS_STRING(self);
1396
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001397 if (PyObject_GetBuffer(substr, &vsubstr, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001398 return -1;
1399
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001400 ADJUST_INDICES(start, end, len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001401
1402 if (direction < 0) {
1403 /* startswith */
1404 if (start+vsubstr.len > len) {
1405 goto done;
1406 }
1407 } else {
1408 /* endswith */
1409 if (end-start < vsubstr.len || start > len) {
1410 goto done;
1411 }
1412
1413 if (end-vsubstr.len > start)
1414 start = end - vsubstr.len;
1415 }
1416 if (end-start >= vsubstr.len)
1417 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1418
1419done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001420 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001421 return rv;
1422}
1423
1424
1425PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001426"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001427\n\
1428Return True if B starts with the specified prefix, False otherwise.\n\
1429With optional start, test B beginning at that position.\n\
1430With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001431prefix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001432
1433static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001434bytearray_startswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001435{
1436 Py_ssize_t start = 0;
1437 Py_ssize_t end = PY_SSIZE_T_MAX;
1438 PyObject *subobj;
1439 int result;
1440
Jesus Ceaac451502011-04-20 17:09:23 +02001441 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001442 return NULL;
1443 if (PyTuple_Check(subobj)) {
1444 Py_ssize_t i;
1445 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001446 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001447 PyTuple_GET_ITEM(subobj, i),
1448 start, end, -1);
1449 if (result == -1)
1450 return NULL;
1451 else if (result) {
1452 Py_RETURN_TRUE;
1453 }
1454 }
1455 Py_RETURN_FALSE;
1456 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001457 result = _bytearray_tailmatch(self, subobj, start, end, -1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001458 if (result == -1) {
1459 if (PyErr_ExceptionMatches(PyExc_TypeError))
1460 PyErr_Format(PyExc_TypeError, "startswith first arg must be bytes "
1461 "or a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001462 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001463 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001464 else
1465 return PyBool_FromLong(result);
1466}
1467
1468PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001469"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001470\n\
1471Return True if B ends with the specified suffix, False otherwise.\n\
1472With optional start, test B beginning at that position.\n\
1473With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001474suffix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001475
1476static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001477bytearray_endswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001478{
1479 Py_ssize_t start = 0;
1480 Py_ssize_t end = PY_SSIZE_T_MAX;
1481 PyObject *subobj;
1482 int result;
1483
Jesus Ceaac451502011-04-20 17:09:23 +02001484 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001485 return NULL;
1486 if (PyTuple_Check(subobj)) {
1487 Py_ssize_t i;
1488 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001489 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001490 PyTuple_GET_ITEM(subobj, i),
1491 start, end, +1);
1492 if (result == -1)
1493 return NULL;
1494 else if (result) {
1495 Py_RETURN_TRUE;
1496 }
1497 }
1498 Py_RETURN_FALSE;
1499 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001500 result = _bytearray_tailmatch(self, subobj, start, end, +1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001501 if (result == -1) {
1502 if (PyErr_ExceptionMatches(PyExc_TypeError))
1503 PyErr_Format(PyExc_TypeError, "endswith first arg must be bytes or "
1504 "a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001505 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001506 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001507 else
1508 return PyBool_FromLong(result);
1509}
1510
1511
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001512/*[clinic input]
1513bytearray.translate
1514
1515 self: self(type="PyByteArrayObject *")
1516 table: object
1517 Translation table, which must be a bytes object of length 256.
1518 [
1519 deletechars: object
1520 ]
1521 /
1522
1523Return a copy with each character mapped by the given translation table.
1524
1525All characters occurring in the optional argument deletechars are removed.
1526The remaining characters are mapped through the given translation table.
1527[clinic start generated code]*/
1528
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001529static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001530bytearray_translate_impl(PyByteArrayObject *self, PyObject *table,
1531 int group_right_1, PyObject *deletechars)
1532/*[clinic end generated code: output=2bebc86a9a1ff083 input=b749ad85f4860824]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001533{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001534 char *input, *output;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001535 const char *table_chars;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001536 Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001537 PyObject *input_obj = (PyObject*)self;
1538 const char *output_start;
1539 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001540 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001541 int trans_table[256];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001542 Py_buffer vtable, vdel;
1543
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001544 if (table == Py_None) {
1545 table_chars = NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001546 table = NULL;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001547 } else if (PyObject_GetBuffer(table, &vtable, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001548 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001549 } else {
1550 if (vtable.len != 256) {
1551 PyErr_SetString(PyExc_ValueError,
1552 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001553 PyBuffer_Release(&vtable);
1554 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001555 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001556 table_chars = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001557 }
1558
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001559 if (deletechars != NULL) {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001560 if (PyObject_GetBuffer(deletechars, &vdel, PyBUF_SIMPLE) != 0) {
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001561 if (table != NULL)
Georg Brandl953152f2009-07-22 12:03:59 +00001562 PyBuffer_Release(&vtable);
1563 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001564 }
1565 }
1566 else {
1567 vdel.buf = NULL;
1568 vdel.len = 0;
1569 }
1570
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001571 inlen = PyByteArray_GET_SIZE(input_obj);
1572 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1573 if (result == NULL)
1574 goto done;
1575 output_start = output = PyByteArray_AsString(result);
1576 input = PyByteArray_AS_STRING(input_obj);
1577
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001578 if (vdel.len == 0 && table_chars != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001579 /* If no deletions are required, use faster code */
1580 for (i = inlen; --i >= 0; ) {
1581 c = Py_CHARMASK(*input++);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001582 *output++ = table_chars[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001583 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001584 goto done;
1585 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001586
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001587 if (table_chars == NULL) {
Georg Brandlccc47b62008-12-28 11:44:14 +00001588 for (i = 0; i < 256; i++)
1589 trans_table[i] = Py_CHARMASK(i);
1590 } else {
1591 for (i = 0; i < 256; i++)
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001592 trans_table[i] = Py_CHARMASK(table_chars[i]);
Georg Brandlccc47b62008-12-28 11:44:14 +00001593 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001594
1595 for (i = 0; i < vdel.len; i++)
1596 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1597
1598 for (i = inlen; --i >= 0; ) {
1599 c = Py_CHARMASK(*input++);
1600 if (trans_table[c] != -1)
1601 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1602 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001603 }
1604 /* Fix the size of the resulting string */
1605 if (inlen > 0)
Christian Heimesc731bbe2013-07-21 02:04:35 +02001606 if (PyByteArray_Resize(result, output - output_start) < 0) {
1607 Py_CLEAR(result);
1608 goto done;
1609 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001610
1611done:
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001612 if (table != NULL)
Georg Brandlccc47b62008-12-28 11:44:14 +00001613 PyBuffer_Release(&vtable);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001614 if (deletechars != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001615 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001616 return result;
1617}
1618
1619
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001620/*[clinic input]
1621
1622@staticmethod
1623bytearray.maketrans
1624
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001625 frm: Py_buffer
1626 to: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001627 /
1628
1629Return a translation table useable for the bytes or bytearray translate method.
1630
1631The returned table will be one where each byte in frm is mapped to the byte at
1632the same position in to.
1633
1634The bytes objects frm and to must be of the same length.
1635[clinic start generated code]*/
1636
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001637static PyObject *
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001638bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001639/*[clinic end generated code: output=1df267d99f56b15e input=5925a81d2fbbf151]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001640{
1641 return _Py_bytes_maketrans(frm, to);
Georg Brandlabc38772009-04-12 15:51:51 +00001642}
1643
1644
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001645/* find and count characters and substrings */
1646
1647#define findchar(target, target_len, c) \
1648 ((char *)memchr((const void *)(target), c, target_len))
1649
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001650
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001651/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001652Py_LOCAL(PyByteArrayObject *)
1653return_self(PyByteArrayObject *self)
1654{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001655 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001656 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1657 PyByteArray_AS_STRING(self),
1658 PyByteArray_GET_SIZE(self));
1659}
1660
1661Py_LOCAL_INLINE(Py_ssize_t)
1662countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1663{
1664 Py_ssize_t count=0;
1665 const char *start=target;
1666 const char *end=target+target_len;
1667
1668 while ( (start=findchar(start, end-start, c)) != NULL ) {
1669 count++;
1670 if (count >= maxcount)
1671 break;
1672 start += 1;
1673 }
1674 return count;
1675}
1676
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001677
1678/* Algorithms for different cases of string replacement */
1679
1680/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1681Py_LOCAL(PyByteArrayObject *)
1682replace_interleave(PyByteArrayObject *self,
1683 const char *to_s, Py_ssize_t to_len,
1684 Py_ssize_t maxcount)
1685{
1686 char *self_s, *result_s;
1687 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001688 Py_ssize_t count, i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001689 PyByteArrayObject *result;
1690
1691 self_len = PyByteArray_GET_SIZE(self);
1692
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001693 /* 1 at the end plus 1 after every character;
1694 count = min(maxcount, self_len + 1) */
1695 if (maxcount <= self_len)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001696 count = maxcount;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001697 else
1698 /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
1699 count = self_len + 1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001700
1701 /* Check for overflow */
1702 /* result_len = count * to_len + self_len; */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001703 assert(count > 0);
1704 if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001705 PyErr_SetString(PyExc_OverflowError,
1706 "replace string is too long");
1707 return NULL;
1708 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001709 result_len = count * to_len + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001710
1711 if (! (result = (PyByteArrayObject *)
1712 PyByteArray_FromStringAndSize(NULL, result_len)) )
1713 return NULL;
1714
1715 self_s = PyByteArray_AS_STRING(self);
1716 result_s = PyByteArray_AS_STRING(result);
1717
1718 /* TODO: special case single character, which doesn't need memcpy */
1719
1720 /* Lay the first one down (guaranteed this will occur) */
1721 Py_MEMCPY(result_s, to_s, to_len);
1722 result_s += to_len;
1723 count -= 1;
1724
1725 for (i=0; i<count; i++) {
1726 *result_s++ = *self_s++;
1727 Py_MEMCPY(result_s, to_s, to_len);
1728 result_s += to_len;
1729 }
1730
1731 /* Copy the rest of the original string */
1732 Py_MEMCPY(result_s, self_s, self_len-i);
1733
1734 return result;
1735}
1736
1737/* Special case for deleting a single character */
1738/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1739Py_LOCAL(PyByteArrayObject *)
1740replace_delete_single_character(PyByteArrayObject *self,
1741 char from_c, Py_ssize_t maxcount)
1742{
1743 char *self_s, *result_s;
1744 char *start, *next, *end;
1745 Py_ssize_t self_len, result_len;
1746 Py_ssize_t count;
1747 PyByteArrayObject *result;
1748
1749 self_len = PyByteArray_GET_SIZE(self);
1750 self_s = PyByteArray_AS_STRING(self);
1751
1752 count = countchar(self_s, self_len, from_c, maxcount);
1753 if (count == 0) {
1754 return return_self(self);
1755 }
1756
1757 result_len = self_len - count; /* from_len == 1 */
1758 assert(result_len>=0);
1759
1760 if ( (result = (PyByteArrayObject *)
1761 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1762 return NULL;
1763 result_s = PyByteArray_AS_STRING(result);
1764
1765 start = self_s;
1766 end = self_s + self_len;
1767 while (count-- > 0) {
1768 next = findchar(start, end-start, from_c);
1769 if (next == NULL)
1770 break;
1771 Py_MEMCPY(result_s, start, next-start);
1772 result_s += (next-start);
1773 start = next+1;
1774 }
1775 Py_MEMCPY(result_s, start, end-start);
1776
1777 return result;
1778}
1779
1780/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1781
1782Py_LOCAL(PyByteArrayObject *)
1783replace_delete_substring(PyByteArrayObject *self,
1784 const char *from_s, Py_ssize_t from_len,
1785 Py_ssize_t maxcount)
1786{
1787 char *self_s, *result_s;
1788 char *start, *next, *end;
1789 Py_ssize_t self_len, result_len;
1790 Py_ssize_t count, offset;
1791 PyByteArrayObject *result;
1792
1793 self_len = PyByteArray_GET_SIZE(self);
1794 self_s = PyByteArray_AS_STRING(self);
1795
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001796 count = stringlib_count(self_s, self_len,
1797 from_s, from_len,
1798 maxcount);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001799
1800 if (count == 0) {
1801 /* no matches */
1802 return return_self(self);
1803 }
1804
1805 result_len = self_len - (count * from_len);
1806 assert (result_len>=0);
1807
1808 if ( (result = (PyByteArrayObject *)
1809 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1810 return NULL;
1811
1812 result_s = PyByteArray_AS_STRING(result);
1813
1814 start = self_s;
1815 end = self_s + self_len;
1816 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001817 offset = stringlib_find(start, end-start,
1818 from_s, from_len,
1819 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001820 if (offset == -1)
1821 break;
1822 next = start + offset;
1823
1824 Py_MEMCPY(result_s, start, next-start);
1825
1826 result_s += (next-start);
1827 start = next+from_len;
1828 }
1829 Py_MEMCPY(result_s, start, end-start);
1830 return result;
1831}
1832
1833/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1834Py_LOCAL(PyByteArrayObject *)
1835replace_single_character_in_place(PyByteArrayObject *self,
1836 char from_c, char to_c,
1837 Py_ssize_t maxcount)
1838{
Antoine Pitroud1188562010-06-09 16:38:55 +00001839 char *self_s, *result_s, *start, *end, *next;
1840 Py_ssize_t self_len;
1841 PyByteArrayObject *result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001842
Antoine Pitroud1188562010-06-09 16:38:55 +00001843 /* The result string will be the same size */
1844 self_s = PyByteArray_AS_STRING(self);
1845 self_len = PyByteArray_GET_SIZE(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001846
Antoine Pitroud1188562010-06-09 16:38:55 +00001847 next = findchar(self_s, self_len, from_c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001848
Antoine Pitroud1188562010-06-09 16:38:55 +00001849 if (next == NULL) {
1850 /* No matches; return the original bytes */
1851 return return_self(self);
1852 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001853
Antoine Pitroud1188562010-06-09 16:38:55 +00001854 /* Need to make a new bytes */
1855 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1856 if (result == NULL)
1857 return NULL;
1858 result_s = PyByteArray_AS_STRING(result);
1859 Py_MEMCPY(result_s, self_s, self_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001860
Antoine Pitroud1188562010-06-09 16:38:55 +00001861 /* change everything in-place, starting with this one */
1862 start = result_s + (next-self_s);
1863 *start = to_c;
1864 start++;
1865 end = result_s + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001866
Antoine Pitroud1188562010-06-09 16:38:55 +00001867 while (--maxcount > 0) {
1868 next = findchar(start, end-start, from_c);
1869 if (next == NULL)
1870 break;
1871 *next = to_c;
1872 start = next+1;
1873 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001874
Antoine Pitroud1188562010-06-09 16:38:55 +00001875 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001876}
1877
1878/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1879Py_LOCAL(PyByteArrayObject *)
1880replace_substring_in_place(PyByteArrayObject *self,
1881 const char *from_s, Py_ssize_t from_len,
1882 const char *to_s, Py_ssize_t to_len,
1883 Py_ssize_t maxcount)
1884{
1885 char *result_s, *start, *end;
1886 char *self_s;
1887 Py_ssize_t self_len, offset;
1888 PyByteArrayObject *result;
1889
1890 /* The result bytes will be the same size */
1891
1892 self_s = PyByteArray_AS_STRING(self);
1893 self_len = PyByteArray_GET_SIZE(self);
1894
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001895 offset = stringlib_find(self_s, self_len,
1896 from_s, from_len,
1897 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001898 if (offset == -1) {
1899 /* No matches; return the original bytes */
1900 return return_self(self);
1901 }
1902
1903 /* Need to make a new bytes */
1904 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1905 if (result == NULL)
1906 return NULL;
1907 result_s = PyByteArray_AS_STRING(result);
1908 Py_MEMCPY(result_s, self_s, self_len);
1909
1910 /* change everything in-place, starting with this one */
1911 start = result_s + offset;
1912 Py_MEMCPY(start, to_s, from_len);
1913 start += from_len;
1914 end = result_s + self_len;
1915
1916 while ( --maxcount > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001917 offset = stringlib_find(start, end-start,
1918 from_s, from_len,
1919 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001920 if (offset==-1)
1921 break;
1922 Py_MEMCPY(start+offset, to_s, from_len);
1923 start += offset+from_len;
1924 }
1925
1926 return result;
1927}
1928
1929/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
1930Py_LOCAL(PyByteArrayObject *)
1931replace_single_character(PyByteArrayObject *self,
1932 char from_c,
1933 const char *to_s, Py_ssize_t to_len,
1934 Py_ssize_t maxcount)
1935{
1936 char *self_s, *result_s;
1937 char *start, *next, *end;
1938 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001939 Py_ssize_t count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001940 PyByteArrayObject *result;
1941
1942 self_s = PyByteArray_AS_STRING(self);
1943 self_len = PyByteArray_GET_SIZE(self);
1944
1945 count = countchar(self_s, self_len, from_c, maxcount);
1946 if (count == 0) {
1947 /* no matches, return unchanged */
1948 return return_self(self);
1949 }
1950
1951 /* use the difference between current and new, hence the "-1" */
1952 /* result_len = self_len + count * (to_len-1) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001953 assert(count > 0);
1954 if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001955 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1956 return NULL;
1957 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001958 result_len = self_len + count * (to_len - 1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001959
1960 if ( (result = (PyByteArrayObject *)
1961 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1962 return NULL;
1963 result_s = PyByteArray_AS_STRING(result);
1964
1965 start = self_s;
1966 end = self_s + self_len;
1967 while (count-- > 0) {
1968 next = findchar(start, end-start, from_c);
1969 if (next == NULL)
1970 break;
1971
1972 if (next == start) {
1973 /* replace with the 'to' */
1974 Py_MEMCPY(result_s, to_s, to_len);
1975 result_s += to_len;
1976 start += 1;
1977 } else {
1978 /* copy the unchanged old then the 'to' */
1979 Py_MEMCPY(result_s, start, next-start);
1980 result_s += (next-start);
1981 Py_MEMCPY(result_s, to_s, to_len);
1982 result_s += to_len;
1983 start = next+1;
1984 }
1985 }
1986 /* Copy the remainder of the remaining bytes */
1987 Py_MEMCPY(result_s, start, end-start);
1988
1989 return result;
1990}
1991
1992/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
1993Py_LOCAL(PyByteArrayObject *)
1994replace_substring(PyByteArrayObject *self,
1995 const char *from_s, Py_ssize_t from_len,
1996 const char *to_s, Py_ssize_t to_len,
1997 Py_ssize_t maxcount)
1998{
1999 char *self_s, *result_s;
2000 char *start, *next, *end;
2001 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002002 Py_ssize_t count, offset;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002003 PyByteArrayObject *result;
2004
2005 self_s = PyByteArray_AS_STRING(self);
2006 self_len = PyByteArray_GET_SIZE(self);
2007
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002008 count = stringlib_count(self_s, self_len,
2009 from_s, from_len,
2010 maxcount);
2011
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002012 if (count == 0) {
2013 /* no matches, return unchanged */
2014 return return_self(self);
2015 }
2016
2017 /* Check for overflow */
2018 /* result_len = self_len + count * (to_len-from_len) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002019 assert(count > 0);
2020 if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002021 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
2022 return NULL;
2023 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002024 result_len = self_len + count * (to_len - from_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002025
2026 if ( (result = (PyByteArrayObject *)
2027 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
2028 return NULL;
2029 result_s = PyByteArray_AS_STRING(result);
2030
2031 start = self_s;
2032 end = self_s + self_len;
2033 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002034 offset = stringlib_find(start, end-start,
2035 from_s, from_len,
2036 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002037 if (offset == -1)
2038 break;
2039 next = start+offset;
2040 if (next == start) {
2041 /* replace with the 'to' */
2042 Py_MEMCPY(result_s, to_s, to_len);
2043 result_s += to_len;
2044 start += from_len;
2045 } else {
2046 /* copy the unchanged old then the 'to' */
2047 Py_MEMCPY(result_s, start, next-start);
2048 result_s += (next-start);
2049 Py_MEMCPY(result_s, to_s, to_len);
2050 result_s += to_len;
2051 start = next+from_len;
2052 }
2053 }
2054 /* Copy the remainder of the remaining bytes */
2055 Py_MEMCPY(result_s, start, end-start);
2056
2057 return result;
2058}
2059
2060
2061Py_LOCAL(PyByteArrayObject *)
2062replace(PyByteArrayObject *self,
2063 const char *from_s, Py_ssize_t from_len,
2064 const char *to_s, Py_ssize_t to_len,
2065 Py_ssize_t maxcount)
2066{
2067 if (maxcount < 0) {
2068 maxcount = PY_SSIZE_T_MAX;
2069 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
2070 /* nothing to do; return the original bytes */
2071 return return_self(self);
2072 }
2073
2074 if (maxcount == 0 ||
2075 (from_len == 0 && to_len == 0)) {
2076 /* nothing to do; return the original bytes */
2077 return return_self(self);
2078 }
2079
2080 /* Handle zero-length special cases */
2081
2082 if (from_len == 0) {
2083 /* insert the 'to' bytes everywhere. */
2084 /* >>> "Python".replace("", ".") */
2085 /* '.P.y.t.h.o.n.' */
2086 return replace_interleave(self, to_s, to_len, maxcount);
2087 }
2088
2089 /* Except for "".replace("", "A") == "A" there is no way beyond this */
2090 /* point for an empty self bytes to generate a non-empty bytes */
2091 /* Special case so the remaining code always gets a non-empty bytes */
2092 if (PyByteArray_GET_SIZE(self) == 0) {
2093 return return_self(self);
2094 }
2095
2096 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00002097 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002098 if (from_len == 1) {
2099 return replace_delete_single_character(
2100 self, from_s[0], maxcount);
2101 } else {
2102 return replace_delete_substring(self, from_s, from_len, maxcount);
2103 }
2104 }
2105
2106 /* Handle special case where both bytes have the same length */
2107
2108 if (from_len == to_len) {
2109 if (from_len == 1) {
2110 return replace_single_character_in_place(
2111 self,
2112 from_s[0],
2113 to_s[0],
2114 maxcount);
2115 } else {
2116 return replace_substring_in_place(
2117 self, from_s, from_len, to_s, to_len, maxcount);
2118 }
2119 }
2120
2121 /* Otherwise use the more generic algorithms */
2122 if (from_len == 1) {
2123 return replace_single_character(self, from_s[0],
2124 to_s, to_len, maxcount);
2125 } else {
2126 /* len('from')>=2, len('to')>=1 */
2127 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
2128 }
2129}
2130
2131
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002132/*[clinic input]
2133bytearray.replace
2134
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002135 old: Py_buffer
2136 new: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002137 count: Py_ssize_t = -1
2138 Maximum number of occurrences to replace.
2139 -1 (the default value) means replace all occurrences.
2140 /
2141
2142Return a copy with all occurrences of substring old replaced by new.
2143
2144If the optional argument count is given, only the first count occurrences are
2145replaced.
2146[clinic start generated code]*/
2147
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002148static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04002149bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old,
2150 Py_buffer *new, Py_ssize_t count)
2151/*[clinic end generated code: output=d39884c4dc59412a input=aa379d988637c7fb]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002152{
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002153 return (PyObject *)replace((PyByteArrayObject *) self,
2154 old->buf, old->len,
2155 new->buf, new->len, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002156}
2157
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002158/*[clinic input]
2159bytearray.split
2160
2161 sep: object = None
2162 The delimiter according which to split the bytearray.
2163 None (the default value) means split on ASCII whitespace characters
2164 (space, tab, return, newline, formfeed, vertical tab).
2165 maxsplit: Py_ssize_t = -1
2166 Maximum number of splits to do.
2167 -1 (the default value) means no limit.
2168
2169Return a list of the sections in the bytearray, using sep as the delimiter.
2170[clinic start generated code]*/
2171
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002172static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04002173bytearray_split_impl(PyByteArrayObject *self, PyObject *sep,
2174 Py_ssize_t maxsplit)
2175/*[clinic end generated code: output=833e2cf385d9a04d input=24f82669f41bf523]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002176{
2177 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002178 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002179 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002180 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002181
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002182 if (maxsplit < 0)
2183 maxsplit = PY_SSIZE_T_MAX;
2184
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002185 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002186 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002187
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002188 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002189 return NULL;
2190 sub = vsub.buf;
2191 n = vsub.len;
2192
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002193 list = stringlib_split(
2194 (PyObject*) self, s, len, sub, n, maxsplit
2195 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002196 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002197 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002198}
2199
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002200/*[clinic input]
2201bytearray.partition
2202
2203 self: self(type="PyByteArrayObject *")
2204 sep: object
2205 /
2206
2207Partition the bytearray into three parts using the given separator.
2208
2209This will search for the separator sep in the bytearray. If the separator is
2210found, returns a 3-tuple containing the part before the separator, the
2211separator itself, and the part after it.
2212
2213If the separator is not found, returns a 3-tuple containing the original
2214bytearray object and two empty bytearray objects.
2215[clinic start generated code]*/
2216
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002217static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002218bytearray_partition(PyByteArrayObject *self, PyObject *sep)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002219/*[clinic end generated code: output=45d2525ddd35f957 input=7d7fe37b1696d506]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002220{
2221 PyObject *bytesep, *result;
2222
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002223 bytesep = PyByteArray_FromObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002224 if (! bytesep)
2225 return NULL;
2226
2227 result = stringlib_partition(
2228 (PyObject*) self,
2229 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2230 bytesep,
2231 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2232 );
2233
2234 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002235 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002236}
2237
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002238/*[clinic input]
2239bytearray.rpartition
2240
2241 self: self(type="PyByteArrayObject *")
2242 sep: object
2243 /
2244
2245Partition the bytes into three parts using the given separator.
2246
2247This will search for the separator sep in the bytearray, starting and the end.
2248If the separator is found, returns a 3-tuple containing the part before the
2249separator, the separator itself, and the part after it.
2250
2251If the separator is not found, returns a 3-tuple containing two empty bytearray
2252objects and the original bytearray object.
2253[clinic start generated code]*/
2254
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002255static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002256bytearray_rpartition(PyByteArrayObject *self, PyObject *sep)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002257/*[clinic end generated code: output=440de3c9426115e8 input=9b8cd540c1b75853]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002258{
2259 PyObject *bytesep, *result;
2260
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002261 bytesep = PyByteArray_FromObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002262 if (! bytesep)
2263 return NULL;
2264
2265 result = stringlib_rpartition(
2266 (PyObject*) self,
2267 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2268 bytesep,
2269 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2270 );
2271
2272 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002273 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002274}
2275
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002276/*[clinic input]
2277bytearray.rsplit = bytearray.split
2278
2279Return a list of the sections in the bytearray, using sep as the delimiter.
2280
2281Splitting is done starting at the end of the bytearray and working to the front.
2282[clinic start generated code]*/
2283
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002284static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04002285bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep,
2286 Py_ssize_t maxsplit)
2287/*[clinic end generated code: output=a55e0b5a03cb6190 input=a68286e4dd692ffe]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002288{
2289 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002290 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002291 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002292 Py_buffer vsub;
2293
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002294 if (maxsplit < 0)
2295 maxsplit = PY_SSIZE_T_MAX;
2296
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002297 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002298 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002299
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002300 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002301 return NULL;
2302 sub = vsub.buf;
2303 n = vsub.len;
2304
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002305 list = stringlib_rsplit(
2306 (PyObject*) self, s, len, sub, n, maxsplit
2307 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002308 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002309 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002310}
2311
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002312/*[clinic input]
2313bytearray.reverse
2314
2315 self: self(type="PyByteArrayObject *")
2316
2317Reverse the order of the values in B in place.
2318[clinic start generated code]*/
2319
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002320static PyObject *
2321bytearray_reverse_impl(PyByteArrayObject *self)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002322/*[clinic end generated code: output=9f7616f29ab309d3 input=7933a499b8597bd1]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002323{
2324 char swap, *head, *tail;
2325 Py_ssize_t i, j, n = Py_SIZE(self);
2326
2327 j = n / 2;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002328 head = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002329 tail = head + n - 1;
2330 for (i = 0; i < j; i++) {
2331 swap = *head;
2332 *head++ = *tail;
2333 *tail-- = swap;
2334 }
2335
2336 Py_RETURN_NONE;
2337}
2338
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002339
2340/*[python input]
2341class bytesvalue_converter(CConverter):
2342 type = 'int'
2343 converter = '_getbytevalue'
2344[python start generated code]*/
2345/*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/
2346
2347
2348/*[clinic input]
2349bytearray.insert
2350
2351 self: self(type="PyByteArrayObject *")
2352 index: Py_ssize_t
2353 The index where the value is to be inserted.
2354 item: bytesvalue
2355 The item to be inserted.
2356 /
2357
2358Insert a single item into the bytearray before the given index.
2359[clinic start generated code]*/
2360
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002361static PyObject *
2362bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002363/*[clinic end generated code: output=76c775a70e7b07b7 input=833766836ba30e1e]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002364{
2365 Py_ssize_t n = Py_SIZE(self);
2366 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002367
2368 if (n == PY_SSIZE_T_MAX) {
2369 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002370 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002371 return NULL;
2372 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002373 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2374 return NULL;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002375 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002376
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002377 if (index < 0) {
2378 index += n;
2379 if (index < 0)
2380 index = 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002381 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002382 if (index > n)
2383 index = n;
2384 memmove(buf + index + 1, buf + index, n - index);
2385 buf[index] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002386
2387 Py_RETURN_NONE;
2388}
2389
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002390/*[clinic input]
2391bytearray.append
2392
2393 self: self(type="PyByteArrayObject *")
2394 item: bytesvalue
2395 The item to be appended.
2396 /
2397
2398Append a single item to the end of the bytearray.
2399[clinic start generated code]*/
2400
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002401static PyObject *
2402bytearray_append_impl(PyByteArrayObject *self, int item)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002403/*[clinic end generated code: output=a154e19ed1886cb6 input=ae56ea87380407cc]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002404{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002405 Py_ssize_t n = Py_SIZE(self);
2406
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002407 if (n == PY_SSIZE_T_MAX) {
2408 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002409 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002410 return NULL;
2411 }
2412 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2413 return NULL;
2414
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002415 PyByteArray_AS_STRING(self)[n] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002416
2417 Py_RETURN_NONE;
2418}
2419
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002420/*[clinic input]
2421bytearray.extend
2422
2423 self: self(type="PyByteArrayObject *")
2424 iterable_of_ints: object
2425 The iterable of items to append.
2426 /
2427
2428Append all the items from the iterator or sequence to the end of the bytearray.
2429[clinic start generated code]*/
2430
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002431static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002432bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002433/*[clinic end generated code: output=98155dbe249170b1 input=ce83a5d75b70d850]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002434{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002435 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002436 Py_ssize_t buf_size = 0, len = 0;
2437 int value;
2438 char *buf;
2439
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002440 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002441 if (PyObject_CheckBuffer(iterable_of_ints)) {
2442 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002443 return NULL;
2444
2445 Py_RETURN_NONE;
2446 }
2447
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002448 it = PyObject_GetIter(iterable_of_ints);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002449 if (it == NULL)
2450 return NULL;
2451
Ezio Melotti42da6632011-03-15 05:18:48 +02002452 /* Try to determine the length of the argument. 32 is arbitrary. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002453 buf_size = PyObject_LengthHint(iterable_of_ints, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002454 if (buf_size == -1) {
2455 Py_DECREF(it);
2456 return NULL;
2457 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002458
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002459 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002460 if (bytearray_obj == NULL) {
2461 Py_DECREF(it);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002462 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002463 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002464 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002465
2466 while ((item = PyIter_Next(it)) != NULL) {
2467 if (! _getbytevalue(item, &value)) {
2468 Py_DECREF(item);
2469 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002470 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002471 return NULL;
2472 }
2473 buf[len++] = value;
2474 Py_DECREF(item);
2475
2476 if (len >= buf_size) {
Martin Panter371731e2016-07-18 07:53:13 +00002477 Py_ssize_t addition;
2478 if (len == PY_SSIZE_T_MAX) {
2479 Py_DECREF(it);
2480 Py_DECREF(bytearray_obj);
2481 return PyErr_NoMemory();
2482 }
2483 addition = len >> 1;
2484 if (addition > PY_SSIZE_T_MAX - len - 1)
2485 buf_size = PY_SSIZE_T_MAX;
2486 else
2487 buf_size = len + addition + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002488 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002489 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002490 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002491 return NULL;
2492 }
2493 /* Recompute the `buf' pointer, since the resizing operation may
2494 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002495 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002496 }
2497 }
2498 Py_DECREF(it);
2499
2500 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002501 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
2502 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002503 return NULL;
2504 }
2505
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002506 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
2507 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002508 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002509 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002510 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002511
2512 Py_RETURN_NONE;
2513}
2514
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002515/*[clinic input]
2516bytearray.pop
2517
2518 self: self(type="PyByteArrayObject *")
2519 index: Py_ssize_t = -1
2520 The index from where to remove the item.
2521 -1 (the default value) means remove the last item.
2522 /
2523
2524Remove and return a single item from B.
2525
2526If no index argument is given, will pop the last item.
2527[clinic start generated code]*/
2528
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002529static PyObject *
2530bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002531/*[clinic end generated code: output=e0ccd401f8021da8 input=0797e6c0ca9d5a85]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002532{
2533 int value;
2534 Py_ssize_t n = Py_SIZE(self);
2535 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002536
2537 if (n == 0) {
Eli Bendersky1bc4f192011-03-04 04:55:25 +00002538 PyErr_SetString(PyExc_IndexError,
2539 "pop from empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002540 return NULL;
2541 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002542 if (index < 0)
2543 index += Py_SIZE(self);
2544 if (index < 0 || index >= Py_SIZE(self)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002545 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2546 return NULL;
2547 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002548 if (!_canresize(self))
2549 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002550
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002551 buf = PyByteArray_AS_STRING(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002552 value = buf[index];
2553 memmove(buf + index, buf + index + 1, n - index);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002554 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2555 return NULL;
2556
Mark Dickinson54a3db92009-09-06 10:19:23 +00002557 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002558}
2559
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002560/*[clinic input]
2561bytearray.remove
2562
2563 self: self(type="PyByteArrayObject *")
2564 value: bytesvalue
2565 The value to remove.
2566 /
2567
2568Remove the first occurrence of a value in the bytearray.
2569[clinic start generated code]*/
2570
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002571static PyObject *
2572bytearray_remove_impl(PyByteArrayObject *self, int value)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002573/*[clinic end generated code: output=d659e37866709c13 input=47560b11fd856c24]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002574{
Serhiy Storchaka7bf36da2016-05-16 22:15:38 +03002575 Py_ssize_t n = Py_SIZE(self);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002576 char *buf = PyByteArray_AS_STRING(self);
Serhiy Storchaka7bf36da2016-05-16 22:15:38 +03002577 char *where = memchr(buf, value, n);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002578
Serhiy Storchaka7bf36da2016-05-16 22:15:38 +03002579 if (!where) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002580 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002581 return NULL;
2582 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002583 if (!_canresize(self))
2584 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002585
Serhiy Storchaka7bf36da2016-05-16 22:15:38 +03002586 memmove(where, where + 1, buf + n - where);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002587 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2588 return NULL;
2589
2590 Py_RETURN_NONE;
2591}
2592
2593/* XXX These two helpers could be optimized if argsize == 1 */
2594
2595static Py_ssize_t
Antoine Pitrou5b720752013-10-05 21:24:10 +02002596lstrip_helper(char *myptr, Py_ssize_t mysize,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002597 void *argptr, Py_ssize_t argsize)
2598{
2599 Py_ssize_t i = 0;
Antoine Pitrou5b720752013-10-05 21:24:10 +02002600 while (i < mysize && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002601 i++;
2602 return i;
2603}
2604
2605static Py_ssize_t
Antoine Pitrou5b720752013-10-05 21:24:10 +02002606rstrip_helper(char *myptr, Py_ssize_t mysize,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002607 void *argptr, Py_ssize_t argsize)
2608{
2609 Py_ssize_t i = mysize - 1;
Antoine Pitrou5b720752013-10-05 21:24:10 +02002610 while (i >= 0 && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002611 i--;
2612 return i + 1;
2613}
2614
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002615/*[clinic input]
2616bytearray.strip
2617
2618 bytes: object = None
2619 /
2620
2621Strip leading and trailing bytes contained in the argument.
2622
2623If the argument is omitted or None, strip leading and trailing ASCII whitespace.
2624[clinic start generated code]*/
2625
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002626static PyObject *
2627bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002628/*[clinic end generated code: output=760412661a34ad5a input=ef7bb59b09c21d62]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002629{
2630 Py_ssize_t left, right, mysize, byteslen;
2631 char *myptr, *bytesptr;
2632 Py_buffer vbytes;
2633
2634 if (bytes == Py_None) {
2635 bytesptr = "\t\n\r\f\v ";
2636 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002637 }
2638 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002639 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002640 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002641 bytesptr = (char *) vbytes.buf;
2642 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002643 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002644 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002645 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002646 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002647 if (left == mysize)
2648 right = left;
2649 else
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002650 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
2651 if (bytes != Py_None)
2652 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002653 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002654}
2655
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002656/*[clinic input]
2657bytearray.lstrip
2658
2659 bytes: object = None
2660 /
2661
2662Strip leading bytes contained in the argument.
2663
2664If the argument is omitted or None, strip leading ASCII whitespace.
2665[clinic start generated code]*/
2666
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002667static PyObject *
2668bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002669/*[clinic end generated code: output=d005c9d0ab909e66 input=80843f975dd7c480]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002670{
2671 Py_ssize_t left, right, mysize, byteslen;
2672 char *myptr, *bytesptr;
2673 Py_buffer vbytes;
2674
2675 if (bytes == Py_None) {
2676 bytesptr = "\t\n\r\f\v ";
2677 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002678 }
2679 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002680 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002681 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002682 bytesptr = (char *) vbytes.buf;
2683 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002684 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002685 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002686 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002687 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002688 right = mysize;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002689 if (bytes != Py_None)
2690 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002691 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002692}
2693
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002694/*[clinic input]
2695bytearray.rstrip
2696
2697 bytes: object = None
2698 /
2699
2700Strip trailing bytes contained in the argument.
2701
2702If the argument is omitted or None, strip trailing ASCII whitespace.
2703[clinic start generated code]*/
2704
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002705static PyObject *
2706bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002707/*[clinic end generated code: output=030e2fbd2f7276bd input=e728b994954cfd91]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002708{
2709 Py_ssize_t right, mysize, byteslen;
2710 char *myptr, *bytesptr;
2711 Py_buffer vbytes;
2712
2713 if (bytes == Py_None) {
2714 bytesptr = "\t\n\r\f\v ";
2715 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002716 }
2717 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002718 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002719 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002720 bytesptr = (char *) vbytes.buf;
2721 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002722 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002723 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002724 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002725 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
2726 if (bytes != Py_None)
2727 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002728 return PyByteArray_FromStringAndSize(myptr, right);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002729}
2730
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002731/*[clinic input]
2732bytearray.decode
2733
2734 encoding: str(c_default="NULL") = 'utf-8'
2735 The encoding with which to decode the bytearray.
2736 errors: str(c_default="NULL") = 'strict'
2737 The error handling scheme to use for the handling of decoding errors.
2738 The default is 'strict' meaning that decoding errors raise a
2739 UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
2740 as well as any other name registered with codecs.register_error that
2741 can handle UnicodeDecodeErrors.
2742
2743Decode the bytearray using the codec registered for encoding.
2744[clinic start generated code]*/
2745
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002746static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04002747bytearray_decode_impl(PyByteArrayObject *self, const char *encoding,
2748 const char *errors)
2749/*[clinic end generated code: output=f57d43f4a00b42c5 input=f28d8f903020257b]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002750{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002751 if (encoding == NULL)
2752 encoding = PyUnicode_GetDefaultEncoding();
Martin v. Löwis0efea322014-07-27 17:29:17 +02002753 return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002754}
2755
2756PyDoc_STRVAR(alloc_doc,
2757"B.__alloc__() -> int\n\
2758\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002759Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002760
2761static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002762bytearray_alloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002763{
2764 return PyLong_FromSsize_t(self->ob_alloc);
2765}
2766
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002767/*[clinic input]
2768bytearray.join
2769
2770 iterable_of_bytes: object
2771 /
2772
2773Concatenate any number of bytes/bytearray objects.
2774
2775The bytearray whose method is called is inserted in between each pair.
2776
2777The result is returned as a new bytearray object.
2778[clinic start generated code]*/
2779
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002780static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002781bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002782/*[clinic end generated code: output=a8516370bf68ae08 input=aba6b1f9b30fcb8e]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002783{
Martin v. Löwis0efea322014-07-27 17:29:17 +02002784 return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002785}
2786
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002787/*[clinic input]
2788bytearray.splitlines
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002789
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +03002790 keepends: int(c_default="0") = False
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002791
2792Return a list of the lines in the bytearray, breaking at line boundaries.
2793
2794Line breaks are not included in the resulting list unless keepends is given and
2795true.
2796[clinic start generated code]*/
2797
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002798static PyObject *
2799bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +03002800/*[clinic end generated code: output=4223c94b895f6ad9 input=8ccade941e5ea0bd]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002801{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002802 return stringlib_splitlines(
2803 (PyObject*) self, PyByteArray_AS_STRING(self),
2804 PyByteArray_GET_SIZE(self), keepends
2805 );
2806}
2807
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002808static int
Victor Stinner6430fd52011-09-29 04:02:13 +02002809hex_digit_to_int(Py_UCS4 c)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002810{
2811 if (c >= 128)
2812 return -1;
Eric Smith6dc46f52009-04-27 20:39:49 +00002813 if (Py_ISDIGIT(c))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002814 return c - '0';
2815 else {
Eric Smith6dc46f52009-04-27 20:39:49 +00002816 if (Py_ISUPPER(c))
2817 c = Py_TOLOWER(c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002818 if (c >= 'a' && c <= 'f')
2819 return c - 'a' + 10;
2820 }
2821 return -1;
2822}
2823
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002824/*[clinic input]
2825@classmethod
2826bytearray.fromhex
2827
2828 cls: self(type="PyObject*")
2829 string: unicode
2830 /
2831
2832Create a bytearray object from a string of hexadecimal numbers.
2833
2834Spaces between two numbers are accepted.
2835Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
2836[clinic start generated code]*/
2837
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002838static PyObject *
2839bytearray_fromhex_impl(PyObject*cls, PyObject *string)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002840/*[clinic end generated code: output=df3da60129b3700c input=907bbd2d34d9367a]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002841{
2842 PyObject *newbytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002843 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002844 Py_ssize_t hexlen, byteslen, i, j;
2845 int top, bot;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002846 void *data;
2847 unsigned int kind;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002848
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002849 assert(PyUnicode_Check(string));
2850 if (PyUnicode_READY(string))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002851 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002852 kind = PyUnicode_KIND(string);
2853 data = PyUnicode_DATA(string);
2854 hexlen = PyUnicode_GET_LENGTH(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002855
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002856 byteslen = hexlen/2; /* This overestimates if there are spaces */
2857 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
2858 if (!newbytes)
2859 return NULL;
2860 buf = PyByteArray_AS_STRING(newbytes);
2861 for (i = j = 0; i < hexlen; i += 2) {
2862 /* skip over spaces in the input */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002863 while (PyUnicode_READ(kind, data, i) == ' ')
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002864 i++;
2865 if (i >= hexlen)
2866 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002867 top = hex_digit_to_int(PyUnicode_READ(kind, data, i));
2868 bot = hex_digit_to_int(PyUnicode_READ(kind, data, i+1));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002869 if (top == -1 || bot == -1) {
2870 PyErr_Format(PyExc_ValueError,
2871 "non-hexadecimal number found in "
2872 "fromhex() arg at position %zd", i);
2873 goto error;
2874 }
2875 buf[j++] = (top << 4) + bot;
2876 }
2877 if (PyByteArray_Resize(newbytes, j) < 0)
2878 goto error;
2879 return newbytes;
2880
2881 error:
2882 Py_DECREF(newbytes);
2883 return NULL;
2884}
2885
Gregory P. Smith8cb65692015-04-25 23:22:26 +00002886PyDoc_STRVAR(hex__doc__,
2887"B.hex() -> string\n\
2888\n\
2889Create a string of hexadecimal numbers from a bytearray object.\n\
2890Example: bytearray([0xb9, 0x01, 0xef]).hex() -> 'b901ef'.");
2891
2892static PyObject *
2893bytearray_hex(PyBytesObject *self)
2894{
2895 char* argbuf = PyByteArray_AS_STRING(self);
2896 Py_ssize_t arglen = PyByteArray_GET_SIZE(self);
2897 return _Py_strhex(argbuf, arglen);
2898}
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002899
2900static PyObject *
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002901_common_reduce(PyByteArrayObject *self, int proto)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002902{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002903 PyObject *dict;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002904 _Py_IDENTIFIER(__dict__);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002905 char *buf;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002906
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002907 dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002908 if (dict == NULL) {
2909 PyErr_Clear();
2910 dict = Py_None;
2911 Py_INCREF(dict);
2912 }
2913
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002914 buf = PyByteArray_AS_STRING(self);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002915 if (proto < 3) {
2916 /* use str based reduction for backwards compatibility with Python 2.x */
2917 PyObject *latin1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002918 if (Py_SIZE(self))
2919 latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002920 else
2921 latin1 = PyUnicode_FromString("");
2922 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
2923 }
2924 else {
2925 /* use more efficient byte based reduction */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002926 if (Py_SIZE(self)) {
2927 return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), dict);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002928 }
2929 else {
2930 return Py_BuildValue("(O()N)", Py_TYPE(self), dict);
2931 }
2932 }
2933}
2934
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002935/*[clinic input]
2936bytearray.__reduce__ as bytearray_reduce
2937
2938 self: self(type="PyByteArrayObject *")
2939
2940Return state information for pickling.
2941[clinic start generated code]*/
2942
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002943static PyObject *
2944bytearray_reduce_impl(PyByteArrayObject *self)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002945/*[clinic end generated code: output=52bf304086464cab input=fbb07de4d102a03a]*/
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002946{
2947 return _common_reduce(self, 2);
2948}
2949
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002950/*[clinic input]
2951bytearray.__reduce_ex__ as bytearray_reduce_ex
2952
2953 self: self(type="PyByteArrayObject *")
2954 proto: int = 0
2955 /
2956
2957Return state information for pickling.
2958[clinic start generated code]*/
2959
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002960static PyObject *
2961bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002962/*[clinic end generated code: output=52eac33377197520 input=0e091a42ca6dbd91]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002963{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002964 return _common_reduce(self, proto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002965}
2966
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002967/*[clinic input]
2968bytearray.__sizeof__ as bytearray_sizeof
2969
2970 self: self(type="PyByteArrayObject *")
2971
2972Returns the size of the bytearray object in memory, in bytes.
2973[clinic start generated code]*/
2974
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002975static PyObject *
2976bytearray_sizeof_impl(PyByteArrayObject *self)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002977/*[clinic end generated code: output=738abdd17951c427 input=6b23d305362b462b]*/
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002978{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002979 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002980
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002981 res = _PyObject_SIZE(Py_TYPE(self)) + self->ob_alloc * sizeof(char);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002982 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002983}
2984
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002985static PySequenceMethods bytearray_as_sequence = {
2986 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002987 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002988 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
2989 (ssizeargfunc)bytearray_getitem, /* sq_item */
2990 0, /* sq_slice */
2991 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
2992 0, /* sq_ass_slice */
2993 (objobjproc)bytearray_contains, /* sq_contains */
2994 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
2995 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002996};
2997
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002998static PyMappingMethods bytearray_as_mapping = {
2999 (lenfunc)bytearray_length,
3000 (binaryfunc)bytearray_subscript,
3001 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003002};
3003
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003004static PyBufferProcs bytearray_as_buffer = {
3005 (getbufferproc)bytearray_getbuffer,
3006 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003007};
3008
3009static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003010bytearray_methods[] = {
3011 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003012 BYTEARRAY_REDUCE_METHODDEF
3013 BYTEARRAY_REDUCE_EX_METHODDEF
3014 BYTEARRAY_SIZEOF_METHODDEF
3015 BYTEARRAY_APPEND_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003016 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
3017 _Py_capitalize__doc__},
3018 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003019 BYTEARRAY_CLEAR_METHODDEF
3020 BYTEARRAY_COPY_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003021 {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003022 BYTEARRAY_DECODE_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003023 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +02003024 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS | METH_KEYWORDS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003025 expandtabs__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003026 BYTEARRAY_EXTEND_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003027 {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003028 BYTEARRAY_FROMHEX_METHODDEF
Gregory P. Smith8cb65692015-04-25 23:22:26 +00003029 {"hex", (PyCFunction)bytearray_hex, METH_NOARGS, hex__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003030 {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003031 BYTEARRAY_INSERT_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003032 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
3033 _Py_isalnum__doc__},
3034 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
3035 _Py_isalpha__doc__},
3036 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
3037 _Py_isdigit__doc__},
3038 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
3039 _Py_islower__doc__},
3040 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
3041 _Py_isspace__doc__},
3042 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
3043 _Py_istitle__doc__},
3044 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
3045 _Py_isupper__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003046 BYTEARRAY_JOIN_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003047 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
3048 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003049 BYTEARRAY_LSTRIP_METHODDEF
3050 BYTEARRAY_MAKETRANS_METHODDEF
3051 BYTEARRAY_PARTITION_METHODDEF
3052 BYTEARRAY_POP_METHODDEF
3053 BYTEARRAY_REMOVE_METHODDEF
3054 BYTEARRAY_REPLACE_METHODDEF
3055 BYTEARRAY_REVERSE_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003056 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
3057 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003058 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003059 BYTEARRAY_RPARTITION_METHODDEF
3060 BYTEARRAY_RSPLIT_METHODDEF
3061 BYTEARRAY_RSTRIP_METHODDEF
3062 BYTEARRAY_SPLIT_METHODDEF
3063 BYTEARRAY_SPLITLINES_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003064 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003065 startswith__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003066 BYTEARRAY_STRIP_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003067 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
3068 _Py_swapcase__doc__},
3069 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003070 BYTEARRAY_TRANSLATE_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003071 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
3072 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
3073 {NULL}
3074};
3075
Ethan Furmanb95b5612015-01-23 20:05:18 -08003076static PyObject *
3077bytearray_mod(PyObject *v, PyObject *w)
3078{
3079 if (!PyByteArray_Check(v))
3080 Py_RETURN_NOTIMPLEMENTED;
3081 return bytearray_format((PyByteArrayObject *)v, w);
3082}
3083
3084static PyNumberMethods bytearray_as_number = {
3085 0, /*nb_add*/
3086 0, /*nb_subtract*/
3087 0, /*nb_multiply*/
3088 bytearray_mod, /*nb_remainder*/
3089};
3090
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003091PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00003092"bytearray(iterable_of_ints) -> bytearray\n\
3093bytearray(string, encoding[, errors]) -> bytearray\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003094bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
3095bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
3096bytearray() -> empty bytes array\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003097\n\
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03003098Construct a mutable bytearray object from:\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003099 - an iterable yielding integers in range(256)\n\
3100 - a text string encoded using the specified encoding\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003101 - a bytes or a buffer object\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003102 - any object implementing the buffer API.\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003103 - an integer");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003104
3105
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003106static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003107
3108PyTypeObject PyByteArray_Type = {
3109 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3110 "bytearray",
3111 sizeof(PyByteArrayObject),
3112 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003113 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003114 0, /* tp_print */
3115 0, /* tp_getattr */
3116 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003117 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003118 (reprfunc)bytearray_repr, /* tp_repr */
Ethan Furmanb95b5612015-01-23 20:05:18 -08003119 &bytearray_as_number, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003120 &bytearray_as_sequence, /* tp_as_sequence */
3121 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003122 0, /* tp_hash */
3123 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003124 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003125 PyObject_GenericGetAttr, /* tp_getattro */
3126 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003127 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003128 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003129 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003130 0, /* tp_traverse */
3131 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003132 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003133 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003134 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003135 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003136 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003137 0, /* tp_members */
3138 0, /* tp_getset */
3139 0, /* tp_base */
3140 0, /* tp_dict */
3141 0, /* tp_descr_get */
3142 0, /* tp_descr_set */
3143 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003144 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003145 PyType_GenericAlloc, /* tp_alloc */
3146 PyType_GenericNew, /* tp_new */
3147 PyObject_Del, /* tp_free */
3148};
3149
3150/*********************** Bytes Iterator ****************************/
3151
3152typedef struct {
3153 PyObject_HEAD
3154 Py_ssize_t it_index;
3155 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
3156} bytesiterobject;
3157
3158static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003159bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003160{
3161 _PyObject_GC_UNTRACK(it);
3162 Py_XDECREF(it->it_seq);
3163 PyObject_GC_Del(it);
3164}
3165
3166static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003167bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003168{
3169 Py_VISIT(it->it_seq);
3170 return 0;
3171}
3172
3173static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003174bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003175{
3176 PyByteArrayObject *seq;
3177 PyObject *item;
3178
3179 assert(it != NULL);
3180 seq = it->it_seq;
3181 if (seq == NULL)
3182 return NULL;
3183 assert(PyByteArray_Check(seq));
3184
3185 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
3186 item = PyLong_FromLong(
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003187 (unsigned char)PyByteArray_AS_STRING(seq)[it->it_index]);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003188 if (item != NULL)
3189 ++it->it_index;
3190 return item;
3191 }
3192
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003193 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003194 Py_DECREF(seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003195 return NULL;
3196}
3197
3198static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003199bytearrayiter_length_hint(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003200{
3201 Py_ssize_t len = 0;
Serhiy Storchakaaf658722016-07-03 14:41:36 +03003202 if (it->it_seq) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003203 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
Serhiy Storchakaaf658722016-07-03 14:41:36 +03003204 if (len < 0) {
3205 len = 0;
3206 }
3207 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003208 return PyLong_FromSsize_t(len);
3209}
3210
3211PyDoc_STRVAR(length_hint_doc,
3212 "Private method returning an estimate of len(list(it)).");
3213
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003214static PyObject *
3215bytearrayiter_reduce(bytesiterobject *it)
3216{
3217 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +02003218 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003219 it->it_seq, it->it_index);
3220 } else {
3221 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
3222 if (u == NULL)
3223 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02003224 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003225 }
3226}
3227
3228static PyObject *
3229bytearrayiter_setstate(bytesiterobject *it, PyObject *state)
3230{
3231 Py_ssize_t index = PyLong_AsSsize_t(state);
3232 if (index == -1 && PyErr_Occurred())
3233 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00003234 if (it->it_seq != NULL) {
3235 if (index < 0)
3236 index = 0;
3237 else if (index > PyByteArray_GET_SIZE(it->it_seq))
3238 index = PyByteArray_GET_SIZE(it->it_seq); /* iterator exhausted */
3239 it->it_index = index;
3240 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003241 Py_RETURN_NONE;
3242}
3243
3244PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
3245
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003246static PyMethodDef bytearrayiter_methods[] = {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003247 {"__length_hint__", (PyCFunction)bytearrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003248 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003249 {"__reduce__", (PyCFunction)bytearrayiter_reduce, METH_NOARGS,
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003250 bytearray_reduce__doc__},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003251 {"__setstate__", (PyCFunction)bytearrayiter_setstate, METH_O,
3252 setstate_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003253 {NULL, NULL} /* sentinel */
3254};
3255
3256PyTypeObject PyByteArrayIter_Type = {
3257 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3258 "bytearray_iterator", /* tp_name */
3259 sizeof(bytesiterobject), /* tp_basicsize */
3260 0, /* tp_itemsize */
3261 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003262 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003263 0, /* tp_print */
3264 0, /* tp_getattr */
3265 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003266 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003267 0, /* tp_repr */
3268 0, /* tp_as_number */
3269 0, /* tp_as_sequence */
3270 0, /* tp_as_mapping */
3271 0, /* tp_hash */
3272 0, /* tp_call */
3273 0, /* tp_str */
3274 PyObject_GenericGetAttr, /* tp_getattro */
3275 0, /* tp_setattro */
3276 0, /* tp_as_buffer */
3277 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
3278 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003279 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003280 0, /* tp_clear */
3281 0, /* tp_richcompare */
3282 0, /* tp_weaklistoffset */
3283 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003284 (iternextfunc)bytearrayiter_next, /* tp_iternext */
3285 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003286 0,
3287};
3288
3289static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003290bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003291{
3292 bytesiterobject *it;
3293
3294 if (!PyByteArray_Check(seq)) {
3295 PyErr_BadInternalCall();
3296 return NULL;
3297 }
3298 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
3299 if (it == NULL)
3300 return NULL;
3301 it->it_index = 0;
3302 Py_INCREF(seq);
3303 it->it_seq = (PyByteArrayObject *)seq;
3304 _PyObject_GC_TRACK(it);
3305 return (PyObject *)it;
3306}