blob: f055269b40a14bc752d2b8649f8c3c3e882a4bf2 [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"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00008
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02009/*[clinic input]
10class bytearray "PyByteArrayObject *" "&PyByteArray_Type"
11[clinic start generated code]*/
12/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5535b77c37a119e0]*/
13
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000014char _PyByteArray_empty_string[] = "";
Christian Heimes2c9c7a52008-05-26 13:42:13 +000015
16void
17PyByteArray_Fini(void)
18{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000019}
20
21int
22PyByteArray_Init(void)
23{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000024 return 1;
25}
26
27/* end nullbytes support */
28
29/* Helpers */
30
31static int
32_getbytevalue(PyObject* arg, int *value)
33{
34 long face_value;
35
36 if (PyLong_Check(arg)) {
37 face_value = PyLong_AsLong(arg);
Georg Brandl9a54d7c2008-07-16 23:15:30 +000038 } else {
39 PyObject *index = PyNumber_Index(arg);
40 if (index == NULL) {
41 PyErr_Format(PyExc_TypeError, "an integer is required");
Mark Dickinson10de93a2010-07-09 19:25:48 +000042 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000043 return 0;
44 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +000045 face_value = PyLong_AsLong(index);
46 Py_DECREF(index);
47 }
48
49 if (face_value < 0 || face_value >= 256) {
50 /* this includes the OverflowError in case the long is too large */
51 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
Mark Dickinson10de93a2010-07-09 19:25:48 +000052 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000053 return 0;
54 }
55
56 *value = face_value;
57 return 1;
58}
59
60static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +000061bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000062{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000063 void *ptr;
64 if (view == NULL) {
Stefan Krah5178d912015-02-03 16:57:21 +010065 PyErr_SetString(PyExc_BufferError,
66 "bytearray_getbuffer: view==NULL argument is obsolete");
67 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000068 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000069 ptr = (void *) PyByteArray_AS_STRING(obj);
Stefan Krah5178d912015-02-03 16:57:21 +010070 /* cannot fail if view != NULL and readonly == 0 */
71 (void)PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
72 obj->ob_exports++;
73 return 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000074}
75
76static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +000077bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000078{
79 obj->ob_exports--;
80}
81
Antoine Pitrou5504e892008-12-06 21:27:53 +000082static int
83_canresize(PyByteArrayObject *self)
84{
85 if (self->ob_exports > 0) {
86 PyErr_SetString(PyExc_BufferError,
87 "Existing exports of data: object cannot be re-sized");
88 return 0;
89 }
90 return 1;
91}
92
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030093#include "clinic/bytearrayobject.c.h"
94
Christian Heimes2c9c7a52008-05-26 13:42:13 +000095/* Direct API functions */
96
97PyObject *
98PyByteArray_FromObject(PyObject *input)
99{
100 return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
101 input, NULL);
102}
103
104PyObject *
105PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
106{
107 PyByteArrayObject *new;
108 Py_ssize_t alloc;
109
110 if (size < 0) {
111 PyErr_SetString(PyExc_SystemError,
112 "Negative size passed to PyByteArray_FromStringAndSize");
113 return NULL;
114 }
115
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000116 /* Prevent buffer overflow when setting alloc to size+1. */
117 if (size == PY_SSIZE_T_MAX) {
118 return PyErr_NoMemory();
119 }
120
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000121 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
122 if (new == NULL)
123 return NULL;
124
125 if (size == 0) {
126 new->ob_bytes = NULL;
127 alloc = 0;
128 }
129 else {
130 alloc = size + 1;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100131 new->ob_bytes = PyObject_Malloc(alloc);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000132 if (new->ob_bytes == NULL) {
133 Py_DECREF(new);
134 return PyErr_NoMemory();
135 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +0000136 if (bytes != NULL && size > 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000137 memcpy(new->ob_bytes, bytes, size);
138 new->ob_bytes[size] = '\0'; /* Trailing null byte */
139 }
140 Py_SIZE(new) = size;
141 new->ob_alloc = alloc;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200142 new->ob_start = new->ob_bytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000143 new->ob_exports = 0;
144
145 return (PyObject *)new;
146}
147
148Py_ssize_t
149PyByteArray_Size(PyObject *self)
150{
151 assert(self != NULL);
152 assert(PyByteArray_Check(self));
153
154 return PyByteArray_GET_SIZE(self);
155}
156
157char *
158PyByteArray_AsString(PyObject *self)
159{
160 assert(self != NULL);
161 assert(PyByteArray_Check(self));
162
163 return PyByteArray_AS_STRING(self);
164}
165
166int
Antoine Pitroucc231542014-11-02 18:40:09 +0100167PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000168{
169 void *sval;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200170 PyByteArrayObject *obj = ((PyByteArrayObject *)self);
Antoine Pitroucc231542014-11-02 18:40:09 +0100171 /* All computations are done unsigned to avoid integer overflows
172 (see issue #22335). */
173 size_t alloc = (size_t) obj->ob_alloc;
174 size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes);
175 size_t size = (size_t) requested_size;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000176
177 assert(self != NULL);
178 assert(PyByteArray_Check(self));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200179 assert(logical_offset <= alloc);
Antoine Pitroucc231542014-11-02 18:40:09 +0100180 assert(requested_size >= 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000181
Antoine Pitroucc231542014-11-02 18:40:09 +0100182 if (requested_size == Py_SIZE(self)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000183 return 0;
184 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200185 if (!_canresize(obj)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000186 return -1;
187 }
188
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200189 if (size + logical_offset + 1 < alloc) {
190 /* Current buffer is large enough to host the requested size,
191 decide on a strategy. */
192 if (size < alloc / 2) {
193 /* Major downsize; resize down to exact size */
194 alloc = size + 1;
195 }
196 else {
197 /* Minor downsize; quick exit */
198 Py_SIZE(self) = size;
199 PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */
200 return 0;
201 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000202 }
203 else {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200204 /* Need growing, decide on a strategy */
205 if (size <= alloc * 1.125) {
206 /* Moderate upsize; overallocate similar to list_resize() */
207 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
208 }
209 else {
210 /* Major upsize; resize up to exact size */
211 alloc = size + 1;
212 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000213 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100214 if (alloc > PY_SSIZE_T_MAX) {
215 PyErr_NoMemory();
216 return -1;
217 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000218
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200219 if (logical_offset > 0) {
220 sval = PyObject_Malloc(alloc);
221 if (sval == NULL) {
222 PyErr_NoMemory();
223 return -1;
224 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100225 memcpy(sval, PyByteArray_AS_STRING(self),
226 Py_MIN(requested_size, Py_SIZE(self)));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200227 PyObject_Free(obj->ob_bytes);
228 }
229 else {
230 sval = PyObject_Realloc(obj->ob_bytes, alloc);
231 if (sval == NULL) {
232 PyErr_NoMemory();
233 return -1;
234 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000235 }
236
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200237 obj->ob_bytes = obj->ob_start = sval;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000238 Py_SIZE(self) = size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200239 obj->ob_alloc = alloc;
240 obj->ob_bytes[size] = '\0'; /* Trailing null byte */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000241
242 return 0;
243}
244
245PyObject *
246PyByteArray_Concat(PyObject *a, PyObject *b)
247{
248 Py_ssize_t size;
249 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
261 size = va.len + vb.len;
262 if (size < 0) {
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000263 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000264 goto done;
265 }
266
267 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
268 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{
317 Py_ssize_t mysize;
318 Py_ssize_t size;
319 Py_buffer vo;
320
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200321 if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000322 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
323 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
324 return NULL;
325 }
326
327 mysize = Py_SIZE(self);
328 size = mysize + vo.len;
329 if (size < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000330 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000331 return PyErr_NoMemory();
332 }
333 if (size < self->ob_alloc) {
334 Py_SIZE(self) = size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200335 PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0'; /* Trailing null byte */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000336 }
337 else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000338 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000339 return NULL;
340 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200341 memcpy(PyByteArray_AS_STRING(self) + mysize, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000342 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000343 Py_INCREF(self);
344 return (PyObject *)self;
345}
346
347static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000348bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000349{
350 PyByteArrayObject *result;
351 Py_ssize_t mysize;
352 Py_ssize_t size;
353
354 if (count < 0)
355 count = 0;
356 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000357 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000358 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000359 size = mysize * count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000360 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
361 if (result != NULL && size != 0) {
362 if (mysize == 1)
363 memset(result->ob_bytes, self->ob_bytes[0], size);
364 else {
365 Py_ssize_t i;
366 for (i = 0; i < count; i++)
367 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
368 }
369 }
370 return (PyObject *)result;
371}
372
373static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000374bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000375{
376 Py_ssize_t mysize;
377 Py_ssize_t size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200378 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000379
380 if (count < 0)
381 count = 0;
382 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000383 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000384 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000385 size = mysize * count;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200386 if (PyByteArray_Resize((PyObject *)self, size) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000387 return NULL;
388
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200389 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000390 if (mysize == 1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200391 memset(buf, buf[0], size);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000392 else {
393 Py_ssize_t i;
394 for (i = 1; i < count; i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200395 memcpy(buf + i*mysize, buf, mysize);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000396 }
397
398 Py_INCREF(self);
399 return (PyObject *)self;
400}
401
402static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000403bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000404{
405 if (i < 0)
406 i += Py_SIZE(self);
407 if (i < 0 || i >= Py_SIZE(self)) {
408 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
409 return NULL;
410 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200411 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000412}
413
414static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000415bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000416{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000417 if (PyIndex_Check(index)) {
418 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000419
420 if (i == -1 && PyErr_Occurred())
421 return NULL;
422
423 if (i < 0)
424 i += PyByteArray_GET_SIZE(self);
425
426 if (i < 0 || i >= Py_SIZE(self)) {
427 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
428 return NULL;
429 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200430 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000431 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000432 else if (PySlice_Check(index)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000433 Py_ssize_t start, stop, step, slicelength, cur, i;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000434 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000435 PyByteArray_GET_SIZE(self),
436 &start, &stop, &step, &slicelength) < 0) {
437 return NULL;
438 }
439
440 if (slicelength <= 0)
441 return PyByteArray_FromStringAndSize("", 0);
442 else if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200443 return PyByteArray_FromStringAndSize(
444 PyByteArray_AS_STRING(self) + start, slicelength);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000445 }
446 else {
447 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000448 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000449 PyObject *result;
450
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000451 result = PyByteArray_FromStringAndSize(NULL, slicelength);
452 if (result == NULL)
453 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000454
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000455 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000456 for (cur = start, i = 0; i < slicelength;
457 cur += step, i++) {
458 result_buf[i] = source_buf[cur];
459 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000460 return result;
461 }
462 }
463 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400464 PyErr_Format(PyExc_TypeError,
465 "bytearray indices must be integers or slices, not %.200s",
466 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000467 return NULL;
468 }
469}
470
471static int
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200472bytearray_setslice_linear(PyByteArrayObject *self,
473 Py_ssize_t lo, Py_ssize_t hi,
474 char *bytes, Py_ssize_t bytes_len)
475{
476 Py_ssize_t avail = hi - lo;
477 char *buf = PyByteArray_AS_STRING(self);
478 Py_ssize_t growth = bytes_len - avail;
Victor Stinner84557232013-11-21 12:29:51 +0100479 int res = 0;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200480 assert(avail >= 0);
481
Victor Stinner84557232013-11-21 12:29:51 +0100482 if (growth < 0) {
483 if (!_canresize(self))
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200484 return -1;
Victor Stinner84557232013-11-21 12:29:51 +0100485
486 if (lo == 0) {
487 /* Shrink the buffer by advancing its logical start */
488 self->ob_start -= growth;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200489 /*
Victor Stinner84557232013-11-21 12:29:51 +0100490 0 lo hi old_size
491 | |<----avail----->|<-----tail------>|
492 | |<-bytes_len->|<-----tail------>|
493 0 new_lo new_hi new_size
494 */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200495 }
Victor Stinner84557232013-11-21 12:29:51 +0100496 else {
497 /*
498 0 lo hi old_size
499 | |<----avail----->|<-----tomove------>|
500 | |<-bytes_len->|<-----tomove------>|
501 0 lo new_hi new_size
502 */
503 memmove(buf + lo + bytes_len, buf + hi,
504 Py_SIZE(self) - hi);
505 }
506 if (PyByteArray_Resize((PyObject *)self,
507 Py_SIZE(self) + growth) < 0) {
508 /* Issue #19578: Handling the memory allocation failure here is
509 tricky here because the bytearray object has already been
510 modified. Depending on growth and lo, the behaviour is
511 different.
512
513 If growth < 0 and lo != 0, the operation is completed, but a
514 MemoryError is still raised and the memory block is not
515 shrinked. Otherwise, the bytearray is restored in its previous
516 state and a MemoryError is raised. */
517 if (lo == 0) {
518 self->ob_start += growth;
519 return -1;
520 }
521 /* memmove() removed bytes, the bytearray object cannot be
522 restored in its previous state. */
523 Py_SIZE(self) += growth;
524 res = -1;
525 }
526 buf = PyByteArray_AS_STRING(self);
527 }
528 else if (growth > 0) {
529 if (Py_SIZE(self) > (Py_ssize_t)PY_SSIZE_T_MAX - growth) {
530 PyErr_NoMemory();
531 return -1;
532 }
533
534 if (PyByteArray_Resize((PyObject *)self,
535 Py_SIZE(self) + growth) < 0) {
536 return -1;
537 }
538 buf = PyByteArray_AS_STRING(self);
539 /* Make the place for the additional bytes */
540 /*
541 0 lo hi old_size
542 | |<-avail->|<-----tomove------>|
543 | |<---bytes_len-->|<-----tomove------>|
544 0 lo new_hi new_size
545 */
546 memmove(buf + lo + bytes_len, buf + hi,
547 Py_SIZE(self) - lo - bytes_len);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200548 }
549
550 if (bytes_len > 0)
551 memcpy(buf + lo, bytes, bytes_len);
Victor Stinner84557232013-11-21 12:29:51 +0100552 return res;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200553}
554
555static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000556bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000557 PyObject *values)
558{
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200559 Py_ssize_t needed;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000560 void *bytes;
561 Py_buffer vbytes;
562 int res = 0;
563
564 vbytes.len = -1;
565 if (values == (PyObject *)self) {
566 /* Make a copy and call this function recursively */
567 int err;
568 values = PyByteArray_FromObject(values);
569 if (values == NULL)
570 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000571 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000572 Py_DECREF(values);
573 return err;
574 }
575 if (values == NULL) {
576 /* del b[lo:hi] */
577 bytes = NULL;
578 needed = 0;
579 }
580 else {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200581 if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) {
582 PyErr_Format(PyExc_TypeError,
583 "can't set bytearray slice from %.100s",
584 Py_TYPE(values)->tp_name);
585 return -1;
586 }
587 needed = vbytes.len;
588 bytes = vbytes.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000589 }
590
591 if (lo < 0)
592 lo = 0;
593 if (hi < lo)
594 hi = lo;
595 if (hi > Py_SIZE(self))
596 hi = Py_SIZE(self);
597
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200598 res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000599 if (vbytes.len != -1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200600 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000601 return res;
602}
603
604static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000605bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000606{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000607 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000608
609 if (i < 0)
610 i += Py_SIZE(self);
611
612 if (i < 0 || i >= Py_SIZE(self)) {
613 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
614 return -1;
615 }
616
617 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000618 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000619
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000620 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000621 return -1;
622
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200623 PyByteArray_AS_STRING(self)[i] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000624 return 0;
625}
626
627static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000628bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000629{
630 Py_ssize_t start, stop, step, slicelen, needed;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200631 char *buf, *bytes;
632 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000633
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000634 if (PyIndex_Check(index)) {
635 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000636
637 if (i == -1 && PyErr_Occurred())
638 return -1;
639
640 if (i < 0)
641 i += PyByteArray_GET_SIZE(self);
642
643 if (i < 0 || i >= Py_SIZE(self)) {
644 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
645 return -1;
646 }
647
648 if (values == NULL) {
649 /* Fall through to slice assignment */
650 start = i;
651 stop = i + 1;
652 step = 1;
653 slicelen = 1;
654 }
655 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000656 int ival;
657 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000658 return -1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200659 buf[i] = (char)ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000660 return 0;
661 }
662 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000663 else if (PySlice_Check(index)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000664 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000665 PyByteArray_GET_SIZE(self),
666 &start, &stop, &step, &slicelen) < 0) {
667 return -1;
668 }
669 }
670 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400671 PyErr_Format(PyExc_TypeError,
672 "bytearray indices must be integers or slices, not %.200s",
673 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000674 return -1;
675 }
676
677 if (values == NULL) {
678 bytes = NULL;
679 needed = 0;
680 }
681 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
Christian Heimes6d26ade2012-11-03 23:07:59 +0100682 int err;
Ezio Melottic64bcbe2012-11-03 21:19:06 +0200683 if (PyNumber_Check(values) || PyUnicode_Check(values)) {
684 PyErr_SetString(PyExc_TypeError,
685 "can assign only bytes, buffers, or iterables "
686 "of ints in range(0, 256)");
687 return -1;
688 }
Georg Brandlf3fa5682010-12-04 17:09:30 +0000689 /* Make a copy and call this function recursively */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000690 values = PyByteArray_FromObject(values);
691 if (values == NULL)
692 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000693 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000694 Py_DECREF(values);
695 return err;
696 }
697 else {
698 assert(PyByteArray_Check(values));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200699 bytes = PyByteArray_AS_STRING(values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000700 needed = Py_SIZE(values);
701 }
702 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
703 if ((step < 0 && start < stop) ||
704 (step > 0 && start > stop))
705 stop = start;
706 if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200707 return bytearray_setslice_linear(self, start, stop, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000708 }
709 else {
710 if (needed == 0) {
711 /* Delete slice */
Mark Dickinsonbc099642010-01-29 17:27:24 +0000712 size_t cur;
713 Py_ssize_t i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000714
Antoine Pitrou5504e892008-12-06 21:27:53 +0000715 if (!_canresize(self))
716 return -1;
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000717
718 if (slicelen == 0)
719 /* Nothing to do here. */
720 return 0;
721
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000722 if (step < 0) {
723 stop = start + 1;
724 start = stop + step * (slicelen - 1) - 1;
725 step = -step;
726 }
727 for (cur = start, i = 0;
728 i < slicelen; cur += step, i++) {
729 Py_ssize_t lim = step - 1;
730
Mark Dickinson66f575b2010-02-14 12:53:32 +0000731 if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000732 lim = PyByteArray_GET_SIZE(self) - cur - 1;
733
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200734 memmove(buf + cur - i,
735 buf + cur + 1, lim);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000736 }
737 /* Move the tail of the bytes, in one chunk */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000738 cur = start + (size_t)slicelen*step;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000739 if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200740 memmove(buf + cur - slicelen,
741 buf + cur,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000742 PyByteArray_GET_SIZE(self) - cur);
743 }
744 if (PyByteArray_Resize((PyObject *)self,
745 PyByteArray_GET_SIZE(self) - slicelen) < 0)
746 return -1;
747
748 return 0;
749 }
750 else {
751 /* Assign slice */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000752 Py_ssize_t i;
753 size_t cur;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000754
755 if (needed != slicelen) {
756 PyErr_Format(PyExc_ValueError,
757 "attempt to assign bytes of size %zd "
758 "to extended slice of size %zd",
759 needed, slicelen);
760 return -1;
761 }
762 for (cur = start, i = 0; i < slicelen; cur += step, i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200763 buf[cur] = bytes[i];
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000764 return 0;
765 }
766 }
767}
768
769static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000770bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000771{
772 static char *kwlist[] = {"source", "encoding", "errors", 0};
773 PyObject *arg = NULL;
774 const char *encoding = NULL;
775 const char *errors = NULL;
776 Py_ssize_t count;
777 PyObject *it;
778 PyObject *(*iternext)(PyObject *);
779
780 if (Py_SIZE(self) != 0) {
781 /* Empty previous contents (yes, do this first of all!) */
782 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
783 return -1;
784 }
785
786 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000787 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000788 &arg, &encoding, &errors))
789 return -1;
790
791 /* Make a quick exit if no first argument */
792 if (arg == NULL) {
793 if (encoding != NULL || errors != NULL) {
794 PyErr_SetString(PyExc_TypeError,
795 "encoding or errors without sequence argument");
796 return -1;
797 }
798 return 0;
799 }
800
801 if (PyUnicode_Check(arg)) {
802 /* Encode via the codec registry */
803 PyObject *encoded, *new;
804 if (encoding == NULL) {
805 PyErr_SetString(PyExc_TypeError,
806 "string argument without an encoding");
807 return -1;
808 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000809 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000810 if (encoded == NULL)
811 return -1;
812 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000813 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000814 Py_DECREF(encoded);
815 if (new == NULL)
816 return -1;
817 Py_DECREF(new);
818 return 0;
819 }
820
821 /* If it's not unicode, there can't be encoding or errors */
822 if (encoding != NULL || errors != NULL) {
823 PyErr_SetString(PyExc_TypeError,
824 "encoding or errors without a string argument");
825 return -1;
826 }
827
828 /* Is it an int? */
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000829 count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
830 if (count == -1 && PyErr_Occurred()) {
831 if (PyErr_ExceptionMatches(PyExc_OverflowError))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000832 return -1;
Benjamin Peterson9c0e94f2010-04-16 23:00:53 +0000833 PyErr_Clear();
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000834 }
835 else if (count < 0) {
836 PyErr_SetString(PyExc_ValueError, "negative count");
837 return -1;
838 }
839 else {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000840 if (count > 0) {
Victor Stinner2bc4d952014-06-02 22:22:42 +0200841 if (PyByteArray_Resize((PyObject *)self, count))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000842 return -1;
Victor Stinner2bc4d952014-06-02 22:22:42 +0200843 memset(PyByteArray_AS_STRING(self), 0, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000844 }
845 return 0;
846 }
847
848 /* Use the buffer API */
849 if (PyObject_CheckBuffer(arg)) {
850 Py_ssize_t size;
851 Py_buffer view;
852 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
853 return -1;
854 size = view.len;
855 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200856 if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
857 &view, size, 'C') < 0)
Stefan Krah7d12d9d2012-07-28 12:25:55 +0200858 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000859 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000860 return 0;
861 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000862 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000863 return -1;
864 }
865
866 /* XXX Optimize this if the arguments is a list, tuple */
867
868 /* Get the iterator */
869 it = PyObject_GetIter(arg);
870 if (it == NULL)
871 return -1;
872 iternext = *Py_TYPE(it)->tp_iternext;
873
874 /* Run the iterator to exhaustion */
875 for (;;) {
876 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000877 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000878
879 /* Get the next item */
880 item = iternext(it);
881 if (item == NULL) {
882 if (PyErr_Occurred()) {
883 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
884 goto error;
885 PyErr_Clear();
886 }
887 break;
888 }
889
890 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000891 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000892 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000893 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000894 goto error;
895
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000896 /* Append the byte */
897 if (Py_SIZE(self) < self->ob_alloc)
898 Py_SIZE(self)++;
899 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
900 goto error;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200901 PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000902 }
903
904 /* Clean up and return success */
905 Py_DECREF(it);
906 return 0;
907
908 error:
909 /* Error handling when it != NULL */
910 Py_DECREF(it);
911 return -1;
912}
913
914/* Mostly copied from string_repr, but without the
915 "smart quote" functionality. */
916static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000917bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000918{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000919 const char *quote_prefix = "bytearray(b";
920 const char *quote_postfix = ")";
921 Py_ssize_t length = Py_SIZE(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200922 /* 15 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */
Mark Dickinson66f575b2010-02-14 12:53:32 +0000923 size_t newsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000924 PyObject *v;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200925 Py_ssize_t i;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200926 char *bytes;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200927 char c;
928 char *p;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200929 int quote;
930 char *test, *start;
931 char *buffer;
932
933 if (length > (PY_SSIZE_T_MAX - 15) / 4) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000934 PyErr_SetString(PyExc_OverflowError,
935 "bytearray object is too large to make repr");
936 return NULL;
937 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200938
939 newsize = 15 + length * 4;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100940 buffer = PyObject_Malloc(newsize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200941 if (buffer == NULL) {
942 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000943 return NULL;
944 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000945
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200946 /* Figure out which quote to use; single is preferred */
947 quote = '\'';
948 start = PyByteArray_AS_STRING(self);
949 for (test = start; test < start+length; ++test) {
950 if (*test == '"') {
951 quote = '\''; /* back to single */
952 break;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000953 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200954 else if (*test == '\'')
955 quote = '"';
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000956 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200957
958 p = buffer;
959 while (*quote_prefix)
960 *p++ = *quote_prefix++;
961 *p++ = quote;
962
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200963 bytes = PyByteArray_AS_STRING(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200964 for (i = 0; i < length; i++) {
965 /* There's at least enough room for a hex escape
966 and a closing quote. */
967 assert(newsize - (p - buffer) >= 5);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200968 c = bytes[i];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200969 if (c == '\'' || c == '\\')
970 *p++ = '\\', *p++ = c;
971 else if (c == '\t')
972 *p++ = '\\', *p++ = 't';
973 else if (c == '\n')
974 *p++ = '\\', *p++ = 'n';
975 else if (c == '\r')
976 *p++ = '\\', *p++ = 'r';
977 else if (c == 0)
978 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
979 else if (c < ' ' || c >= 0x7f) {
980 *p++ = '\\';
981 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +0200982 *p++ = Py_hexdigits[(c & 0xf0) >> 4];
983 *p++ = Py_hexdigits[c & 0xf];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200984 }
985 else
986 *p++ = c;
987 }
988 assert(newsize - (p - buffer) >= 1);
989 *p++ = quote;
990 while (*quote_postfix) {
991 *p++ = *quote_postfix++;
992 }
993
994 v = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100995 PyObject_Free(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200996 return v;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000997}
998
999static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001000bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001001{
Alexander Belopolskyf0f45142010-08-11 17:31:17 +00001002 if (Py_BytesWarningFlag) {
1003 if (PyErr_WarnEx(PyExc_BytesWarning,
1004 "str() on a bytearray instance", 1))
1005 return NULL;
1006 }
1007 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001008}
1009
1010static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001011bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001012{
1013 Py_ssize_t self_size, other_size;
1014 Py_buffer self_bytes, other_bytes;
1015 PyObject *res;
1016 Py_ssize_t minsize;
1017 int cmp;
1018
1019 /* Bytes can be compared to anything that supports the (binary)
1020 buffer API. Except that a comparison with Unicode is always an
1021 error, even if the comparison is for equality. */
1022 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
1023 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
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;
Victor Stinnerdabbfe72015-03-25 03:16:32 +01001171 /* Issue #23573: FIXME, windows has no memrchr() */
1172 else if (sub_len == 1 && dir > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02001173 unsigned char needle = *sub;
1174 int mode = (dir > 0) ? FAST_SEARCH : FAST_RSEARCH;
1175 res = stringlib_fastsearch_memchr_1char(
1176 PyByteArray_AS_STRING(self) + start, end - start,
1177 needle, needle, mode);
1178 if (res >= 0)
1179 res += start;
1180 }
1181 else {
1182 if (dir > 0)
1183 res = stringlib_find_slice(
1184 PyByteArray_AS_STRING(self), len,
1185 sub, sub_len, start, end);
1186 else
1187 res = stringlib_rfind_slice(
1188 PyByteArray_AS_STRING(self), len,
1189 sub, sub_len, start, end);
1190 }
Antoine Pitrouac65d962011-10-20 23:54:17 +02001191
1192 if (subobj)
1193 PyBuffer_Release(&subbuf);
1194
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001195 return res;
1196}
1197
1198PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001199"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001200\n\
1201Return the lowest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001202such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001203arguments start and end are interpreted as in slice notation.\n\
1204\n\
1205Return -1 on failure.");
1206
1207static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001208bytearray_find(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001209{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001210 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001211 if (result == -2)
1212 return NULL;
1213 return PyLong_FromSsize_t(result);
1214}
1215
1216PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001217"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001218\n\
1219Return the number of non-overlapping occurrences of subsection sub in\n\
1220bytes B[start:end]. Optional arguments start and end are interpreted\n\
1221as in slice notation.");
1222
1223static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001224bytearray_count(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001225{
1226 PyObject *sub_obj;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001227 const char *str = PyByteArray_AS_STRING(self), *sub;
1228 Py_ssize_t sub_len;
1229 char byte;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001230 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001231
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001232 Py_buffer vsub;
1233 PyObject *count_obj;
1234
Antoine Pitrouac65d962011-10-20 23:54:17 +02001235 if (!stringlib_parse_args_finds_byte("count", args, &sub_obj, &byte,
1236 &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001237 return NULL;
1238
Antoine Pitrouac65d962011-10-20 23:54:17 +02001239 if (sub_obj) {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001240 if (PyObject_GetBuffer(sub_obj, &vsub, PyBUF_SIMPLE) != 0)
Antoine Pitrouac65d962011-10-20 23:54:17 +02001241 return NULL;
1242
1243 sub = vsub.buf;
1244 sub_len = vsub.len;
1245 }
1246 else {
1247 sub = &byte;
1248 sub_len = 1;
1249 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001250
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001251 ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001252
1253 count_obj = PyLong_FromSsize_t(
Antoine Pitrouac65d962011-10-20 23:54:17 +02001254 stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001255 );
Antoine Pitrouac65d962011-10-20 23:54:17 +02001256
1257 if (sub_obj)
1258 PyBuffer_Release(&vsub);
1259
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001260 return count_obj;
1261}
1262
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001263/*[clinic input]
1264bytearray.clear
1265
1266 self: self(type="PyByteArrayObject *")
1267
1268Remove all items from the bytearray.
1269[clinic start generated code]*/
1270
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001271static PyObject *
1272bytearray_clear_impl(PyByteArrayObject *self)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001273/*[clinic end generated code: output=85c2fe6aede0956c input=e524fd330abcdc18]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001274{
1275 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
1276 return NULL;
1277 Py_RETURN_NONE;
1278}
1279
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001280/*[clinic input]
1281bytearray.copy
1282
1283 self: self(type="PyByteArrayObject *")
1284
1285Return a copy of B.
1286[clinic start generated code]*/
1287
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001288static PyObject *
1289bytearray_copy_impl(PyByteArrayObject *self)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001290/*[clinic end generated code: output=68cfbcfed484c132 input=6d5d2975aa0f33f3]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001291{
1292 return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
1293 PyByteArray_GET_SIZE(self));
1294}
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001295
1296PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001297"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001298\n\
1299Like B.find() but raise ValueError when the subsection is not found.");
1300
1301static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001302bytearray_index(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001303{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001304 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001305 if (result == -2)
1306 return NULL;
1307 if (result == -1) {
1308 PyErr_SetString(PyExc_ValueError,
1309 "subsection not found");
1310 return NULL;
1311 }
1312 return PyLong_FromSsize_t(result);
1313}
1314
1315
1316PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001317"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001318\n\
1319Return the highest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001320such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001321arguments start and end are interpreted as in slice notation.\n\
1322\n\
1323Return -1 on failure.");
1324
1325static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001326bytearray_rfind(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001327{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001328 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001329 if (result == -2)
1330 return NULL;
1331 return PyLong_FromSsize_t(result);
1332}
1333
1334
1335PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001336"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001337\n\
1338Like B.rfind() but raise ValueError when the subsection is not found.");
1339
1340static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001341bytearray_rindex(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001342{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001343 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001344 if (result == -2)
1345 return NULL;
1346 if (result == -1) {
1347 PyErr_SetString(PyExc_ValueError,
1348 "subsection not found");
1349 return NULL;
1350 }
1351 return PyLong_FromSsize_t(result);
1352}
1353
1354
1355static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001356bytearray_contains(PyObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001357{
1358 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1359 if (ival == -1 && PyErr_Occurred()) {
1360 Py_buffer varg;
Antoine Pitrou0010d372010-08-15 17:12:55 +00001361 Py_ssize_t pos;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001362 PyErr_Clear();
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001363 if (PyObject_GetBuffer(arg, &varg, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001364 return -1;
1365 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1366 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001367 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001368 return pos >= 0;
1369 }
1370 if (ival < 0 || ival >= 256) {
1371 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1372 return -1;
1373 }
1374
Antoine Pitrou0010d372010-08-15 17:12:55 +00001375 return memchr(PyByteArray_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001376}
1377
1378
1379/* Matches the end (direction >= 0) or start (direction < 0) of self
1380 * against substr, using the start and end arguments. Returns
1381 * -1 on error, 0 if not found and 1 if found.
1382 */
1383Py_LOCAL(int)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001384_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001385 Py_ssize_t end, int direction)
1386{
1387 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1388 const char* str;
1389 Py_buffer vsubstr;
1390 int rv = 0;
1391
1392 str = PyByteArray_AS_STRING(self);
1393
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001394 if (PyObject_GetBuffer(substr, &vsubstr, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001395 return -1;
1396
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001397 ADJUST_INDICES(start, end, len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001398
1399 if (direction < 0) {
1400 /* startswith */
1401 if (start+vsubstr.len > len) {
1402 goto done;
1403 }
1404 } else {
1405 /* endswith */
1406 if (end-start < vsubstr.len || start > len) {
1407 goto done;
1408 }
1409
1410 if (end-vsubstr.len > start)
1411 start = end - vsubstr.len;
1412 }
1413 if (end-start >= vsubstr.len)
1414 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1415
1416done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001417 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001418 return rv;
1419}
1420
1421
1422PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001423"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001424\n\
1425Return True if B starts with the specified prefix, False otherwise.\n\
1426With optional start, test B beginning at that position.\n\
1427With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001428prefix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001429
1430static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001431bytearray_startswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001432{
1433 Py_ssize_t start = 0;
1434 Py_ssize_t end = PY_SSIZE_T_MAX;
1435 PyObject *subobj;
1436 int result;
1437
Jesus Ceaac451502011-04-20 17:09:23 +02001438 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001439 return NULL;
1440 if (PyTuple_Check(subobj)) {
1441 Py_ssize_t i;
1442 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001443 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001444 PyTuple_GET_ITEM(subobj, i),
1445 start, end, -1);
1446 if (result == -1)
1447 return NULL;
1448 else if (result) {
1449 Py_RETURN_TRUE;
1450 }
1451 }
1452 Py_RETURN_FALSE;
1453 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001454 result = _bytearray_tailmatch(self, subobj, start, end, -1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001455 if (result == -1) {
1456 if (PyErr_ExceptionMatches(PyExc_TypeError))
1457 PyErr_Format(PyExc_TypeError, "startswith first arg must be bytes "
1458 "or a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001459 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001460 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001461 else
1462 return PyBool_FromLong(result);
1463}
1464
1465PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001466"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001467\n\
1468Return True if B ends with the specified suffix, False otherwise.\n\
1469With optional start, test B beginning at that position.\n\
1470With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001471suffix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001472
1473static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001474bytearray_endswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001475{
1476 Py_ssize_t start = 0;
1477 Py_ssize_t end = PY_SSIZE_T_MAX;
1478 PyObject *subobj;
1479 int result;
1480
Jesus Ceaac451502011-04-20 17:09:23 +02001481 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001482 return NULL;
1483 if (PyTuple_Check(subobj)) {
1484 Py_ssize_t i;
1485 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001486 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001487 PyTuple_GET_ITEM(subobj, i),
1488 start, end, +1);
1489 if (result == -1)
1490 return NULL;
1491 else if (result) {
1492 Py_RETURN_TRUE;
1493 }
1494 }
1495 Py_RETURN_FALSE;
1496 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001497 result = _bytearray_tailmatch(self, subobj, start, end, +1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001498 if (result == -1) {
1499 if (PyErr_ExceptionMatches(PyExc_TypeError))
1500 PyErr_Format(PyExc_TypeError, "endswith first arg must be bytes or "
1501 "a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001502 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001503 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001504 else
1505 return PyBool_FromLong(result);
1506}
1507
1508
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001509/*[clinic input]
1510bytearray.translate
1511
1512 self: self(type="PyByteArrayObject *")
1513 table: object
1514 Translation table, which must be a bytes object of length 256.
1515 [
1516 deletechars: object
1517 ]
1518 /
1519
1520Return a copy with each character mapped by the given translation table.
1521
1522All characters occurring in the optional argument deletechars are removed.
1523The remaining characters are mapped through the given translation table.
1524[clinic start generated code]*/
1525
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001526static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001527bytearray_translate_impl(PyByteArrayObject *self, PyObject *table,
1528 int group_right_1, PyObject *deletechars)
1529/*[clinic end generated code: output=2bebc86a9a1ff083 input=b749ad85f4860824]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001530{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001531 char *input, *output;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001532 const char *table_chars;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001533 Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001534 PyObject *input_obj = (PyObject*)self;
1535 const char *output_start;
1536 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001537 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001538 int trans_table[256];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001539 Py_buffer vtable, vdel;
1540
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001541 if (table == Py_None) {
1542 table_chars = NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001543 table = NULL;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001544 } else if (PyObject_GetBuffer(table, &vtable, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001545 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001546 } else {
1547 if (vtable.len != 256) {
1548 PyErr_SetString(PyExc_ValueError,
1549 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001550 PyBuffer_Release(&vtable);
1551 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001552 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001553 table_chars = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001554 }
1555
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001556 if (deletechars != NULL) {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001557 if (PyObject_GetBuffer(deletechars, &vdel, PyBUF_SIMPLE) != 0) {
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001558 if (table != NULL)
Georg Brandl953152f2009-07-22 12:03:59 +00001559 PyBuffer_Release(&vtable);
1560 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001561 }
1562 }
1563 else {
1564 vdel.buf = NULL;
1565 vdel.len = 0;
1566 }
1567
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001568 inlen = PyByteArray_GET_SIZE(input_obj);
1569 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1570 if (result == NULL)
1571 goto done;
1572 output_start = output = PyByteArray_AsString(result);
1573 input = PyByteArray_AS_STRING(input_obj);
1574
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001575 if (vdel.len == 0 && table_chars != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001576 /* If no deletions are required, use faster code */
1577 for (i = inlen; --i >= 0; ) {
1578 c = Py_CHARMASK(*input++);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001579 *output++ = table_chars[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001580 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001581 goto done;
1582 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001583
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001584 if (table_chars == NULL) {
Georg Brandlccc47b62008-12-28 11:44:14 +00001585 for (i = 0; i < 256; i++)
1586 trans_table[i] = Py_CHARMASK(i);
1587 } else {
1588 for (i = 0; i < 256; i++)
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001589 trans_table[i] = Py_CHARMASK(table_chars[i]);
Georg Brandlccc47b62008-12-28 11:44:14 +00001590 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001591
1592 for (i = 0; i < vdel.len; i++)
1593 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1594
1595 for (i = inlen; --i >= 0; ) {
1596 c = Py_CHARMASK(*input++);
1597 if (trans_table[c] != -1)
1598 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1599 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001600 }
1601 /* Fix the size of the resulting string */
1602 if (inlen > 0)
Christian Heimesc731bbe2013-07-21 02:04:35 +02001603 if (PyByteArray_Resize(result, output - output_start) < 0) {
1604 Py_CLEAR(result);
1605 goto done;
1606 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001607
1608done:
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001609 if (table != NULL)
Georg Brandlccc47b62008-12-28 11:44:14 +00001610 PyBuffer_Release(&vtable);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001611 if (deletechars != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001612 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001613 return result;
1614}
1615
1616
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001617/*[clinic input]
1618
1619@staticmethod
1620bytearray.maketrans
1621
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001622 frm: Py_buffer
1623 to: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001624 /
1625
1626Return a translation table useable for the bytes or bytearray translate method.
1627
1628The returned table will be one where each byte in frm is mapped to the byte at
1629the same position in to.
1630
1631The bytes objects frm and to must be of the same length.
1632[clinic start generated code]*/
1633
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001634static PyObject *
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001635bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001636/*[clinic end generated code: output=1df267d99f56b15e input=5925a81d2fbbf151]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001637{
1638 return _Py_bytes_maketrans(frm, to);
Georg Brandlabc38772009-04-12 15:51:51 +00001639}
1640
1641
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001642/* find and count characters and substrings */
1643
1644#define findchar(target, target_len, c) \
1645 ((char *)memchr((const void *)(target), c, target_len))
1646
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001647
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001648/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001649Py_LOCAL(PyByteArrayObject *)
1650return_self(PyByteArrayObject *self)
1651{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001652 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001653 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1654 PyByteArray_AS_STRING(self),
1655 PyByteArray_GET_SIZE(self));
1656}
1657
1658Py_LOCAL_INLINE(Py_ssize_t)
1659countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1660{
1661 Py_ssize_t count=0;
1662 const char *start=target;
1663 const char *end=target+target_len;
1664
1665 while ( (start=findchar(start, end-start, c)) != NULL ) {
1666 count++;
1667 if (count >= maxcount)
1668 break;
1669 start += 1;
1670 }
1671 return count;
1672}
1673
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001674
1675/* Algorithms for different cases of string replacement */
1676
1677/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1678Py_LOCAL(PyByteArrayObject *)
1679replace_interleave(PyByteArrayObject *self,
1680 const char *to_s, Py_ssize_t to_len,
1681 Py_ssize_t maxcount)
1682{
1683 char *self_s, *result_s;
1684 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001685 Py_ssize_t count, i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001686 PyByteArrayObject *result;
1687
1688 self_len = PyByteArray_GET_SIZE(self);
1689
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001690 /* 1 at the end plus 1 after every character;
1691 count = min(maxcount, self_len + 1) */
1692 if (maxcount <= self_len)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001693 count = maxcount;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001694 else
1695 /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
1696 count = self_len + 1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001697
1698 /* Check for overflow */
1699 /* result_len = count * to_len + self_len; */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001700 assert(count > 0);
1701 if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001702 PyErr_SetString(PyExc_OverflowError,
1703 "replace string is too long");
1704 return NULL;
1705 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001706 result_len = count * to_len + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001707
1708 if (! (result = (PyByteArrayObject *)
1709 PyByteArray_FromStringAndSize(NULL, result_len)) )
1710 return NULL;
1711
1712 self_s = PyByteArray_AS_STRING(self);
1713 result_s = PyByteArray_AS_STRING(result);
1714
1715 /* TODO: special case single character, which doesn't need memcpy */
1716
1717 /* Lay the first one down (guaranteed this will occur) */
1718 Py_MEMCPY(result_s, to_s, to_len);
1719 result_s += to_len;
1720 count -= 1;
1721
1722 for (i=0; i<count; i++) {
1723 *result_s++ = *self_s++;
1724 Py_MEMCPY(result_s, to_s, to_len);
1725 result_s += to_len;
1726 }
1727
1728 /* Copy the rest of the original string */
1729 Py_MEMCPY(result_s, self_s, self_len-i);
1730
1731 return result;
1732}
1733
1734/* Special case for deleting a single character */
1735/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1736Py_LOCAL(PyByteArrayObject *)
1737replace_delete_single_character(PyByteArrayObject *self,
1738 char from_c, Py_ssize_t maxcount)
1739{
1740 char *self_s, *result_s;
1741 char *start, *next, *end;
1742 Py_ssize_t self_len, result_len;
1743 Py_ssize_t count;
1744 PyByteArrayObject *result;
1745
1746 self_len = PyByteArray_GET_SIZE(self);
1747 self_s = PyByteArray_AS_STRING(self);
1748
1749 count = countchar(self_s, self_len, from_c, maxcount);
1750 if (count == 0) {
1751 return return_self(self);
1752 }
1753
1754 result_len = self_len - count; /* from_len == 1 */
1755 assert(result_len>=0);
1756
1757 if ( (result = (PyByteArrayObject *)
1758 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1759 return NULL;
1760 result_s = PyByteArray_AS_STRING(result);
1761
1762 start = self_s;
1763 end = self_s + self_len;
1764 while (count-- > 0) {
1765 next = findchar(start, end-start, from_c);
1766 if (next == NULL)
1767 break;
1768 Py_MEMCPY(result_s, start, next-start);
1769 result_s += (next-start);
1770 start = next+1;
1771 }
1772 Py_MEMCPY(result_s, start, end-start);
1773
1774 return result;
1775}
1776
1777/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1778
1779Py_LOCAL(PyByteArrayObject *)
1780replace_delete_substring(PyByteArrayObject *self,
1781 const char *from_s, Py_ssize_t from_len,
1782 Py_ssize_t maxcount)
1783{
1784 char *self_s, *result_s;
1785 char *start, *next, *end;
1786 Py_ssize_t self_len, result_len;
1787 Py_ssize_t count, offset;
1788 PyByteArrayObject *result;
1789
1790 self_len = PyByteArray_GET_SIZE(self);
1791 self_s = PyByteArray_AS_STRING(self);
1792
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001793 count = stringlib_count(self_s, self_len,
1794 from_s, from_len,
1795 maxcount);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001796
1797 if (count == 0) {
1798 /* no matches */
1799 return return_self(self);
1800 }
1801
1802 result_len = self_len - (count * from_len);
1803 assert (result_len>=0);
1804
1805 if ( (result = (PyByteArrayObject *)
1806 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1807 return NULL;
1808
1809 result_s = PyByteArray_AS_STRING(result);
1810
1811 start = self_s;
1812 end = self_s + self_len;
1813 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001814 offset = stringlib_find(start, end-start,
1815 from_s, from_len,
1816 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001817 if (offset == -1)
1818 break;
1819 next = start + offset;
1820
1821 Py_MEMCPY(result_s, start, next-start);
1822
1823 result_s += (next-start);
1824 start = next+from_len;
1825 }
1826 Py_MEMCPY(result_s, start, end-start);
1827 return result;
1828}
1829
1830/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1831Py_LOCAL(PyByteArrayObject *)
1832replace_single_character_in_place(PyByteArrayObject *self,
1833 char from_c, char to_c,
1834 Py_ssize_t maxcount)
1835{
Antoine Pitroud1188562010-06-09 16:38:55 +00001836 char *self_s, *result_s, *start, *end, *next;
1837 Py_ssize_t self_len;
1838 PyByteArrayObject *result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001839
Antoine Pitroud1188562010-06-09 16:38:55 +00001840 /* The result string will be the same size */
1841 self_s = PyByteArray_AS_STRING(self);
1842 self_len = PyByteArray_GET_SIZE(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001843
Antoine Pitroud1188562010-06-09 16:38:55 +00001844 next = findchar(self_s, self_len, from_c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001845
Antoine Pitroud1188562010-06-09 16:38:55 +00001846 if (next == NULL) {
1847 /* No matches; return the original bytes */
1848 return return_self(self);
1849 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001850
Antoine Pitroud1188562010-06-09 16:38:55 +00001851 /* Need to make a new bytes */
1852 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1853 if (result == NULL)
1854 return NULL;
1855 result_s = PyByteArray_AS_STRING(result);
1856 Py_MEMCPY(result_s, self_s, self_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001857
Antoine Pitroud1188562010-06-09 16:38:55 +00001858 /* change everything in-place, starting with this one */
1859 start = result_s + (next-self_s);
1860 *start = to_c;
1861 start++;
1862 end = result_s + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001863
Antoine Pitroud1188562010-06-09 16:38:55 +00001864 while (--maxcount > 0) {
1865 next = findchar(start, end-start, from_c);
1866 if (next == NULL)
1867 break;
1868 *next = to_c;
1869 start = next+1;
1870 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001871
Antoine Pitroud1188562010-06-09 16:38:55 +00001872 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001873}
1874
1875/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1876Py_LOCAL(PyByteArrayObject *)
1877replace_substring_in_place(PyByteArrayObject *self,
1878 const char *from_s, Py_ssize_t from_len,
1879 const char *to_s, Py_ssize_t to_len,
1880 Py_ssize_t maxcount)
1881{
1882 char *result_s, *start, *end;
1883 char *self_s;
1884 Py_ssize_t self_len, offset;
1885 PyByteArrayObject *result;
1886
1887 /* The result bytes will be the same size */
1888
1889 self_s = PyByteArray_AS_STRING(self);
1890 self_len = PyByteArray_GET_SIZE(self);
1891
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001892 offset = stringlib_find(self_s, self_len,
1893 from_s, from_len,
1894 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001895 if (offset == -1) {
1896 /* No matches; return the original bytes */
1897 return return_self(self);
1898 }
1899
1900 /* Need to make a new bytes */
1901 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1902 if (result == NULL)
1903 return NULL;
1904 result_s = PyByteArray_AS_STRING(result);
1905 Py_MEMCPY(result_s, self_s, self_len);
1906
1907 /* change everything in-place, starting with this one */
1908 start = result_s + offset;
1909 Py_MEMCPY(start, to_s, from_len);
1910 start += from_len;
1911 end = result_s + self_len;
1912
1913 while ( --maxcount > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001914 offset = stringlib_find(start, end-start,
1915 from_s, from_len,
1916 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001917 if (offset==-1)
1918 break;
1919 Py_MEMCPY(start+offset, to_s, from_len);
1920 start += offset+from_len;
1921 }
1922
1923 return result;
1924}
1925
1926/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
1927Py_LOCAL(PyByteArrayObject *)
1928replace_single_character(PyByteArrayObject *self,
1929 char from_c,
1930 const char *to_s, Py_ssize_t to_len,
1931 Py_ssize_t maxcount)
1932{
1933 char *self_s, *result_s;
1934 char *start, *next, *end;
1935 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001936 Py_ssize_t count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001937 PyByteArrayObject *result;
1938
1939 self_s = PyByteArray_AS_STRING(self);
1940 self_len = PyByteArray_GET_SIZE(self);
1941
1942 count = countchar(self_s, self_len, from_c, maxcount);
1943 if (count == 0) {
1944 /* no matches, return unchanged */
1945 return return_self(self);
1946 }
1947
1948 /* use the difference between current and new, hence the "-1" */
1949 /* result_len = self_len + count * (to_len-1) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001950 assert(count > 0);
1951 if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001952 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1953 return NULL;
1954 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001955 result_len = self_len + count * (to_len - 1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001956
1957 if ( (result = (PyByteArrayObject *)
1958 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1959 return NULL;
1960 result_s = PyByteArray_AS_STRING(result);
1961
1962 start = self_s;
1963 end = self_s + self_len;
1964 while (count-- > 0) {
1965 next = findchar(start, end-start, from_c);
1966 if (next == NULL)
1967 break;
1968
1969 if (next == start) {
1970 /* replace with the 'to' */
1971 Py_MEMCPY(result_s, to_s, to_len);
1972 result_s += to_len;
1973 start += 1;
1974 } else {
1975 /* copy the unchanged old then the 'to' */
1976 Py_MEMCPY(result_s, start, next-start);
1977 result_s += (next-start);
1978 Py_MEMCPY(result_s, to_s, to_len);
1979 result_s += to_len;
1980 start = next+1;
1981 }
1982 }
1983 /* Copy the remainder of the remaining bytes */
1984 Py_MEMCPY(result_s, start, end-start);
1985
1986 return result;
1987}
1988
1989/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
1990Py_LOCAL(PyByteArrayObject *)
1991replace_substring(PyByteArrayObject *self,
1992 const char *from_s, Py_ssize_t from_len,
1993 const char *to_s, Py_ssize_t to_len,
1994 Py_ssize_t maxcount)
1995{
1996 char *self_s, *result_s;
1997 char *start, *next, *end;
1998 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001999 Py_ssize_t count, offset;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002000 PyByteArrayObject *result;
2001
2002 self_s = PyByteArray_AS_STRING(self);
2003 self_len = PyByteArray_GET_SIZE(self);
2004
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002005 count = stringlib_count(self_s, self_len,
2006 from_s, from_len,
2007 maxcount);
2008
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002009 if (count == 0) {
2010 /* no matches, return unchanged */
2011 return return_self(self);
2012 }
2013
2014 /* Check for overflow */
2015 /* result_len = self_len + count * (to_len-from_len) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002016 assert(count > 0);
2017 if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002018 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
2019 return NULL;
2020 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002021 result_len = self_len + count * (to_len - from_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002022
2023 if ( (result = (PyByteArrayObject *)
2024 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
2025 return NULL;
2026 result_s = PyByteArray_AS_STRING(result);
2027
2028 start = self_s;
2029 end = self_s + self_len;
2030 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002031 offset = stringlib_find(start, end-start,
2032 from_s, from_len,
2033 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002034 if (offset == -1)
2035 break;
2036 next = start+offset;
2037 if (next == start) {
2038 /* replace with the 'to' */
2039 Py_MEMCPY(result_s, to_s, to_len);
2040 result_s += to_len;
2041 start += from_len;
2042 } else {
2043 /* copy the unchanged old then the 'to' */
2044 Py_MEMCPY(result_s, start, next-start);
2045 result_s += (next-start);
2046 Py_MEMCPY(result_s, to_s, to_len);
2047 result_s += to_len;
2048 start = next+from_len;
2049 }
2050 }
2051 /* Copy the remainder of the remaining bytes */
2052 Py_MEMCPY(result_s, start, end-start);
2053
2054 return result;
2055}
2056
2057
2058Py_LOCAL(PyByteArrayObject *)
2059replace(PyByteArrayObject *self,
2060 const char *from_s, Py_ssize_t from_len,
2061 const char *to_s, Py_ssize_t to_len,
2062 Py_ssize_t maxcount)
2063{
2064 if (maxcount < 0) {
2065 maxcount = PY_SSIZE_T_MAX;
2066 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
2067 /* nothing to do; return the original bytes */
2068 return return_self(self);
2069 }
2070
2071 if (maxcount == 0 ||
2072 (from_len == 0 && to_len == 0)) {
2073 /* nothing to do; return the original bytes */
2074 return return_self(self);
2075 }
2076
2077 /* Handle zero-length special cases */
2078
2079 if (from_len == 0) {
2080 /* insert the 'to' bytes everywhere. */
2081 /* >>> "Python".replace("", ".") */
2082 /* '.P.y.t.h.o.n.' */
2083 return replace_interleave(self, to_s, to_len, maxcount);
2084 }
2085
2086 /* Except for "".replace("", "A") == "A" there is no way beyond this */
2087 /* point for an empty self bytes to generate a non-empty bytes */
2088 /* Special case so the remaining code always gets a non-empty bytes */
2089 if (PyByteArray_GET_SIZE(self) == 0) {
2090 return return_self(self);
2091 }
2092
2093 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00002094 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002095 if (from_len == 1) {
2096 return replace_delete_single_character(
2097 self, from_s[0], maxcount);
2098 } else {
2099 return replace_delete_substring(self, from_s, from_len, maxcount);
2100 }
2101 }
2102
2103 /* Handle special case where both bytes have the same length */
2104
2105 if (from_len == to_len) {
2106 if (from_len == 1) {
2107 return replace_single_character_in_place(
2108 self,
2109 from_s[0],
2110 to_s[0],
2111 maxcount);
2112 } else {
2113 return replace_substring_in_place(
2114 self, from_s, from_len, to_s, to_len, maxcount);
2115 }
2116 }
2117
2118 /* Otherwise use the more generic algorithms */
2119 if (from_len == 1) {
2120 return replace_single_character(self, from_s[0],
2121 to_s, to_len, maxcount);
2122 } else {
2123 /* len('from')>=2, len('to')>=1 */
2124 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
2125 }
2126}
2127
2128
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002129/*[clinic input]
2130bytearray.replace
2131
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002132 old: Py_buffer
2133 new: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002134 count: Py_ssize_t = -1
2135 Maximum number of occurrences to replace.
2136 -1 (the default value) means replace all occurrences.
2137 /
2138
2139Return a copy with all occurrences of substring old replaced by new.
2140
2141If the optional argument count is given, only the first count occurrences are
2142replaced.
2143[clinic start generated code]*/
2144
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002145static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04002146bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old,
2147 Py_buffer *new, Py_ssize_t count)
2148/*[clinic end generated code: output=d39884c4dc59412a input=aa379d988637c7fb]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002149{
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002150 return (PyObject *)replace((PyByteArrayObject *) self,
2151 old->buf, old->len,
2152 new->buf, new->len, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002153}
2154
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002155/*[clinic input]
2156bytearray.split
2157
2158 sep: object = None
2159 The delimiter according which to split the bytearray.
2160 None (the default value) means split on ASCII whitespace characters
2161 (space, tab, return, newline, formfeed, vertical tab).
2162 maxsplit: Py_ssize_t = -1
2163 Maximum number of splits to do.
2164 -1 (the default value) means no limit.
2165
2166Return a list of the sections in the bytearray, using sep as the delimiter.
2167[clinic start generated code]*/
2168
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002169static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04002170bytearray_split_impl(PyByteArrayObject *self, PyObject *sep,
2171 Py_ssize_t maxsplit)
2172/*[clinic end generated code: output=833e2cf385d9a04d input=24f82669f41bf523]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002173{
2174 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002175 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002176 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002177 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002178
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002179 if (maxsplit < 0)
2180 maxsplit = PY_SSIZE_T_MAX;
2181
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002182 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002183 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002184
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002185 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002186 return NULL;
2187 sub = vsub.buf;
2188 n = vsub.len;
2189
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002190 list = stringlib_split(
2191 (PyObject*) self, s, len, sub, n, maxsplit
2192 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002193 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002194 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002195}
2196
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002197/*[clinic input]
2198bytearray.partition
2199
2200 self: self(type="PyByteArrayObject *")
2201 sep: object
2202 /
2203
2204Partition the bytearray into three parts using the given separator.
2205
2206This will search for the separator sep in the bytearray. If the separator is
2207found, returns a 3-tuple containing the part before the separator, the
2208separator itself, and the part after it.
2209
2210If the separator is not found, returns a 3-tuple containing the original
2211bytearray object and two empty bytearray objects.
2212[clinic start generated code]*/
2213
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002214static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002215bytearray_partition(PyByteArrayObject *self, PyObject *sep)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002216/*[clinic end generated code: output=45d2525ddd35f957 input=7d7fe37b1696d506]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002217{
2218 PyObject *bytesep, *result;
2219
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002220 bytesep = PyByteArray_FromObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002221 if (! bytesep)
2222 return NULL;
2223
2224 result = stringlib_partition(
2225 (PyObject*) self,
2226 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2227 bytesep,
2228 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2229 );
2230
2231 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002232 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002233}
2234
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002235/*[clinic input]
2236bytearray.rpartition
2237
2238 self: self(type="PyByteArrayObject *")
2239 sep: object
2240 /
2241
2242Partition the bytes into three parts using the given separator.
2243
2244This will search for the separator sep in the bytearray, starting and the end.
2245If the separator is found, returns a 3-tuple containing the part before the
2246separator, the separator itself, and the part after it.
2247
2248If the separator is not found, returns a 3-tuple containing two empty bytearray
2249objects and the original bytearray object.
2250[clinic start generated code]*/
2251
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002252static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002253bytearray_rpartition(PyByteArrayObject *self, PyObject *sep)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002254/*[clinic end generated code: output=440de3c9426115e8 input=9b8cd540c1b75853]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002255{
2256 PyObject *bytesep, *result;
2257
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002258 bytesep = PyByteArray_FromObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002259 if (! bytesep)
2260 return NULL;
2261
2262 result = stringlib_rpartition(
2263 (PyObject*) self,
2264 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2265 bytesep,
2266 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2267 );
2268
2269 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002270 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002271}
2272
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002273/*[clinic input]
2274bytearray.rsplit = bytearray.split
2275
2276Return a list of the sections in the bytearray, using sep as the delimiter.
2277
2278Splitting is done starting at the end of the bytearray and working to the front.
2279[clinic start generated code]*/
2280
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002281static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04002282bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep,
2283 Py_ssize_t maxsplit)
2284/*[clinic end generated code: output=a55e0b5a03cb6190 input=a68286e4dd692ffe]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002285{
2286 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002287 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002288 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002289 Py_buffer vsub;
2290
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002291 if (maxsplit < 0)
2292 maxsplit = PY_SSIZE_T_MAX;
2293
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002294 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002295 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002296
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002297 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002298 return NULL;
2299 sub = vsub.buf;
2300 n = vsub.len;
2301
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002302 list = stringlib_rsplit(
2303 (PyObject*) self, s, len, sub, n, maxsplit
2304 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002305 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002306 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002307}
2308
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002309/*[clinic input]
2310bytearray.reverse
2311
2312 self: self(type="PyByteArrayObject *")
2313
2314Reverse the order of the values in B in place.
2315[clinic start generated code]*/
2316
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002317static PyObject *
2318bytearray_reverse_impl(PyByteArrayObject *self)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002319/*[clinic end generated code: output=9f7616f29ab309d3 input=7933a499b8597bd1]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002320{
2321 char swap, *head, *tail;
2322 Py_ssize_t i, j, n = Py_SIZE(self);
2323
2324 j = n / 2;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002325 head = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002326 tail = head + n - 1;
2327 for (i = 0; i < j; i++) {
2328 swap = *head;
2329 *head++ = *tail;
2330 *tail-- = swap;
2331 }
2332
2333 Py_RETURN_NONE;
2334}
2335
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002336
2337/*[python input]
2338class bytesvalue_converter(CConverter):
2339 type = 'int'
2340 converter = '_getbytevalue'
2341[python start generated code]*/
2342/*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/
2343
2344
2345/*[clinic input]
2346bytearray.insert
2347
2348 self: self(type="PyByteArrayObject *")
2349 index: Py_ssize_t
2350 The index where the value is to be inserted.
2351 item: bytesvalue
2352 The item to be inserted.
2353 /
2354
2355Insert a single item into the bytearray before the given index.
2356[clinic start generated code]*/
2357
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002358static PyObject *
2359bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002360/*[clinic end generated code: output=76c775a70e7b07b7 input=833766836ba30e1e]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002361{
2362 Py_ssize_t n = Py_SIZE(self);
2363 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002364
2365 if (n == PY_SSIZE_T_MAX) {
2366 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002367 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002368 return NULL;
2369 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002370 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2371 return NULL;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002372 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002373
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002374 if (index < 0) {
2375 index += n;
2376 if (index < 0)
2377 index = 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002378 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002379 if (index > n)
2380 index = n;
2381 memmove(buf + index + 1, buf + index, n - index);
2382 buf[index] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002383
2384 Py_RETURN_NONE;
2385}
2386
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002387/*[clinic input]
2388bytearray.append
2389
2390 self: self(type="PyByteArrayObject *")
2391 item: bytesvalue
2392 The item to be appended.
2393 /
2394
2395Append a single item to the end of the bytearray.
2396[clinic start generated code]*/
2397
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002398static PyObject *
2399bytearray_append_impl(PyByteArrayObject *self, int item)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002400/*[clinic end generated code: output=a154e19ed1886cb6 input=ae56ea87380407cc]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002401{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002402 Py_ssize_t n = Py_SIZE(self);
2403
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002404 if (n == PY_SSIZE_T_MAX) {
2405 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002406 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002407 return NULL;
2408 }
2409 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2410 return NULL;
2411
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002412 PyByteArray_AS_STRING(self)[n] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002413
2414 Py_RETURN_NONE;
2415}
2416
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002417/*[clinic input]
2418bytearray.extend
2419
2420 self: self(type="PyByteArrayObject *")
2421 iterable_of_ints: object
2422 The iterable of items to append.
2423 /
2424
2425Append all the items from the iterator or sequence to the end of the bytearray.
2426[clinic start generated code]*/
2427
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002428static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002429bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002430/*[clinic end generated code: output=98155dbe249170b1 input=ce83a5d75b70d850]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002431{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002432 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002433 Py_ssize_t buf_size = 0, len = 0;
2434 int value;
2435 char *buf;
2436
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002437 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002438 if (PyObject_CheckBuffer(iterable_of_ints)) {
2439 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002440 return NULL;
2441
2442 Py_RETURN_NONE;
2443 }
2444
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002445 it = PyObject_GetIter(iterable_of_ints);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002446 if (it == NULL)
2447 return NULL;
2448
Ezio Melotti42da6632011-03-15 05:18:48 +02002449 /* Try to determine the length of the argument. 32 is arbitrary. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002450 buf_size = PyObject_LengthHint(iterable_of_ints, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002451 if (buf_size == -1) {
2452 Py_DECREF(it);
2453 return NULL;
2454 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002455
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002456 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002457 if (bytearray_obj == NULL) {
2458 Py_DECREF(it);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002459 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002460 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002461 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002462
2463 while ((item = PyIter_Next(it)) != NULL) {
2464 if (! _getbytevalue(item, &value)) {
2465 Py_DECREF(item);
2466 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002467 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002468 return NULL;
2469 }
2470 buf[len++] = value;
2471 Py_DECREF(item);
2472
2473 if (len >= buf_size) {
2474 buf_size = len + (len >> 1) + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002475 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002476 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002477 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002478 return NULL;
2479 }
2480 /* Recompute the `buf' pointer, since the resizing operation may
2481 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002482 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002483 }
2484 }
2485 Py_DECREF(it);
2486
2487 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002488 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
2489 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002490 return NULL;
2491 }
2492
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002493 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
2494 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002495 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002496 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002497 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002498
2499 Py_RETURN_NONE;
2500}
2501
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002502/*[clinic input]
2503bytearray.pop
2504
2505 self: self(type="PyByteArrayObject *")
2506 index: Py_ssize_t = -1
2507 The index from where to remove the item.
2508 -1 (the default value) means remove the last item.
2509 /
2510
2511Remove and return a single item from B.
2512
2513If no index argument is given, will pop the last item.
2514[clinic start generated code]*/
2515
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002516static PyObject *
2517bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002518/*[clinic end generated code: output=e0ccd401f8021da8 input=0797e6c0ca9d5a85]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002519{
2520 int value;
2521 Py_ssize_t n = Py_SIZE(self);
2522 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002523
2524 if (n == 0) {
Eli Bendersky1bc4f192011-03-04 04:55:25 +00002525 PyErr_SetString(PyExc_IndexError,
2526 "pop from empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002527 return NULL;
2528 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002529 if (index < 0)
2530 index += Py_SIZE(self);
2531 if (index < 0 || index >= Py_SIZE(self)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002532 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2533 return NULL;
2534 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002535 if (!_canresize(self))
2536 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002537
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002538 buf = PyByteArray_AS_STRING(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002539 value = buf[index];
2540 memmove(buf + index, buf + index + 1, n - index);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002541 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2542 return NULL;
2543
Mark Dickinson54a3db92009-09-06 10:19:23 +00002544 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002545}
2546
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002547/*[clinic input]
2548bytearray.remove
2549
2550 self: self(type="PyByteArrayObject *")
2551 value: bytesvalue
2552 The value to remove.
2553 /
2554
2555Remove the first occurrence of a value in the bytearray.
2556[clinic start generated code]*/
2557
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002558static PyObject *
2559bytearray_remove_impl(PyByteArrayObject *self, int value)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002560/*[clinic end generated code: output=d659e37866709c13 input=47560b11fd856c24]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002561{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002562 Py_ssize_t where, n = Py_SIZE(self);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002563 char *buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002564
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002565 for (where = 0; where < n; where++) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002566 if (buf[where] == value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002567 break;
2568 }
2569 if (where == n) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002570 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002571 return NULL;
2572 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002573 if (!_canresize(self))
2574 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002575
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002576 memmove(buf + where, buf + where + 1, n - where);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002577 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2578 return NULL;
2579
2580 Py_RETURN_NONE;
2581}
2582
2583/* XXX These two helpers could be optimized if argsize == 1 */
2584
2585static Py_ssize_t
Antoine Pitrou5b720752013-10-05 21:24:10 +02002586lstrip_helper(char *myptr, Py_ssize_t mysize,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002587 void *argptr, Py_ssize_t argsize)
2588{
2589 Py_ssize_t i = 0;
Antoine Pitrou5b720752013-10-05 21:24:10 +02002590 while (i < mysize && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002591 i++;
2592 return i;
2593}
2594
2595static Py_ssize_t
Antoine Pitrou5b720752013-10-05 21:24:10 +02002596rstrip_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 = mysize - 1;
Antoine Pitrou5b720752013-10-05 21:24:10 +02002600 while (i >= 0 && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002601 i--;
2602 return i + 1;
2603}
2604
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002605/*[clinic input]
2606bytearray.strip
2607
2608 bytes: object = None
2609 /
2610
2611Strip leading and trailing bytes contained in the argument.
2612
2613If the argument is omitted or None, strip leading and trailing ASCII whitespace.
2614[clinic start generated code]*/
2615
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002616static PyObject *
2617bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002618/*[clinic end generated code: output=760412661a34ad5a input=ef7bb59b09c21d62]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002619{
2620 Py_ssize_t left, right, mysize, byteslen;
2621 char *myptr, *bytesptr;
2622 Py_buffer vbytes;
2623
2624 if (bytes == Py_None) {
2625 bytesptr = "\t\n\r\f\v ";
2626 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002627 }
2628 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002629 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002630 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002631 bytesptr = (char *) vbytes.buf;
2632 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002633 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002634 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002635 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002636 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002637 if (left == mysize)
2638 right = left;
2639 else
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002640 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
2641 if (bytes != Py_None)
2642 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002643 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002644}
2645
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002646/*[clinic input]
2647bytearray.lstrip
2648
2649 bytes: object = None
2650 /
2651
2652Strip leading bytes contained in the argument.
2653
2654If the argument is omitted or None, strip leading ASCII whitespace.
2655[clinic start generated code]*/
2656
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002657static PyObject *
2658bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002659/*[clinic end generated code: output=d005c9d0ab909e66 input=80843f975dd7c480]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002660{
2661 Py_ssize_t left, right, mysize, byteslen;
2662 char *myptr, *bytesptr;
2663 Py_buffer vbytes;
2664
2665 if (bytes == Py_None) {
2666 bytesptr = "\t\n\r\f\v ";
2667 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002668 }
2669 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002670 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002671 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002672 bytesptr = (char *) vbytes.buf;
2673 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002674 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002675 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002676 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002677 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002678 right = mysize;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002679 if (bytes != Py_None)
2680 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002681 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002682}
2683
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002684/*[clinic input]
2685bytearray.rstrip
2686
2687 bytes: object = None
2688 /
2689
2690Strip trailing bytes contained in the argument.
2691
2692If the argument is omitted or None, strip trailing ASCII whitespace.
2693[clinic start generated code]*/
2694
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002695static PyObject *
2696bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002697/*[clinic end generated code: output=030e2fbd2f7276bd input=e728b994954cfd91]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002698{
2699 Py_ssize_t right, mysize, byteslen;
2700 char *myptr, *bytesptr;
2701 Py_buffer vbytes;
2702
2703 if (bytes == Py_None) {
2704 bytesptr = "\t\n\r\f\v ";
2705 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002706 }
2707 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002708 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002709 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002710 bytesptr = (char *) vbytes.buf;
2711 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002712 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002713 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002714 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002715 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
2716 if (bytes != Py_None)
2717 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002718 return PyByteArray_FromStringAndSize(myptr, right);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002719}
2720
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002721/*[clinic input]
2722bytearray.decode
2723
2724 encoding: str(c_default="NULL") = 'utf-8'
2725 The encoding with which to decode the bytearray.
2726 errors: str(c_default="NULL") = 'strict'
2727 The error handling scheme to use for the handling of decoding errors.
2728 The default is 'strict' meaning that decoding errors raise a
2729 UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
2730 as well as any other name registered with codecs.register_error that
2731 can handle UnicodeDecodeErrors.
2732
2733Decode the bytearray using the codec registered for encoding.
2734[clinic start generated code]*/
2735
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002736static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04002737bytearray_decode_impl(PyByteArrayObject *self, const char *encoding,
2738 const char *errors)
2739/*[clinic end generated code: output=f57d43f4a00b42c5 input=f28d8f903020257b]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002740{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002741 if (encoding == NULL)
2742 encoding = PyUnicode_GetDefaultEncoding();
Martin v. Löwis0efea322014-07-27 17:29:17 +02002743 return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002744}
2745
2746PyDoc_STRVAR(alloc_doc,
2747"B.__alloc__() -> int\n\
2748\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002749Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002750
2751static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002752bytearray_alloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002753{
2754 return PyLong_FromSsize_t(self->ob_alloc);
2755}
2756
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002757/*[clinic input]
2758bytearray.join
2759
2760 iterable_of_bytes: object
2761 /
2762
2763Concatenate any number of bytes/bytearray objects.
2764
2765The bytearray whose method is called is inserted in between each pair.
2766
2767The result is returned as a new bytearray object.
2768[clinic start generated code]*/
2769
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002770static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002771bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002772/*[clinic end generated code: output=a8516370bf68ae08 input=aba6b1f9b30fcb8e]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002773{
Martin v. Löwis0efea322014-07-27 17:29:17 +02002774 return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002775}
2776
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002777/*[clinic input]
2778bytearray.splitlines
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002779
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002780 keepends: int(py_default="False") = 0
2781
2782Return a list of the lines in the bytearray, breaking at line boundaries.
2783
2784Line breaks are not included in the resulting list unless keepends is given and
2785true.
2786[clinic start generated code]*/
2787
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002788static PyObject *
2789bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002790/*[clinic end generated code: output=4223c94b895f6ad9 input=36f0b25bc792f6c0]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002791{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002792 return stringlib_splitlines(
2793 (PyObject*) self, PyByteArray_AS_STRING(self),
2794 PyByteArray_GET_SIZE(self), keepends
2795 );
2796}
2797
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002798static int
Victor Stinner6430fd52011-09-29 04:02:13 +02002799hex_digit_to_int(Py_UCS4 c)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002800{
2801 if (c >= 128)
2802 return -1;
Eric Smith6dc46f52009-04-27 20:39:49 +00002803 if (Py_ISDIGIT(c))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002804 return c - '0';
2805 else {
Eric Smith6dc46f52009-04-27 20:39:49 +00002806 if (Py_ISUPPER(c))
2807 c = Py_TOLOWER(c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002808 if (c >= 'a' && c <= 'f')
2809 return c - 'a' + 10;
2810 }
2811 return -1;
2812}
2813
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002814/*[clinic input]
2815@classmethod
2816bytearray.fromhex
2817
2818 cls: self(type="PyObject*")
2819 string: unicode
2820 /
2821
2822Create a bytearray object from a string of hexadecimal numbers.
2823
2824Spaces between two numbers are accepted.
2825Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
2826[clinic start generated code]*/
2827
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002828static PyObject *
2829bytearray_fromhex_impl(PyObject*cls, PyObject *string)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002830/*[clinic end generated code: output=df3da60129b3700c input=907bbd2d34d9367a]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002831{
2832 PyObject *newbytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002833 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002834 Py_ssize_t hexlen, byteslen, i, j;
2835 int top, bot;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002836 void *data;
2837 unsigned int kind;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002838
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002839 assert(PyUnicode_Check(string));
2840 if (PyUnicode_READY(string))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002841 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002842 kind = PyUnicode_KIND(string);
2843 data = PyUnicode_DATA(string);
2844 hexlen = PyUnicode_GET_LENGTH(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002845
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002846 byteslen = hexlen/2; /* This overestimates if there are spaces */
2847 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
2848 if (!newbytes)
2849 return NULL;
2850 buf = PyByteArray_AS_STRING(newbytes);
2851 for (i = j = 0; i < hexlen; i += 2) {
2852 /* skip over spaces in the input */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002853 while (PyUnicode_READ(kind, data, i) == ' ')
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002854 i++;
2855 if (i >= hexlen)
2856 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002857 top = hex_digit_to_int(PyUnicode_READ(kind, data, i));
2858 bot = hex_digit_to_int(PyUnicode_READ(kind, data, i+1));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002859 if (top == -1 || bot == -1) {
2860 PyErr_Format(PyExc_ValueError,
2861 "non-hexadecimal number found in "
2862 "fromhex() arg at position %zd", i);
2863 goto error;
2864 }
2865 buf[j++] = (top << 4) + bot;
2866 }
2867 if (PyByteArray_Resize(newbytes, j) < 0)
2868 goto error;
2869 return newbytes;
2870
2871 error:
2872 Py_DECREF(newbytes);
2873 return NULL;
2874}
2875
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002876
2877static PyObject *
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002878_common_reduce(PyByteArrayObject *self, int proto)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002879{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002880 PyObject *dict;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002881 _Py_IDENTIFIER(__dict__);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002882 char *buf;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002883
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002884 dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002885 if (dict == NULL) {
2886 PyErr_Clear();
2887 dict = Py_None;
2888 Py_INCREF(dict);
2889 }
2890
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002891 buf = PyByteArray_AS_STRING(self);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002892 if (proto < 3) {
2893 /* use str based reduction for backwards compatibility with Python 2.x */
2894 PyObject *latin1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002895 if (Py_SIZE(self))
2896 latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002897 else
2898 latin1 = PyUnicode_FromString("");
2899 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
2900 }
2901 else {
2902 /* use more efficient byte based reduction */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002903 if (Py_SIZE(self)) {
2904 return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), dict);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002905 }
2906 else {
2907 return Py_BuildValue("(O()N)", Py_TYPE(self), dict);
2908 }
2909 }
2910}
2911
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002912/*[clinic input]
2913bytearray.__reduce__ as bytearray_reduce
2914
2915 self: self(type="PyByteArrayObject *")
2916
2917Return state information for pickling.
2918[clinic start generated code]*/
2919
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002920static PyObject *
2921bytearray_reduce_impl(PyByteArrayObject *self)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002922/*[clinic end generated code: output=52bf304086464cab input=fbb07de4d102a03a]*/
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002923{
2924 return _common_reduce(self, 2);
2925}
2926
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002927/*[clinic input]
2928bytearray.__reduce_ex__ as bytearray_reduce_ex
2929
2930 self: self(type="PyByteArrayObject *")
2931 proto: int = 0
2932 /
2933
2934Return state information for pickling.
2935[clinic start generated code]*/
2936
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002937static PyObject *
2938bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002939/*[clinic end generated code: output=52eac33377197520 input=0e091a42ca6dbd91]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002940{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01002941 return _common_reduce(self, proto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002942}
2943
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002944/*[clinic input]
2945bytearray.__sizeof__ as bytearray_sizeof
2946
2947 self: self(type="PyByteArrayObject *")
2948
2949Returns the size of the bytearray object in memory, in bytes.
2950[clinic start generated code]*/
2951
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002952static PyObject *
2953bytearray_sizeof_impl(PyByteArrayObject *self)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002954/*[clinic end generated code: output=738abdd17951c427 input=6b23d305362b462b]*/
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002955{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002956 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002957
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002958 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
2959 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002960}
2961
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002962static PySequenceMethods bytearray_as_sequence = {
2963 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002964 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002965 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
2966 (ssizeargfunc)bytearray_getitem, /* sq_item */
2967 0, /* sq_slice */
2968 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
2969 0, /* sq_ass_slice */
2970 (objobjproc)bytearray_contains, /* sq_contains */
2971 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
2972 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002973};
2974
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002975static PyMappingMethods bytearray_as_mapping = {
2976 (lenfunc)bytearray_length,
2977 (binaryfunc)bytearray_subscript,
2978 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002979};
2980
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002981static PyBufferProcs bytearray_as_buffer = {
2982 (getbufferproc)bytearray_getbuffer,
2983 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002984};
2985
2986static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002987bytearray_methods[] = {
2988 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002989 BYTEARRAY_REDUCE_METHODDEF
2990 BYTEARRAY_REDUCE_EX_METHODDEF
2991 BYTEARRAY_SIZEOF_METHODDEF
2992 BYTEARRAY_APPEND_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002993 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
2994 _Py_capitalize__doc__},
2995 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002996 BYTEARRAY_CLEAR_METHODDEF
2997 BYTEARRAY_COPY_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002998 {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002999 BYTEARRAY_DECODE_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003000 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +02003001 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS | METH_KEYWORDS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003002 expandtabs__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003003 BYTEARRAY_EXTEND_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003004 {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003005 BYTEARRAY_FROMHEX_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003006 {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003007 BYTEARRAY_INSERT_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003008 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
3009 _Py_isalnum__doc__},
3010 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
3011 _Py_isalpha__doc__},
3012 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
3013 _Py_isdigit__doc__},
3014 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
3015 _Py_islower__doc__},
3016 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
3017 _Py_isspace__doc__},
3018 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
3019 _Py_istitle__doc__},
3020 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
3021 _Py_isupper__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003022 BYTEARRAY_JOIN_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003023 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
3024 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003025 BYTEARRAY_LSTRIP_METHODDEF
3026 BYTEARRAY_MAKETRANS_METHODDEF
3027 BYTEARRAY_PARTITION_METHODDEF
3028 BYTEARRAY_POP_METHODDEF
3029 BYTEARRAY_REMOVE_METHODDEF
3030 BYTEARRAY_REPLACE_METHODDEF
3031 BYTEARRAY_REVERSE_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003032 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
3033 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003034 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003035 BYTEARRAY_RPARTITION_METHODDEF
3036 BYTEARRAY_RSPLIT_METHODDEF
3037 BYTEARRAY_RSTRIP_METHODDEF
3038 BYTEARRAY_SPLIT_METHODDEF
3039 BYTEARRAY_SPLITLINES_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003040 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003041 startswith__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003042 BYTEARRAY_STRIP_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003043 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
3044 _Py_swapcase__doc__},
3045 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003046 BYTEARRAY_TRANSLATE_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003047 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
3048 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
3049 {NULL}
3050};
3051
Ethan Furmanb95b5612015-01-23 20:05:18 -08003052static PyObject *
3053bytearray_mod(PyObject *v, PyObject *w)
3054{
3055 if (!PyByteArray_Check(v))
3056 Py_RETURN_NOTIMPLEMENTED;
3057 return bytearray_format((PyByteArrayObject *)v, w);
3058}
3059
3060static PyNumberMethods bytearray_as_number = {
3061 0, /*nb_add*/
3062 0, /*nb_subtract*/
3063 0, /*nb_multiply*/
3064 bytearray_mod, /*nb_remainder*/
3065};
3066
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003067PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00003068"bytearray(iterable_of_ints) -> bytearray\n\
3069bytearray(string, encoding[, errors]) -> bytearray\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003070bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
3071bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
3072bytearray() -> empty bytes array\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003073\n\
3074Construct an mutable bytearray object from:\n\
3075 - an iterable yielding integers in range(256)\n\
3076 - a text string encoded using the specified encoding\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003077 - a bytes or a buffer object\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003078 - any object implementing the buffer API.\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003079 - an integer");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003080
3081
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003082static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003083
3084PyTypeObject PyByteArray_Type = {
3085 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3086 "bytearray",
3087 sizeof(PyByteArrayObject),
3088 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003089 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003090 0, /* tp_print */
3091 0, /* tp_getattr */
3092 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003093 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003094 (reprfunc)bytearray_repr, /* tp_repr */
Ethan Furmanb95b5612015-01-23 20:05:18 -08003095 &bytearray_as_number, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003096 &bytearray_as_sequence, /* tp_as_sequence */
3097 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003098 0, /* tp_hash */
3099 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003100 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003101 PyObject_GenericGetAttr, /* tp_getattro */
3102 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003103 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003104 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003105 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003106 0, /* tp_traverse */
3107 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003108 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003109 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003110 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003111 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003112 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003113 0, /* tp_members */
3114 0, /* tp_getset */
3115 0, /* tp_base */
3116 0, /* tp_dict */
3117 0, /* tp_descr_get */
3118 0, /* tp_descr_set */
3119 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003120 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003121 PyType_GenericAlloc, /* tp_alloc */
3122 PyType_GenericNew, /* tp_new */
3123 PyObject_Del, /* tp_free */
3124};
3125
3126/*********************** Bytes Iterator ****************************/
3127
3128typedef struct {
3129 PyObject_HEAD
3130 Py_ssize_t it_index;
3131 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
3132} bytesiterobject;
3133
3134static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003135bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003136{
3137 _PyObject_GC_UNTRACK(it);
3138 Py_XDECREF(it->it_seq);
3139 PyObject_GC_Del(it);
3140}
3141
3142static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003143bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003144{
3145 Py_VISIT(it->it_seq);
3146 return 0;
3147}
3148
3149static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003150bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003151{
3152 PyByteArrayObject *seq;
3153 PyObject *item;
3154
3155 assert(it != NULL);
3156 seq = it->it_seq;
3157 if (seq == NULL)
3158 return NULL;
3159 assert(PyByteArray_Check(seq));
3160
3161 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
3162 item = PyLong_FromLong(
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003163 (unsigned char)PyByteArray_AS_STRING(seq)[it->it_index]);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003164 if (item != NULL)
3165 ++it->it_index;
3166 return item;
3167 }
3168
3169 Py_DECREF(seq);
3170 it->it_seq = NULL;
3171 return NULL;
3172}
3173
3174static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003175bytearrayiter_length_hint(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003176{
3177 Py_ssize_t len = 0;
3178 if (it->it_seq)
3179 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
3180 return PyLong_FromSsize_t(len);
3181}
3182
3183PyDoc_STRVAR(length_hint_doc,
3184 "Private method returning an estimate of len(list(it)).");
3185
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003186static PyObject *
3187bytearrayiter_reduce(bytesiterobject *it)
3188{
3189 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +02003190 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003191 it->it_seq, it->it_index);
3192 } else {
3193 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
3194 if (u == NULL)
3195 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02003196 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003197 }
3198}
3199
3200static PyObject *
3201bytearrayiter_setstate(bytesiterobject *it, PyObject *state)
3202{
3203 Py_ssize_t index = PyLong_AsSsize_t(state);
3204 if (index == -1 && PyErr_Occurred())
3205 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00003206 if (it->it_seq != NULL) {
3207 if (index < 0)
3208 index = 0;
3209 else if (index > PyByteArray_GET_SIZE(it->it_seq))
3210 index = PyByteArray_GET_SIZE(it->it_seq); /* iterator exhausted */
3211 it->it_index = index;
3212 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003213 Py_RETURN_NONE;
3214}
3215
3216PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
3217
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003218static PyMethodDef bytearrayiter_methods[] = {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003219 {"__length_hint__", (PyCFunction)bytearrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003220 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003221 {"__reduce__", (PyCFunction)bytearrayiter_reduce, METH_NOARGS,
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003222 bytearray_reduce__doc__},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003223 {"__setstate__", (PyCFunction)bytearrayiter_setstate, METH_O,
3224 setstate_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003225 {NULL, NULL} /* sentinel */
3226};
3227
3228PyTypeObject PyByteArrayIter_Type = {
3229 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3230 "bytearray_iterator", /* tp_name */
3231 sizeof(bytesiterobject), /* tp_basicsize */
3232 0, /* tp_itemsize */
3233 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003234 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003235 0, /* tp_print */
3236 0, /* tp_getattr */
3237 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003238 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003239 0, /* tp_repr */
3240 0, /* tp_as_number */
3241 0, /* tp_as_sequence */
3242 0, /* tp_as_mapping */
3243 0, /* tp_hash */
3244 0, /* tp_call */
3245 0, /* tp_str */
3246 PyObject_GenericGetAttr, /* tp_getattro */
3247 0, /* tp_setattro */
3248 0, /* tp_as_buffer */
3249 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
3250 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003251 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003252 0, /* tp_clear */
3253 0, /* tp_richcompare */
3254 0, /* tp_weaklistoffset */
3255 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003256 (iternextfunc)bytearrayiter_next, /* tp_iternext */
3257 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003258 0,
3259};
3260
3261static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003262bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003263{
3264 bytesiterobject *it;
3265
3266 if (!PyByteArray_Check(seq)) {
3267 PyErr_BadInternalCall();
3268 return NULL;
3269 }
3270 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
3271 if (it == NULL)
3272 return NULL;
3273 it->it_index = 0;
3274 Py_INCREF(seq);
3275 it->it_seq = (PyByteArrayObject *)seq;
3276 _PyObject_GC_TRACK(it);
3277 return (PyObject *)it;
3278}