blob: 333f9c8bf00a8c1d84786ae804302a6b1cbcf766 [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
Christian Heimes2c9c7a52008-05-26 13:42:13 +000093/* Direct API functions */
94
95PyObject *
96PyByteArray_FromObject(PyObject *input)
97{
98 return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
99 input, NULL);
100}
101
102PyObject *
103PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
104{
105 PyByteArrayObject *new;
106 Py_ssize_t alloc;
107
108 if (size < 0) {
109 PyErr_SetString(PyExc_SystemError,
110 "Negative size passed to PyByteArray_FromStringAndSize");
111 return NULL;
112 }
113
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000114 /* Prevent buffer overflow when setting alloc to size+1. */
115 if (size == PY_SSIZE_T_MAX) {
116 return PyErr_NoMemory();
117 }
118
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000119 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
120 if (new == NULL)
121 return NULL;
122
123 if (size == 0) {
124 new->ob_bytes = NULL;
125 alloc = 0;
126 }
127 else {
128 alloc = size + 1;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100129 new->ob_bytes = PyObject_Malloc(alloc);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000130 if (new->ob_bytes == NULL) {
131 Py_DECREF(new);
132 return PyErr_NoMemory();
133 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +0000134 if (bytes != NULL && size > 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000135 memcpy(new->ob_bytes, bytes, size);
136 new->ob_bytes[size] = '\0'; /* Trailing null byte */
137 }
138 Py_SIZE(new) = size;
139 new->ob_alloc = alloc;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200140 new->ob_start = new->ob_bytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000141 new->ob_exports = 0;
142
143 return (PyObject *)new;
144}
145
146Py_ssize_t
147PyByteArray_Size(PyObject *self)
148{
149 assert(self != NULL);
150 assert(PyByteArray_Check(self));
151
152 return PyByteArray_GET_SIZE(self);
153}
154
155char *
156PyByteArray_AsString(PyObject *self)
157{
158 assert(self != NULL);
159 assert(PyByteArray_Check(self));
160
161 return PyByteArray_AS_STRING(self);
162}
163
164int
Antoine Pitroucc231542014-11-02 18:40:09 +0100165PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000166{
167 void *sval;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200168 PyByteArrayObject *obj = ((PyByteArrayObject *)self);
Antoine Pitroucc231542014-11-02 18:40:09 +0100169 /* All computations are done unsigned to avoid integer overflows
170 (see issue #22335). */
171 size_t alloc = (size_t) obj->ob_alloc;
172 size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes);
173 size_t size = (size_t) requested_size;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000174
175 assert(self != NULL);
176 assert(PyByteArray_Check(self));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200177 assert(logical_offset <= alloc);
Antoine Pitroucc231542014-11-02 18:40:09 +0100178 assert(requested_size >= 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000179
Antoine Pitroucc231542014-11-02 18:40:09 +0100180 if (requested_size == Py_SIZE(self)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000181 return 0;
182 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200183 if (!_canresize(obj)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000184 return -1;
185 }
186
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200187 if (size + logical_offset + 1 < alloc) {
188 /* Current buffer is large enough to host the requested size,
189 decide on a strategy. */
190 if (size < alloc / 2) {
191 /* Major downsize; resize down to exact size */
192 alloc = size + 1;
193 }
194 else {
195 /* Minor downsize; quick exit */
196 Py_SIZE(self) = size;
197 PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */
198 return 0;
199 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000200 }
201 else {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200202 /* Need growing, decide on a strategy */
203 if (size <= alloc * 1.125) {
204 /* Moderate upsize; overallocate similar to list_resize() */
205 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
206 }
207 else {
208 /* Major upsize; resize up to exact size */
209 alloc = size + 1;
210 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000211 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100212 if (alloc > PY_SSIZE_T_MAX) {
213 PyErr_NoMemory();
214 return -1;
215 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000216
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200217 if (logical_offset > 0) {
218 sval = PyObject_Malloc(alloc);
219 if (sval == NULL) {
220 PyErr_NoMemory();
221 return -1;
222 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100223 memcpy(sval, PyByteArray_AS_STRING(self),
224 Py_MIN(requested_size, Py_SIZE(self)));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200225 PyObject_Free(obj->ob_bytes);
226 }
227 else {
228 sval = PyObject_Realloc(obj->ob_bytes, alloc);
229 if (sval == NULL) {
230 PyErr_NoMemory();
231 return -1;
232 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000233 }
234
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200235 obj->ob_bytes = obj->ob_start = sval;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000236 Py_SIZE(self) = size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200237 obj->ob_alloc = alloc;
238 obj->ob_bytes[size] = '\0'; /* Trailing null byte */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000239
240 return 0;
241}
242
243PyObject *
244PyByteArray_Concat(PyObject *a, PyObject *b)
245{
246 Py_ssize_t size;
247 Py_buffer va, vb;
248 PyByteArrayObject *result = NULL;
249
250 va.len = -1;
251 vb.len = -1;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200252 if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 ||
253 PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000254 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
255 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
256 goto done;
257 }
258
259 size = va.len + vb.len;
260 if (size < 0) {
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000261 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000262 goto done;
263 }
264
265 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
266 if (result != NULL) {
267 memcpy(result->ob_bytes, va.buf, va.len);
268 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
269 }
270
271 done:
272 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000273 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000274 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000275 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000276 return (PyObject *)result;
277}
278
Ethan Furmanb95b5612015-01-23 20:05:18 -0800279static PyObject *
280bytearray_format(PyByteArrayObject *self, PyObject *args)
281{
282 PyObject *bytes_in, *bytes_out, *res;
283 char *bytestring;
284
285 if (self == NULL || !PyByteArray_Check(self) || args == NULL) {
286 PyErr_BadInternalCall();
287 return NULL;
288 }
289 bytestring = PyByteArray_AS_STRING(self);
290 bytes_in = PyBytes_FromString(bytestring);
291 if (bytes_in == NULL)
292 return NULL;
293 bytes_out = _PyBytes_Format(bytes_in, args);
294 Py_DECREF(bytes_in);
295 if (bytes_out == NULL)
296 return NULL;
297 res = PyByteArray_FromObject(bytes_out);
298 Py_DECREF(bytes_out);
299 if (res == NULL)
300 return NULL;
301 return res;
302}
303
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000304/* Functions stuffed into the type object */
305
306static Py_ssize_t
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000307bytearray_length(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000308{
309 return Py_SIZE(self);
310}
311
312static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000313bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000314{
315 Py_ssize_t mysize;
316 Py_ssize_t size;
317 Py_buffer vo;
318
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200319 if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000320 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
321 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
322 return NULL;
323 }
324
325 mysize = Py_SIZE(self);
326 size = mysize + vo.len;
327 if (size < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000328 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000329 return PyErr_NoMemory();
330 }
331 if (size < self->ob_alloc) {
332 Py_SIZE(self) = size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200333 PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0'; /* Trailing null byte */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000334 }
335 else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000336 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000337 return NULL;
338 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200339 memcpy(PyByteArray_AS_STRING(self) + mysize, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000340 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000341 Py_INCREF(self);
342 return (PyObject *)self;
343}
344
345static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000346bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000347{
348 PyByteArrayObject *result;
349 Py_ssize_t mysize;
350 Py_ssize_t size;
351
352 if (count < 0)
353 count = 0;
354 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000355 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000356 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000357 size = mysize * count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000358 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
359 if (result != NULL && size != 0) {
360 if (mysize == 1)
361 memset(result->ob_bytes, self->ob_bytes[0], size);
362 else {
363 Py_ssize_t i;
364 for (i = 0; i < count; i++)
365 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
366 }
367 }
368 return (PyObject *)result;
369}
370
371static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000372bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000373{
374 Py_ssize_t mysize;
375 Py_ssize_t size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200376 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000377
378 if (count < 0)
379 count = 0;
380 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000381 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000382 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000383 size = mysize * count;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200384 if (PyByteArray_Resize((PyObject *)self, size) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000385 return NULL;
386
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200387 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000388 if (mysize == 1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200389 memset(buf, buf[0], size);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000390 else {
391 Py_ssize_t i;
392 for (i = 1; i < count; i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200393 memcpy(buf + i*mysize, buf, mysize);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000394 }
395
396 Py_INCREF(self);
397 return (PyObject *)self;
398}
399
400static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000401bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000402{
403 if (i < 0)
404 i += Py_SIZE(self);
405 if (i < 0 || i >= Py_SIZE(self)) {
406 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
407 return NULL;
408 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200409 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000410}
411
412static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000413bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000414{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000415 if (PyIndex_Check(index)) {
416 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000417
418 if (i == -1 && PyErr_Occurred())
419 return NULL;
420
421 if (i < 0)
422 i += PyByteArray_GET_SIZE(self);
423
424 if (i < 0 || i >= Py_SIZE(self)) {
425 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
426 return NULL;
427 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200428 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000429 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000430 else if (PySlice_Check(index)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000431 Py_ssize_t start, stop, step, slicelength, cur, i;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000432 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000433 PyByteArray_GET_SIZE(self),
434 &start, &stop, &step, &slicelength) < 0) {
435 return NULL;
436 }
437
438 if (slicelength <= 0)
439 return PyByteArray_FromStringAndSize("", 0);
440 else if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200441 return PyByteArray_FromStringAndSize(
442 PyByteArray_AS_STRING(self) + start, slicelength);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000443 }
444 else {
445 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000446 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000447 PyObject *result;
448
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000449 result = PyByteArray_FromStringAndSize(NULL, slicelength);
450 if (result == NULL)
451 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000452
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000453 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000454 for (cur = start, i = 0; i < slicelength;
455 cur += step, i++) {
456 result_buf[i] = source_buf[cur];
457 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000458 return result;
459 }
460 }
461 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400462 PyErr_Format(PyExc_TypeError,
463 "bytearray indices must be integers or slices, not %.200s",
464 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000465 return NULL;
466 }
467}
468
469static int
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200470bytearray_setslice_linear(PyByteArrayObject *self,
471 Py_ssize_t lo, Py_ssize_t hi,
472 char *bytes, Py_ssize_t bytes_len)
473{
474 Py_ssize_t avail = hi - lo;
475 char *buf = PyByteArray_AS_STRING(self);
476 Py_ssize_t growth = bytes_len - avail;
Victor Stinner84557232013-11-21 12:29:51 +0100477 int res = 0;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200478 assert(avail >= 0);
479
Victor Stinner84557232013-11-21 12:29:51 +0100480 if (growth < 0) {
481 if (!_canresize(self))
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200482 return -1;
Victor Stinner84557232013-11-21 12:29:51 +0100483
484 if (lo == 0) {
485 /* Shrink the buffer by advancing its logical start */
486 self->ob_start -= growth;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200487 /*
Victor Stinner84557232013-11-21 12:29:51 +0100488 0 lo hi old_size
489 | |<----avail----->|<-----tail------>|
490 | |<-bytes_len->|<-----tail------>|
491 0 new_lo new_hi new_size
492 */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200493 }
Victor Stinner84557232013-11-21 12:29:51 +0100494 else {
495 /*
496 0 lo hi old_size
497 | |<----avail----->|<-----tomove------>|
498 | |<-bytes_len->|<-----tomove------>|
499 0 lo new_hi new_size
500 */
501 memmove(buf + lo + bytes_len, buf + hi,
502 Py_SIZE(self) - hi);
503 }
504 if (PyByteArray_Resize((PyObject *)self,
505 Py_SIZE(self) + growth) < 0) {
506 /* Issue #19578: Handling the memory allocation failure here is
507 tricky here because the bytearray object has already been
508 modified. Depending on growth and lo, the behaviour is
509 different.
510
511 If growth < 0 and lo != 0, the operation is completed, but a
512 MemoryError is still raised and the memory block is not
513 shrinked. Otherwise, the bytearray is restored in its previous
514 state and a MemoryError is raised. */
515 if (lo == 0) {
516 self->ob_start += growth;
517 return -1;
518 }
519 /* memmove() removed bytes, the bytearray object cannot be
520 restored in its previous state. */
521 Py_SIZE(self) += growth;
522 res = -1;
523 }
524 buf = PyByteArray_AS_STRING(self);
525 }
526 else if (growth > 0) {
527 if (Py_SIZE(self) > (Py_ssize_t)PY_SSIZE_T_MAX - growth) {
528 PyErr_NoMemory();
529 return -1;
530 }
531
532 if (PyByteArray_Resize((PyObject *)self,
533 Py_SIZE(self) + growth) < 0) {
534 return -1;
535 }
536 buf = PyByteArray_AS_STRING(self);
537 /* Make the place for the additional bytes */
538 /*
539 0 lo hi old_size
540 | |<-avail->|<-----tomove------>|
541 | |<---bytes_len-->|<-----tomove------>|
542 0 lo new_hi new_size
543 */
544 memmove(buf + lo + bytes_len, buf + hi,
545 Py_SIZE(self) - lo - bytes_len);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200546 }
547
548 if (bytes_len > 0)
549 memcpy(buf + lo, bytes, bytes_len);
Victor Stinner84557232013-11-21 12:29:51 +0100550 return res;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200551}
552
553static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000554bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000555 PyObject *values)
556{
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200557 Py_ssize_t needed;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000558 void *bytes;
559 Py_buffer vbytes;
560 int res = 0;
561
562 vbytes.len = -1;
563 if (values == (PyObject *)self) {
564 /* Make a copy and call this function recursively */
565 int err;
566 values = PyByteArray_FromObject(values);
567 if (values == NULL)
568 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000569 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000570 Py_DECREF(values);
571 return err;
572 }
573 if (values == NULL) {
574 /* del b[lo:hi] */
575 bytes = NULL;
576 needed = 0;
577 }
578 else {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200579 if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) {
580 PyErr_Format(PyExc_TypeError,
581 "can't set bytearray slice from %.100s",
582 Py_TYPE(values)->tp_name);
583 return -1;
584 }
585 needed = vbytes.len;
586 bytes = vbytes.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000587 }
588
589 if (lo < 0)
590 lo = 0;
591 if (hi < lo)
592 hi = lo;
593 if (hi > Py_SIZE(self))
594 hi = Py_SIZE(self);
595
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200596 res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000597 if (vbytes.len != -1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200598 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000599 return res;
600}
601
602static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000603bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000604{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000605 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000606
607 if (i < 0)
608 i += Py_SIZE(self);
609
610 if (i < 0 || i >= Py_SIZE(self)) {
611 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
612 return -1;
613 }
614
615 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000616 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000617
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000618 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000619 return -1;
620
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200621 PyByteArray_AS_STRING(self)[i] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000622 return 0;
623}
624
625static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000626bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000627{
628 Py_ssize_t start, stop, step, slicelen, needed;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200629 char *buf, *bytes;
630 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000631
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000632 if (PyIndex_Check(index)) {
633 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000634
635 if (i == -1 && PyErr_Occurred())
636 return -1;
637
638 if (i < 0)
639 i += PyByteArray_GET_SIZE(self);
640
641 if (i < 0 || i >= Py_SIZE(self)) {
642 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
643 return -1;
644 }
645
646 if (values == NULL) {
647 /* Fall through to slice assignment */
648 start = i;
649 stop = i + 1;
650 step = 1;
651 slicelen = 1;
652 }
653 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000654 int ival;
655 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000656 return -1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200657 buf[i] = (char)ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000658 return 0;
659 }
660 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000661 else if (PySlice_Check(index)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000662 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000663 PyByteArray_GET_SIZE(self),
664 &start, &stop, &step, &slicelen) < 0) {
665 return -1;
666 }
667 }
668 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400669 PyErr_Format(PyExc_TypeError,
670 "bytearray indices must be integers or slices, not %.200s",
671 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000672 return -1;
673 }
674
675 if (values == NULL) {
676 bytes = NULL;
677 needed = 0;
678 }
679 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
Christian Heimes6d26ade2012-11-03 23:07:59 +0100680 int err;
Ezio Melottic64bcbe2012-11-03 21:19:06 +0200681 if (PyNumber_Check(values) || PyUnicode_Check(values)) {
682 PyErr_SetString(PyExc_TypeError,
683 "can assign only bytes, buffers, or iterables "
684 "of ints in range(0, 256)");
685 return -1;
686 }
Georg Brandlf3fa5682010-12-04 17:09:30 +0000687 /* Make a copy and call this function recursively */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000688 values = PyByteArray_FromObject(values);
689 if (values == NULL)
690 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000691 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000692 Py_DECREF(values);
693 return err;
694 }
695 else {
696 assert(PyByteArray_Check(values));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200697 bytes = PyByteArray_AS_STRING(values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000698 needed = Py_SIZE(values);
699 }
700 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
701 if ((step < 0 && start < stop) ||
702 (step > 0 && start > stop))
703 stop = start;
704 if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200705 return bytearray_setslice_linear(self, start, stop, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000706 }
707 else {
708 if (needed == 0) {
709 /* Delete slice */
Mark Dickinsonbc099642010-01-29 17:27:24 +0000710 size_t cur;
711 Py_ssize_t i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000712
Antoine Pitrou5504e892008-12-06 21:27:53 +0000713 if (!_canresize(self))
714 return -1;
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000715
716 if (slicelen == 0)
717 /* Nothing to do here. */
718 return 0;
719
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000720 if (step < 0) {
721 stop = start + 1;
722 start = stop + step * (slicelen - 1) - 1;
723 step = -step;
724 }
725 for (cur = start, i = 0;
726 i < slicelen; cur += step, i++) {
727 Py_ssize_t lim = step - 1;
728
Mark Dickinson66f575b2010-02-14 12:53:32 +0000729 if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000730 lim = PyByteArray_GET_SIZE(self) - cur - 1;
731
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200732 memmove(buf + cur - i,
733 buf + cur + 1, lim);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000734 }
735 /* Move the tail of the bytes, in one chunk */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000736 cur = start + (size_t)slicelen*step;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000737 if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200738 memmove(buf + cur - slicelen,
739 buf + cur,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000740 PyByteArray_GET_SIZE(self) - cur);
741 }
742 if (PyByteArray_Resize((PyObject *)self,
743 PyByteArray_GET_SIZE(self) - slicelen) < 0)
744 return -1;
745
746 return 0;
747 }
748 else {
749 /* Assign slice */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000750 Py_ssize_t i;
751 size_t cur;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000752
753 if (needed != slicelen) {
754 PyErr_Format(PyExc_ValueError,
755 "attempt to assign bytes of size %zd "
756 "to extended slice of size %zd",
757 needed, slicelen);
758 return -1;
759 }
760 for (cur = start, i = 0; i < slicelen; cur += step, i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200761 buf[cur] = bytes[i];
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000762 return 0;
763 }
764 }
765}
766
767static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000768bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000769{
770 static char *kwlist[] = {"source", "encoding", "errors", 0};
771 PyObject *arg = NULL;
772 const char *encoding = NULL;
773 const char *errors = NULL;
774 Py_ssize_t count;
775 PyObject *it;
776 PyObject *(*iternext)(PyObject *);
777
778 if (Py_SIZE(self) != 0) {
779 /* Empty previous contents (yes, do this first of all!) */
780 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
781 return -1;
782 }
783
784 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000785 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000786 &arg, &encoding, &errors))
787 return -1;
788
789 /* Make a quick exit if no first argument */
790 if (arg == NULL) {
791 if (encoding != NULL || errors != NULL) {
792 PyErr_SetString(PyExc_TypeError,
793 "encoding or errors without sequence argument");
794 return -1;
795 }
796 return 0;
797 }
798
799 if (PyUnicode_Check(arg)) {
800 /* Encode via the codec registry */
801 PyObject *encoded, *new;
802 if (encoding == NULL) {
803 PyErr_SetString(PyExc_TypeError,
804 "string argument without an encoding");
805 return -1;
806 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000807 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000808 if (encoded == NULL)
809 return -1;
810 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000811 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000812 Py_DECREF(encoded);
813 if (new == NULL)
814 return -1;
815 Py_DECREF(new);
816 return 0;
817 }
818
819 /* If it's not unicode, there can't be encoding or errors */
820 if (encoding != NULL || errors != NULL) {
821 PyErr_SetString(PyExc_TypeError,
822 "encoding or errors without a string argument");
823 return -1;
824 }
825
826 /* Is it an int? */
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000827 count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
828 if (count == -1 && PyErr_Occurred()) {
829 if (PyErr_ExceptionMatches(PyExc_OverflowError))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000830 return -1;
Benjamin Peterson9c0e94f2010-04-16 23:00:53 +0000831 PyErr_Clear();
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000832 }
833 else if (count < 0) {
834 PyErr_SetString(PyExc_ValueError, "negative count");
835 return -1;
836 }
837 else {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000838 if (count > 0) {
Victor Stinner2bc4d952014-06-02 22:22:42 +0200839 if (PyByteArray_Resize((PyObject *)self, count))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000840 return -1;
Victor Stinner2bc4d952014-06-02 22:22:42 +0200841 memset(PyByteArray_AS_STRING(self), 0, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000842 }
843 return 0;
844 }
845
846 /* Use the buffer API */
847 if (PyObject_CheckBuffer(arg)) {
848 Py_ssize_t size;
849 Py_buffer view;
850 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
851 return -1;
852 size = view.len;
853 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200854 if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
855 &view, size, 'C') < 0)
Stefan Krah7d12d9d2012-07-28 12:25:55 +0200856 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000857 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000858 return 0;
859 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000860 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000861 return -1;
862 }
863
864 /* XXX Optimize this if the arguments is a list, tuple */
865
866 /* Get the iterator */
867 it = PyObject_GetIter(arg);
868 if (it == NULL)
869 return -1;
870 iternext = *Py_TYPE(it)->tp_iternext;
871
872 /* Run the iterator to exhaustion */
873 for (;;) {
874 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000875 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000876
877 /* Get the next item */
878 item = iternext(it);
879 if (item == NULL) {
880 if (PyErr_Occurred()) {
881 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
882 goto error;
883 PyErr_Clear();
884 }
885 break;
886 }
887
888 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000889 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000890 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000891 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000892 goto error;
893
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000894 /* Append the byte */
895 if (Py_SIZE(self) < self->ob_alloc)
896 Py_SIZE(self)++;
897 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
898 goto error;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200899 PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000900 }
901
902 /* Clean up and return success */
903 Py_DECREF(it);
904 return 0;
905
906 error:
907 /* Error handling when it != NULL */
908 Py_DECREF(it);
909 return -1;
910}
911
912/* Mostly copied from string_repr, but without the
913 "smart quote" functionality. */
914static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000915bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000916{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000917 const char *quote_prefix = "bytearray(b";
918 const char *quote_postfix = ")";
919 Py_ssize_t length = Py_SIZE(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200920 /* 15 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */
Mark Dickinson66f575b2010-02-14 12:53:32 +0000921 size_t newsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000922 PyObject *v;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200923 Py_ssize_t i;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200924 char *bytes;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200925 char c;
926 char *p;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200927 int quote;
928 char *test, *start;
929 char *buffer;
930
931 if (length > (PY_SSIZE_T_MAX - 15) / 4) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000932 PyErr_SetString(PyExc_OverflowError,
933 "bytearray object is too large to make repr");
934 return NULL;
935 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200936
937 newsize = 15 + length * 4;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100938 buffer = PyObject_Malloc(newsize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200939 if (buffer == NULL) {
940 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000941 return NULL;
942 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000943
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200944 /* Figure out which quote to use; single is preferred */
945 quote = '\'';
946 start = PyByteArray_AS_STRING(self);
947 for (test = start; test < start+length; ++test) {
948 if (*test == '"') {
949 quote = '\''; /* back to single */
950 break;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000951 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200952 else if (*test == '\'')
953 quote = '"';
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000954 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200955
956 p = buffer;
957 while (*quote_prefix)
958 *p++ = *quote_prefix++;
959 *p++ = quote;
960
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200961 bytes = PyByteArray_AS_STRING(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200962 for (i = 0; i < length; i++) {
963 /* There's at least enough room for a hex escape
964 and a closing quote. */
965 assert(newsize - (p - buffer) >= 5);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200966 c = bytes[i];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200967 if (c == '\'' || c == '\\')
968 *p++ = '\\', *p++ = c;
969 else if (c == '\t')
970 *p++ = '\\', *p++ = 't';
971 else if (c == '\n')
972 *p++ = '\\', *p++ = 'n';
973 else if (c == '\r')
974 *p++ = '\\', *p++ = 'r';
975 else if (c == 0)
976 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
977 else if (c < ' ' || c >= 0x7f) {
978 *p++ = '\\';
979 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +0200980 *p++ = Py_hexdigits[(c & 0xf0) >> 4];
981 *p++ = Py_hexdigits[c & 0xf];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200982 }
983 else
984 *p++ = c;
985 }
986 assert(newsize - (p - buffer) >= 1);
987 *p++ = quote;
988 while (*quote_postfix) {
989 *p++ = *quote_postfix++;
990 }
991
992 v = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100993 PyObject_Free(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200994 return v;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000995}
996
997static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000998bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000999{
Alexander Belopolskyf0f45142010-08-11 17:31:17 +00001000 if (Py_BytesWarningFlag) {
1001 if (PyErr_WarnEx(PyExc_BytesWarning,
1002 "str() on a bytearray instance", 1))
1003 return NULL;
1004 }
1005 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001006}
1007
1008static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001009bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001010{
1011 Py_ssize_t self_size, other_size;
1012 Py_buffer self_bytes, other_bytes;
1013 PyObject *res;
1014 Py_ssize_t minsize;
1015 int cmp;
1016
1017 /* Bytes can be compared to anything that supports the (binary)
1018 buffer API. Except that a comparison with Unicode is always an
1019 error, even if the comparison is for equality. */
1020 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
1021 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
Barry Warsaw9e9dcd62008-10-17 01:50:37 +00001022 if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001023 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +00001024 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001025 return NULL;
1026 }
1027
Brian Curtindfc80e32011-08-10 20:28:54 -05001028 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001029 }
1030
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001031 if (PyObject_GetBuffer(self, &self_bytes, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001032 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05001033 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001034 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001035 self_size = self_bytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001036
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001037 if (PyObject_GetBuffer(other, &other_bytes, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001038 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +00001039 PyBuffer_Release(&self_bytes);
Brian Curtindfc80e32011-08-10 20:28:54 -05001040 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001041 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001042 other_size = other_bytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001043
1044 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
1045 /* Shortcut: if the lengths differ, the objects differ */
1046 cmp = (op == Py_NE);
1047 }
1048 else {
1049 minsize = self_size;
1050 if (other_size < minsize)
1051 minsize = other_size;
1052
1053 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
1054 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
1055
1056 if (cmp == 0) {
1057 if (self_size < other_size)
1058 cmp = -1;
1059 else if (self_size > other_size)
1060 cmp = 1;
1061 }
1062
1063 switch (op) {
1064 case Py_LT: cmp = cmp < 0; break;
1065 case Py_LE: cmp = cmp <= 0; break;
1066 case Py_EQ: cmp = cmp == 0; break;
1067 case Py_NE: cmp = cmp != 0; break;
1068 case Py_GT: cmp = cmp > 0; break;
1069 case Py_GE: cmp = cmp >= 0; break;
1070 }
1071 }
1072
1073 res = cmp ? Py_True : Py_False;
Martin v. Löwis423be952008-08-13 15:53:07 +00001074 PyBuffer_Release(&self_bytes);
1075 PyBuffer_Release(&other_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001076 Py_INCREF(res);
1077 return res;
1078}
1079
1080static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001081bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001082{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001083 if (self->ob_exports > 0) {
1084 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001085 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001086 PyErr_Print();
1087 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001088 if (self->ob_bytes != 0) {
Antoine Pitrou39aba4f2011-11-12 21:15:28 +01001089 PyObject_Free(self->ob_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001090 }
1091 Py_TYPE(self)->tp_free((PyObject *)self);
1092}
1093
1094
1095/* -------------------------------------------------------------------- */
1096/* Methods */
1097
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001098#define FASTSEARCH fastsearch
1099#define STRINGLIB(F) stringlib_##F
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001100#define STRINGLIB_CHAR char
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001101#define STRINGLIB_SIZEOF_CHAR 1
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001102#define STRINGLIB_LEN PyByteArray_GET_SIZE
1103#define STRINGLIB_STR PyByteArray_AS_STRING
1104#define STRINGLIB_NEW PyByteArray_FromStringAndSize
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001105#define STRINGLIB_ISSPACE Py_ISSPACE
1106#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001107#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1108#define STRINGLIB_MUTABLE 1
1109
1110#include "stringlib/fastsearch.h"
1111#include "stringlib/count.h"
1112#include "stringlib/find.h"
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001113#include "stringlib/join.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001114#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001115#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001116#include "stringlib/ctype.h"
1117#include "stringlib/transmogrify.h"
1118
1119
1120/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1121were copied from the old char* style string object. */
1122
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001123/* helper macro to fixup start/end slice values */
1124#define ADJUST_INDICES(start, end, len) \
1125 if (end > len) \
1126 end = len; \
1127 else if (end < 0) { \
1128 end += len; \
1129 if (end < 0) \
1130 end = 0; \
1131 } \
1132 if (start < 0) { \
1133 start += len; \
1134 if (start < 0) \
1135 start = 0; \
1136 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001137
1138Py_LOCAL_INLINE(Py_ssize_t)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001139bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001140{
1141 PyObject *subobj;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001142 char byte;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001143 Py_buffer subbuf;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001144 const char *sub;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02001145 Py_ssize_t len, sub_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001146 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1147 Py_ssize_t res;
1148
Antoine Pitrouac65d962011-10-20 23:54:17 +02001149 if (!stringlib_parse_args_finds_byte("find/rfind/index/rindex",
1150 args, &subobj, &byte, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001151 return -2;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001152
1153 if (subobj) {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001154 if (PyObject_GetBuffer(subobj, &subbuf, PyBUF_SIMPLE) != 0)
Antoine Pitrouac65d962011-10-20 23:54:17 +02001155 return -2;
1156
1157 sub = subbuf.buf;
1158 sub_len = subbuf.len;
1159 }
1160 else {
1161 sub = &byte;
1162 sub_len = 1;
1163 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02001164 len = PyByteArray_GET_SIZE(self);
Antoine Pitrouac65d962011-10-20 23:54:17 +02001165
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02001166 ADJUST_INDICES(start, end, len);
1167 if (end - start < sub_len)
1168 res = -1;
Victor Stinnerdabbfe72015-03-25 03:16:32 +01001169 /* Issue #23573: FIXME, windows has no memrchr() */
1170 else if (sub_len == 1 && dir > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02001171 unsigned char needle = *sub;
1172 int mode = (dir > 0) ? FAST_SEARCH : FAST_RSEARCH;
1173 res = stringlib_fastsearch_memchr_1char(
1174 PyByteArray_AS_STRING(self) + start, end - start,
1175 needle, needle, mode);
1176 if (res >= 0)
1177 res += start;
1178 }
1179 else {
1180 if (dir > 0)
1181 res = stringlib_find_slice(
1182 PyByteArray_AS_STRING(self), len,
1183 sub, sub_len, start, end);
1184 else
1185 res = stringlib_rfind_slice(
1186 PyByteArray_AS_STRING(self), len,
1187 sub, sub_len, start, end);
1188 }
Antoine Pitrouac65d962011-10-20 23:54:17 +02001189
1190 if (subobj)
1191 PyBuffer_Release(&subbuf);
1192
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001193 return res;
1194}
1195
1196PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001197"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001198\n\
1199Return the lowest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001200such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001201arguments start and end are interpreted as in slice notation.\n\
1202\n\
1203Return -1 on failure.");
1204
1205static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001206bytearray_find(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001207{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001208 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001209 if (result == -2)
1210 return NULL;
1211 return PyLong_FromSsize_t(result);
1212}
1213
1214PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001215"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001216\n\
1217Return the number of non-overlapping occurrences of subsection sub in\n\
1218bytes B[start:end]. Optional arguments start and end are interpreted\n\
1219as in slice notation.");
1220
1221static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001222bytearray_count(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001223{
1224 PyObject *sub_obj;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001225 const char *str = PyByteArray_AS_STRING(self), *sub;
1226 Py_ssize_t sub_len;
1227 char byte;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001228 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001229
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001230 Py_buffer vsub;
1231 PyObject *count_obj;
1232
Antoine Pitrouac65d962011-10-20 23:54:17 +02001233 if (!stringlib_parse_args_finds_byte("count", args, &sub_obj, &byte,
1234 &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001235 return NULL;
1236
Antoine Pitrouac65d962011-10-20 23:54:17 +02001237 if (sub_obj) {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001238 if (PyObject_GetBuffer(sub_obj, &vsub, PyBUF_SIMPLE) != 0)
Antoine Pitrouac65d962011-10-20 23:54:17 +02001239 return NULL;
1240
1241 sub = vsub.buf;
1242 sub_len = vsub.len;
1243 }
1244 else {
1245 sub = &byte;
1246 sub_len = 1;
1247 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001248
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001249 ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001250
1251 count_obj = PyLong_FromSsize_t(
Antoine Pitrouac65d962011-10-20 23:54:17 +02001252 stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001253 );
Antoine Pitrouac65d962011-10-20 23:54:17 +02001254
1255 if (sub_obj)
1256 PyBuffer_Release(&vsub);
1257
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001258 return count_obj;
1259}
1260
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001261/*[clinic input]
1262bytearray.clear
1263
1264 self: self(type="PyByteArrayObject *")
1265
1266Remove all items from the bytearray.
1267[clinic start generated code]*/
1268
1269PyDoc_STRVAR(bytearray_clear__doc__,
1270"clear($self, /)\n"
1271"--\n"
1272"\n"
1273"Remove all items from the bytearray.");
1274
1275#define BYTEARRAY_CLEAR_METHODDEF \
1276 {"clear", (PyCFunction)bytearray_clear, METH_NOARGS, bytearray_clear__doc__},
Eli Bendersky4db28d32011-03-03 18:21:02 +00001277
Victor Stinner6430fd52011-09-29 04:02:13 +02001278static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001279bytearray_clear_impl(PyByteArrayObject *self);
1280
1281static PyObject *
1282bytearray_clear(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
1283{
1284 return bytearray_clear_impl(self);
1285}
1286
1287static PyObject *
1288bytearray_clear_impl(PyByteArrayObject *self)
1289/*[clinic end generated code: output=5344093031e2f36c input=e524fd330abcdc18]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001290{
1291 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
1292 return NULL;
1293 Py_RETURN_NONE;
1294}
1295
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001296/*[clinic input]
1297bytearray.copy
1298
1299 self: self(type="PyByteArrayObject *")
1300
1301Return a copy of B.
1302[clinic start generated code]*/
1303
1304PyDoc_STRVAR(bytearray_copy__doc__,
1305"copy($self, /)\n"
1306"--\n"
1307"\n"
1308"Return a copy of B.");
1309
1310#define BYTEARRAY_COPY_METHODDEF \
1311 {"copy", (PyCFunction)bytearray_copy, METH_NOARGS, bytearray_copy__doc__},
Eli Bendersky4db28d32011-03-03 18:21:02 +00001312
1313static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001314bytearray_copy_impl(PyByteArrayObject *self);
1315
1316static PyObject *
1317bytearray_copy(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
1318{
1319 return bytearray_copy_impl(self);
1320}
1321
1322static PyObject *
1323bytearray_copy_impl(PyByteArrayObject *self)
1324/*[clinic end generated code: output=8788ed299f7f2214 input=6d5d2975aa0f33f3]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001325{
1326 return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
1327 PyByteArray_GET_SIZE(self));
1328}
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001329
1330PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001331"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001332\n\
1333Like B.find() but raise ValueError when the subsection is not found.");
1334
1335static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001336bytearray_index(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001337{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001338 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001339 if (result == -2)
1340 return NULL;
1341 if (result == -1) {
1342 PyErr_SetString(PyExc_ValueError,
1343 "subsection not found");
1344 return NULL;
1345 }
1346 return PyLong_FromSsize_t(result);
1347}
1348
1349
1350PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001351"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001352\n\
1353Return the highest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001354such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001355arguments start and end are interpreted as in slice notation.\n\
1356\n\
1357Return -1 on failure.");
1358
1359static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001360bytearray_rfind(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001361{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001362 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001363 if (result == -2)
1364 return NULL;
1365 return PyLong_FromSsize_t(result);
1366}
1367
1368
1369PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001370"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001371\n\
1372Like B.rfind() but raise ValueError when the subsection is not found.");
1373
1374static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001375bytearray_rindex(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001376{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001377 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001378 if (result == -2)
1379 return NULL;
1380 if (result == -1) {
1381 PyErr_SetString(PyExc_ValueError,
1382 "subsection not found");
1383 return NULL;
1384 }
1385 return PyLong_FromSsize_t(result);
1386}
1387
1388
1389static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001390bytearray_contains(PyObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001391{
1392 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1393 if (ival == -1 && PyErr_Occurred()) {
1394 Py_buffer varg;
Antoine Pitrou0010d372010-08-15 17:12:55 +00001395 Py_ssize_t pos;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001396 PyErr_Clear();
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001397 if (PyObject_GetBuffer(arg, &varg, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001398 return -1;
1399 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1400 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001401 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001402 return pos >= 0;
1403 }
1404 if (ival < 0 || ival >= 256) {
1405 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1406 return -1;
1407 }
1408
Antoine Pitrou0010d372010-08-15 17:12:55 +00001409 return memchr(PyByteArray_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001410}
1411
1412
1413/* Matches the end (direction >= 0) or start (direction < 0) of self
1414 * against substr, using the start and end arguments. Returns
1415 * -1 on error, 0 if not found and 1 if found.
1416 */
1417Py_LOCAL(int)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001418_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001419 Py_ssize_t end, int direction)
1420{
1421 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1422 const char* str;
1423 Py_buffer vsubstr;
1424 int rv = 0;
1425
1426 str = PyByteArray_AS_STRING(self);
1427
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001428 if (PyObject_GetBuffer(substr, &vsubstr, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001429 return -1;
1430
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001431 ADJUST_INDICES(start, end, len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001432
1433 if (direction < 0) {
1434 /* startswith */
1435 if (start+vsubstr.len > len) {
1436 goto done;
1437 }
1438 } else {
1439 /* endswith */
1440 if (end-start < vsubstr.len || start > len) {
1441 goto done;
1442 }
1443
1444 if (end-vsubstr.len > start)
1445 start = end - vsubstr.len;
1446 }
1447 if (end-start >= vsubstr.len)
1448 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1449
1450done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001451 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001452 return rv;
1453}
1454
1455
1456PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001457"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001458\n\
1459Return True if B starts with the specified prefix, False otherwise.\n\
1460With optional start, test B beginning at that position.\n\
1461With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001462prefix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001463
1464static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001465bytearray_startswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001466{
1467 Py_ssize_t start = 0;
1468 Py_ssize_t end = PY_SSIZE_T_MAX;
1469 PyObject *subobj;
1470 int result;
1471
Jesus Ceaac451502011-04-20 17:09:23 +02001472 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001473 return NULL;
1474 if (PyTuple_Check(subobj)) {
1475 Py_ssize_t i;
1476 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001477 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001478 PyTuple_GET_ITEM(subobj, i),
1479 start, end, -1);
1480 if (result == -1)
1481 return NULL;
1482 else if (result) {
1483 Py_RETURN_TRUE;
1484 }
1485 }
1486 Py_RETURN_FALSE;
1487 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001488 result = _bytearray_tailmatch(self, subobj, start, end, -1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001489 if (result == -1) {
1490 if (PyErr_ExceptionMatches(PyExc_TypeError))
1491 PyErr_Format(PyExc_TypeError, "startswith first arg must be bytes "
1492 "or a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001493 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001494 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001495 else
1496 return PyBool_FromLong(result);
1497}
1498
1499PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001500"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001501\n\
1502Return True if B ends with the specified suffix, False otherwise.\n\
1503With optional start, test B beginning at that position.\n\
1504With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001505suffix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001506
1507static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001508bytearray_endswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001509{
1510 Py_ssize_t start = 0;
1511 Py_ssize_t end = PY_SSIZE_T_MAX;
1512 PyObject *subobj;
1513 int result;
1514
Jesus Ceaac451502011-04-20 17:09:23 +02001515 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001516 return NULL;
1517 if (PyTuple_Check(subobj)) {
1518 Py_ssize_t i;
1519 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001520 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001521 PyTuple_GET_ITEM(subobj, i),
1522 start, end, +1);
1523 if (result == -1)
1524 return NULL;
1525 else if (result) {
1526 Py_RETURN_TRUE;
1527 }
1528 }
1529 Py_RETURN_FALSE;
1530 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001531 result = _bytearray_tailmatch(self, subobj, start, end, +1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001532 if (result == -1) {
1533 if (PyErr_ExceptionMatches(PyExc_TypeError))
1534 PyErr_Format(PyExc_TypeError, "endswith first arg must be bytes or "
1535 "a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001536 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001537 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001538 else
1539 return PyBool_FromLong(result);
1540}
1541
1542
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001543/*[clinic input]
1544bytearray.translate
1545
1546 self: self(type="PyByteArrayObject *")
1547 table: object
1548 Translation table, which must be a bytes object of length 256.
1549 [
1550 deletechars: object
1551 ]
1552 /
1553
1554Return a copy with each character mapped by the given translation table.
1555
1556All characters occurring in the optional argument deletechars are removed.
1557The remaining characters are mapped through the given translation table.
1558[clinic start generated code]*/
1559
1560PyDoc_STRVAR(bytearray_translate__doc__,
1561"translate(table, [deletechars])\n"
1562"Return a copy with each character mapped by the given translation table.\n"
1563"\n"
1564" table\n"
1565" Translation table, which must be a bytes object of length 256.\n"
1566"\n"
1567"All characters occurring in the optional argument deletechars are removed.\n"
1568"The remaining characters are mapped through the given translation table.");
1569
1570#define BYTEARRAY_TRANSLATE_METHODDEF \
1571 {"translate", (PyCFunction)bytearray_translate, METH_VARARGS, bytearray_translate__doc__},
1572
1573static PyObject *
1574bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, int group_right_1, PyObject *deletechars);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001575
1576static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001577bytearray_translate(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001578{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001579 PyObject *return_value = NULL;
1580 PyObject *table;
1581 int group_right_1 = 0;
1582 PyObject *deletechars = NULL;
1583
1584 switch (PyTuple_GET_SIZE(args)) {
1585 case 1:
1586 if (!PyArg_ParseTuple(args, "O:translate", &table))
1587 goto exit;
1588 break;
1589 case 2:
1590 if (!PyArg_ParseTuple(args, "OO:translate", &table, &deletechars))
1591 goto exit;
1592 group_right_1 = 1;
1593 break;
1594 default:
1595 PyErr_SetString(PyExc_TypeError, "bytearray.translate requires 1 to 2 arguments");
1596 goto exit;
1597 }
1598 return_value = bytearray_translate_impl(self, table, group_right_1, deletechars);
1599
1600exit:
1601 return return_value;
1602}
1603
1604static PyObject *
1605bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, int group_right_1, PyObject *deletechars)
1606/*[clinic end generated code: output=a709df81d41db4b7 input=b749ad85f4860824]*/
1607{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001608 char *input, *output;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001609 const char *table_chars;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001610 Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001611 PyObject *input_obj = (PyObject*)self;
1612 const char *output_start;
1613 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001614 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001615 int trans_table[256];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001616 Py_buffer vtable, vdel;
1617
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001618 if (table == Py_None) {
1619 table_chars = NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001620 table = NULL;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001621 } else if (PyObject_GetBuffer(table, &vtable, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001622 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001623 } else {
1624 if (vtable.len != 256) {
1625 PyErr_SetString(PyExc_ValueError,
1626 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001627 PyBuffer_Release(&vtable);
1628 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001629 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001630 table_chars = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001631 }
1632
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001633 if (deletechars != NULL) {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001634 if (PyObject_GetBuffer(deletechars, &vdel, PyBUF_SIMPLE) != 0) {
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001635 if (table != NULL)
Georg Brandl953152f2009-07-22 12:03:59 +00001636 PyBuffer_Release(&vtable);
1637 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001638 }
1639 }
1640 else {
1641 vdel.buf = NULL;
1642 vdel.len = 0;
1643 }
1644
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001645 inlen = PyByteArray_GET_SIZE(input_obj);
1646 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1647 if (result == NULL)
1648 goto done;
1649 output_start = output = PyByteArray_AsString(result);
1650 input = PyByteArray_AS_STRING(input_obj);
1651
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001652 if (vdel.len == 0 && table_chars != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001653 /* If no deletions are required, use faster code */
1654 for (i = inlen; --i >= 0; ) {
1655 c = Py_CHARMASK(*input++);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001656 *output++ = table_chars[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001657 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001658 goto done;
1659 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001660
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001661 if (table_chars == NULL) {
Georg Brandlccc47b62008-12-28 11:44:14 +00001662 for (i = 0; i < 256; i++)
1663 trans_table[i] = Py_CHARMASK(i);
1664 } else {
1665 for (i = 0; i < 256; i++)
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001666 trans_table[i] = Py_CHARMASK(table_chars[i]);
Georg Brandlccc47b62008-12-28 11:44:14 +00001667 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001668
1669 for (i = 0; i < vdel.len; i++)
1670 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1671
1672 for (i = inlen; --i >= 0; ) {
1673 c = Py_CHARMASK(*input++);
1674 if (trans_table[c] != -1)
1675 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1676 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001677 }
1678 /* Fix the size of the resulting string */
1679 if (inlen > 0)
Christian Heimesc731bbe2013-07-21 02:04:35 +02001680 if (PyByteArray_Resize(result, output - output_start) < 0) {
1681 Py_CLEAR(result);
1682 goto done;
1683 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001684
1685done:
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001686 if (table != NULL)
Georg Brandlccc47b62008-12-28 11:44:14 +00001687 PyBuffer_Release(&vtable);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001688 if (deletechars != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001689 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001690 return result;
1691}
1692
1693
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001694/*[clinic input]
1695
1696@staticmethod
1697bytearray.maketrans
1698
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001699 frm: Py_buffer
1700 to: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001701 /
1702
1703Return a translation table useable for the bytes or bytearray translate method.
1704
1705The returned table will be one where each byte in frm is mapped to the byte at
1706the same position in to.
1707
1708The bytes objects frm and to must be of the same length.
1709[clinic start generated code]*/
1710
1711PyDoc_STRVAR(bytearray_maketrans__doc__,
1712"maketrans(frm, to, /)\n"
1713"--\n"
1714"\n"
1715"Return a translation table useable for the bytes or bytearray translate method.\n"
1716"\n"
1717"The returned table will be one where each byte in frm is mapped to the byte at\n"
1718"the same position in to.\n"
1719"\n"
1720"The bytes objects frm and to must be of the same length.");
1721
1722#define BYTEARRAY_MAKETRANS_METHODDEF \
1723 {"maketrans", (PyCFunction)bytearray_maketrans, METH_VARARGS|METH_STATIC, bytearray_maketrans__doc__},
1724
Georg Brandlabc38772009-04-12 15:51:51 +00001725static PyObject *
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001726bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001727
1728static PyObject *
1729bytearray_maketrans(void *null, PyObject *args)
Georg Brandlabc38772009-04-12 15:51:51 +00001730{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001731 PyObject *return_value = NULL;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001732 Py_buffer frm = {NULL, NULL};
1733 Py_buffer to = {NULL, NULL};
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001734
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001735 if (!PyArg_ParseTuple(args,
1736 "y*y*:maketrans",
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001737 &frm, &to))
1738 goto exit;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001739 return_value = bytearray_maketrans_impl(&frm, &to);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001740
1741exit:
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001742 /* Cleanup for frm */
1743 if (frm.obj)
1744 PyBuffer_Release(&frm);
1745 /* Cleanup for to */
1746 if (to.obj)
1747 PyBuffer_Release(&to);
1748
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001749 return return_value;
1750}
1751
1752static PyObject *
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001753bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to)
1754/*[clinic end generated code: output=d332622814c26f4b input=5925a81d2fbbf151]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001755{
1756 return _Py_bytes_maketrans(frm, to);
Georg Brandlabc38772009-04-12 15:51:51 +00001757}
1758
1759
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001760/* find and count characters and substrings */
1761
1762#define findchar(target, target_len, c) \
1763 ((char *)memchr((const void *)(target), c, target_len))
1764
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001765
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001766/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001767Py_LOCAL(PyByteArrayObject *)
1768return_self(PyByteArrayObject *self)
1769{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001770 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001771 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1772 PyByteArray_AS_STRING(self),
1773 PyByteArray_GET_SIZE(self));
1774}
1775
1776Py_LOCAL_INLINE(Py_ssize_t)
1777countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1778{
1779 Py_ssize_t count=0;
1780 const char *start=target;
1781 const char *end=target+target_len;
1782
1783 while ( (start=findchar(start, end-start, c)) != NULL ) {
1784 count++;
1785 if (count >= maxcount)
1786 break;
1787 start += 1;
1788 }
1789 return count;
1790}
1791
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001792
1793/* Algorithms for different cases of string replacement */
1794
1795/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1796Py_LOCAL(PyByteArrayObject *)
1797replace_interleave(PyByteArrayObject *self,
1798 const char *to_s, Py_ssize_t to_len,
1799 Py_ssize_t maxcount)
1800{
1801 char *self_s, *result_s;
1802 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001803 Py_ssize_t count, i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001804 PyByteArrayObject *result;
1805
1806 self_len = PyByteArray_GET_SIZE(self);
1807
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001808 /* 1 at the end plus 1 after every character;
1809 count = min(maxcount, self_len + 1) */
1810 if (maxcount <= self_len)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001811 count = maxcount;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001812 else
1813 /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
1814 count = self_len + 1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001815
1816 /* Check for overflow */
1817 /* result_len = count * to_len + self_len; */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001818 assert(count > 0);
1819 if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001820 PyErr_SetString(PyExc_OverflowError,
1821 "replace string is too long");
1822 return NULL;
1823 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001824 result_len = count * to_len + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001825
1826 if (! (result = (PyByteArrayObject *)
1827 PyByteArray_FromStringAndSize(NULL, result_len)) )
1828 return NULL;
1829
1830 self_s = PyByteArray_AS_STRING(self);
1831 result_s = PyByteArray_AS_STRING(result);
1832
1833 /* TODO: special case single character, which doesn't need memcpy */
1834
1835 /* Lay the first one down (guaranteed this will occur) */
1836 Py_MEMCPY(result_s, to_s, to_len);
1837 result_s += to_len;
1838 count -= 1;
1839
1840 for (i=0; i<count; i++) {
1841 *result_s++ = *self_s++;
1842 Py_MEMCPY(result_s, to_s, to_len);
1843 result_s += to_len;
1844 }
1845
1846 /* Copy the rest of the original string */
1847 Py_MEMCPY(result_s, self_s, self_len-i);
1848
1849 return result;
1850}
1851
1852/* Special case for deleting a single character */
1853/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1854Py_LOCAL(PyByteArrayObject *)
1855replace_delete_single_character(PyByteArrayObject *self,
1856 char from_c, Py_ssize_t maxcount)
1857{
1858 char *self_s, *result_s;
1859 char *start, *next, *end;
1860 Py_ssize_t self_len, result_len;
1861 Py_ssize_t count;
1862 PyByteArrayObject *result;
1863
1864 self_len = PyByteArray_GET_SIZE(self);
1865 self_s = PyByteArray_AS_STRING(self);
1866
1867 count = countchar(self_s, self_len, from_c, maxcount);
1868 if (count == 0) {
1869 return return_self(self);
1870 }
1871
1872 result_len = self_len - count; /* from_len == 1 */
1873 assert(result_len>=0);
1874
1875 if ( (result = (PyByteArrayObject *)
1876 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1877 return NULL;
1878 result_s = PyByteArray_AS_STRING(result);
1879
1880 start = self_s;
1881 end = self_s + self_len;
1882 while (count-- > 0) {
1883 next = findchar(start, end-start, from_c);
1884 if (next == NULL)
1885 break;
1886 Py_MEMCPY(result_s, start, next-start);
1887 result_s += (next-start);
1888 start = next+1;
1889 }
1890 Py_MEMCPY(result_s, start, end-start);
1891
1892 return result;
1893}
1894
1895/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1896
1897Py_LOCAL(PyByteArrayObject *)
1898replace_delete_substring(PyByteArrayObject *self,
1899 const char *from_s, Py_ssize_t from_len,
1900 Py_ssize_t maxcount)
1901{
1902 char *self_s, *result_s;
1903 char *start, *next, *end;
1904 Py_ssize_t self_len, result_len;
1905 Py_ssize_t count, offset;
1906 PyByteArrayObject *result;
1907
1908 self_len = PyByteArray_GET_SIZE(self);
1909 self_s = PyByteArray_AS_STRING(self);
1910
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001911 count = stringlib_count(self_s, self_len,
1912 from_s, from_len,
1913 maxcount);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001914
1915 if (count == 0) {
1916 /* no matches */
1917 return return_self(self);
1918 }
1919
1920 result_len = self_len - (count * from_len);
1921 assert (result_len>=0);
1922
1923 if ( (result = (PyByteArrayObject *)
1924 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1925 return NULL;
1926
1927 result_s = PyByteArray_AS_STRING(result);
1928
1929 start = self_s;
1930 end = self_s + self_len;
1931 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001932 offset = stringlib_find(start, end-start,
1933 from_s, from_len,
1934 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001935 if (offset == -1)
1936 break;
1937 next = start + offset;
1938
1939 Py_MEMCPY(result_s, start, next-start);
1940
1941 result_s += (next-start);
1942 start = next+from_len;
1943 }
1944 Py_MEMCPY(result_s, start, end-start);
1945 return result;
1946}
1947
1948/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1949Py_LOCAL(PyByteArrayObject *)
1950replace_single_character_in_place(PyByteArrayObject *self,
1951 char from_c, char to_c,
1952 Py_ssize_t maxcount)
1953{
Antoine Pitroud1188562010-06-09 16:38:55 +00001954 char *self_s, *result_s, *start, *end, *next;
1955 Py_ssize_t self_len;
1956 PyByteArrayObject *result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001957
Antoine Pitroud1188562010-06-09 16:38:55 +00001958 /* The result string will be the same size */
1959 self_s = PyByteArray_AS_STRING(self);
1960 self_len = PyByteArray_GET_SIZE(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001961
Antoine Pitroud1188562010-06-09 16:38:55 +00001962 next = findchar(self_s, self_len, from_c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001963
Antoine Pitroud1188562010-06-09 16:38:55 +00001964 if (next == NULL) {
1965 /* No matches; return the original bytes */
1966 return return_self(self);
1967 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001968
Antoine Pitroud1188562010-06-09 16:38:55 +00001969 /* Need to make a new bytes */
1970 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1971 if (result == NULL)
1972 return NULL;
1973 result_s = PyByteArray_AS_STRING(result);
1974 Py_MEMCPY(result_s, self_s, self_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001975
Antoine Pitroud1188562010-06-09 16:38:55 +00001976 /* change everything in-place, starting with this one */
1977 start = result_s + (next-self_s);
1978 *start = to_c;
1979 start++;
1980 end = result_s + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001981
Antoine Pitroud1188562010-06-09 16:38:55 +00001982 while (--maxcount > 0) {
1983 next = findchar(start, end-start, from_c);
1984 if (next == NULL)
1985 break;
1986 *next = to_c;
1987 start = next+1;
1988 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001989
Antoine Pitroud1188562010-06-09 16:38:55 +00001990 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001991}
1992
1993/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1994Py_LOCAL(PyByteArrayObject *)
1995replace_substring_in_place(PyByteArrayObject *self,
1996 const char *from_s, Py_ssize_t from_len,
1997 const char *to_s, Py_ssize_t to_len,
1998 Py_ssize_t maxcount)
1999{
2000 char *result_s, *start, *end;
2001 char *self_s;
2002 Py_ssize_t self_len, offset;
2003 PyByteArrayObject *result;
2004
2005 /* The result bytes will be the same size */
2006
2007 self_s = PyByteArray_AS_STRING(self);
2008 self_len = PyByteArray_GET_SIZE(self);
2009
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002010 offset = stringlib_find(self_s, self_len,
2011 from_s, from_len,
2012 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002013 if (offset == -1) {
2014 /* No matches; return the original bytes */
2015 return return_self(self);
2016 }
2017
2018 /* Need to make a new bytes */
2019 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
2020 if (result == NULL)
2021 return NULL;
2022 result_s = PyByteArray_AS_STRING(result);
2023 Py_MEMCPY(result_s, self_s, self_len);
2024
2025 /* change everything in-place, starting with this one */
2026 start = result_s + offset;
2027 Py_MEMCPY(start, to_s, from_len);
2028 start += from_len;
2029 end = result_s + self_len;
2030
2031 while ( --maxcount > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002032 offset = stringlib_find(start, end-start,
2033 from_s, from_len,
2034 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002035 if (offset==-1)
2036 break;
2037 Py_MEMCPY(start+offset, to_s, from_len);
2038 start += offset+from_len;
2039 }
2040
2041 return result;
2042}
2043
2044/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
2045Py_LOCAL(PyByteArrayObject *)
2046replace_single_character(PyByteArrayObject *self,
2047 char from_c,
2048 const char *to_s, Py_ssize_t to_len,
2049 Py_ssize_t maxcount)
2050{
2051 char *self_s, *result_s;
2052 char *start, *next, *end;
2053 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002054 Py_ssize_t count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002055 PyByteArrayObject *result;
2056
2057 self_s = PyByteArray_AS_STRING(self);
2058 self_len = PyByteArray_GET_SIZE(self);
2059
2060 count = countchar(self_s, self_len, from_c, maxcount);
2061 if (count == 0) {
2062 /* no matches, return unchanged */
2063 return return_self(self);
2064 }
2065
2066 /* use the difference between current and new, hence the "-1" */
2067 /* result_len = self_len + count * (to_len-1) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002068 assert(count > 0);
2069 if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002070 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
2071 return NULL;
2072 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002073 result_len = self_len + count * (to_len - 1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002074
2075 if ( (result = (PyByteArrayObject *)
2076 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
2077 return NULL;
2078 result_s = PyByteArray_AS_STRING(result);
2079
2080 start = self_s;
2081 end = self_s + self_len;
2082 while (count-- > 0) {
2083 next = findchar(start, end-start, from_c);
2084 if (next == NULL)
2085 break;
2086
2087 if (next == start) {
2088 /* replace with the 'to' */
2089 Py_MEMCPY(result_s, to_s, to_len);
2090 result_s += to_len;
2091 start += 1;
2092 } else {
2093 /* copy the unchanged old then the 'to' */
2094 Py_MEMCPY(result_s, start, next-start);
2095 result_s += (next-start);
2096 Py_MEMCPY(result_s, to_s, to_len);
2097 result_s += to_len;
2098 start = next+1;
2099 }
2100 }
2101 /* Copy the remainder of the remaining bytes */
2102 Py_MEMCPY(result_s, start, end-start);
2103
2104 return result;
2105}
2106
2107/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
2108Py_LOCAL(PyByteArrayObject *)
2109replace_substring(PyByteArrayObject *self,
2110 const char *from_s, Py_ssize_t from_len,
2111 const char *to_s, Py_ssize_t to_len,
2112 Py_ssize_t maxcount)
2113{
2114 char *self_s, *result_s;
2115 char *start, *next, *end;
2116 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002117 Py_ssize_t count, offset;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002118 PyByteArrayObject *result;
2119
2120 self_s = PyByteArray_AS_STRING(self);
2121 self_len = PyByteArray_GET_SIZE(self);
2122
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002123 count = stringlib_count(self_s, self_len,
2124 from_s, from_len,
2125 maxcount);
2126
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002127 if (count == 0) {
2128 /* no matches, return unchanged */
2129 return return_self(self);
2130 }
2131
2132 /* Check for overflow */
2133 /* result_len = self_len + count * (to_len-from_len) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002134 assert(count > 0);
2135 if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002136 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
2137 return NULL;
2138 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002139 result_len = self_len + count * (to_len - from_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002140
2141 if ( (result = (PyByteArrayObject *)
2142 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
2143 return NULL;
2144 result_s = PyByteArray_AS_STRING(result);
2145
2146 start = self_s;
2147 end = self_s + self_len;
2148 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002149 offset = stringlib_find(start, end-start,
2150 from_s, from_len,
2151 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002152 if (offset == -1)
2153 break;
2154 next = start+offset;
2155 if (next == start) {
2156 /* replace with the 'to' */
2157 Py_MEMCPY(result_s, to_s, to_len);
2158 result_s += to_len;
2159 start += from_len;
2160 } else {
2161 /* copy the unchanged old then the 'to' */
2162 Py_MEMCPY(result_s, start, next-start);
2163 result_s += (next-start);
2164 Py_MEMCPY(result_s, to_s, to_len);
2165 result_s += to_len;
2166 start = next+from_len;
2167 }
2168 }
2169 /* Copy the remainder of the remaining bytes */
2170 Py_MEMCPY(result_s, start, end-start);
2171
2172 return result;
2173}
2174
2175
2176Py_LOCAL(PyByteArrayObject *)
2177replace(PyByteArrayObject *self,
2178 const char *from_s, Py_ssize_t from_len,
2179 const char *to_s, Py_ssize_t to_len,
2180 Py_ssize_t maxcount)
2181{
2182 if (maxcount < 0) {
2183 maxcount = PY_SSIZE_T_MAX;
2184 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
2185 /* nothing to do; return the original bytes */
2186 return return_self(self);
2187 }
2188
2189 if (maxcount == 0 ||
2190 (from_len == 0 && to_len == 0)) {
2191 /* nothing to do; return the original bytes */
2192 return return_self(self);
2193 }
2194
2195 /* Handle zero-length special cases */
2196
2197 if (from_len == 0) {
2198 /* insert the 'to' bytes everywhere. */
2199 /* >>> "Python".replace("", ".") */
2200 /* '.P.y.t.h.o.n.' */
2201 return replace_interleave(self, to_s, to_len, maxcount);
2202 }
2203
2204 /* Except for "".replace("", "A") == "A" there is no way beyond this */
2205 /* point for an empty self bytes to generate a non-empty bytes */
2206 /* Special case so the remaining code always gets a non-empty bytes */
2207 if (PyByteArray_GET_SIZE(self) == 0) {
2208 return return_self(self);
2209 }
2210
2211 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00002212 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002213 if (from_len == 1) {
2214 return replace_delete_single_character(
2215 self, from_s[0], maxcount);
2216 } else {
2217 return replace_delete_substring(self, from_s, from_len, maxcount);
2218 }
2219 }
2220
2221 /* Handle special case where both bytes have the same length */
2222
2223 if (from_len == to_len) {
2224 if (from_len == 1) {
2225 return replace_single_character_in_place(
2226 self,
2227 from_s[0],
2228 to_s[0],
2229 maxcount);
2230 } else {
2231 return replace_substring_in_place(
2232 self, from_s, from_len, to_s, to_len, maxcount);
2233 }
2234 }
2235
2236 /* Otherwise use the more generic algorithms */
2237 if (from_len == 1) {
2238 return replace_single_character(self, from_s[0],
2239 to_s, to_len, maxcount);
2240 } else {
2241 /* len('from')>=2, len('to')>=1 */
2242 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
2243 }
2244}
2245
2246
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002247/*[clinic input]
2248bytearray.replace
2249
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002250 old: Py_buffer
2251 new: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002252 count: Py_ssize_t = -1
2253 Maximum number of occurrences to replace.
2254 -1 (the default value) means replace all occurrences.
2255 /
2256
2257Return a copy with all occurrences of substring old replaced by new.
2258
2259If the optional argument count is given, only the first count occurrences are
2260replaced.
2261[clinic start generated code]*/
2262
2263PyDoc_STRVAR(bytearray_replace__doc__,
2264"replace($self, old, new, count=-1, /)\n"
2265"--\n"
2266"\n"
2267"Return a copy with all occurrences of substring old replaced by new.\n"
2268"\n"
2269" count\n"
2270" Maximum number of occurrences to replace.\n"
2271" -1 (the default value) means replace all occurrences.\n"
2272"\n"
2273"If the optional argument count is given, only the first count occurrences are\n"
2274"replaced.");
2275
2276#define BYTEARRAY_REPLACE_METHODDEF \
2277 {"replace", (PyCFunction)bytearray_replace, METH_VARARGS, bytearray_replace__doc__},
2278
2279static PyObject *
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002280bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old, Py_buffer *new, Py_ssize_t count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002281
2282static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002283bytearray_replace(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002284{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002285 PyObject *return_value = NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02002286 Py_buffer old = {NULL, NULL};
2287 Py_buffer new = {NULL, NULL};
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002288 Py_ssize_t count = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002289
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002290 if (!PyArg_ParseTuple(args,
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002291 "y*y*|n:replace",
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002292 &old, &new, &count))
2293 goto exit;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002294 return_value = bytearray_replace_impl(self, &old, &new, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002295
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002296exit:
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002297 /* Cleanup for old */
2298 if (old.obj)
2299 PyBuffer_Release(&old);
2300 /* Cleanup for new */
2301 if (new.obj)
2302 PyBuffer_Release(&new);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002303
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002304 return return_value;
2305}
2306
2307static PyObject *
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002308bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old, Py_buffer *new, Py_ssize_t count)
2309/*[clinic end generated code: output=9997fbbd5bac4883 input=aa379d988637c7fb]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002310{
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002311 return (PyObject *)replace((PyByteArrayObject *) self,
2312 old->buf, old->len,
2313 new->buf, new->len, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002314}
2315
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002316/*[clinic input]
2317bytearray.split
2318
2319 sep: object = None
2320 The delimiter according which to split the bytearray.
2321 None (the default value) means split on ASCII whitespace characters
2322 (space, tab, return, newline, formfeed, vertical tab).
2323 maxsplit: Py_ssize_t = -1
2324 Maximum number of splits to do.
2325 -1 (the default value) means no limit.
2326
2327Return a list of the sections in the bytearray, using sep as the delimiter.
2328[clinic start generated code]*/
2329
2330PyDoc_STRVAR(bytearray_split__doc__,
2331"split($self, /, sep=None, maxsplit=-1)\n"
2332"--\n"
2333"\n"
2334"Return a list of the sections in the bytearray, using sep as the delimiter.\n"
2335"\n"
2336" sep\n"
2337" The delimiter according which to split the bytearray.\n"
2338" None (the default value) means split on ASCII whitespace characters\n"
2339" (space, tab, return, newline, formfeed, vertical tab).\n"
2340" maxsplit\n"
2341" Maximum number of splits to do.\n"
2342" -1 (the default value) means no limit.");
2343
2344#define BYTEARRAY_SPLIT_METHODDEF \
2345 {"split", (PyCFunction)bytearray_split, METH_VARARGS|METH_KEYWORDS, bytearray_split__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002346
2347static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002348bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit);
2349
2350static PyObject *
2351bytearray_split(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002352{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002353 PyObject *return_value = NULL;
2354 static char *_keywords[] = {"sep", "maxsplit", NULL};
2355 PyObject *sep = Py_None;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002356 Py_ssize_t maxsplit = -1;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002357
2358 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
2359 "|On:split", _keywords,
2360 &sep, &maxsplit))
2361 goto exit;
2362 return_value = bytearray_split_impl(self, sep, maxsplit);
2363
2364exit:
2365 return return_value;
2366}
2367
2368static PyObject *
2369bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit)
2370/*[clinic end generated code: output=062a3d87d6f918fa input=24f82669f41bf523]*/
2371{
2372 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002373 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002374 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002375 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002376
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002377 if (maxsplit < 0)
2378 maxsplit = PY_SSIZE_T_MAX;
2379
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002380 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002381 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002382
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002383 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002384 return NULL;
2385 sub = vsub.buf;
2386 n = vsub.len;
2387
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002388 list = stringlib_split(
2389 (PyObject*) self, s, len, sub, n, maxsplit
2390 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002391 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002392 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002393}
2394
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002395/*[clinic input]
2396bytearray.partition
2397
2398 self: self(type="PyByteArrayObject *")
2399 sep: object
2400 /
2401
2402Partition the bytearray into three parts using the given separator.
2403
2404This will search for the separator sep in the bytearray. If the separator is
2405found, returns a 3-tuple containing the part before the separator, the
2406separator itself, and the part after it.
2407
2408If the separator is not found, returns a 3-tuple containing the original
2409bytearray object and two empty bytearray objects.
2410[clinic start generated code]*/
2411
2412PyDoc_STRVAR(bytearray_partition__doc__,
2413"partition($self, sep, /)\n"
2414"--\n"
2415"\n"
2416"Partition the bytearray into three parts using the given separator.\n"
2417"\n"
2418"This will search for the separator sep in the bytearray. If the separator is\n"
2419"found, returns a 3-tuple containing the part before the separator, the\n"
2420"separator itself, and the part after it.\n"
2421"\n"
2422"If the separator is not found, returns a 3-tuple containing the original\n"
2423"bytearray object and two empty bytearray objects.");
2424
2425#define BYTEARRAY_PARTITION_METHODDEF \
2426 {"partition", (PyCFunction)bytearray_partition, METH_O, bytearray_partition__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002427
2428static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002429bytearray_partition(PyByteArrayObject *self, PyObject *sep)
2430/*[clinic end generated code: output=2645138221fe6f4d input=7d7fe37b1696d506]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002431{
2432 PyObject *bytesep, *result;
2433
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002434 bytesep = PyByteArray_FromObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002435 if (! bytesep)
2436 return NULL;
2437
2438 result = stringlib_partition(
2439 (PyObject*) self,
2440 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2441 bytesep,
2442 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2443 );
2444
2445 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002446 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002447}
2448
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002449/*[clinic input]
2450bytearray.rpartition
2451
2452 self: self(type="PyByteArrayObject *")
2453 sep: object
2454 /
2455
2456Partition the bytes into three parts using the given separator.
2457
2458This will search for the separator sep in the bytearray, starting and the end.
2459If the separator is found, returns a 3-tuple containing the part before the
2460separator, the separator itself, and the part after it.
2461
2462If the separator is not found, returns a 3-tuple containing two empty bytearray
2463objects and the original bytearray object.
2464[clinic start generated code]*/
2465
2466PyDoc_STRVAR(bytearray_rpartition__doc__,
2467"rpartition($self, sep, /)\n"
2468"--\n"
2469"\n"
2470"Partition the bytes into three parts using the given separator.\n"
2471"\n"
2472"This will search for the separator sep in the bytearray, starting and the end.\n"
2473"If the separator is found, returns a 3-tuple containing the part before the\n"
2474"separator, the separator itself, and the part after it.\n"
2475"\n"
2476"If the separator is not found, returns a 3-tuple containing two empty bytearray\n"
2477"objects and the original bytearray object.");
2478
2479#define BYTEARRAY_RPARTITION_METHODDEF \
2480 {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, bytearray_rpartition__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002481
2482static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002483bytearray_rpartition(PyByteArrayObject *self, PyObject *sep)
2484/*[clinic end generated code: output=ed13e54605d007de input=9b8cd540c1b75853]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002485{
2486 PyObject *bytesep, *result;
2487
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002488 bytesep = PyByteArray_FromObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002489 if (! bytesep)
2490 return NULL;
2491
2492 result = stringlib_rpartition(
2493 (PyObject*) self,
2494 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2495 bytesep,
2496 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2497 );
2498
2499 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002500 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002501}
2502
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002503/*[clinic input]
2504bytearray.rsplit = bytearray.split
2505
2506Return a list of the sections in the bytearray, using sep as the delimiter.
2507
2508Splitting is done starting at the end of the bytearray and working to the front.
2509[clinic start generated code]*/
2510
2511PyDoc_STRVAR(bytearray_rsplit__doc__,
2512"rsplit($self, /, sep=None, maxsplit=-1)\n"
2513"--\n"
2514"\n"
2515"Return a list of the sections in the bytearray, using sep as the delimiter.\n"
2516"\n"
2517" sep\n"
2518" The delimiter according which to split the bytearray.\n"
2519" None (the default value) means split on ASCII whitespace characters\n"
2520" (space, tab, return, newline, formfeed, vertical tab).\n"
2521" maxsplit\n"
2522" Maximum number of splits to do.\n"
2523" -1 (the default value) means no limit.\n"
2524"\n"
2525"Splitting is done starting at the end of the bytearray and working to the front.");
2526
2527#define BYTEARRAY_RSPLIT_METHODDEF \
2528 {"rsplit", (PyCFunction)bytearray_rsplit, METH_VARARGS|METH_KEYWORDS, bytearray_rsplit__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002529
2530static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002531bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit);
2532
2533static PyObject *
2534bytearray_rsplit(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002535{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002536 PyObject *return_value = NULL;
2537 static char *_keywords[] = {"sep", "maxsplit", NULL};
2538 PyObject *sep = Py_None;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002539 Py_ssize_t maxsplit = -1;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002540
2541 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
2542 "|On:rsplit", _keywords,
2543 &sep, &maxsplit))
2544 goto exit;
2545 return_value = bytearray_rsplit_impl(self, sep, maxsplit);
2546
2547exit:
2548 return return_value;
2549}
2550
2551static PyObject *
2552bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit)
2553/*[clinic end generated code: output=affaf9fc2aae8d41 input=a68286e4dd692ffe]*/
2554{
2555 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002556 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002557 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002558 Py_buffer vsub;
2559
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002560 if (maxsplit < 0)
2561 maxsplit = PY_SSIZE_T_MAX;
2562
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002563 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002564 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002565
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002566 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002567 return NULL;
2568 sub = vsub.buf;
2569 n = vsub.len;
2570
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002571 list = stringlib_rsplit(
2572 (PyObject*) self, s, len, sub, n, maxsplit
2573 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002574 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002575 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002576}
2577
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002578/*[clinic input]
2579bytearray.reverse
2580
2581 self: self(type="PyByteArrayObject *")
2582
2583Reverse the order of the values in B in place.
2584[clinic start generated code]*/
2585
2586PyDoc_STRVAR(bytearray_reverse__doc__,
2587"reverse($self, /)\n"
2588"--\n"
2589"\n"
2590"Reverse the order of the values in B in place.");
2591
2592#define BYTEARRAY_REVERSE_METHODDEF \
2593 {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, bytearray_reverse__doc__},
2594
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002595static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002596bytearray_reverse_impl(PyByteArrayObject *self);
2597
2598static PyObject *
2599bytearray_reverse(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
2600{
2601 return bytearray_reverse_impl(self);
2602}
2603
2604static PyObject *
2605bytearray_reverse_impl(PyByteArrayObject *self)
2606/*[clinic end generated code: output=5d5e5f0bfc67f476 input=7933a499b8597bd1]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002607{
2608 char swap, *head, *tail;
2609 Py_ssize_t i, j, n = Py_SIZE(self);
2610
2611 j = n / 2;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002612 head = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002613 tail = head + n - 1;
2614 for (i = 0; i < j; i++) {
2615 swap = *head;
2616 *head++ = *tail;
2617 *tail-- = swap;
2618 }
2619
2620 Py_RETURN_NONE;
2621}
2622
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002623
2624/*[python input]
2625class bytesvalue_converter(CConverter):
2626 type = 'int'
2627 converter = '_getbytevalue'
2628[python start generated code]*/
2629/*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/
2630
2631
2632/*[clinic input]
2633bytearray.insert
2634
2635 self: self(type="PyByteArrayObject *")
2636 index: Py_ssize_t
2637 The index where the value is to be inserted.
2638 item: bytesvalue
2639 The item to be inserted.
2640 /
2641
2642Insert a single item into the bytearray before the given index.
2643[clinic start generated code]*/
2644
2645PyDoc_STRVAR(bytearray_insert__doc__,
2646"insert($self, index, item, /)\n"
2647"--\n"
2648"\n"
2649"Insert a single item into the bytearray before the given index.\n"
2650"\n"
2651" index\n"
2652" The index where the value is to be inserted.\n"
2653" item\n"
2654" The item to be inserted.");
2655
2656#define BYTEARRAY_INSERT_METHODDEF \
2657 {"insert", (PyCFunction)bytearray_insert, METH_VARARGS, bytearray_insert__doc__},
2658
2659static PyObject *
2660bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item);
2661
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002662static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002663bytearray_insert(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002664{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002665 PyObject *return_value = NULL;
2666 Py_ssize_t index;
2667 int item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002668
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002669 if (!PyArg_ParseTuple(args,
2670 "nO&:insert",
2671 &index, _getbytevalue, &item))
2672 goto exit;
2673 return_value = bytearray_insert_impl(self, index, item);
2674
2675exit:
2676 return return_value;
2677}
2678
2679static PyObject *
2680bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
2681/*[clinic end generated code: output=5ec9340d4ad19080 input=833766836ba30e1e]*/
2682{
2683 Py_ssize_t n = Py_SIZE(self);
2684 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002685
2686 if (n == PY_SSIZE_T_MAX) {
2687 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002688 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002689 return NULL;
2690 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002691 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2692 return NULL;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002693 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002694
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002695 if (index < 0) {
2696 index += n;
2697 if (index < 0)
2698 index = 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002699 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002700 if (index > n)
2701 index = n;
2702 memmove(buf + index + 1, buf + index, n - index);
2703 buf[index] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002704
2705 Py_RETURN_NONE;
2706}
2707
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002708/*[clinic input]
2709bytearray.append
2710
2711 self: self(type="PyByteArrayObject *")
2712 item: bytesvalue
2713 The item to be appended.
2714 /
2715
2716Append a single item to the end of the bytearray.
2717[clinic start generated code]*/
2718
2719PyDoc_STRVAR(bytearray_append__doc__,
2720"append($self, item, /)\n"
2721"--\n"
2722"\n"
2723"Append a single item to the end of the bytearray.\n"
2724"\n"
2725" item\n"
2726" The item to be appended.");
2727
2728#define BYTEARRAY_APPEND_METHODDEF \
2729 {"append", (PyCFunction)bytearray_append, METH_VARARGS, bytearray_append__doc__},
2730
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002731static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002732bytearray_append_impl(PyByteArrayObject *self, int item);
2733
2734static PyObject *
2735bytearray_append(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002736{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002737 PyObject *return_value = NULL;
2738 int item;
2739
2740 if (!PyArg_ParseTuple(args,
2741 "O&:append",
2742 _getbytevalue, &item))
2743 goto exit;
2744 return_value = bytearray_append_impl(self, item);
2745
2746exit:
2747 return return_value;
2748}
2749
2750static PyObject *
2751bytearray_append_impl(PyByteArrayObject *self, int item)
2752/*[clinic end generated code: output=b5b3325bb3bbaf85 input=ae56ea87380407cc]*/
2753{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002754 Py_ssize_t n = Py_SIZE(self);
2755
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002756 if (n == PY_SSIZE_T_MAX) {
2757 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002758 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002759 return NULL;
2760 }
2761 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2762 return NULL;
2763
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002764 PyByteArray_AS_STRING(self)[n] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002765
2766 Py_RETURN_NONE;
2767}
2768
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002769/*[clinic input]
2770bytearray.extend
2771
2772 self: self(type="PyByteArrayObject *")
2773 iterable_of_ints: object
2774 The iterable of items to append.
2775 /
2776
2777Append all the items from the iterator or sequence to the end of the bytearray.
2778[clinic start generated code]*/
2779
2780PyDoc_STRVAR(bytearray_extend__doc__,
2781"extend($self, iterable_of_ints, /)\n"
2782"--\n"
2783"\n"
2784"Append all the items from the iterator or sequence to the end of the bytearray.\n"
2785"\n"
2786" iterable_of_ints\n"
2787" The iterable of items to append.");
2788
2789#define BYTEARRAY_EXTEND_METHODDEF \
2790 {"extend", (PyCFunction)bytearray_extend, METH_O, bytearray_extend__doc__},
2791
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002792static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002793bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
2794/*[clinic end generated code: output=13b0c13ad5110dfb input=ce83a5d75b70d850]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002795{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002796 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002797 Py_ssize_t buf_size = 0, len = 0;
2798 int value;
2799 char *buf;
2800
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002801 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002802 if (PyObject_CheckBuffer(iterable_of_ints)) {
2803 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002804 return NULL;
2805
2806 Py_RETURN_NONE;
2807 }
2808
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002809 it = PyObject_GetIter(iterable_of_ints);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002810 if (it == NULL)
2811 return NULL;
2812
Ezio Melotti42da6632011-03-15 05:18:48 +02002813 /* Try to determine the length of the argument. 32 is arbitrary. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002814 buf_size = PyObject_LengthHint(iterable_of_ints, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002815 if (buf_size == -1) {
2816 Py_DECREF(it);
2817 return NULL;
2818 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002819
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002820 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002821 if (bytearray_obj == NULL) {
2822 Py_DECREF(it);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002823 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002824 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002825 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002826
2827 while ((item = PyIter_Next(it)) != NULL) {
2828 if (! _getbytevalue(item, &value)) {
2829 Py_DECREF(item);
2830 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002831 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002832 return NULL;
2833 }
2834 buf[len++] = value;
2835 Py_DECREF(item);
2836
2837 if (len >= buf_size) {
2838 buf_size = len + (len >> 1) + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002839 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002840 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002841 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002842 return NULL;
2843 }
2844 /* Recompute the `buf' pointer, since the resizing operation may
2845 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002846 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002847 }
2848 }
2849 Py_DECREF(it);
2850
2851 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002852 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
2853 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002854 return NULL;
2855 }
2856
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002857 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
2858 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002859 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002860 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002861 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002862
2863 Py_RETURN_NONE;
2864}
2865
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002866/*[clinic input]
2867bytearray.pop
2868
2869 self: self(type="PyByteArrayObject *")
2870 index: Py_ssize_t = -1
2871 The index from where to remove the item.
2872 -1 (the default value) means remove the last item.
2873 /
2874
2875Remove and return a single item from B.
2876
2877If no index argument is given, will pop the last item.
2878[clinic start generated code]*/
2879
2880PyDoc_STRVAR(bytearray_pop__doc__,
2881"pop($self, index=-1, /)\n"
2882"--\n"
2883"\n"
2884"Remove and return a single item from B.\n"
2885"\n"
2886" index\n"
2887" The index from where to remove the item.\n"
2888" -1 (the default value) means remove the last item.\n"
2889"\n"
2890"If no index argument is given, will pop the last item.");
2891
2892#define BYTEARRAY_POP_METHODDEF \
2893 {"pop", (PyCFunction)bytearray_pop, METH_VARARGS, bytearray_pop__doc__},
2894
2895static PyObject *
2896bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index);
2897
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002898static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002899bytearray_pop(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002900{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002901 PyObject *return_value = NULL;
2902 Py_ssize_t index = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002903
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002904 if (!PyArg_ParseTuple(args,
2905 "|n:pop",
2906 &index))
2907 goto exit;
2908 return_value = bytearray_pop_impl(self, index);
2909
2910exit:
2911 return return_value;
2912}
2913
2914static PyObject *
2915bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
2916/*[clinic end generated code: output=3b763e548e79af96 input=0797e6c0ca9d5a85]*/
2917{
2918 int value;
2919 Py_ssize_t n = Py_SIZE(self);
2920 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002921
2922 if (n == 0) {
Eli Bendersky1bc4f192011-03-04 04:55:25 +00002923 PyErr_SetString(PyExc_IndexError,
2924 "pop from empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002925 return NULL;
2926 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002927 if (index < 0)
2928 index += Py_SIZE(self);
2929 if (index < 0 || index >= Py_SIZE(self)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002930 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2931 return NULL;
2932 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002933 if (!_canresize(self))
2934 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002935
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002936 buf = PyByteArray_AS_STRING(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002937 value = buf[index];
2938 memmove(buf + index, buf + index + 1, n - index);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002939 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2940 return NULL;
2941
Mark Dickinson54a3db92009-09-06 10:19:23 +00002942 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002943}
2944
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002945/*[clinic input]
2946bytearray.remove
2947
2948 self: self(type="PyByteArrayObject *")
2949 value: bytesvalue
2950 The value to remove.
2951 /
2952
2953Remove the first occurrence of a value in the bytearray.
2954[clinic start generated code]*/
2955
2956PyDoc_STRVAR(bytearray_remove__doc__,
2957"remove($self, value, /)\n"
2958"--\n"
2959"\n"
2960"Remove the first occurrence of a value in the bytearray.\n"
2961"\n"
2962" value\n"
2963" The value to remove.");
2964
2965#define BYTEARRAY_REMOVE_METHODDEF \
2966 {"remove", (PyCFunction)bytearray_remove, METH_VARARGS, bytearray_remove__doc__},
2967
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002968static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002969bytearray_remove_impl(PyByteArrayObject *self, int value);
2970
2971static PyObject *
2972bytearray_remove(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002973{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002974 PyObject *return_value = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002975 int value;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002976
2977 if (!PyArg_ParseTuple(args,
2978 "O&:remove",
2979 _getbytevalue, &value))
2980 goto exit;
2981 return_value = bytearray_remove_impl(self, value);
2982
2983exit:
2984 return return_value;
2985}
2986
2987static PyObject *
2988bytearray_remove_impl(PyByteArrayObject *self, int value)
2989/*[clinic end generated code: output=c71c8bcf4703abfc input=47560b11fd856c24]*/
2990{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002991 Py_ssize_t where, n = Py_SIZE(self);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002992 char *buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002993
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002994 for (where = 0; where < n; where++) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002995 if (buf[where] == value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002996 break;
2997 }
2998 if (where == n) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002999 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003000 return NULL;
3001 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00003002 if (!_canresize(self))
3003 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003004
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003005 memmove(buf + where, buf + where + 1, n - where);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003006 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
3007 return NULL;
3008
3009 Py_RETURN_NONE;
3010}
3011
3012/* XXX These two helpers could be optimized if argsize == 1 */
3013
3014static Py_ssize_t
Antoine Pitrou5b720752013-10-05 21:24:10 +02003015lstrip_helper(char *myptr, Py_ssize_t mysize,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003016 void *argptr, Py_ssize_t argsize)
3017{
3018 Py_ssize_t i = 0;
Antoine Pitrou5b720752013-10-05 21:24:10 +02003019 while (i < mysize && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003020 i++;
3021 return i;
3022}
3023
3024static Py_ssize_t
Antoine Pitrou5b720752013-10-05 21:24:10 +02003025rstrip_helper(char *myptr, Py_ssize_t mysize,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003026 void *argptr, Py_ssize_t argsize)
3027{
3028 Py_ssize_t i = mysize - 1;
Antoine Pitrou5b720752013-10-05 21:24:10 +02003029 while (i >= 0 && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003030 i--;
3031 return i + 1;
3032}
3033
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003034/*[clinic input]
3035bytearray.strip
3036
3037 bytes: object = None
3038 /
3039
3040Strip leading and trailing bytes contained in the argument.
3041
3042If the argument is omitted or None, strip leading and trailing ASCII whitespace.
3043[clinic start generated code]*/
3044
3045PyDoc_STRVAR(bytearray_strip__doc__,
3046"strip($self, bytes=None, /)\n"
3047"--\n"
3048"\n"
3049"Strip leading and trailing bytes contained in the argument.\n"
3050"\n"
3051"If the argument is omitted or None, strip leading and trailing ASCII whitespace.");
3052
3053#define BYTEARRAY_STRIP_METHODDEF \
3054 {"strip", (PyCFunction)bytearray_strip, METH_VARARGS, bytearray_strip__doc__},
3055
3056static PyObject *
3057bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes);
3058
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003059static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003060bytearray_strip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003061{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003062 PyObject *return_value = NULL;
3063 PyObject *bytes = Py_None;
3064
3065 if (!PyArg_UnpackTuple(args, "strip",
3066 0, 1,
3067 &bytes))
3068 goto exit;
3069 return_value = bytearray_strip_impl(self, bytes);
3070
3071exit:
3072 return return_value;
3073}
3074
3075static PyObject *
3076bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
3077/*[clinic end generated code: output=2e3d3358acc4c235 input=ef7bb59b09c21d62]*/
3078{
3079 Py_ssize_t left, right, mysize, byteslen;
3080 char *myptr, *bytesptr;
3081 Py_buffer vbytes;
3082
3083 if (bytes == Py_None) {
3084 bytesptr = "\t\n\r\f\v ";
3085 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003086 }
3087 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02003088 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003089 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003090 bytesptr = (char *) vbytes.buf;
3091 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003092 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003093 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003094 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003095 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003096 if (left == mysize)
3097 right = left;
3098 else
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003099 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
3100 if (bytes != Py_None)
3101 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003102 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003103}
3104
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003105/*[clinic input]
3106bytearray.lstrip
3107
3108 bytes: object = None
3109 /
3110
3111Strip leading bytes contained in the argument.
3112
3113If the argument is omitted or None, strip leading ASCII whitespace.
3114[clinic start generated code]*/
3115
3116PyDoc_STRVAR(bytearray_lstrip__doc__,
3117"lstrip($self, bytes=None, /)\n"
3118"--\n"
3119"\n"
3120"Strip leading bytes contained in the argument.\n"
3121"\n"
3122"If the argument is omitted or None, strip leading ASCII whitespace.");
3123
3124#define BYTEARRAY_LSTRIP_METHODDEF \
3125 {"lstrip", (PyCFunction)bytearray_lstrip, METH_VARARGS, bytearray_lstrip__doc__},
3126
3127static PyObject *
3128bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes);
3129
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003130static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003131bytearray_lstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003132{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003133 PyObject *return_value = NULL;
3134 PyObject *bytes = Py_None;
3135
3136 if (!PyArg_UnpackTuple(args, "lstrip",
3137 0, 1,
3138 &bytes))
3139 goto exit;
3140 return_value = bytearray_lstrip_impl(self, bytes);
3141
3142exit:
3143 return return_value;
3144}
3145
3146static PyObject *
3147bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
3148/*[clinic end generated code: output=2599309808a9ec02 input=80843f975dd7c480]*/
3149{
3150 Py_ssize_t left, right, mysize, byteslen;
3151 char *myptr, *bytesptr;
3152 Py_buffer vbytes;
3153
3154 if (bytes == Py_None) {
3155 bytesptr = "\t\n\r\f\v ";
3156 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003157 }
3158 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02003159 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003160 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003161 bytesptr = (char *) vbytes.buf;
3162 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003163 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003164 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003165 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003166 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003167 right = mysize;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003168 if (bytes != Py_None)
3169 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003170 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003171}
3172
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003173/*[clinic input]
3174bytearray.rstrip
3175
3176 bytes: object = None
3177 /
3178
3179Strip trailing bytes contained in the argument.
3180
3181If the argument is omitted or None, strip trailing ASCII whitespace.
3182[clinic start generated code]*/
3183
3184PyDoc_STRVAR(bytearray_rstrip__doc__,
3185"rstrip($self, bytes=None, /)\n"
3186"--\n"
3187"\n"
3188"Strip trailing bytes contained in the argument.\n"
3189"\n"
3190"If the argument is omitted or None, strip trailing ASCII whitespace.");
3191
3192#define BYTEARRAY_RSTRIP_METHODDEF \
3193 {"rstrip", (PyCFunction)bytearray_rstrip, METH_VARARGS, bytearray_rstrip__doc__},
3194
3195static PyObject *
3196bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes);
3197
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003198static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003199bytearray_rstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003200{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003201 PyObject *return_value = NULL;
3202 PyObject *bytes = Py_None;
3203
3204 if (!PyArg_UnpackTuple(args, "rstrip",
3205 0, 1,
3206 &bytes))
3207 goto exit;
3208 return_value = bytearray_rstrip_impl(self, bytes);
3209
3210exit:
3211 return return_value;
3212}
3213
3214static PyObject *
3215bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
3216/*[clinic end generated code: output=b5ca6259f4f4f2a3 input=e728b994954cfd91]*/
3217{
3218 Py_ssize_t right, mysize, byteslen;
3219 char *myptr, *bytesptr;
3220 Py_buffer vbytes;
3221
3222 if (bytes == Py_None) {
3223 bytesptr = "\t\n\r\f\v ";
3224 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003225 }
3226 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02003227 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003228 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003229 bytesptr = (char *) vbytes.buf;
3230 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003231 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003232 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003233 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003234 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
3235 if (bytes != Py_None)
3236 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003237 return PyByteArray_FromStringAndSize(myptr, right);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003238}
3239
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003240/*[clinic input]
3241bytearray.decode
3242
3243 encoding: str(c_default="NULL") = 'utf-8'
3244 The encoding with which to decode the bytearray.
3245 errors: str(c_default="NULL") = 'strict'
3246 The error handling scheme to use for the handling of decoding errors.
3247 The default is 'strict' meaning that decoding errors raise a
3248 UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
3249 as well as any other name registered with codecs.register_error that
3250 can handle UnicodeDecodeErrors.
3251
3252Decode the bytearray using the codec registered for encoding.
3253[clinic start generated code]*/
3254
3255PyDoc_STRVAR(bytearray_decode__doc__,
3256"decode($self, /, encoding=\'utf-8\', errors=\'strict\')\n"
3257"--\n"
3258"\n"
3259"Decode the bytearray using the codec registered for encoding.\n"
3260"\n"
3261" encoding\n"
3262" The encoding with which to decode the bytearray.\n"
3263" errors\n"
3264" The error handling scheme to use for the handling of decoding errors.\n"
3265" The default is \'strict\' meaning that decoding errors raise a\n"
3266" UnicodeDecodeError. Other possible values are \'ignore\' and \'replace\'\n"
3267" as well as any other name registered with codecs.register_error that\n"
3268" can handle UnicodeDecodeErrors.");
3269
3270#define BYTEARRAY_DECODE_METHODDEF \
3271 {"decode", (PyCFunction)bytearray_decode, METH_VARARGS|METH_KEYWORDS, bytearray_decode__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003272
3273static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003274bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors);
3275
3276static PyObject *
3277bytearray_decode(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003278{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003279 PyObject *return_value = NULL;
3280 static char *_keywords[] = {"encoding", "errors", NULL};
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003281 const char *encoding = NULL;
3282 const char *errors = NULL;
3283
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003284 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
3285 "|ss:decode", _keywords,
3286 &encoding, &errors))
3287 goto exit;
3288 return_value = bytearray_decode_impl(self, encoding, errors);
3289
3290exit:
3291 return return_value;
3292}
3293
3294static PyObject *
3295bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors)
3296/*[clinic end generated code: output=38b83681f1e38a6c input=f28d8f903020257b]*/
3297{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003298 if (encoding == NULL)
3299 encoding = PyUnicode_GetDefaultEncoding();
Martin v. Löwis0efea322014-07-27 17:29:17 +02003300 return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003301}
3302
3303PyDoc_STRVAR(alloc_doc,
3304"B.__alloc__() -> int\n\
3305\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00003306Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003307
3308static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003309bytearray_alloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003310{
3311 return PyLong_FromSsize_t(self->ob_alloc);
3312}
3313
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003314/*[clinic input]
3315bytearray.join
3316
3317 iterable_of_bytes: object
3318 /
3319
3320Concatenate any number of bytes/bytearray objects.
3321
3322The bytearray whose method is called is inserted in between each pair.
3323
3324The result is returned as a new bytearray object.
3325[clinic start generated code]*/
3326
3327PyDoc_STRVAR(bytearray_join__doc__,
3328"join($self, iterable_of_bytes, /)\n"
3329"--\n"
3330"\n"
3331"Concatenate any number of bytes/bytearray objects.\n"
3332"\n"
3333"The bytearray whose method is called is inserted in between each pair.\n"
3334"\n"
3335"The result is returned as a new bytearray object.");
3336
3337#define BYTEARRAY_JOIN_METHODDEF \
3338 {"join", (PyCFunction)bytearray_join, METH_O, bytearray_join__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003339
3340static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003341bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes)
3342/*[clinic end generated code: output=544e7430032dfdf4 input=aba6b1f9b30fcb8e]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003343{
Martin v. Löwis0efea322014-07-27 17:29:17 +02003344 return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003345}
3346
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003347/*[clinic input]
3348bytearray.splitlines
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003349
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003350 keepends: int(py_default="False") = 0
3351
3352Return a list of the lines in the bytearray, breaking at line boundaries.
3353
3354Line breaks are not included in the resulting list unless keepends is given and
3355true.
3356[clinic start generated code]*/
3357
3358PyDoc_STRVAR(bytearray_splitlines__doc__,
3359"splitlines($self, /, keepends=False)\n"
3360"--\n"
3361"\n"
3362"Return a list of the lines in the bytearray, breaking at line boundaries.\n"
3363"\n"
3364"Line breaks are not included in the resulting list unless keepends is given and\n"
3365"true.");
3366
3367#define BYTEARRAY_SPLITLINES_METHODDEF \
3368 {"splitlines", (PyCFunction)bytearray_splitlines, METH_VARARGS|METH_KEYWORDS, bytearray_splitlines__doc__},
3369
3370static PyObject *
3371bytearray_splitlines_impl(PyByteArrayObject *self, int keepends);
3372
3373static PyObject *
3374bytearray_splitlines(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003375{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003376 PyObject *return_value = NULL;
3377 static char *_keywords[] = {"keepends", NULL};
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003378 int keepends = 0;
3379
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003380 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
3381 "|i:splitlines", _keywords,
3382 &keepends))
3383 goto exit;
3384 return_value = bytearray_splitlines_impl(self, keepends);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003385
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003386exit:
3387 return return_value;
3388}
3389
3390static PyObject *
3391bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
3392/*[clinic end generated code: output=a837fd0512ad46ff input=36f0b25bc792f6c0]*/
3393{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003394 return stringlib_splitlines(
3395 (PyObject*) self, PyByteArray_AS_STRING(self),
3396 PyByteArray_GET_SIZE(self), keepends
3397 );
3398}
3399
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003400static int
Victor Stinner6430fd52011-09-29 04:02:13 +02003401hex_digit_to_int(Py_UCS4 c)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003402{
3403 if (c >= 128)
3404 return -1;
Eric Smith6dc46f52009-04-27 20:39:49 +00003405 if (Py_ISDIGIT(c))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003406 return c - '0';
3407 else {
Eric Smith6dc46f52009-04-27 20:39:49 +00003408 if (Py_ISUPPER(c))
3409 c = Py_TOLOWER(c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003410 if (c >= 'a' && c <= 'f')
3411 return c - 'a' + 10;
3412 }
3413 return -1;
3414}
3415
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003416/*[clinic input]
3417@classmethod
3418bytearray.fromhex
3419
3420 cls: self(type="PyObject*")
3421 string: unicode
3422 /
3423
3424Create a bytearray object from a string of hexadecimal numbers.
3425
3426Spaces between two numbers are accepted.
3427Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
3428[clinic start generated code]*/
3429
3430PyDoc_STRVAR(bytearray_fromhex__doc__,
3431"fromhex($type, string, /)\n"
3432"--\n"
3433"\n"
3434"Create a bytearray object from a string of hexadecimal numbers.\n"
3435"\n"
3436"Spaces between two numbers are accepted.\n"
3437"Example: bytearray.fromhex(\'B9 01EF\') -> bytearray(b\'\\\\xb9\\\\x01\\\\xef\')");
3438
3439#define BYTEARRAY_FROMHEX_METHODDEF \
3440 {"fromhex", (PyCFunction)bytearray_fromhex, METH_VARARGS|METH_CLASS, bytearray_fromhex__doc__},
3441
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003442static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003443bytearray_fromhex_impl(PyObject*cls, PyObject *string);
3444
3445static PyObject *
3446bytearray_fromhex(PyTypeObject *cls, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003447{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003448 PyObject *return_value = NULL;
3449 PyObject *string;
3450
3451 if (!PyArg_ParseTuple(args,
3452 "U:fromhex",
3453 &string))
3454 goto exit;
3455 return_value = bytearray_fromhex_impl((PyObject*)cls, string);
3456
3457exit:
3458 return return_value;
3459}
3460
3461static PyObject *
3462bytearray_fromhex_impl(PyObject*cls, PyObject *string)
3463/*[clinic end generated code: output=adc3c804a74e56d4 input=907bbd2d34d9367a]*/
3464{
3465 PyObject *newbytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003466 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003467 Py_ssize_t hexlen, byteslen, i, j;
3468 int top, bot;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003469 void *data;
3470 unsigned int kind;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003471
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003472 assert(PyUnicode_Check(string));
3473 if (PyUnicode_READY(string))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003474 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003475 kind = PyUnicode_KIND(string);
3476 data = PyUnicode_DATA(string);
3477 hexlen = PyUnicode_GET_LENGTH(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003478
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003479 byteslen = hexlen/2; /* This overestimates if there are spaces */
3480 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
3481 if (!newbytes)
3482 return NULL;
3483 buf = PyByteArray_AS_STRING(newbytes);
3484 for (i = j = 0; i < hexlen; i += 2) {
3485 /* skip over spaces in the input */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003486 while (PyUnicode_READ(kind, data, i) == ' ')
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003487 i++;
3488 if (i >= hexlen)
3489 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003490 top = hex_digit_to_int(PyUnicode_READ(kind, data, i));
3491 bot = hex_digit_to_int(PyUnicode_READ(kind, data, i+1));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003492 if (top == -1 || bot == -1) {
3493 PyErr_Format(PyExc_ValueError,
3494 "non-hexadecimal number found in "
3495 "fromhex() arg at position %zd", i);
3496 goto error;
3497 }
3498 buf[j++] = (top << 4) + bot;
3499 }
3500 if (PyByteArray_Resize(newbytes, j) < 0)
3501 goto error;
3502 return newbytes;
3503
3504 error:
3505 Py_DECREF(newbytes);
3506 return NULL;
3507}
3508
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003509
3510static PyObject *
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003511_common_reduce(PyByteArrayObject *self, int proto)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003512{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003513 PyObject *dict;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003514 _Py_IDENTIFIER(__dict__);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003515 char *buf;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003516
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003517 dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003518 if (dict == NULL) {
3519 PyErr_Clear();
3520 dict = Py_None;
3521 Py_INCREF(dict);
3522 }
3523
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003524 buf = PyByteArray_AS_STRING(self);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003525 if (proto < 3) {
3526 /* use str based reduction for backwards compatibility with Python 2.x */
3527 PyObject *latin1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003528 if (Py_SIZE(self))
3529 latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003530 else
3531 latin1 = PyUnicode_FromString("");
3532 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
3533 }
3534 else {
3535 /* use more efficient byte based reduction */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003536 if (Py_SIZE(self)) {
3537 return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), dict);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003538 }
3539 else {
3540 return Py_BuildValue("(O()N)", Py_TYPE(self), dict);
3541 }
3542 }
3543}
3544
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003545/*[clinic input]
3546bytearray.__reduce__ as bytearray_reduce
3547
3548 self: self(type="PyByteArrayObject *")
3549
3550Return state information for pickling.
3551[clinic start generated code]*/
3552
3553PyDoc_STRVAR(bytearray_reduce__doc__,
3554"__reduce__($self, /)\n"
3555"--\n"
3556"\n"
3557"Return state information for pickling.");
3558
3559#define BYTEARRAY_REDUCE_METHODDEF \
3560 {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, bytearray_reduce__doc__},
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003561
3562static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003563bytearray_reduce_impl(PyByteArrayObject *self);
3564
3565static PyObject *
3566bytearray_reduce(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
3567{
3568 return bytearray_reduce_impl(self);
3569}
3570
3571static PyObject *
3572bytearray_reduce_impl(PyByteArrayObject *self)
3573/*[clinic end generated code: output=b1b56fe87bf30fb0 input=fbb07de4d102a03a]*/
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003574{
3575 return _common_reduce(self, 2);
3576}
3577
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003578/*[clinic input]
3579bytearray.__reduce_ex__ as bytearray_reduce_ex
3580
3581 self: self(type="PyByteArrayObject *")
3582 proto: int = 0
3583 /
3584
3585Return state information for pickling.
3586[clinic start generated code]*/
3587
3588PyDoc_STRVAR(bytearray_reduce_ex__doc__,
3589"__reduce_ex__($self, proto=0, /)\n"
3590"--\n"
3591"\n"
3592"Return state information for pickling.");
3593
3594#define BYTEARRAY_REDUCE_EX_METHODDEF \
3595 {"__reduce_ex__", (PyCFunction)bytearray_reduce_ex, METH_VARARGS, bytearray_reduce_ex__doc__},
3596
3597static PyObject *
3598bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003599
3600static PyObject *
3601bytearray_reduce_ex(PyByteArrayObject *self, PyObject *args)
3602{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003603 PyObject *return_value = NULL;
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003604 int proto = 0;
3605
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003606 if (!PyArg_ParseTuple(args,
3607 "|i:__reduce_ex__",
3608 &proto))
3609 goto exit;
3610 return_value = bytearray_reduce_ex_impl(self, proto);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003611
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003612exit:
3613 return return_value;
3614}
3615
3616static PyObject *
3617bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
3618/*[clinic end generated code: output=bbd9afb2f5953dc1 input=0e091a42ca6dbd91]*/
3619{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003620 return _common_reduce(self, proto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003621}
3622
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003623/*[clinic input]
3624bytearray.__sizeof__ as bytearray_sizeof
3625
3626 self: self(type="PyByteArrayObject *")
3627
3628Returns the size of the bytearray object in memory, in bytes.
3629[clinic start generated code]*/
3630
3631PyDoc_STRVAR(bytearray_sizeof__doc__,
3632"__sizeof__($self, /)\n"
3633"--\n"
3634"\n"
3635"Returns the size of the bytearray object in memory, in bytes.");
3636
3637#define BYTEARRAY_SIZEOF_METHODDEF \
3638 {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, bytearray_sizeof__doc__},
3639
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003640static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003641bytearray_sizeof_impl(PyByteArrayObject *self);
3642
3643static PyObject *
3644bytearray_sizeof(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
3645{
3646 return bytearray_sizeof_impl(self);
3647}
3648
3649static PyObject *
3650bytearray_sizeof_impl(PyByteArrayObject *self)
3651/*[clinic end generated code: output=4a2254b0a85630c6 input=6b23d305362b462b]*/
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003652{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00003653 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003654
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00003655 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
3656 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003657}
3658
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003659static PySequenceMethods bytearray_as_sequence = {
3660 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003661 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003662 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
3663 (ssizeargfunc)bytearray_getitem, /* sq_item */
3664 0, /* sq_slice */
3665 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
3666 0, /* sq_ass_slice */
3667 (objobjproc)bytearray_contains, /* sq_contains */
3668 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
3669 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003670};
3671
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003672static PyMappingMethods bytearray_as_mapping = {
3673 (lenfunc)bytearray_length,
3674 (binaryfunc)bytearray_subscript,
3675 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003676};
3677
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003678static PyBufferProcs bytearray_as_buffer = {
3679 (getbufferproc)bytearray_getbuffer,
3680 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003681};
3682
3683static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003684bytearray_methods[] = {
3685 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003686 BYTEARRAY_REDUCE_METHODDEF
3687 BYTEARRAY_REDUCE_EX_METHODDEF
3688 BYTEARRAY_SIZEOF_METHODDEF
3689 BYTEARRAY_APPEND_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003690 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
3691 _Py_capitalize__doc__},
3692 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003693 BYTEARRAY_CLEAR_METHODDEF
3694 BYTEARRAY_COPY_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003695 {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003696 BYTEARRAY_DECODE_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003697 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +02003698 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS | METH_KEYWORDS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003699 expandtabs__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003700 BYTEARRAY_EXTEND_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003701 {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003702 BYTEARRAY_FROMHEX_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003703 {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003704 BYTEARRAY_INSERT_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003705 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
3706 _Py_isalnum__doc__},
3707 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
3708 _Py_isalpha__doc__},
3709 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
3710 _Py_isdigit__doc__},
3711 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
3712 _Py_islower__doc__},
3713 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
3714 _Py_isspace__doc__},
3715 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
3716 _Py_istitle__doc__},
3717 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
3718 _Py_isupper__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003719 BYTEARRAY_JOIN_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003720 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
3721 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003722 BYTEARRAY_LSTRIP_METHODDEF
3723 BYTEARRAY_MAKETRANS_METHODDEF
3724 BYTEARRAY_PARTITION_METHODDEF
3725 BYTEARRAY_POP_METHODDEF
3726 BYTEARRAY_REMOVE_METHODDEF
3727 BYTEARRAY_REPLACE_METHODDEF
3728 BYTEARRAY_REVERSE_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003729 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
3730 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003731 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003732 BYTEARRAY_RPARTITION_METHODDEF
3733 BYTEARRAY_RSPLIT_METHODDEF
3734 BYTEARRAY_RSTRIP_METHODDEF
3735 BYTEARRAY_SPLIT_METHODDEF
3736 BYTEARRAY_SPLITLINES_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003737 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003738 startswith__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003739 BYTEARRAY_STRIP_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003740 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
3741 _Py_swapcase__doc__},
3742 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003743 BYTEARRAY_TRANSLATE_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003744 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
3745 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
3746 {NULL}
3747};
3748
Ethan Furmanb95b5612015-01-23 20:05:18 -08003749static PyObject *
3750bytearray_mod(PyObject *v, PyObject *w)
3751{
3752 if (!PyByteArray_Check(v))
3753 Py_RETURN_NOTIMPLEMENTED;
3754 return bytearray_format((PyByteArrayObject *)v, w);
3755}
3756
3757static PyNumberMethods bytearray_as_number = {
3758 0, /*nb_add*/
3759 0, /*nb_subtract*/
3760 0, /*nb_multiply*/
3761 bytearray_mod, /*nb_remainder*/
3762};
3763
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003764PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00003765"bytearray(iterable_of_ints) -> bytearray\n\
3766bytearray(string, encoding[, errors]) -> bytearray\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003767bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
3768bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
3769bytearray() -> empty bytes array\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003770\n\
3771Construct an mutable bytearray object from:\n\
3772 - an iterable yielding integers in range(256)\n\
3773 - a text string encoded using the specified encoding\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003774 - a bytes or a buffer object\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003775 - any object implementing the buffer API.\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003776 - an integer");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003777
3778
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003779static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003780
3781PyTypeObject PyByteArray_Type = {
3782 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3783 "bytearray",
3784 sizeof(PyByteArrayObject),
3785 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003786 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003787 0, /* tp_print */
3788 0, /* tp_getattr */
3789 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003790 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003791 (reprfunc)bytearray_repr, /* tp_repr */
Ethan Furmanb95b5612015-01-23 20:05:18 -08003792 &bytearray_as_number, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003793 &bytearray_as_sequence, /* tp_as_sequence */
3794 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003795 0, /* tp_hash */
3796 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003797 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003798 PyObject_GenericGetAttr, /* tp_getattro */
3799 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003800 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003801 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003802 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003803 0, /* tp_traverse */
3804 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003805 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003806 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003807 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003808 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003809 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003810 0, /* tp_members */
3811 0, /* tp_getset */
3812 0, /* tp_base */
3813 0, /* tp_dict */
3814 0, /* tp_descr_get */
3815 0, /* tp_descr_set */
3816 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003817 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003818 PyType_GenericAlloc, /* tp_alloc */
3819 PyType_GenericNew, /* tp_new */
3820 PyObject_Del, /* tp_free */
3821};
3822
3823/*********************** Bytes Iterator ****************************/
3824
3825typedef struct {
3826 PyObject_HEAD
3827 Py_ssize_t it_index;
3828 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
3829} bytesiterobject;
3830
3831static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003832bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003833{
3834 _PyObject_GC_UNTRACK(it);
3835 Py_XDECREF(it->it_seq);
3836 PyObject_GC_Del(it);
3837}
3838
3839static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003840bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003841{
3842 Py_VISIT(it->it_seq);
3843 return 0;
3844}
3845
3846static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003847bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003848{
3849 PyByteArrayObject *seq;
3850 PyObject *item;
3851
3852 assert(it != NULL);
3853 seq = it->it_seq;
3854 if (seq == NULL)
3855 return NULL;
3856 assert(PyByteArray_Check(seq));
3857
3858 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
3859 item = PyLong_FromLong(
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003860 (unsigned char)PyByteArray_AS_STRING(seq)[it->it_index]);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003861 if (item != NULL)
3862 ++it->it_index;
3863 return item;
3864 }
3865
3866 Py_DECREF(seq);
3867 it->it_seq = NULL;
3868 return NULL;
3869}
3870
3871static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003872bytearrayiter_length_hint(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003873{
3874 Py_ssize_t len = 0;
3875 if (it->it_seq)
3876 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
3877 return PyLong_FromSsize_t(len);
3878}
3879
3880PyDoc_STRVAR(length_hint_doc,
3881 "Private method returning an estimate of len(list(it)).");
3882
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003883static PyObject *
3884bytearrayiter_reduce(bytesiterobject *it)
3885{
3886 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +02003887 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003888 it->it_seq, it->it_index);
3889 } else {
3890 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
3891 if (u == NULL)
3892 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02003893 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003894 }
3895}
3896
3897static PyObject *
3898bytearrayiter_setstate(bytesiterobject *it, PyObject *state)
3899{
3900 Py_ssize_t index = PyLong_AsSsize_t(state);
3901 if (index == -1 && PyErr_Occurred())
3902 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00003903 if (it->it_seq != NULL) {
3904 if (index < 0)
3905 index = 0;
3906 else if (index > PyByteArray_GET_SIZE(it->it_seq))
3907 index = PyByteArray_GET_SIZE(it->it_seq); /* iterator exhausted */
3908 it->it_index = index;
3909 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003910 Py_RETURN_NONE;
3911}
3912
3913PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
3914
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003915static PyMethodDef bytearrayiter_methods[] = {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003916 {"__length_hint__", (PyCFunction)bytearrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003917 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003918 {"__reduce__", (PyCFunction)bytearrayiter_reduce, METH_NOARGS,
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003919 bytearray_reduce__doc__},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003920 {"__setstate__", (PyCFunction)bytearrayiter_setstate, METH_O,
3921 setstate_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003922 {NULL, NULL} /* sentinel */
3923};
3924
3925PyTypeObject PyByteArrayIter_Type = {
3926 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3927 "bytearray_iterator", /* tp_name */
3928 sizeof(bytesiterobject), /* tp_basicsize */
3929 0, /* tp_itemsize */
3930 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003931 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003932 0, /* tp_print */
3933 0, /* tp_getattr */
3934 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003935 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003936 0, /* tp_repr */
3937 0, /* tp_as_number */
3938 0, /* tp_as_sequence */
3939 0, /* tp_as_mapping */
3940 0, /* tp_hash */
3941 0, /* tp_call */
3942 0, /* tp_str */
3943 PyObject_GenericGetAttr, /* tp_getattro */
3944 0, /* tp_setattro */
3945 0, /* tp_as_buffer */
3946 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
3947 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003948 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003949 0, /* tp_clear */
3950 0, /* tp_richcompare */
3951 0, /* tp_weaklistoffset */
3952 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003953 (iternextfunc)bytearrayiter_next, /* tp_iternext */
3954 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003955 0,
3956};
3957
3958static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003959bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003960{
3961 bytesiterobject *it;
3962
3963 if (!PyByteArray_Check(seq)) {
3964 PyErr_BadInternalCall();
3965 return NULL;
3966 }
3967 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
3968 if (it == NULL)
3969 return NULL;
3970 it->it_index = 0;
3971 Py_INCREF(seq);
3972 it->it_seq = (PyByteArrayObject *)seq;
3973 _PyObject_GC_TRACK(it);
3974 return (PyObject *)it;
3975}