blob: ce22f4bb49800e30db8eea3f9a435bd5ddbd7888 [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{
63 int ret;
64 void *ptr;
65 if (view == NULL) {
66 obj->ob_exports++;
67 return 0;
68 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000069 ptr = (void *) PyByteArray_AS_STRING(obj);
Martin v. Löwis423be952008-08-13 15:53:07 +000070 ret = PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
Christian Heimes2c9c7a52008-05-26 13:42:13 +000071 if (ret >= 0) {
72 obj->ob_exports++;
73 }
74 return ret;
75}
76
77static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +000078bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000079{
80 obj->ob_exports--;
81}
82
Antoine Pitrou5504e892008-12-06 21:27:53 +000083static int
84_canresize(PyByteArrayObject *self)
85{
86 if (self->ob_exports > 0) {
87 PyErr_SetString(PyExc_BufferError,
88 "Existing exports of data: object cannot be re-sized");
89 return 0;
90 }
91 return 1;
92}
93
Christian Heimes2c9c7a52008-05-26 13:42:13 +000094/* Direct API functions */
95
96PyObject *
97PyByteArray_FromObject(PyObject *input)
98{
99 return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
100 input, NULL);
101}
102
103PyObject *
104PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
105{
106 PyByteArrayObject *new;
107 Py_ssize_t alloc;
108
109 if (size < 0) {
110 PyErr_SetString(PyExc_SystemError,
111 "Negative size passed to PyByteArray_FromStringAndSize");
112 return NULL;
113 }
114
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000115 /* Prevent buffer overflow when setting alloc to size+1. */
116 if (size == PY_SSIZE_T_MAX) {
117 return PyErr_NoMemory();
118 }
119
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000120 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
121 if (new == NULL)
122 return NULL;
123
124 if (size == 0) {
125 new->ob_bytes = NULL;
126 alloc = 0;
127 }
128 else {
129 alloc = size + 1;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100130 new->ob_bytes = PyObject_Malloc(alloc);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000131 if (new->ob_bytes == NULL) {
132 Py_DECREF(new);
133 return PyErr_NoMemory();
134 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +0000135 if (bytes != NULL && size > 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000136 memcpy(new->ob_bytes, bytes, size);
137 new->ob_bytes[size] = '\0'; /* Trailing null byte */
138 }
139 Py_SIZE(new) = size;
140 new->ob_alloc = alloc;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200141 new->ob_start = new->ob_bytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000142 new->ob_exports = 0;
143
144 return (PyObject *)new;
145}
146
147Py_ssize_t
148PyByteArray_Size(PyObject *self)
149{
150 assert(self != NULL);
151 assert(PyByteArray_Check(self));
152
153 return PyByteArray_GET_SIZE(self);
154}
155
156char *
157PyByteArray_AsString(PyObject *self)
158{
159 assert(self != NULL);
160 assert(PyByteArray_Check(self));
161
162 return PyByteArray_AS_STRING(self);
163}
164
165int
Antoine Pitroucc231542014-11-02 18:40:09 +0100166PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000167{
168 void *sval;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200169 PyByteArrayObject *obj = ((PyByteArrayObject *)self);
Antoine Pitroucc231542014-11-02 18:40:09 +0100170 /* All computations are done unsigned to avoid integer overflows
171 (see issue #22335). */
172 size_t alloc = (size_t) obj->ob_alloc;
173 size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes);
174 size_t size = (size_t) requested_size;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000175
176 assert(self != NULL);
177 assert(PyByteArray_Check(self));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200178 assert(logical_offset <= alloc);
Antoine Pitroucc231542014-11-02 18:40:09 +0100179 assert(requested_size >= 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000180
Antoine Pitroucc231542014-11-02 18:40:09 +0100181 if (requested_size == Py_SIZE(self)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000182 return 0;
183 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200184 if (!_canresize(obj)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000185 return -1;
186 }
187
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200188 if (size + logical_offset + 1 < alloc) {
189 /* Current buffer is large enough to host the requested size,
190 decide on a strategy. */
191 if (size < alloc / 2) {
192 /* Major downsize; resize down to exact size */
193 alloc = size + 1;
194 }
195 else {
196 /* Minor downsize; quick exit */
197 Py_SIZE(self) = size;
198 PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */
199 return 0;
200 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000201 }
202 else {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200203 /* Need growing, decide on a strategy */
204 if (size <= alloc * 1.125) {
205 /* Moderate upsize; overallocate similar to list_resize() */
206 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
207 }
208 else {
209 /* Major upsize; resize up to exact size */
210 alloc = size + 1;
211 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000212 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100213 if (alloc > PY_SSIZE_T_MAX) {
214 PyErr_NoMemory();
215 return -1;
216 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000217
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200218 if (logical_offset > 0) {
219 sval = PyObject_Malloc(alloc);
220 if (sval == NULL) {
221 PyErr_NoMemory();
222 return -1;
223 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100224 memcpy(sval, PyByteArray_AS_STRING(self),
225 Py_MIN(requested_size, Py_SIZE(self)));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200226 PyObject_Free(obj->ob_bytes);
227 }
228 else {
229 sval = PyObject_Realloc(obj->ob_bytes, alloc);
230 if (sval == NULL) {
231 PyErr_NoMemory();
232 return -1;
233 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000234 }
235
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200236 obj->ob_bytes = obj->ob_start = sval;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000237 Py_SIZE(self) = size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200238 obj->ob_alloc = alloc;
239 obj->ob_bytes[size] = '\0'; /* Trailing null byte */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000240
241 return 0;
242}
243
244PyObject *
245PyByteArray_Concat(PyObject *a, PyObject *b)
246{
247 Py_ssize_t size;
248 Py_buffer va, vb;
249 PyByteArrayObject *result = NULL;
250
251 va.len = -1;
252 vb.len = -1;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200253 if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 ||
254 PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000255 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
256 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
257 goto done;
258 }
259
260 size = va.len + vb.len;
261 if (size < 0) {
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000262 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000263 goto done;
264 }
265
266 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
267 if (result != NULL) {
268 memcpy(result->ob_bytes, va.buf, va.len);
269 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
270 }
271
272 done:
273 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000274 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000275 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000276 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000277 return (PyObject *)result;
278}
279
Ethan Furmanb95b5612015-01-23 20:05:18 -0800280static PyObject *
281bytearray_format(PyByteArrayObject *self, PyObject *args)
282{
283 PyObject *bytes_in, *bytes_out, *res;
284 char *bytestring;
285
286 if (self == NULL || !PyByteArray_Check(self) || args == NULL) {
287 PyErr_BadInternalCall();
288 return NULL;
289 }
290 bytestring = PyByteArray_AS_STRING(self);
291 bytes_in = PyBytes_FromString(bytestring);
292 if (bytes_in == NULL)
293 return NULL;
294 bytes_out = _PyBytes_Format(bytes_in, args);
295 Py_DECREF(bytes_in);
296 if (bytes_out == NULL)
297 return NULL;
298 res = PyByteArray_FromObject(bytes_out);
299 Py_DECREF(bytes_out);
300 if (res == NULL)
301 return NULL;
302 return res;
303}
304
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000305/* Functions stuffed into the type object */
306
307static Py_ssize_t
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000308bytearray_length(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000309{
310 return Py_SIZE(self);
311}
312
313static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000314bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000315{
316 Py_ssize_t mysize;
317 Py_ssize_t size;
318 Py_buffer vo;
319
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200320 if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000321 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
322 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
323 return NULL;
324 }
325
326 mysize = Py_SIZE(self);
327 size = mysize + vo.len;
328 if (size < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000329 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000330 return PyErr_NoMemory();
331 }
332 if (size < self->ob_alloc) {
333 Py_SIZE(self) = size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200334 PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0'; /* Trailing null byte */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000335 }
336 else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000337 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000338 return NULL;
339 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200340 memcpy(PyByteArray_AS_STRING(self) + mysize, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000341 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000342 Py_INCREF(self);
343 return (PyObject *)self;
344}
345
346static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000347bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000348{
349 PyByteArrayObject *result;
350 Py_ssize_t mysize;
351 Py_ssize_t size;
352
353 if (count < 0)
354 count = 0;
355 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000356 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000357 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000358 size = mysize * count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000359 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
360 if (result != NULL && size != 0) {
361 if (mysize == 1)
362 memset(result->ob_bytes, self->ob_bytes[0], size);
363 else {
364 Py_ssize_t i;
365 for (i = 0; i < count; i++)
366 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
367 }
368 }
369 return (PyObject *)result;
370}
371
372static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000373bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000374{
375 Py_ssize_t mysize;
376 Py_ssize_t size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200377 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000378
379 if (count < 0)
380 count = 0;
381 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000382 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000383 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000384 size = mysize * count;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200385 if (PyByteArray_Resize((PyObject *)self, size) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000386 return NULL;
387
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200388 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000389 if (mysize == 1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200390 memset(buf, buf[0], size);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000391 else {
392 Py_ssize_t i;
393 for (i = 1; i < count; i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200394 memcpy(buf + i*mysize, buf, mysize);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000395 }
396
397 Py_INCREF(self);
398 return (PyObject *)self;
399}
400
401static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000402bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000403{
404 if (i < 0)
405 i += Py_SIZE(self);
406 if (i < 0 || i >= Py_SIZE(self)) {
407 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
408 return NULL;
409 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200410 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000411}
412
413static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000414bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000415{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000416 if (PyIndex_Check(index)) {
417 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000418
419 if (i == -1 && PyErr_Occurred())
420 return NULL;
421
422 if (i < 0)
423 i += PyByteArray_GET_SIZE(self);
424
425 if (i < 0 || i >= Py_SIZE(self)) {
426 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
427 return NULL;
428 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200429 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000430 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000431 else if (PySlice_Check(index)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000432 Py_ssize_t start, stop, step, slicelength, cur, i;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000433 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000434 PyByteArray_GET_SIZE(self),
435 &start, &stop, &step, &slicelength) < 0) {
436 return NULL;
437 }
438
439 if (slicelength <= 0)
440 return PyByteArray_FromStringAndSize("", 0);
441 else if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200442 return PyByteArray_FromStringAndSize(
443 PyByteArray_AS_STRING(self) + start, slicelength);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000444 }
445 else {
446 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000447 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000448 PyObject *result;
449
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000450 result = PyByteArray_FromStringAndSize(NULL, slicelength);
451 if (result == NULL)
452 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000453
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000454 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000455 for (cur = start, i = 0; i < slicelength;
456 cur += step, i++) {
457 result_buf[i] = source_buf[cur];
458 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000459 return result;
460 }
461 }
462 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400463 PyErr_Format(PyExc_TypeError,
464 "bytearray indices must be integers or slices, not %.200s",
465 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000466 return NULL;
467 }
468}
469
470static int
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200471bytearray_setslice_linear(PyByteArrayObject *self,
472 Py_ssize_t lo, Py_ssize_t hi,
473 char *bytes, Py_ssize_t bytes_len)
474{
475 Py_ssize_t avail = hi - lo;
476 char *buf = PyByteArray_AS_STRING(self);
477 Py_ssize_t growth = bytes_len - avail;
Victor Stinner84557232013-11-21 12:29:51 +0100478 int res = 0;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200479 assert(avail >= 0);
480
Victor Stinner84557232013-11-21 12:29:51 +0100481 if (growth < 0) {
482 if (!_canresize(self))
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200483 return -1;
Victor Stinner84557232013-11-21 12:29:51 +0100484
485 if (lo == 0) {
486 /* Shrink the buffer by advancing its logical start */
487 self->ob_start -= growth;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200488 /*
Victor Stinner84557232013-11-21 12:29:51 +0100489 0 lo hi old_size
490 | |<----avail----->|<-----tail------>|
491 | |<-bytes_len->|<-----tail------>|
492 0 new_lo new_hi new_size
493 */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200494 }
Victor Stinner84557232013-11-21 12:29:51 +0100495 else {
496 /*
497 0 lo hi old_size
498 | |<----avail----->|<-----tomove------>|
499 | |<-bytes_len->|<-----tomove------>|
500 0 lo new_hi new_size
501 */
502 memmove(buf + lo + bytes_len, buf + hi,
503 Py_SIZE(self) - hi);
504 }
505 if (PyByteArray_Resize((PyObject *)self,
506 Py_SIZE(self) + growth) < 0) {
507 /* Issue #19578: Handling the memory allocation failure here is
508 tricky here because the bytearray object has already been
509 modified. Depending on growth and lo, the behaviour is
510 different.
511
512 If growth < 0 and lo != 0, the operation is completed, but a
513 MemoryError is still raised and the memory block is not
514 shrinked. Otherwise, the bytearray is restored in its previous
515 state and a MemoryError is raised. */
516 if (lo == 0) {
517 self->ob_start += growth;
518 return -1;
519 }
520 /* memmove() removed bytes, the bytearray object cannot be
521 restored in its previous state. */
522 Py_SIZE(self) += growth;
523 res = -1;
524 }
525 buf = PyByteArray_AS_STRING(self);
526 }
527 else if (growth > 0) {
528 if (Py_SIZE(self) > (Py_ssize_t)PY_SSIZE_T_MAX - growth) {
529 PyErr_NoMemory();
530 return -1;
531 }
532
533 if (PyByteArray_Resize((PyObject *)self,
534 Py_SIZE(self) + growth) < 0) {
535 return -1;
536 }
537 buf = PyByteArray_AS_STRING(self);
538 /* Make the place for the additional bytes */
539 /*
540 0 lo hi old_size
541 | |<-avail->|<-----tomove------>|
542 | |<---bytes_len-->|<-----tomove------>|
543 0 lo new_hi new_size
544 */
545 memmove(buf + lo + bytes_len, buf + hi,
546 Py_SIZE(self) - lo - bytes_len);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200547 }
548
549 if (bytes_len > 0)
550 memcpy(buf + lo, bytes, bytes_len);
Victor Stinner84557232013-11-21 12:29:51 +0100551 return res;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200552}
553
554static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000555bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000556 PyObject *values)
557{
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200558 Py_ssize_t needed;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000559 void *bytes;
560 Py_buffer vbytes;
561 int res = 0;
562
563 vbytes.len = -1;
564 if (values == (PyObject *)self) {
565 /* Make a copy and call this function recursively */
566 int err;
567 values = PyByteArray_FromObject(values);
568 if (values == NULL)
569 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000570 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000571 Py_DECREF(values);
572 return err;
573 }
574 if (values == NULL) {
575 /* del b[lo:hi] */
576 bytes = NULL;
577 needed = 0;
578 }
579 else {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200580 if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) {
581 PyErr_Format(PyExc_TypeError,
582 "can't set bytearray slice from %.100s",
583 Py_TYPE(values)->tp_name);
584 return -1;
585 }
586 needed = vbytes.len;
587 bytes = vbytes.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000588 }
589
590 if (lo < 0)
591 lo = 0;
592 if (hi < lo)
593 hi = lo;
594 if (hi > Py_SIZE(self))
595 hi = Py_SIZE(self);
596
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200597 res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000598 if (vbytes.len != -1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200599 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000600 return res;
601}
602
603static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000604bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000605{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000606 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000607
608 if (i < 0)
609 i += Py_SIZE(self);
610
611 if (i < 0 || i >= Py_SIZE(self)) {
612 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
613 return -1;
614 }
615
616 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000617 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000618
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000619 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000620 return -1;
621
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200622 PyByteArray_AS_STRING(self)[i] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000623 return 0;
624}
625
626static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000627bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000628{
629 Py_ssize_t start, stop, step, slicelen, needed;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200630 char *buf, *bytes;
631 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000632
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000633 if (PyIndex_Check(index)) {
634 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000635
636 if (i == -1 && PyErr_Occurred())
637 return -1;
638
639 if (i < 0)
640 i += PyByteArray_GET_SIZE(self);
641
642 if (i < 0 || i >= Py_SIZE(self)) {
643 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
644 return -1;
645 }
646
647 if (values == NULL) {
648 /* Fall through to slice assignment */
649 start = i;
650 stop = i + 1;
651 step = 1;
652 slicelen = 1;
653 }
654 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000655 int ival;
656 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000657 return -1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200658 buf[i] = (char)ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000659 return 0;
660 }
661 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000662 else if (PySlice_Check(index)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000663 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000664 PyByteArray_GET_SIZE(self),
665 &start, &stop, &step, &slicelen) < 0) {
666 return -1;
667 }
668 }
669 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400670 PyErr_Format(PyExc_TypeError,
671 "bytearray indices must be integers or slices, not %.200s",
672 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000673 return -1;
674 }
675
676 if (values == NULL) {
677 bytes = NULL;
678 needed = 0;
679 }
680 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
Christian Heimes6d26ade2012-11-03 23:07:59 +0100681 int err;
Ezio Melottic64bcbe2012-11-03 21:19:06 +0200682 if (PyNumber_Check(values) || PyUnicode_Check(values)) {
683 PyErr_SetString(PyExc_TypeError,
684 "can assign only bytes, buffers, or iterables "
685 "of ints in range(0, 256)");
686 return -1;
687 }
Georg Brandlf3fa5682010-12-04 17:09:30 +0000688 /* Make a copy and call this function recursively */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000689 values = PyByteArray_FromObject(values);
690 if (values == NULL)
691 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000692 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000693 Py_DECREF(values);
694 return err;
695 }
696 else {
697 assert(PyByteArray_Check(values));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200698 bytes = PyByteArray_AS_STRING(values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000699 needed = Py_SIZE(values);
700 }
701 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
702 if ((step < 0 && start < stop) ||
703 (step > 0 && start > stop))
704 stop = start;
705 if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200706 return bytearray_setslice_linear(self, start, stop, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000707 }
708 else {
709 if (needed == 0) {
710 /* Delete slice */
Mark Dickinsonbc099642010-01-29 17:27:24 +0000711 size_t cur;
712 Py_ssize_t i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000713
Antoine Pitrou5504e892008-12-06 21:27:53 +0000714 if (!_canresize(self))
715 return -1;
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000716
717 if (slicelen == 0)
718 /* Nothing to do here. */
719 return 0;
720
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000721 if (step < 0) {
722 stop = start + 1;
723 start = stop + step * (slicelen - 1) - 1;
724 step = -step;
725 }
726 for (cur = start, i = 0;
727 i < slicelen; cur += step, i++) {
728 Py_ssize_t lim = step - 1;
729
Mark Dickinson66f575b2010-02-14 12:53:32 +0000730 if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000731 lim = PyByteArray_GET_SIZE(self) - cur - 1;
732
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200733 memmove(buf + cur - i,
734 buf + cur + 1, lim);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000735 }
736 /* Move the tail of the bytes, in one chunk */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000737 cur = start + (size_t)slicelen*step;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000738 if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200739 memmove(buf + cur - slicelen,
740 buf + cur,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000741 PyByteArray_GET_SIZE(self) - cur);
742 }
743 if (PyByteArray_Resize((PyObject *)self,
744 PyByteArray_GET_SIZE(self) - slicelen) < 0)
745 return -1;
746
747 return 0;
748 }
749 else {
750 /* Assign slice */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000751 Py_ssize_t i;
752 size_t cur;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000753
754 if (needed != slicelen) {
755 PyErr_Format(PyExc_ValueError,
756 "attempt to assign bytes of size %zd "
757 "to extended slice of size %zd",
758 needed, slicelen);
759 return -1;
760 }
761 for (cur = start, i = 0; i < slicelen; cur += step, i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200762 buf[cur] = bytes[i];
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000763 return 0;
764 }
765 }
766}
767
768static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000769bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000770{
771 static char *kwlist[] = {"source", "encoding", "errors", 0};
772 PyObject *arg = NULL;
773 const char *encoding = NULL;
774 const char *errors = NULL;
775 Py_ssize_t count;
776 PyObject *it;
777 PyObject *(*iternext)(PyObject *);
778
779 if (Py_SIZE(self) != 0) {
780 /* Empty previous contents (yes, do this first of all!) */
781 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
782 return -1;
783 }
784
785 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000786 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000787 &arg, &encoding, &errors))
788 return -1;
789
790 /* Make a quick exit if no first argument */
791 if (arg == NULL) {
792 if (encoding != NULL || errors != NULL) {
793 PyErr_SetString(PyExc_TypeError,
794 "encoding or errors without sequence argument");
795 return -1;
796 }
797 return 0;
798 }
799
800 if (PyUnicode_Check(arg)) {
801 /* Encode via the codec registry */
802 PyObject *encoded, *new;
803 if (encoding == NULL) {
804 PyErr_SetString(PyExc_TypeError,
805 "string argument without an encoding");
806 return -1;
807 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000808 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000809 if (encoded == NULL)
810 return -1;
811 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000812 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000813 Py_DECREF(encoded);
814 if (new == NULL)
815 return -1;
816 Py_DECREF(new);
817 return 0;
818 }
819
820 /* If it's not unicode, there can't be encoding or errors */
821 if (encoding != NULL || errors != NULL) {
822 PyErr_SetString(PyExc_TypeError,
823 "encoding or errors without a string argument");
824 return -1;
825 }
826
827 /* Is it an int? */
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000828 count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
829 if (count == -1 && PyErr_Occurred()) {
830 if (PyErr_ExceptionMatches(PyExc_OverflowError))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000831 return -1;
Benjamin Peterson9c0e94f2010-04-16 23:00:53 +0000832 PyErr_Clear();
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000833 }
834 else if (count < 0) {
835 PyErr_SetString(PyExc_ValueError, "negative count");
836 return -1;
837 }
838 else {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000839 if (count > 0) {
Victor Stinner2bc4d952014-06-02 22:22:42 +0200840 if (PyByteArray_Resize((PyObject *)self, count))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000841 return -1;
Victor Stinner2bc4d952014-06-02 22:22:42 +0200842 memset(PyByteArray_AS_STRING(self), 0, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000843 }
844 return 0;
845 }
846
847 /* Use the buffer API */
848 if (PyObject_CheckBuffer(arg)) {
849 Py_ssize_t size;
850 Py_buffer view;
851 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
852 return -1;
853 size = view.len;
854 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200855 if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
856 &view, size, 'C') < 0)
Stefan Krah7d12d9d2012-07-28 12:25:55 +0200857 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000858 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000859 return 0;
860 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000861 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000862 return -1;
863 }
864
865 /* XXX Optimize this if the arguments is a list, tuple */
866
867 /* Get the iterator */
868 it = PyObject_GetIter(arg);
869 if (it == NULL)
870 return -1;
871 iternext = *Py_TYPE(it)->tp_iternext;
872
873 /* Run the iterator to exhaustion */
874 for (;;) {
875 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000876 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000877
878 /* Get the next item */
879 item = iternext(it);
880 if (item == NULL) {
881 if (PyErr_Occurred()) {
882 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
883 goto error;
884 PyErr_Clear();
885 }
886 break;
887 }
888
889 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000890 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000891 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000892 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000893 goto error;
894
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000895 /* Append the byte */
896 if (Py_SIZE(self) < self->ob_alloc)
897 Py_SIZE(self)++;
898 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
899 goto error;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200900 PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000901 }
902
903 /* Clean up and return success */
904 Py_DECREF(it);
905 return 0;
906
907 error:
908 /* Error handling when it != NULL */
909 Py_DECREF(it);
910 return -1;
911}
912
913/* Mostly copied from string_repr, but without the
914 "smart quote" functionality. */
915static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000916bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000917{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000918 const char *quote_prefix = "bytearray(b";
919 const char *quote_postfix = ")";
920 Py_ssize_t length = Py_SIZE(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200921 /* 15 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */
Mark Dickinson66f575b2010-02-14 12:53:32 +0000922 size_t newsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000923 PyObject *v;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200924 Py_ssize_t i;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200925 char *bytes;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200926 char c;
927 char *p;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200928 int quote;
929 char *test, *start;
930 char *buffer;
931
932 if (length > (PY_SSIZE_T_MAX - 15) / 4) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000933 PyErr_SetString(PyExc_OverflowError,
934 "bytearray object is too large to make repr");
935 return NULL;
936 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200937
938 newsize = 15 + length * 4;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100939 buffer = PyObject_Malloc(newsize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200940 if (buffer == NULL) {
941 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000942 return NULL;
943 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000944
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200945 /* Figure out which quote to use; single is preferred */
946 quote = '\'';
947 start = PyByteArray_AS_STRING(self);
948 for (test = start; test < start+length; ++test) {
949 if (*test == '"') {
950 quote = '\''; /* back to single */
951 break;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000952 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200953 else if (*test == '\'')
954 quote = '"';
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000955 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200956
957 p = buffer;
958 while (*quote_prefix)
959 *p++ = *quote_prefix++;
960 *p++ = quote;
961
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200962 bytes = PyByteArray_AS_STRING(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200963 for (i = 0; i < length; i++) {
964 /* There's at least enough room for a hex escape
965 and a closing quote. */
966 assert(newsize - (p - buffer) >= 5);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200967 c = bytes[i];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200968 if (c == '\'' || c == '\\')
969 *p++ = '\\', *p++ = c;
970 else if (c == '\t')
971 *p++ = '\\', *p++ = 't';
972 else if (c == '\n')
973 *p++ = '\\', *p++ = 'n';
974 else if (c == '\r')
975 *p++ = '\\', *p++ = 'r';
976 else if (c == 0)
977 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
978 else if (c < ' ' || c >= 0x7f) {
979 *p++ = '\\';
980 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +0200981 *p++ = Py_hexdigits[(c & 0xf0) >> 4];
982 *p++ = Py_hexdigits[c & 0xf];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983 }
984 else
985 *p++ = c;
986 }
987 assert(newsize - (p - buffer) >= 1);
988 *p++ = quote;
989 while (*quote_postfix) {
990 *p++ = *quote_postfix++;
991 }
992
993 v = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100994 PyObject_Free(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200995 return v;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000996}
997
998static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000999bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001000{
Alexander Belopolskyf0f45142010-08-11 17:31:17 +00001001 if (Py_BytesWarningFlag) {
1002 if (PyErr_WarnEx(PyExc_BytesWarning,
1003 "str() on a bytearray instance", 1))
1004 return NULL;
1005 }
1006 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001007}
1008
1009static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001010bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001011{
1012 Py_ssize_t self_size, other_size;
1013 Py_buffer self_bytes, other_bytes;
1014 PyObject *res;
1015 Py_ssize_t minsize;
1016 int cmp;
1017
1018 /* Bytes can be compared to anything that supports the (binary)
1019 buffer API. Except that a comparison with Unicode is always an
1020 error, even if the comparison is for equality. */
1021 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
1022 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
Barry Warsaw9e9dcd62008-10-17 01:50:37 +00001023 if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001024 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +00001025 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001026 return NULL;
1027 }
1028
Brian Curtindfc80e32011-08-10 20:28:54 -05001029 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001030 }
1031
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001032 if (PyObject_GetBuffer(self, &self_bytes, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001033 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05001034 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001035 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001036 self_size = self_bytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001037
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001038 if (PyObject_GetBuffer(other, &other_bytes, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001039 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +00001040 PyBuffer_Release(&self_bytes);
Brian Curtindfc80e32011-08-10 20:28:54 -05001041 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001042 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001043 other_size = other_bytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001044
1045 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
1046 /* Shortcut: if the lengths differ, the objects differ */
1047 cmp = (op == Py_NE);
1048 }
1049 else {
1050 minsize = self_size;
1051 if (other_size < minsize)
1052 minsize = other_size;
1053
1054 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
1055 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
1056
1057 if (cmp == 0) {
1058 if (self_size < other_size)
1059 cmp = -1;
1060 else if (self_size > other_size)
1061 cmp = 1;
1062 }
1063
1064 switch (op) {
1065 case Py_LT: cmp = cmp < 0; break;
1066 case Py_LE: cmp = cmp <= 0; break;
1067 case Py_EQ: cmp = cmp == 0; break;
1068 case Py_NE: cmp = cmp != 0; break;
1069 case Py_GT: cmp = cmp > 0; break;
1070 case Py_GE: cmp = cmp >= 0; break;
1071 }
1072 }
1073
1074 res = cmp ? Py_True : Py_False;
Martin v. Löwis423be952008-08-13 15:53:07 +00001075 PyBuffer_Release(&self_bytes);
1076 PyBuffer_Release(&other_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001077 Py_INCREF(res);
1078 return res;
1079}
1080
1081static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001082bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001083{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001084 if (self->ob_exports > 0) {
1085 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001086 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001087 PyErr_Print();
1088 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001089 if (self->ob_bytes != 0) {
Antoine Pitrou39aba4f2011-11-12 21:15:28 +01001090 PyObject_Free(self->ob_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001091 }
1092 Py_TYPE(self)->tp_free((PyObject *)self);
1093}
1094
1095
1096/* -------------------------------------------------------------------- */
1097/* Methods */
1098
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001099#define FASTSEARCH fastsearch
1100#define STRINGLIB(F) stringlib_##F
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001101#define STRINGLIB_CHAR char
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001102#define STRINGLIB_SIZEOF_CHAR 1
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001103#define STRINGLIB_LEN PyByteArray_GET_SIZE
1104#define STRINGLIB_STR PyByteArray_AS_STRING
1105#define STRINGLIB_NEW PyByteArray_FromStringAndSize
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001106#define STRINGLIB_ISSPACE Py_ISSPACE
1107#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001108#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1109#define STRINGLIB_MUTABLE 1
1110
1111#include "stringlib/fastsearch.h"
1112#include "stringlib/count.h"
1113#include "stringlib/find.h"
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001114#include "stringlib/join.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001115#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001116#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001117#include "stringlib/ctype.h"
1118#include "stringlib/transmogrify.h"
1119
1120
1121/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1122were copied from the old char* style string object. */
1123
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001124/* helper macro to fixup start/end slice values */
1125#define ADJUST_INDICES(start, end, len) \
1126 if (end > len) \
1127 end = len; \
1128 else if (end < 0) { \
1129 end += len; \
1130 if (end < 0) \
1131 end = 0; \
1132 } \
1133 if (start < 0) { \
1134 start += len; \
1135 if (start < 0) \
1136 start = 0; \
1137 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001138
1139Py_LOCAL_INLINE(Py_ssize_t)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001140bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001141{
1142 PyObject *subobj;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001143 char byte;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001144 Py_buffer subbuf;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001145 const char *sub;
1146 Py_ssize_t sub_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001147 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1148 Py_ssize_t res;
1149
Antoine Pitrouac65d962011-10-20 23:54:17 +02001150 if (!stringlib_parse_args_finds_byte("find/rfind/index/rindex",
1151 args, &subobj, &byte, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001152 return -2;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001153
1154 if (subobj) {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001155 if (PyObject_GetBuffer(subobj, &subbuf, PyBUF_SIMPLE) != 0)
Antoine Pitrouac65d962011-10-20 23:54:17 +02001156 return -2;
1157
1158 sub = subbuf.buf;
1159 sub_len = subbuf.len;
1160 }
1161 else {
1162 sub = &byte;
1163 sub_len = 1;
1164 }
1165
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001166 if (dir > 0)
1167 res = stringlib_find_slice(
1168 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
Antoine Pitrouac65d962011-10-20 23:54:17 +02001169 sub, sub_len, start, end);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001170 else
1171 res = stringlib_rfind_slice(
1172 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
Antoine Pitrouac65d962011-10-20 23:54:17 +02001173 sub, sub_len, start, end);
1174
1175 if (subobj)
1176 PyBuffer_Release(&subbuf);
1177
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001178 return res;
1179}
1180
1181PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001182"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001183\n\
1184Return the lowest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001185such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001186arguments start and end are interpreted as in slice notation.\n\
1187\n\
1188Return -1 on failure.");
1189
1190static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001191bytearray_find(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001192{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001193 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001194 if (result == -2)
1195 return NULL;
1196 return PyLong_FromSsize_t(result);
1197}
1198
1199PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001200"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001201\n\
1202Return the number of non-overlapping occurrences of subsection sub in\n\
1203bytes B[start:end]. Optional arguments start and end are interpreted\n\
1204as in slice notation.");
1205
1206static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001207bytearray_count(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001208{
1209 PyObject *sub_obj;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001210 const char *str = PyByteArray_AS_STRING(self), *sub;
1211 Py_ssize_t sub_len;
1212 char byte;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001213 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001214
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001215 Py_buffer vsub;
1216 PyObject *count_obj;
1217
Antoine Pitrouac65d962011-10-20 23:54:17 +02001218 if (!stringlib_parse_args_finds_byte("count", args, &sub_obj, &byte,
1219 &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001220 return NULL;
1221
Antoine Pitrouac65d962011-10-20 23:54:17 +02001222 if (sub_obj) {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001223 if (PyObject_GetBuffer(sub_obj, &vsub, PyBUF_SIMPLE) != 0)
Antoine Pitrouac65d962011-10-20 23:54:17 +02001224 return NULL;
1225
1226 sub = vsub.buf;
1227 sub_len = vsub.len;
1228 }
1229 else {
1230 sub = &byte;
1231 sub_len = 1;
1232 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001233
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001234 ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001235
1236 count_obj = PyLong_FromSsize_t(
Antoine Pitrouac65d962011-10-20 23:54:17 +02001237 stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001238 );
Antoine Pitrouac65d962011-10-20 23:54:17 +02001239
1240 if (sub_obj)
1241 PyBuffer_Release(&vsub);
1242
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001243 return count_obj;
1244}
1245
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001246/*[clinic input]
1247bytearray.clear
1248
1249 self: self(type="PyByteArrayObject *")
1250
1251Remove all items from the bytearray.
1252[clinic start generated code]*/
1253
1254PyDoc_STRVAR(bytearray_clear__doc__,
1255"clear($self, /)\n"
1256"--\n"
1257"\n"
1258"Remove all items from the bytearray.");
1259
1260#define BYTEARRAY_CLEAR_METHODDEF \
1261 {"clear", (PyCFunction)bytearray_clear, METH_NOARGS, bytearray_clear__doc__},
Eli Bendersky4db28d32011-03-03 18:21:02 +00001262
Victor Stinner6430fd52011-09-29 04:02:13 +02001263static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001264bytearray_clear_impl(PyByteArrayObject *self);
1265
1266static PyObject *
1267bytearray_clear(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
1268{
1269 return bytearray_clear_impl(self);
1270}
1271
1272static PyObject *
1273bytearray_clear_impl(PyByteArrayObject *self)
1274/*[clinic end generated code: output=5344093031e2f36c input=e524fd330abcdc18]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001275{
1276 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
1277 return NULL;
1278 Py_RETURN_NONE;
1279}
1280
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001281/*[clinic input]
1282bytearray.copy
1283
1284 self: self(type="PyByteArrayObject *")
1285
1286Return a copy of B.
1287[clinic start generated code]*/
1288
1289PyDoc_STRVAR(bytearray_copy__doc__,
1290"copy($self, /)\n"
1291"--\n"
1292"\n"
1293"Return a copy of B.");
1294
1295#define BYTEARRAY_COPY_METHODDEF \
1296 {"copy", (PyCFunction)bytearray_copy, METH_NOARGS, bytearray_copy__doc__},
Eli Bendersky4db28d32011-03-03 18:21:02 +00001297
1298static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001299bytearray_copy_impl(PyByteArrayObject *self);
1300
1301static PyObject *
1302bytearray_copy(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
1303{
1304 return bytearray_copy_impl(self);
1305}
1306
1307static PyObject *
1308bytearray_copy_impl(PyByteArrayObject *self)
1309/*[clinic end generated code: output=8788ed299f7f2214 input=6d5d2975aa0f33f3]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001310{
1311 return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
1312 PyByteArray_GET_SIZE(self));
1313}
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001314
1315PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001316"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001317\n\
1318Like B.find() but raise ValueError when the subsection is not found.");
1319
1320static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001321bytearray_index(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001322{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001323 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001324 if (result == -2)
1325 return NULL;
1326 if (result == -1) {
1327 PyErr_SetString(PyExc_ValueError,
1328 "subsection not found");
1329 return NULL;
1330 }
1331 return PyLong_FromSsize_t(result);
1332}
1333
1334
1335PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001336"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001337\n\
1338Return the highest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001339such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001340arguments start and end are interpreted as in slice notation.\n\
1341\n\
1342Return -1 on failure.");
1343
1344static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001345bytearray_rfind(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001346{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001347 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001348 if (result == -2)
1349 return NULL;
1350 return PyLong_FromSsize_t(result);
1351}
1352
1353
1354PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001355"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001356\n\
1357Like B.rfind() but raise ValueError when the subsection is not found.");
1358
1359static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001360bytearray_rindex(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 if (result == -1) {
1366 PyErr_SetString(PyExc_ValueError,
1367 "subsection not found");
1368 return NULL;
1369 }
1370 return PyLong_FromSsize_t(result);
1371}
1372
1373
1374static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001375bytearray_contains(PyObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001376{
1377 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1378 if (ival == -1 && PyErr_Occurred()) {
1379 Py_buffer varg;
Antoine Pitrou0010d372010-08-15 17:12:55 +00001380 Py_ssize_t pos;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001381 PyErr_Clear();
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001382 if (PyObject_GetBuffer(arg, &varg, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001383 return -1;
1384 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1385 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001386 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001387 return pos >= 0;
1388 }
1389 if (ival < 0 || ival >= 256) {
1390 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1391 return -1;
1392 }
1393
Antoine Pitrou0010d372010-08-15 17:12:55 +00001394 return memchr(PyByteArray_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001395}
1396
1397
1398/* Matches the end (direction >= 0) or start (direction < 0) of self
1399 * against substr, using the start and end arguments. Returns
1400 * -1 on error, 0 if not found and 1 if found.
1401 */
1402Py_LOCAL(int)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001403_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001404 Py_ssize_t end, int direction)
1405{
1406 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1407 const char* str;
1408 Py_buffer vsubstr;
1409 int rv = 0;
1410
1411 str = PyByteArray_AS_STRING(self);
1412
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001413 if (PyObject_GetBuffer(substr, &vsubstr, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001414 return -1;
1415
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001416 ADJUST_INDICES(start, end, len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001417
1418 if (direction < 0) {
1419 /* startswith */
1420 if (start+vsubstr.len > len) {
1421 goto done;
1422 }
1423 } else {
1424 /* endswith */
1425 if (end-start < vsubstr.len || start > len) {
1426 goto done;
1427 }
1428
1429 if (end-vsubstr.len > start)
1430 start = end - vsubstr.len;
1431 }
1432 if (end-start >= vsubstr.len)
1433 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1434
1435done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001436 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001437 return rv;
1438}
1439
1440
1441PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001442"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001443\n\
1444Return True if B starts with the specified prefix, False otherwise.\n\
1445With optional start, test B beginning at that position.\n\
1446With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001447prefix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001448
1449static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001450bytearray_startswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001451{
1452 Py_ssize_t start = 0;
1453 Py_ssize_t end = PY_SSIZE_T_MAX;
1454 PyObject *subobj;
1455 int result;
1456
Jesus Ceaac451502011-04-20 17:09:23 +02001457 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001458 return NULL;
1459 if (PyTuple_Check(subobj)) {
1460 Py_ssize_t i;
1461 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001462 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001463 PyTuple_GET_ITEM(subobj, i),
1464 start, end, -1);
1465 if (result == -1)
1466 return NULL;
1467 else if (result) {
1468 Py_RETURN_TRUE;
1469 }
1470 }
1471 Py_RETURN_FALSE;
1472 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001473 result = _bytearray_tailmatch(self, subobj, start, end, -1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001474 if (result == -1) {
1475 if (PyErr_ExceptionMatches(PyExc_TypeError))
1476 PyErr_Format(PyExc_TypeError, "startswith first arg must be bytes "
1477 "or a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001478 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001479 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001480 else
1481 return PyBool_FromLong(result);
1482}
1483
1484PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001485"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001486\n\
1487Return True if B ends with the specified suffix, False otherwise.\n\
1488With optional start, test B beginning at that position.\n\
1489With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001490suffix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001491
1492static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001493bytearray_endswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001494{
1495 Py_ssize_t start = 0;
1496 Py_ssize_t end = PY_SSIZE_T_MAX;
1497 PyObject *subobj;
1498 int result;
1499
Jesus Ceaac451502011-04-20 17:09:23 +02001500 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001501 return NULL;
1502 if (PyTuple_Check(subobj)) {
1503 Py_ssize_t i;
1504 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001505 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001506 PyTuple_GET_ITEM(subobj, i),
1507 start, end, +1);
1508 if (result == -1)
1509 return NULL;
1510 else if (result) {
1511 Py_RETURN_TRUE;
1512 }
1513 }
1514 Py_RETURN_FALSE;
1515 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001516 result = _bytearray_tailmatch(self, subobj, start, end, +1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001517 if (result == -1) {
1518 if (PyErr_ExceptionMatches(PyExc_TypeError))
1519 PyErr_Format(PyExc_TypeError, "endswith first arg must be bytes or "
1520 "a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001521 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001522 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001523 else
1524 return PyBool_FromLong(result);
1525}
1526
1527
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001528/*[clinic input]
1529bytearray.translate
1530
1531 self: self(type="PyByteArrayObject *")
1532 table: object
1533 Translation table, which must be a bytes object of length 256.
1534 [
1535 deletechars: object
1536 ]
1537 /
1538
1539Return a copy with each character mapped by the given translation table.
1540
1541All characters occurring in the optional argument deletechars are removed.
1542The remaining characters are mapped through the given translation table.
1543[clinic start generated code]*/
1544
1545PyDoc_STRVAR(bytearray_translate__doc__,
1546"translate(table, [deletechars])\n"
1547"Return a copy with each character mapped by the given translation table.\n"
1548"\n"
1549" table\n"
1550" Translation table, which must be a bytes object of length 256.\n"
1551"\n"
1552"All characters occurring in the optional argument deletechars are removed.\n"
1553"The remaining characters are mapped through the given translation table.");
1554
1555#define BYTEARRAY_TRANSLATE_METHODDEF \
1556 {"translate", (PyCFunction)bytearray_translate, METH_VARARGS, bytearray_translate__doc__},
1557
1558static PyObject *
1559bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, int group_right_1, PyObject *deletechars);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001560
1561static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001562bytearray_translate(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001563{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001564 PyObject *return_value = NULL;
1565 PyObject *table;
1566 int group_right_1 = 0;
1567 PyObject *deletechars = NULL;
1568
1569 switch (PyTuple_GET_SIZE(args)) {
1570 case 1:
1571 if (!PyArg_ParseTuple(args, "O:translate", &table))
1572 goto exit;
1573 break;
1574 case 2:
1575 if (!PyArg_ParseTuple(args, "OO:translate", &table, &deletechars))
1576 goto exit;
1577 group_right_1 = 1;
1578 break;
1579 default:
1580 PyErr_SetString(PyExc_TypeError, "bytearray.translate requires 1 to 2 arguments");
1581 goto exit;
1582 }
1583 return_value = bytearray_translate_impl(self, table, group_right_1, deletechars);
1584
1585exit:
1586 return return_value;
1587}
1588
1589static PyObject *
1590bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, int group_right_1, PyObject *deletechars)
1591/*[clinic end generated code: output=a709df81d41db4b7 input=b749ad85f4860824]*/
1592{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001593 char *input, *output;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001594 const char *table_chars;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001595 Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001596 PyObject *input_obj = (PyObject*)self;
1597 const char *output_start;
1598 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001599 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001600 int trans_table[256];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001601 Py_buffer vtable, vdel;
1602
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001603 if (table == Py_None) {
1604 table_chars = NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001605 table = NULL;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001606 } else if (PyObject_GetBuffer(table, &vtable, PyBUF_SIMPLE) != 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001607 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001608 } else {
1609 if (vtable.len != 256) {
1610 PyErr_SetString(PyExc_ValueError,
1611 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001612 PyBuffer_Release(&vtable);
1613 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001614 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001615 table_chars = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001616 }
1617
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001618 if (deletechars != NULL) {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001619 if (PyObject_GetBuffer(deletechars, &vdel, PyBUF_SIMPLE) != 0) {
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001620 if (table != NULL)
Georg Brandl953152f2009-07-22 12:03:59 +00001621 PyBuffer_Release(&vtable);
1622 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001623 }
1624 }
1625 else {
1626 vdel.buf = NULL;
1627 vdel.len = 0;
1628 }
1629
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001630 inlen = PyByteArray_GET_SIZE(input_obj);
1631 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1632 if (result == NULL)
1633 goto done;
1634 output_start = output = PyByteArray_AsString(result);
1635 input = PyByteArray_AS_STRING(input_obj);
1636
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001637 if (vdel.len == 0 && table_chars != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001638 /* If no deletions are required, use faster code */
1639 for (i = inlen; --i >= 0; ) {
1640 c = Py_CHARMASK(*input++);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001641 *output++ = table_chars[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001642 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001643 goto done;
1644 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001645
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001646 if (table_chars == NULL) {
Georg Brandlccc47b62008-12-28 11:44:14 +00001647 for (i = 0; i < 256; i++)
1648 trans_table[i] = Py_CHARMASK(i);
1649 } else {
1650 for (i = 0; i < 256; i++)
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001651 trans_table[i] = Py_CHARMASK(table_chars[i]);
Georg Brandlccc47b62008-12-28 11:44:14 +00001652 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001653
1654 for (i = 0; i < vdel.len; i++)
1655 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1656
1657 for (i = inlen; --i >= 0; ) {
1658 c = Py_CHARMASK(*input++);
1659 if (trans_table[c] != -1)
1660 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1661 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001662 }
1663 /* Fix the size of the resulting string */
1664 if (inlen > 0)
Christian Heimesc731bbe2013-07-21 02:04:35 +02001665 if (PyByteArray_Resize(result, output - output_start) < 0) {
1666 Py_CLEAR(result);
1667 goto done;
1668 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001669
1670done:
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001671 if (table != NULL)
Georg Brandlccc47b62008-12-28 11:44:14 +00001672 PyBuffer_Release(&vtable);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001673 if (deletechars != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001674 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001675 return result;
1676}
1677
1678
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001679/*[clinic input]
1680
1681@staticmethod
1682bytearray.maketrans
1683
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001684 frm: Py_buffer
1685 to: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001686 /
1687
1688Return a translation table useable for the bytes or bytearray translate method.
1689
1690The returned table will be one where each byte in frm is mapped to the byte at
1691the same position in to.
1692
1693The bytes objects frm and to must be of the same length.
1694[clinic start generated code]*/
1695
1696PyDoc_STRVAR(bytearray_maketrans__doc__,
1697"maketrans(frm, to, /)\n"
1698"--\n"
1699"\n"
1700"Return a translation table useable for the bytes or bytearray translate method.\n"
1701"\n"
1702"The returned table will be one where each byte in frm is mapped to the byte at\n"
1703"the same position in to.\n"
1704"\n"
1705"The bytes objects frm and to must be of the same length.");
1706
1707#define BYTEARRAY_MAKETRANS_METHODDEF \
1708 {"maketrans", (PyCFunction)bytearray_maketrans, METH_VARARGS|METH_STATIC, bytearray_maketrans__doc__},
1709
Georg Brandlabc38772009-04-12 15:51:51 +00001710static PyObject *
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001711bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001712
1713static PyObject *
1714bytearray_maketrans(void *null, PyObject *args)
Georg Brandlabc38772009-04-12 15:51:51 +00001715{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001716 PyObject *return_value = NULL;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001717 Py_buffer frm = {NULL, NULL};
1718 Py_buffer to = {NULL, NULL};
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001719
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001720 if (!PyArg_ParseTuple(args,
1721 "y*y*:maketrans",
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001722 &frm, &to))
1723 goto exit;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001724 return_value = bytearray_maketrans_impl(&frm, &to);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001725
1726exit:
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001727 /* Cleanup for frm */
1728 if (frm.obj)
1729 PyBuffer_Release(&frm);
1730 /* Cleanup for to */
1731 if (to.obj)
1732 PyBuffer_Release(&to);
1733
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001734 return return_value;
1735}
1736
1737static PyObject *
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001738bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to)
1739/*[clinic end generated code: output=d332622814c26f4b input=5925a81d2fbbf151]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001740{
1741 return _Py_bytes_maketrans(frm, to);
Georg Brandlabc38772009-04-12 15:51:51 +00001742}
1743
1744
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001745/* find and count characters and substrings */
1746
1747#define findchar(target, target_len, c) \
1748 ((char *)memchr((const void *)(target), c, target_len))
1749
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001750
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001751/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001752Py_LOCAL(PyByteArrayObject *)
1753return_self(PyByteArrayObject *self)
1754{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001755 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001756 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1757 PyByteArray_AS_STRING(self),
1758 PyByteArray_GET_SIZE(self));
1759}
1760
1761Py_LOCAL_INLINE(Py_ssize_t)
1762countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1763{
1764 Py_ssize_t count=0;
1765 const char *start=target;
1766 const char *end=target+target_len;
1767
1768 while ( (start=findchar(start, end-start, c)) != NULL ) {
1769 count++;
1770 if (count >= maxcount)
1771 break;
1772 start += 1;
1773 }
1774 return count;
1775}
1776
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001777
1778/* Algorithms for different cases of string replacement */
1779
1780/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1781Py_LOCAL(PyByteArrayObject *)
1782replace_interleave(PyByteArrayObject *self,
1783 const char *to_s, Py_ssize_t to_len,
1784 Py_ssize_t maxcount)
1785{
1786 char *self_s, *result_s;
1787 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001788 Py_ssize_t count, i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001789 PyByteArrayObject *result;
1790
1791 self_len = PyByteArray_GET_SIZE(self);
1792
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001793 /* 1 at the end plus 1 after every character;
1794 count = min(maxcount, self_len + 1) */
1795 if (maxcount <= self_len)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001796 count = maxcount;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001797 else
1798 /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
1799 count = self_len + 1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001800
1801 /* Check for overflow */
1802 /* result_len = count * to_len + self_len; */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001803 assert(count > 0);
1804 if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001805 PyErr_SetString(PyExc_OverflowError,
1806 "replace string is too long");
1807 return NULL;
1808 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001809 result_len = count * to_len + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001810
1811 if (! (result = (PyByteArrayObject *)
1812 PyByteArray_FromStringAndSize(NULL, result_len)) )
1813 return NULL;
1814
1815 self_s = PyByteArray_AS_STRING(self);
1816 result_s = PyByteArray_AS_STRING(result);
1817
1818 /* TODO: special case single character, which doesn't need memcpy */
1819
1820 /* Lay the first one down (guaranteed this will occur) */
1821 Py_MEMCPY(result_s, to_s, to_len);
1822 result_s += to_len;
1823 count -= 1;
1824
1825 for (i=0; i<count; i++) {
1826 *result_s++ = *self_s++;
1827 Py_MEMCPY(result_s, to_s, to_len);
1828 result_s += to_len;
1829 }
1830
1831 /* Copy the rest of the original string */
1832 Py_MEMCPY(result_s, self_s, self_len-i);
1833
1834 return result;
1835}
1836
1837/* Special case for deleting a single character */
1838/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1839Py_LOCAL(PyByteArrayObject *)
1840replace_delete_single_character(PyByteArrayObject *self,
1841 char from_c, Py_ssize_t maxcount)
1842{
1843 char *self_s, *result_s;
1844 char *start, *next, *end;
1845 Py_ssize_t self_len, result_len;
1846 Py_ssize_t count;
1847 PyByteArrayObject *result;
1848
1849 self_len = PyByteArray_GET_SIZE(self);
1850 self_s = PyByteArray_AS_STRING(self);
1851
1852 count = countchar(self_s, self_len, from_c, maxcount);
1853 if (count == 0) {
1854 return return_self(self);
1855 }
1856
1857 result_len = self_len - count; /* from_len == 1 */
1858 assert(result_len>=0);
1859
1860 if ( (result = (PyByteArrayObject *)
1861 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1862 return NULL;
1863 result_s = PyByteArray_AS_STRING(result);
1864
1865 start = self_s;
1866 end = self_s + self_len;
1867 while (count-- > 0) {
1868 next = findchar(start, end-start, from_c);
1869 if (next == NULL)
1870 break;
1871 Py_MEMCPY(result_s, start, next-start);
1872 result_s += (next-start);
1873 start = next+1;
1874 }
1875 Py_MEMCPY(result_s, start, end-start);
1876
1877 return result;
1878}
1879
1880/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1881
1882Py_LOCAL(PyByteArrayObject *)
1883replace_delete_substring(PyByteArrayObject *self,
1884 const char *from_s, Py_ssize_t from_len,
1885 Py_ssize_t maxcount)
1886{
1887 char *self_s, *result_s;
1888 char *start, *next, *end;
1889 Py_ssize_t self_len, result_len;
1890 Py_ssize_t count, offset;
1891 PyByteArrayObject *result;
1892
1893 self_len = PyByteArray_GET_SIZE(self);
1894 self_s = PyByteArray_AS_STRING(self);
1895
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001896 count = stringlib_count(self_s, self_len,
1897 from_s, from_len,
1898 maxcount);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001899
1900 if (count == 0) {
1901 /* no matches */
1902 return return_self(self);
1903 }
1904
1905 result_len = self_len - (count * from_len);
1906 assert (result_len>=0);
1907
1908 if ( (result = (PyByteArrayObject *)
1909 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1910 return NULL;
1911
1912 result_s = PyByteArray_AS_STRING(result);
1913
1914 start = self_s;
1915 end = self_s + self_len;
1916 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001917 offset = stringlib_find(start, end-start,
1918 from_s, from_len,
1919 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001920 if (offset == -1)
1921 break;
1922 next = start + offset;
1923
1924 Py_MEMCPY(result_s, start, next-start);
1925
1926 result_s += (next-start);
1927 start = next+from_len;
1928 }
1929 Py_MEMCPY(result_s, start, end-start);
1930 return result;
1931}
1932
1933/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1934Py_LOCAL(PyByteArrayObject *)
1935replace_single_character_in_place(PyByteArrayObject *self,
1936 char from_c, char to_c,
1937 Py_ssize_t maxcount)
1938{
Antoine Pitroud1188562010-06-09 16:38:55 +00001939 char *self_s, *result_s, *start, *end, *next;
1940 Py_ssize_t self_len;
1941 PyByteArrayObject *result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001942
Antoine Pitroud1188562010-06-09 16:38:55 +00001943 /* The result string will be the same size */
1944 self_s = PyByteArray_AS_STRING(self);
1945 self_len = PyByteArray_GET_SIZE(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001946
Antoine Pitroud1188562010-06-09 16:38:55 +00001947 next = findchar(self_s, self_len, from_c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001948
Antoine Pitroud1188562010-06-09 16:38:55 +00001949 if (next == NULL) {
1950 /* No matches; return the original bytes */
1951 return return_self(self);
1952 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001953
Antoine Pitroud1188562010-06-09 16:38:55 +00001954 /* Need to make a new bytes */
1955 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1956 if (result == NULL)
1957 return NULL;
1958 result_s = PyByteArray_AS_STRING(result);
1959 Py_MEMCPY(result_s, self_s, self_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001960
Antoine Pitroud1188562010-06-09 16:38:55 +00001961 /* change everything in-place, starting with this one */
1962 start = result_s + (next-self_s);
1963 *start = to_c;
1964 start++;
1965 end = result_s + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001966
Antoine Pitroud1188562010-06-09 16:38:55 +00001967 while (--maxcount > 0) {
1968 next = findchar(start, end-start, from_c);
1969 if (next == NULL)
1970 break;
1971 *next = to_c;
1972 start = next+1;
1973 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001974
Antoine Pitroud1188562010-06-09 16:38:55 +00001975 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001976}
1977
1978/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1979Py_LOCAL(PyByteArrayObject *)
1980replace_substring_in_place(PyByteArrayObject *self,
1981 const char *from_s, Py_ssize_t from_len,
1982 const char *to_s, Py_ssize_t to_len,
1983 Py_ssize_t maxcount)
1984{
1985 char *result_s, *start, *end;
1986 char *self_s;
1987 Py_ssize_t self_len, offset;
1988 PyByteArrayObject *result;
1989
1990 /* The result bytes will be the same size */
1991
1992 self_s = PyByteArray_AS_STRING(self);
1993 self_len = PyByteArray_GET_SIZE(self);
1994
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001995 offset = stringlib_find(self_s, self_len,
1996 from_s, from_len,
1997 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001998 if (offset == -1) {
1999 /* No matches; return the original bytes */
2000 return return_self(self);
2001 }
2002
2003 /* Need to make a new bytes */
2004 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
2005 if (result == NULL)
2006 return NULL;
2007 result_s = PyByteArray_AS_STRING(result);
2008 Py_MEMCPY(result_s, self_s, self_len);
2009
2010 /* change everything in-place, starting with this one */
2011 start = result_s + offset;
2012 Py_MEMCPY(start, to_s, from_len);
2013 start += from_len;
2014 end = result_s + self_len;
2015
2016 while ( --maxcount > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002017 offset = stringlib_find(start, end-start,
2018 from_s, from_len,
2019 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002020 if (offset==-1)
2021 break;
2022 Py_MEMCPY(start+offset, to_s, from_len);
2023 start += offset+from_len;
2024 }
2025
2026 return result;
2027}
2028
2029/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
2030Py_LOCAL(PyByteArrayObject *)
2031replace_single_character(PyByteArrayObject *self,
2032 char from_c,
2033 const char *to_s, Py_ssize_t to_len,
2034 Py_ssize_t maxcount)
2035{
2036 char *self_s, *result_s;
2037 char *start, *next, *end;
2038 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002039 Py_ssize_t count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002040 PyByteArrayObject *result;
2041
2042 self_s = PyByteArray_AS_STRING(self);
2043 self_len = PyByteArray_GET_SIZE(self);
2044
2045 count = countchar(self_s, self_len, from_c, maxcount);
2046 if (count == 0) {
2047 /* no matches, return unchanged */
2048 return return_self(self);
2049 }
2050
2051 /* use the difference between current and new, hence the "-1" */
2052 /* result_len = self_len + count * (to_len-1) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002053 assert(count > 0);
2054 if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002055 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
2056 return NULL;
2057 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002058 result_len = self_len + count * (to_len - 1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002059
2060 if ( (result = (PyByteArrayObject *)
2061 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
2062 return NULL;
2063 result_s = PyByteArray_AS_STRING(result);
2064
2065 start = self_s;
2066 end = self_s + self_len;
2067 while (count-- > 0) {
2068 next = findchar(start, end-start, from_c);
2069 if (next == NULL)
2070 break;
2071
2072 if (next == start) {
2073 /* replace with the 'to' */
2074 Py_MEMCPY(result_s, to_s, to_len);
2075 result_s += to_len;
2076 start += 1;
2077 } else {
2078 /* copy the unchanged old then the 'to' */
2079 Py_MEMCPY(result_s, start, next-start);
2080 result_s += (next-start);
2081 Py_MEMCPY(result_s, to_s, to_len);
2082 result_s += to_len;
2083 start = next+1;
2084 }
2085 }
2086 /* Copy the remainder of the remaining bytes */
2087 Py_MEMCPY(result_s, start, end-start);
2088
2089 return result;
2090}
2091
2092/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
2093Py_LOCAL(PyByteArrayObject *)
2094replace_substring(PyByteArrayObject *self,
2095 const char *from_s, Py_ssize_t from_len,
2096 const char *to_s, Py_ssize_t to_len,
2097 Py_ssize_t maxcount)
2098{
2099 char *self_s, *result_s;
2100 char *start, *next, *end;
2101 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002102 Py_ssize_t count, offset;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002103 PyByteArrayObject *result;
2104
2105 self_s = PyByteArray_AS_STRING(self);
2106 self_len = PyByteArray_GET_SIZE(self);
2107
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002108 count = stringlib_count(self_s, self_len,
2109 from_s, from_len,
2110 maxcount);
2111
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002112 if (count == 0) {
2113 /* no matches, return unchanged */
2114 return return_self(self);
2115 }
2116
2117 /* Check for overflow */
2118 /* result_len = self_len + count * (to_len-from_len) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002119 assert(count > 0);
2120 if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002121 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
2122 return NULL;
2123 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002124 result_len = self_len + count * (to_len - from_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002125
2126 if ( (result = (PyByteArrayObject *)
2127 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
2128 return NULL;
2129 result_s = PyByteArray_AS_STRING(result);
2130
2131 start = self_s;
2132 end = self_s + self_len;
2133 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002134 offset = stringlib_find(start, end-start,
2135 from_s, from_len,
2136 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002137 if (offset == -1)
2138 break;
2139 next = start+offset;
2140 if (next == start) {
2141 /* replace with the 'to' */
2142 Py_MEMCPY(result_s, to_s, to_len);
2143 result_s += to_len;
2144 start += from_len;
2145 } else {
2146 /* copy the unchanged old then the 'to' */
2147 Py_MEMCPY(result_s, start, next-start);
2148 result_s += (next-start);
2149 Py_MEMCPY(result_s, to_s, to_len);
2150 result_s += to_len;
2151 start = next+from_len;
2152 }
2153 }
2154 /* Copy the remainder of the remaining bytes */
2155 Py_MEMCPY(result_s, start, end-start);
2156
2157 return result;
2158}
2159
2160
2161Py_LOCAL(PyByteArrayObject *)
2162replace(PyByteArrayObject *self,
2163 const char *from_s, Py_ssize_t from_len,
2164 const char *to_s, Py_ssize_t to_len,
2165 Py_ssize_t maxcount)
2166{
2167 if (maxcount < 0) {
2168 maxcount = PY_SSIZE_T_MAX;
2169 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
2170 /* nothing to do; return the original bytes */
2171 return return_self(self);
2172 }
2173
2174 if (maxcount == 0 ||
2175 (from_len == 0 && to_len == 0)) {
2176 /* nothing to do; return the original bytes */
2177 return return_self(self);
2178 }
2179
2180 /* Handle zero-length special cases */
2181
2182 if (from_len == 0) {
2183 /* insert the 'to' bytes everywhere. */
2184 /* >>> "Python".replace("", ".") */
2185 /* '.P.y.t.h.o.n.' */
2186 return replace_interleave(self, to_s, to_len, maxcount);
2187 }
2188
2189 /* Except for "".replace("", "A") == "A" there is no way beyond this */
2190 /* point for an empty self bytes to generate a non-empty bytes */
2191 /* Special case so the remaining code always gets a non-empty bytes */
2192 if (PyByteArray_GET_SIZE(self) == 0) {
2193 return return_self(self);
2194 }
2195
2196 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00002197 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002198 if (from_len == 1) {
2199 return replace_delete_single_character(
2200 self, from_s[0], maxcount);
2201 } else {
2202 return replace_delete_substring(self, from_s, from_len, maxcount);
2203 }
2204 }
2205
2206 /* Handle special case where both bytes have the same length */
2207
2208 if (from_len == to_len) {
2209 if (from_len == 1) {
2210 return replace_single_character_in_place(
2211 self,
2212 from_s[0],
2213 to_s[0],
2214 maxcount);
2215 } else {
2216 return replace_substring_in_place(
2217 self, from_s, from_len, to_s, to_len, maxcount);
2218 }
2219 }
2220
2221 /* Otherwise use the more generic algorithms */
2222 if (from_len == 1) {
2223 return replace_single_character(self, from_s[0],
2224 to_s, to_len, maxcount);
2225 } else {
2226 /* len('from')>=2, len('to')>=1 */
2227 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
2228 }
2229}
2230
2231
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002232/*[clinic input]
2233bytearray.replace
2234
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002235 old: Py_buffer
2236 new: Py_buffer
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002237 count: Py_ssize_t = -1
2238 Maximum number of occurrences to replace.
2239 -1 (the default value) means replace all occurrences.
2240 /
2241
2242Return a copy with all occurrences of substring old replaced by new.
2243
2244If the optional argument count is given, only the first count occurrences are
2245replaced.
2246[clinic start generated code]*/
2247
2248PyDoc_STRVAR(bytearray_replace__doc__,
2249"replace($self, old, new, count=-1, /)\n"
2250"--\n"
2251"\n"
2252"Return a copy with all occurrences of substring old replaced by new.\n"
2253"\n"
2254" count\n"
2255" Maximum number of occurrences to replace.\n"
2256" -1 (the default value) means replace all occurrences.\n"
2257"\n"
2258"If the optional argument count is given, only the first count occurrences are\n"
2259"replaced.");
2260
2261#define BYTEARRAY_REPLACE_METHODDEF \
2262 {"replace", (PyCFunction)bytearray_replace, METH_VARARGS, bytearray_replace__doc__},
2263
2264static PyObject *
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002265bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old, Py_buffer *new, Py_ssize_t count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002266
2267static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002268bytearray_replace(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002269{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002270 PyObject *return_value = NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02002271 Py_buffer old = {NULL, NULL};
2272 Py_buffer new = {NULL, NULL};
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002273 Py_ssize_t count = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002274
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002275 if (!PyArg_ParseTuple(args,
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002276 "y*y*|n:replace",
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002277 &old, &new, &count))
2278 goto exit;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002279 return_value = bytearray_replace_impl(self, &old, &new, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002280
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002281exit:
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002282 /* Cleanup for old */
2283 if (old.obj)
2284 PyBuffer_Release(&old);
2285 /* Cleanup for new */
2286 if (new.obj)
2287 PyBuffer_Release(&new);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002288
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002289 return return_value;
2290}
2291
2292static PyObject *
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002293bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old, Py_buffer *new, Py_ssize_t count)
2294/*[clinic end generated code: output=9997fbbd5bac4883 input=aa379d988637c7fb]*/
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002295{
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002296 return (PyObject *)replace((PyByteArrayObject *) self,
2297 old->buf, old->len,
2298 new->buf, new->len, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002299}
2300
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002301/*[clinic input]
2302bytearray.split
2303
2304 sep: object = None
2305 The delimiter according which to split the bytearray.
2306 None (the default value) means split on ASCII whitespace characters
2307 (space, tab, return, newline, formfeed, vertical tab).
2308 maxsplit: Py_ssize_t = -1
2309 Maximum number of splits to do.
2310 -1 (the default value) means no limit.
2311
2312Return a list of the sections in the bytearray, using sep as the delimiter.
2313[clinic start generated code]*/
2314
2315PyDoc_STRVAR(bytearray_split__doc__,
2316"split($self, /, sep=None, maxsplit=-1)\n"
2317"--\n"
2318"\n"
2319"Return a list of the sections in the bytearray, using sep as the delimiter.\n"
2320"\n"
2321" sep\n"
2322" The delimiter according which to split the bytearray.\n"
2323" None (the default value) means split on ASCII whitespace characters\n"
2324" (space, tab, return, newline, formfeed, vertical tab).\n"
2325" maxsplit\n"
2326" Maximum number of splits to do.\n"
2327" -1 (the default value) means no limit.");
2328
2329#define BYTEARRAY_SPLIT_METHODDEF \
2330 {"split", (PyCFunction)bytearray_split, METH_VARARGS|METH_KEYWORDS, bytearray_split__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002331
2332static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002333bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit);
2334
2335static PyObject *
2336bytearray_split(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002337{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002338 PyObject *return_value = NULL;
2339 static char *_keywords[] = {"sep", "maxsplit", NULL};
2340 PyObject *sep = Py_None;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002341 Py_ssize_t maxsplit = -1;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002342
2343 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
2344 "|On:split", _keywords,
2345 &sep, &maxsplit))
2346 goto exit;
2347 return_value = bytearray_split_impl(self, sep, maxsplit);
2348
2349exit:
2350 return return_value;
2351}
2352
2353static PyObject *
2354bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit)
2355/*[clinic end generated code: output=062a3d87d6f918fa input=24f82669f41bf523]*/
2356{
2357 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002358 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002359 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002360 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002361
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002362 if (maxsplit < 0)
2363 maxsplit = PY_SSIZE_T_MAX;
2364
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002365 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002366 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002367
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002368 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002369 return NULL;
2370 sub = vsub.buf;
2371 n = vsub.len;
2372
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002373 list = stringlib_split(
2374 (PyObject*) self, s, len, sub, n, maxsplit
2375 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002376 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002377 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002378}
2379
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002380/*[clinic input]
2381bytearray.partition
2382
2383 self: self(type="PyByteArrayObject *")
2384 sep: object
2385 /
2386
2387Partition the bytearray into three parts using the given separator.
2388
2389This will search for the separator sep in the bytearray. If the separator is
2390found, returns a 3-tuple containing the part before the separator, the
2391separator itself, and the part after it.
2392
2393If the separator is not found, returns a 3-tuple containing the original
2394bytearray object and two empty bytearray objects.
2395[clinic start generated code]*/
2396
2397PyDoc_STRVAR(bytearray_partition__doc__,
2398"partition($self, sep, /)\n"
2399"--\n"
2400"\n"
2401"Partition the bytearray into three parts using the given separator.\n"
2402"\n"
2403"This will search for the separator sep in the bytearray. If the separator is\n"
2404"found, returns a 3-tuple containing the part before the separator, the\n"
2405"separator itself, and the part after it.\n"
2406"\n"
2407"If the separator is not found, returns a 3-tuple containing the original\n"
2408"bytearray object and two empty bytearray objects.");
2409
2410#define BYTEARRAY_PARTITION_METHODDEF \
2411 {"partition", (PyCFunction)bytearray_partition, METH_O, bytearray_partition__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002412
2413static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002414bytearray_partition(PyByteArrayObject *self, PyObject *sep)
2415/*[clinic end generated code: output=2645138221fe6f4d input=7d7fe37b1696d506]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002416{
2417 PyObject *bytesep, *result;
2418
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002419 bytesep = PyByteArray_FromObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002420 if (! bytesep)
2421 return NULL;
2422
2423 result = stringlib_partition(
2424 (PyObject*) self,
2425 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2426 bytesep,
2427 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2428 );
2429
2430 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002431 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002432}
2433
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002434/*[clinic input]
2435bytearray.rpartition
2436
2437 self: self(type="PyByteArrayObject *")
2438 sep: object
2439 /
2440
2441Partition the bytes into three parts using the given separator.
2442
2443This will search for the separator sep in the bytearray, starting and the end.
2444If the separator is found, returns a 3-tuple containing the part before the
2445separator, the separator itself, and the part after it.
2446
2447If the separator is not found, returns a 3-tuple containing two empty bytearray
2448objects and the original bytearray object.
2449[clinic start generated code]*/
2450
2451PyDoc_STRVAR(bytearray_rpartition__doc__,
2452"rpartition($self, sep, /)\n"
2453"--\n"
2454"\n"
2455"Partition the bytes into three parts using the given separator.\n"
2456"\n"
2457"This will search for the separator sep in the bytearray, starting and the end.\n"
2458"If the separator is found, returns a 3-tuple containing the part before the\n"
2459"separator, the separator itself, and the part after it.\n"
2460"\n"
2461"If the separator is not found, returns a 3-tuple containing two empty bytearray\n"
2462"objects and the original bytearray object.");
2463
2464#define BYTEARRAY_RPARTITION_METHODDEF \
2465 {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, bytearray_rpartition__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002466
2467static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002468bytearray_rpartition(PyByteArrayObject *self, PyObject *sep)
2469/*[clinic end generated code: output=ed13e54605d007de input=9b8cd540c1b75853]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002470{
2471 PyObject *bytesep, *result;
2472
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002473 bytesep = PyByteArray_FromObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002474 if (! bytesep)
2475 return NULL;
2476
2477 result = stringlib_rpartition(
2478 (PyObject*) self,
2479 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2480 bytesep,
2481 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2482 );
2483
2484 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002485 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002486}
2487
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002488/*[clinic input]
2489bytearray.rsplit = bytearray.split
2490
2491Return a list of the sections in the bytearray, using sep as the delimiter.
2492
2493Splitting is done starting at the end of the bytearray and working to the front.
2494[clinic start generated code]*/
2495
2496PyDoc_STRVAR(bytearray_rsplit__doc__,
2497"rsplit($self, /, sep=None, maxsplit=-1)\n"
2498"--\n"
2499"\n"
2500"Return a list of the sections in the bytearray, using sep as the delimiter.\n"
2501"\n"
2502" sep\n"
2503" The delimiter according which to split the bytearray.\n"
2504" None (the default value) means split on ASCII whitespace characters\n"
2505" (space, tab, return, newline, formfeed, vertical tab).\n"
2506" maxsplit\n"
2507" Maximum number of splits to do.\n"
2508" -1 (the default value) means no limit.\n"
2509"\n"
2510"Splitting is done starting at the end of the bytearray and working to the front.");
2511
2512#define BYTEARRAY_RSPLIT_METHODDEF \
2513 {"rsplit", (PyCFunction)bytearray_rsplit, METH_VARARGS|METH_KEYWORDS, bytearray_rsplit__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002514
2515static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002516bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit);
2517
2518static PyObject *
2519bytearray_rsplit(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002520{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002521 PyObject *return_value = NULL;
2522 static char *_keywords[] = {"sep", "maxsplit", NULL};
2523 PyObject *sep = Py_None;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002524 Py_ssize_t maxsplit = -1;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002525
2526 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
2527 "|On:rsplit", _keywords,
2528 &sep, &maxsplit))
2529 goto exit;
2530 return_value = bytearray_rsplit_impl(self, sep, maxsplit);
2531
2532exit:
2533 return return_value;
2534}
2535
2536static PyObject *
2537bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit)
2538/*[clinic end generated code: output=affaf9fc2aae8d41 input=a68286e4dd692ffe]*/
2539{
2540 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002541 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002542 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002543 Py_buffer vsub;
2544
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002545 if (maxsplit < 0)
2546 maxsplit = PY_SSIZE_T_MAX;
2547
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002548 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002549 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002550
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02002551 if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002552 return NULL;
2553 sub = vsub.buf;
2554 n = vsub.len;
2555
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002556 list = stringlib_rsplit(
2557 (PyObject*) self, s, len, sub, n, maxsplit
2558 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002559 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002560 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002561}
2562
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002563/*[clinic input]
2564bytearray.reverse
2565
2566 self: self(type="PyByteArrayObject *")
2567
2568Reverse the order of the values in B in place.
2569[clinic start generated code]*/
2570
2571PyDoc_STRVAR(bytearray_reverse__doc__,
2572"reverse($self, /)\n"
2573"--\n"
2574"\n"
2575"Reverse the order of the values in B in place.");
2576
2577#define BYTEARRAY_REVERSE_METHODDEF \
2578 {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, bytearray_reverse__doc__},
2579
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002580static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002581bytearray_reverse_impl(PyByteArrayObject *self);
2582
2583static PyObject *
2584bytearray_reverse(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
2585{
2586 return bytearray_reverse_impl(self);
2587}
2588
2589static PyObject *
2590bytearray_reverse_impl(PyByteArrayObject *self)
2591/*[clinic end generated code: output=5d5e5f0bfc67f476 input=7933a499b8597bd1]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002592{
2593 char swap, *head, *tail;
2594 Py_ssize_t i, j, n = Py_SIZE(self);
2595
2596 j = n / 2;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002597 head = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002598 tail = head + n - 1;
2599 for (i = 0; i < j; i++) {
2600 swap = *head;
2601 *head++ = *tail;
2602 *tail-- = swap;
2603 }
2604
2605 Py_RETURN_NONE;
2606}
2607
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002608
2609/*[python input]
2610class bytesvalue_converter(CConverter):
2611 type = 'int'
2612 converter = '_getbytevalue'
2613[python start generated code]*/
2614/*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/
2615
2616
2617/*[clinic input]
2618bytearray.insert
2619
2620 self: self(type="PyByteArrayObject *")
2621 index: Py_ssize_t
2622 The index where the value is to be inserted.
2623 item: bytesvalue
2624 The item to be inserted.
2625 /
2626
2627Insert a single item into the bytearray before the given index.
2628[clinic start generated code]*/
2629
2630PyDoc_STRVAR(bytearray_insert__doc__,
2631"insert($self, index, item, /)\n"
2632"--\n"
2633"\n"
2634"Insert a single item into the bytearray before the given index.\n"
2635"\n"
2636" index\n"
2637" The index where the value is to be inserted.\n"
2638" item\n"
2639" The item to be inserted.");
2640
2641#define BYTEARRAY_INSERT_METHODDEF \
2642 {"insert", (PyCFunction)bytearray_insert, METH_VARARGS, bytearray_insert__doc__},
2643
2644static PyObject *
2645bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item);
2646
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002647static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002648bytearray_insert(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002649{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002650 PyObject *return_value = NULL;
2651 Py_ssize_t index;
2652 int item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002653
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002654 if (!PyArg_ParseTuple(args,
2655 "nO&:insert",
2656 &index, _getbytevalue, &item))
2657 goto exit;
2658 return_value = bytearray_insert_impl(self, index, item);
2659
2660exit:
2661 return return_value;
2662}
2663
2664static PyObject *
2665bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
2666/*[clinic end generated code: output=5ec9340d4ad19080 input=833766836ba30e1e]*/
2667{
2668 Py_ssize_t n = Py_SIZE(self);
2669 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002670
2671 if (n == PY_SSIZE_T_MAX) {
2672 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002673 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002674 return NULL;
2675 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002676 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2677 return NULL;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002678 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002679
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002680 if (index < 0) {
2681 index += n;
2682 if (index < 0)
2683 index = 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002684 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002685 if (index > n)
2686 index = n;
2687 memmove(buf + index + 1, buf + index, n - index);
2688 buf[index] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002689
2690 Py_RETURN_NONE;
2691}
2692
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002693/*[clinic input]
2694bytearray.append
2695
2696 self: self(type="PyByteArrayObject *")
2697 item: bytesvalue
2698 The item to be appended.
2699 /
2700
2701Append a single item to the end of the bytearray.
2702[clinic start generated code]*/
2703
2704PyDoc_STRVAR(bytearray_append__doc__,
2705"append($self, item, /)\n"
2706"--\n"
2707"\n"
2708"Append a single item to the end of the bytearray.\n"
2709"\n"
2710" item\n"
2711" The item to be appended.");
2712
2713#define BYTEARRAY_APPEND_METHODDEF \
2714 {"append", (PyCFunction)bytearray_append, METH_VARARGS, bytearray_append__doc__},
2715
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002716static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002717bytearray_append_impl(PyByteArrayObject *self, int item);
2718
2719static PyObject *
2720bytearray_append(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002721{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002722 PyObject *return_value = NULL;
2723 int item;
2724
2725 if (!PyArg_ParseTuple(args,
2726 "O&:append",
2727 _getbytevalue, &item))
2728 goto exit;
2729 return_value = bytearray_append_impl(self, item);
2730
2731exit:
2732 return return_value;
2733}
2734
2735static PyObject *
2736bytearray_append_impl(PyByteArrayObject *self, int item)
2737/*[clinic end generated code: output=b5b3325bb3bbaf85 input=ae56ea87380407cc]*/
2738{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002739 Py_ssize_t n = Py_SIZE(self);
2740
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002741 if (n == PY_SSIZE_T_MAX) {
2742 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002743 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002744 return NULL;
2745 }
2746 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2747 return NULL;
2748
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002749 PyByteArray_AS_STRING(self)[n] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002750
2751 Py_RETURN_NONE;
2752}
2753
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002754/*[clinic input]
2755bytearray.extend
2756
2757 self: self(type="PyByteArrayObject *")
2758 iterable_of_ints: object
2759 The iterable of items to append.
2760 /
2761
2762Append all the items from the iterator or sequence to the end of the bytearray.
2763[clinic start generated code]*/
2764
2765PyDoc_STRVAR(bytearray_extend__doc__,
2766"extend($self, iterable_of_ints, /)\n"
2767"--\n"
2768"\n"
2769"Append all the items from the iterator or sequence to the end of the bytearray.\n"
2770"\n"
2771" iterable_of_ints\n"
2772" The iterable of items to append.");
2773
2774#define BYTEARRAY_EXTEND_METHODDEF \
2775 {"extend", (PyCFunction)bytearray_extend, METH_O, bytearray_extend__doc__},
2776
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002777static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002778bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
2779/*[clinic end generated code: output=13b0c13ad5110dfb input=ce83a5d75b70d850]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002780{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002781 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002782 Py_ssize_t buf_size = 0, len = 0;
2783 int value;
2784 char *buf;
2785
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002786 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002787 if (PyObject_CheckBuffer(iterable_of_ints)) {
2788 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002789 return NULL;
2790
2791 Py_RETURN_NONE;
2792 }
2793
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002794 it = PyObject_GetIter(iterable_of_ints);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002795 if (it == NULL)
2796 return NULL;
2797
Ezio Melotti42da6632011-03-15 05:18:48 +02002798 /* Try to determine the length of the argument. 32 is arbitrary. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002799 buf_size = PyObject_LengthHint(iterable_of_ints, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002800 if (buf_size == -1) {
2801 Py_DECREF(it);
2802 return NULL;
2803 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002804
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002805 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002806 if (bytearray_obj == NULL) {
2807 Py_DECREF(it);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002808 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002809 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002810 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002811
2812 while ((item = PyIter_Next(it)) != NULL) {
2813 if (! _getbytevalue(item, &value)) {
2814 Py_DECREF(item);
2815 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002816 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002817 return NULL;
2818 }
2819 buf[len++] = value;
2820 Py_DECREF(item);
2821
2822 if (len >= buf_size) {
2823 buf_size = len + (len >> 1) + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002824 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002825 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002826 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002827 return NULL;
2828 }
2829 /* Recompute the `buf' pointer, since the resizing operation may
2830 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002831 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002832 }
2833 }
2834 Py_DECREF(it);
2835
2836 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002837 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
2838 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002839 return NULL;
2840 }
2841
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002842 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
2843 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002844 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002845 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002846 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002847
2848 Py_RETURN_NONE;
2849}
2850
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002851/*[clinic input]
2852bytearray.pop
2853
2854 self: self(type="PyByteArrayObject *")
2855 index: Py_ssize_t = -1
2856 The index from where to remove the item.
2857 -1 (the default value) means remove the last item.
2858 /
2859
2860Remove and return a single item from B.
2861
2862If no index argument is given, will pop the last item.
2863[clinic start generated code]*/
2864
2865PyDoc_STRVAR(bytearray_pop__doc__,
2866"pop($self, index=-1, /)\n"
2867"--\n"
2868"\n"
2869"Remove and return a single item from B.\n"
2870"\n"
2871" index\n"
2872" The index from where to remove the item.\n"
2873" -1 (the default value) means remove the last item.\n"
2874"\n"
2875"If no index argument is given, will pop the last item.");
2876
2877#define BYTEARRAY_POP_METHODDEF \
2878 {"pop", (PyCFunction)bytearray_pop, METH_VARARGS, bytearray_pop__doc__},
2879
2880static PyObject *
2881bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index);
2882
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002883static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002884bytearray_pop(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002885{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002886 PyObject *return_value = NULL;
2887 Py_ssize_t index = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002888
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002889 if (!PyArg_ParseTuple(args,
2890 "|n:pop",
2891 &index))
2892 goto exit;
2893 return_value = bytearray_pop_impl(self, index);
2894
2895exit:
2896 return return_value;
2897}
2898
2899static PyObject *
2900bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
2901/*[clinic end generated code: output=3b763e548e79af96 input=0797e6c0ca9d5a85]*/
2902{
2903 int value;
2904 Py_ssize_t n = Py_SIZE(self);
2905 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002906
2907 if (n == 0) {
Eli Bendersky1bc4f192011-03-04 04:55:25 +00002908 PyErr_SetString(PyExc_IndexError,
2909 "pop from empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002910 return NULL;
2911 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002912 if (index < 0)
2913 index += Py_SIZE(self);
2914 if (index < 0 || index >= Py_SIZE(self)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002915 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2916 return NULL;
2917 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002918 if (!_canresize(self))
2919 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002920
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002921 buf = PyByteArray_AS_STRING(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002922 value = buf[index];
2923 memmove(buf + index, buf + index + 1, n - index);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002924 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2925 return NULL;
2926
Mark Dickinson54a3db92009-09-06 10:19:23 +00002927 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002928}
2929
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002930/*[clinic input]
2931bytearray.remove
2932
2933 self: self(type="PyByteArrayObject *")
2934 value: bytesvalue
2935 The value to remove.
2936 /
2937
2938Remove the first occurrence of a value in the bytearray.
2939[clinic start generated code]*/
2940
2941PyDoc_STRVAR(bytearray_remove__doc__,
2942"remove($self, value, /)\n"
2943"--\n"
2944"\n"
2945"Remove the first occurrence of a value in the bytearray.\n"
2946"\n"
2947" value\n"
2948" The value to remove.");
2949
2950#define BYTEARRAY_REMOVE_METHODDEF \
2951 {"remove", (PyCFunction)bytearray_remove, METH_VARARGS, bytearray_remove__doc__},
2952
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002953static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002954bytearray_remove_impl(PyByteArrayObject *self, int value);
2955
2956static PyObject *
2957bytearray_remove(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002958{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002959 PyObject *return_value = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002960 int value;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002961
2962 if (!PyArg_ParseTuple(args,
2963 "O&:remove",
2964 _getbytevalue, &value))
2965 goto exit;
2966 return_value = bytearray_remove_impl(self, value);
2967
2968exit:
2969 return return_value;
2970}
2971
2972static PyObject *
2973bytearray_remove_impl(PyByteArrayObject *self, int value)
2974/*[clinic end generated code: output=c71c8bcf4703abfc input=47560b11fd856c24]*/
2975{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002976 Py_ssize_t where, n = Py_SIZE(self);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002977 char *buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002978
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002979 for (where = 0; where < n; where++) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002980 if (buf[where] == value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002981 break;
2982 }
2983 if (where == n) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002984 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002985 return NULL;
2986 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002987 if (!_canresize(self))
2988 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002989
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002990 memmove(buf + where, buf + where + 1, n - where);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002991 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2992 return NULL;
2993
2994 Py_RETURN_NONE;
2995}
2996
2997/* XXX These two helpers could be optimized if argsize == 1 */
2998
2999static Py_ssize_t
Antoine Pitrou5b720752013-10-05 21:24:10 +02003000lstrip_helper(char *myptr, Py_ssize_t mysize,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003001 void *argptr, Py_ssize_t argsize)
3002{
3003 Py_ssize_t i = 0;
Antoine Pitrou5b720752013-10-05 21:24:10 +02003004 while (i < mysize && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003005 i++;
3006 return i;
3007}
3008
3009static Py_ssize_t
Antoine Pitrou5b720752013-10-05 21:24:10 +02003010rstrip_helper(char *myptr, Py_ssize_t mysize,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003011 void *argptr, Py_ssize_t argsize)
3012{
3013 Py_ssize_t i = mysize - 1;
Antoine Pitrou5b720752013-10-05 21:24:10 +02003014 while (i >= 0 && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003015 i--;
3016 return i + 1;
3017}
3018
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003019/*[clinic input]
3020bytearray.strip
3021
3022 bytes: object = None
3023 /
3024
3025Strip leading and trailing bytes contained in the argument.
3026
3027If the argument is omitted or None, strip leading and trailing ASCII whitespace.
3028[clinic start generated code]*/
3029
3030PyDoc_STRVAR(bytearray_strip__doc__,
3031"strip($self, bytes=None, /)\n"
3032"--\n"
3033"\n"
3034"Strip leading and trailing bytes contained in the argument.\n"
3035"\n"
3036"If the argument is omitted or None, strip leading and trailing ASCII whitespace.");
3037
3038#define BYTEARRAY_STRIP_METHODDEF \
3039 {"strip", (PyCFunction)bytearray_strip, METH_VARARGS, bytearray_strip__doc__},
3040
3041static PyObject *
3042bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes);
3043
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003044static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003045bytearray_strip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003046{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003047 PyObject *return_value = NULL;
3048 PyObject *bytes = Py_None;
3049
3050 if (!PyArg_UnpackTuple(args, "strip",
3051 0, 1,
3052 &bytes))
3053 goto exit;
3054 return_value = bytearray_strip_impl(self, bytes);
3055
3056exit:
3057 return return_value;
3058}
3059
3060static PyObject *
3061bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
3062/*[clinic end generated code: output=2e3d3358acc4c235 input=ef7bb59b09c21d62]*/
3063{
3064 Py_ssize_t left, right, mysize, byteslen;
3065 char *myptr, *bytesptr;
3066 Py_buffer vbytes;
3067
3068 if (bytes == Py_None) {
3069 bytesptr = "\t\n\r\f\v ";
3070 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003071 }
3072 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02003073 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003074 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003075 bytesptr = (char *) vbytes.buf;
3076 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003077 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003078 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003079 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003080 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003081 if (left == mysize)
3082 right = left;
3083 else
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003084 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
3085 if (bytes != Py_None)
3086 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003087 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003088}
3089
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003090/*[clinic input]
3091bytearray.lstrip
3092
3093 bytes: object = None
3094 /
3095
3096Strip leading bytes contained in the argument.
3097
3098If the argument is omitted or None, strip leading ASCII whitespace.
3099[clinic start generated code]*/
3100
3101PyDoc_STRVAR(bytearray_lstrip__doc__,
3102"lstrip($self, bytes=None, /)\n"
3103"--\n"
3104"\n"
3105"Strip leading bytes contained in the argument.\n"
3106"\n"
3107"If the argument is omitted or None, strip leading ASCII whitespace.");
3108
3109#define BYTEARRAY_LSTRIP_METHODDEF \
3110 {"lstrip", (PyCFunction)bytearray_lstrip, METH_VARARGS, bytearray_lstrip__doc__},
3111
3112static PyObject *
3113bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes);
3114
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003115static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003116bytearray_lstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003117{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003118 PyObject *return_value = NULL;
3119 PyObject *bytes = Py_None;
3120
3121 if (!PyArg_UnpackTuple(args, "lstrip",
3122 0, 1,
3123 &bytes))
3124 goto exit;
3125 return_value = bytearray_lstrip_impl(self, bytes);
3126
3127exit:
3128 return return_value;
3129}
3130
3131static PyObject *
3132bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
3133/*[clinic end generated code: output=2599309808a9ec02 input=80843f975dd7c480]*/
3134{
3135 Py_ssize_t left, right, mysize, byteslen;
3136 char *myptr, *bytesptr;
3137 Py_buffer vbytes;
3138
3139 if (bytes == Py_None) {
3140 bytesptr = "\t\n\r\f\v ";
3141 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003142 }
3143 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02003144 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003145 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003146 bytesptr = (char *) vbytes.buf;
3147 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003148 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003149 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003150 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003151 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003152 right = mysize;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003153 if (bytes != Py_None)
3154 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003155 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003156}
3157
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003158/*[clinic input]
3159bytearray.rstrip
3160
3161 bytes: object = None
3162 /
3163
3164Strip trailing bytes contained in the argument.
3165
3166If the argument is omitted or None, strip trailing ASCII whitespace.
3167[clinic start generated code]*/
3168
3169PyDoc_STRVAR(bytearray_rstrip__doc__,
3170"rstrip($self, bytes=None, /)\n"
3171"--\n"
3172"\n"
3173"Strip trailing bytes contained in the argument.\n"
3174"\n"
3175"If the argument is omitted or None, strip trailing ASCII whitespace.");
3176
3177#define BYTEARRAY_RSTRIP_METHODDEF \
3178 {"rstrip", (PyCFunction)bytearray_rstrip, METH_VARARGS, bytearray_rstrip__doc__},
3179
3180static PyObject *
3181bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes);
3182
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003183static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003184bytearray_rstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003185{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003186 PyObject *return_value = NULL;
3187 PyObject *bytes = Py_None;
3188
3189 if (!PyArg_UnpackTuple(args, "rstrip",
3190 0, 1,
3191 &bytes))
3192 goto exit;
3193 return_value = bytearray_rstrip_impl(self, bytes);
3194
3195exit:
3196 return return_value;
3197}
3198
3199static PyObject *
3200bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
3201/*[clinic end generated code: output=b5ca6259f4f4f2a3 input=e728b994954cfd91]*/
3202{
3203 Py_ssize_t right, mysize, byteslen;
3204 char *myptr, *bytesptr;
3205 Py_buffer vbytes;
3206
3207 if (bytes == Py_None) {
3208 bytesptr = "\t\n\r\f\v ";
3209 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003210 }
3211 else {
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02003212 if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003213 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003214 bytesptr = (char *) vbytes.buf;
3215 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003216 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003217 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003218 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003219 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
3220 if (bytes != Py_None)
3221 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003222 return PyByteArray_FromStringAndSize(myptr, right);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003223}
3224
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003225/*[clinic input]
3226bytearray.decode
3227
3228 encoding: str(c_default="NULL") = 'utf-8'
3229 The encoding with which to decode the bytearray.
3230 errors: str(c_default="NULL") = 'strict'
3231 The error handling scheme to use for the handling of decoding errors.
3232 The default is 'strict' meaning that decoding errors raise a
3233 UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
3234 as well as any other name registered with codecs.register_error that
3235 can handle UnicodeDecodeErrors.
3236
3237Decode the bytearray using the codec registered for encoding.
3238[clinic start generated code]*/
3239
3240PyDoc_STRVAR(bytearray_decode__doc__,
3241"decode($self, /, encoding=\'utf-8\', errors=\'strict\')\n"
3242"--\n"
3243"\n"
3244"Decode the bytearray using the codec registered for encoding.\n"
3245"\n"
3246" encoding\n"
3247" The encoding with which to decode the bytearray.\n"
3248" errors\n"
3249" The error handling scheme to use for the handling of decoding errors.\n"
3250" The default is \'strict\' meaning that decoding errors raise a\n"
3251" UnicodeDecodeError. Other possible values are \'ignore\' and \'replace\'\n"
3252" as well as any other name registered with codecs.register_error that\n"
3253" can handle UnicodeDecodeErrors.");
3254
3255#define BYTEARRAY_DECODE_METHODDEF \
3256 {"decode", (PyCFunction)bytearray_decode, METH_VARARGS|METH_KEYWORDS, bytearray_decode__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003257
3258static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003259bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors);
3260
3261static PyObject *
3262bytearray_decode(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003263{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003264 PyObject *return_value = NULL;
3265 static char *_keywords[] = {"encoding", "errors", NULL};
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003266 const char *encoding = NULL;
3267 const char *errors = NULL;
3268
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003269 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
3270 "|ss:decode", _keywords,
3271 &encoding, &errors))
3272 goto exit;
3273 return_value = bytearray_decode_impl(self, encoding, errors);
3274
3275exit:
3276 return return_value;
3277}
3278
3279static PyObject *
3280bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors)
3281/*[clinic end generated code: output=38b83681f1e38a6c input=f28d8f903020257b]*/
3282{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003283 if (encoding == NULL)
3284 encoding = PyUnicode_GetDefaultEncoding();
Martin v. Löwis0efea322014-07-27 17:29:17 +02003285 return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003286}
3287
3288PyDoc_STRVAR(alloc_doc,
3289"B.__alloc__() -> int\n\
3290\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00003291Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003292
3293static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003294bytearray_alloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003295{
3296 return PyLong_FromSsize_t(self->ob_alloc);
3297}
3298
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003299/*[clinic input]
3300bytearray.join
3301
3302 iterable_of_bytes: object
3303 /
3304
3305Concatenate any number of bytes/bytearray objects.
3306
3307The bytearray whose method is called is inserted in between each pair.
3308
3309The result is returned as a new bytearray object.
3310[clinic start generated code]*/
3311
3312PyDoc_STRVAR(bytearray_join__doc__,
3313"join($self, iterable_of_bytes, /)\n"
3314"--\n"
3315"\n"
3316"Concatenate any number of bytes/bytearray objects.\n"
3317"\n"
3318"The bytearray whose method is called is inserted in between each pair.\n"
3319"\n"
3320"The result is returned as a new bytearray object.");
3321
3322#define BYTEARRAY_JOIN_METHODDEF \
3323 {"join", (PyCFunction)bytearray_join, METH_O, bytearray_join__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003324
3325static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003326bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes)
3327/*[clinic end generated code: output=544e7430032dfdf4 input=aba6b1f9b30fcb8e]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003328{
Martin v. Löwis0efea322014-07-27 17:29:17 +02003329 return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003330}
3331
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003332/*[clinic input]
3333bytearray.splitlines
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003334
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003335 keepends: int(py_default="False") = 0
3336
3337Return a list of the lines in the bytearray, breaking at line boundaries.
3338
3339Line breaks are not included in the resulting list unless keepends is given and
3340true.
3341[clinic start generated code]*/
3342
3343PyDoc_STRVAR(bytearray_splitlines__doc__,
3344"splitlines($self, /, keepends=False)\n"
3345"--\n"
3346"\n"
3347"Return a list of the lines in the bytearray, breaking at line boundaries.\n"
3348"\n"
3349"Line breaks are not included in the resulting list unless keepends is given and\n"
3350"true.");
3351
3352#define BYTEARRAY_SPLITLINES_METHODDEF \
3353 {"splitlines", (PyCFunction)bytearray_splitlines, METH_VARARGS|METH_KEYWORDS, bytearray_splitlines__doc__},
3354
3355static PyObject *
3356bytearray_splitlines_impl(PyByteArrayObject *self, int keepends);
3357
3358static PyObject *
3359bytearray_splitlines(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003360{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003361 PyObject *return_value = NULL;
3362 static char *_keywords[] = {"keepends", NULL};
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003363 int keepends = 0;
3364
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003365 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
3366 "|i:splitlines", _keywords,
3367 &keepends))
3368 goto exit;
3369 return_value = bytearray_splitlines_impl(self, keepends);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003370
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003371exit:
3372 return return_value;
3373}
3374
3375static PyObject *
3376bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
3377/*[clinic end generated code: output=a837fd0512ad46ff input=36f0b25bc792f6c0]*/
3378{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003379 return stringlib_splitlines(
3380 (PyObject*) self, PyByteArray_AS_STRING(self),
3381 PyByteArray_GET_SIZE(self), keepends
3382 );
3383}
3384
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003385static int
Victor Stinner6430fd52011-09-29 04:02:13 +02003386hex_digit_to_int(Py_UCS4 c)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003387{
3388 if (c >= 128)
3389 return -1;
Eric Smith6dc46f52009-04-27 20:39:49 +00003390 if (Py_ISDIGIT(c))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003391 return c - '0';
3392 else {
Eric Smith6dc46f52009-04-27 20:39:49 +00003393 if (Py_ISUPPER(c))
3394 c = Py_TOLOWER(c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003395 if (c >= 'a' && c <= 'f')
3396 return c - 'a' + 10;
3397 }
3398 return -1;
3399}
3400
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003401/*[clinic input]
3402@classmethod
3403bytearray.fromhex
3404
3405 cls: self(type="PyObject*")
3406 string: unicode
3407 /
3408
3409Create a bytearray object from a string of hexadecimal numbers.
3410
3411Spaces between two numbers are accepted.
3412Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
3413[clinic start generated code]*/
3414
3415PyDoc_STRVAR(bytearray_fromhex__doc__,
3416"fromhex($type, string, /)\n"
3417"--\n"
3418"\n"
3419"Create a bytearray object from a string of hexadecimal numbers.\n"
3420"\n"
3421"Spaces between two numbers are accepted.\n"
3422"Example: bytearray.fromhex(\'B9 01EF\') -> bytearray(b\'\\\\xb9\\\\x01\\\\xef\')");
3423
3424#define BYTEARRAY_FROMHEX_METHODDEF \
3425 {"fromhex", (PyCFunction)bytearray_fromhex, METH_VARARGS|METH_CLASS, bytearray_fromhex__doc__},
3426
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003427static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003428bytearray_fromhex_impl(PyObject*cls, PyObject *string);
3429
3430static PyObject *
3431bytearray_fromhex(PyTypeObject *cls, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003432{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003433 PyObject *return_value = NULL;
3434 PyObject *string;
3435
3436 if (!PyArg_ParseTuple(args,
3437 "U:fromhex",
3438 &string))
3439 goto exit;
3440 return_value = bytearray_fromhex_impl((PyObject*)cls, string);
3441
3442exit:
3443 return return_value;
3444}
3445
3446static PyObject *
3447bytearray_fromhex_impl(PyObject*cls, PyObject *string)
3448/*[clinic end generated code: output=adc3c804a74e56d4 input=907bbd2d34d9367a]*/
3449{
3450 PyObject *newbytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003451 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003452 Py_ssize_t hexlen, byteslen, i, j;
3453 int top, bot;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003454 void *data;
3455 unsigned int kind;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003456
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003457 assert(PyUnicode_Check(string));
3458 if (PyUnicode_READY(string))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003459 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003460 kind = PyUnicode_KIND(string);
3461 data = PyUnicode_DATA(string);
3462 hexlen = PyUnicode_GET_LENGTH(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003463
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003464 byteslen = hexlen/2; /* This overestimates if there are spaces */
3465 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
3466 if (!newbytes)
3467 return NULL;
3468 buf = PyByteArray_AS_STRING(newbytes);
3469 for (i = j = 0; i < hexlen; i += 2) {
3470 /* skip over spaces in the input */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003471 while (PyUnicode_READ(kind, data, i) == ' ')
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003472 i++;
3473 if (i >= hexlen)
3474 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003475 top = hex_digit_to_int(PyUnicode_READ(kind, data, i));
3476 bot = hex_digit_to_int(PyUnicode_READ(kind, data, i+1));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003477 if (top == -1 || bot == -1) {
3478 PyErr_Format(PyExc_ValueError,
3479 "non-hexadecimal number found in "
3480 "fromhex() arg at position %zd", i);
3481 goto error;
3482 }
3483 buf[j++] = (top << 4) + bot;
3484 }
3485 if (PyByteArray_Resize(newbytes, j) < 0)
3486 goto error;
3487 return newbytes;
3488
3489 error:
3490 Py_DECREF(newbytes);
3491 return NULL;
3492}
3493
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003494
3495static PyObject *
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003496_common_reduce(PyByteArrayObject *self, int proto)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003497{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003498 PyObject *dict;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003499 _Py_IDENTIFIER(__dict__);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003500 char *buf;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003501
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003502 dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003503 if (dict == NULL) {
3504 PyErr_Clear();
3505 dict = Py_None;
3506 Py_INCREF(dict);
3507 }
3508
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003509 buf = PyByteArray_AS_STRING(self);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003510 if (proto < 3) {
3511 /* use str based reduction for backwards compatibility with Python 2.x */
3512 PyObject *latin1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003513 if (Py_SIZE(self))
3514 latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003515 else
3516 latin1 = PyUnicode_FromString("");
3517 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
3518 }
3519 else {
3520 /* use more efficient byte based reduction */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003521 if (Py_SIZE(self)) {
3522 return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), dict);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003523 }
3524 else {
3525 return Py_BuildValue("(O()N)", Py_TYPE(self), dict);
3526 }
3527 }
3528}
3529
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003530/*[clinic input]
3531bytearray.__reduce__ as bytearray_reduce
3532
3533 self: self(type="PyByteArrayObject *")
3534
3535Return state information for pickling.
3536[clinic start generated code]*/
3537
3538PyDoc_STRVAR(bytearray_reduce__doc__,
3539"__reduce__($self, /)\n"
3540"--\n"
3541"\n"
3542"Return state information for pickling.");
3543
3544#define BYTEARRAY_REDUCE_METHODDEF \
3545 {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, bytearray_reduce__doc__},
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003546
3547static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003548bytearray_reduce_impl(PyByteArrayObject *self);
3549
3550static PyObject *
3551bytearray_reduce(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
3552{
3553 return bytearray_reduce_impl(self);
3554}
3555
3556static PyObject *
3557bytearray_reduce_impl(PyByteArrayObject *self)
3558/*[clinic end generated code: output=b1b56fe87bf30fb0 input=fbb07de4d102a03a]*/
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003559{
3560 return _common_reduce(self, 2);
3561}
3562
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003563/*[clinic input]
3564bytearray.__reduce_ex__ as bytearray_reduce_ex
3565
3566 self: self(type="PyByteArrayObject *")
3567 proto: int = 0
3568 /
3569
3570Return state information for pickling.
3571[clinic start generated code]*/
3572
3573PyDoc_STRVAR(bytearray_reduce_ex__doc__,
3574"__reduce_ex__($self, proto=0, /)\n"
3575"--\n"
3576"\n"
3577"Return state information for pickling.");
3578
3579#define BYTEARRAY_REDUCE_EX_METHODDEF \
3580 {"__reduce_ex__", (PyCFunction)bytearray_reduce_ex, METH_VARARGS, bytearray_reduce_ex__doc__},
3581
3582static PyObject *
3583bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003584
3585static PyObject *
3586bytearray_reduce_ex(PyByteArrayObject *self, PyObject *args)
3587{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003588 PyObject *return_value = NULL;
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003589 int proto = 0;
3590
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003591 if (!PyArg_ParseTuple(args,
3592 "|i:__reduce_ex__",
3593 &proto))
3594 goto exit;
3595 return_value = bytearray_reduce_ex_impl(self, proto);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003596
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003597exit:
3598 return return_value;
3599}
3600
3601static PyObject *
3602bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
3603/*[clinic end generated code: output=bbd9afb2f5953dc1 input=0e091a42ca6dbd91]*/
3604{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003605 return _common_reduce(self, proto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003606}
3607
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003608/*[clinic input]
3609bytearray.__sizeof__ as bytearray_sizeof
3610
3611 self: self(type="PyByteArrayObject *")
3612
3613Returns the size of the bytearray object in memory, in bytes.
3614[clinic start generated code]*/
3615
3616PyDoc_STRVAR(bytearray_sizeof__doc__,
3617"__sizeof__($self, /)\n"
3618"--\n"
3619"\n"
3620"Returns the size of the bytearray object in memory, in bytes.");
3621
3622#define BYTEARRAY_SIZEOF_METHODDEF \
3623 {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, bytearray_sizeof__doc__},
3624
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003625static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003626bytearray_sizeof_impl(PyByteArrayObject *self);
3627
3628static PyObject *
3629bytearray_sizeof(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
3630{
3631 return bytearray_sizeof_impl(self);
3632}
3633
3634static PyObject *
3635bytearray_sizeof_impl(PyByteArrayObject *self)
3636/*[clinic end generated code: output=4a2254b0a85630c6 input=6b23d305362b462b]*/
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003637{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00003638 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003639
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00003640 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
3641 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003642}
3643
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003644static PySequenceMethods bytearray_as_sequence = {
3645 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003646 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003647 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
3648 (ssizeargfunc)bytearray_getitem, /* sq_item */
3649 0, /* sq_slice */
3650 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
3651 0, /* sq_ass_slice */
3652 (objobjproc)bytearray_contains, /* sq_contains */
3653 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
3654 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003655};
3656
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003657static PyMappingMethods bytearray_as_mapping = {
3658 (lenfunc)bytearray_length,
3659 (binaryfunc)bytearray_subscript,
3660 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003661};
3662
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003663static PyBufferProcs bytearray_as_buffer = {
3664 (getbufferproc)bytearray_getbuffer,
3665 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003666};
3667
3668static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003669bytearray_methods[] = {
3670 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003671 BYTEARRAY_REDUCE_METHODDEF
3672 BYTEARRAY_REDUCE_EX_METHODDEF
3673 BYTEARRAY_SIZEOF_METHODDEF
3674 BYTEARRAY_APPEND_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003675 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
3676 _Py_capitalize__doc__},
3677 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003678 BYTEARRAY_CLEAR_METHODDEF
3679 BYTEARRAY_COPY_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003680 {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003681 BYTEARRAY_DECODE_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003682 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +02003683 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS | METH_KEYWORDS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003684 expandtabs__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003685 BYTEARRAY_EXTEND_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003686 {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003687 BYTEARRAY_FROMHEX_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003688 {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003689 BYTEARRAY_INSERT_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003690 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
3691 _Py_isalnum__doc__},
3692 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
3693 _Py_isalpha__doc__},
3694 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
3695 _Py_isdigit__doc__},
3696 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
3697 _Py_islower__doc__},
3698 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
3699 _Py_isspace__doc__},
3700 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
3701 _Py_istitle__doc__},
3702 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
3703 _Py_isupper__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003704 BYTEARRAY_JOIN_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003705 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
3706 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003707 BYTEARRAY_LSTRIP_METHODDEF
3708 BYTEARRAY_MAKETRANS_METHODDEF
3709 BYTEARRAY_PARTITION_METHODDEF
3710 BYTEARRAY_POP_METHODDEF
3711 BYTEARRAY_REMOVE_METHODDEF
3712 BYTEARRAY_REPLACE_METHODDEF
3713 BYTEARRAY_REVERSE_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003714 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
3715 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003716 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003717 BYTEARRAY_RPARTITION_METHODDEF
3718 BYTEARRAY_RSPLIT_METHODDEF
3719 BYTEARRAY_RSTRIP_METHODDEF
3720 BYTEARRAY_SPLIT_METHODDEF
3721 BYTEARRAY_SPLITLINES_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003722 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003723 startswith__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003724 BYTEARRAY_STRIP_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003725 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
3726 _Py_swapcase__doc__},
3727 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003728 BYTEARRAY_TRANSLATE_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003729 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
3730 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
3731 {NULL}
3732};
3733
Ethan Furmanb95b5612015-01-23 20:05:18 -08003734static PyObject *
3735bytearray_mod(PyObject *v, PyObject *w)
3736{
3737 if (!PyByteArray_Check(v))
3738 Py_RETURN_NOTIMPLEMENTED;
3739 return bytearray_format((PyByteArrayObject *)v, w);
3740}
3741
3742static PyNumberMethods bytearray_as_number = {
3743 0, /*nb_add*/
3744 0, /*nb_subtract*/
3745 0, /*nb_multiply*/
3746 bytearray_mod, /*nb_remainder*/
3747};
3748
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003749PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00003750"bytearray(iterable_of_ints) -> bytearray\n\
3751bytearray(string, encoding[, errors]) -> bytearray\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003752bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
3753bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
3754bytearray() -> empty bytes array\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003755\n\
3756Construct an mutable bytearray object from:\n\
3757 - an iterable yielding integers in range(256)\n\
3758 - a text string encoded using the specified encoding\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003759 - a bytes or a buffer object\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003760 - any object implementing the buffer API.\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003761 - an integer");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003762
3763
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003764static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003765
3766PyTypeObject PyByteArray_Type = {
3767 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3768 "bytearray",
3769 sizeof(PyByteArrayObject),
3770 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003771 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003772 0, /* tp_print */
3773 0, /* tp_getattr */
3774 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003775 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003776 (reprfunc)bytearray_repr, /* tp_repr */
Ethan Furmanb95b5612015-01-23 20:05:18 -08003777 &bytearray_as_number, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003778 &bytearray_as_sequence, /* tp_as_sequence */
3779 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003780 0, /* tp_hash */
3781 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003782 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003783 PyObject_GenericGetAttr, /* tp_getattro */
3784 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003785 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003786 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003787 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003788 0, /* tp_traverse */
3789 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003790 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003791 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003792 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003793 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003794 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003795 0, /* tp_members */
3796 0, /* tp_getset */
3797 0, /* tp_base */
3798 0, /* tp_dict */
3799 0, /* tp_descr_get */
3800 0, /* tp_descr_set */
3801 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003802 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003803 PyType_GenericAlloc, /* tp_alloc */
3804 PyType_GenericNew, /* tp_new */
3805 PyObject_Del, /* tp_free */
3806};
3807
3808/*********************** Bytes Iterator ****************************/
3809
3810typedef struct {
3811 PyObject_HEAD
3812 Py_ssize_t it_index;
3813 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
3814} bytesiterobject;
3815
3816static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003817bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003818{
3819 _PyObject_GC_UNTRACK(it);
3820 Py_XDECREF(it->it_seq);
3821 PyObject_GC_Del(it);
3822}
3823
3824static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003825bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003826{
3827 Py_VISIT(it->it_seq);
3828 return 0;
3829}
3830
3831static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003832bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003833{
3834 PyByteArrayObject *seq;
3835 PyObject *item;
3836
3837 assert(it != NULL);
3838 seq = it->it_seq;
3839 if (seq == NULL)
3840 return NULL;
3841 assert(PyByteArray_Check(seq));
3842
3843 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
3844 item = PyLong_FromLong(
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003845 (unsigned char)PyByteArray_AS_STRING(seq)[it->it_index]);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003846 if (item != NULL)
3847 ++it->it_index;
3848 return item;
3849 }
3850
3851 Py_DECREF(seq);
3852 it->it_seq = NULL;
3853 return NULL;
3854}
3855
3856static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003857bytearrayiter_length_hint(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003858{
3859 Py_ssize_t len = 0;
3860 if (it->it_seq)
3861 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
3862 return PyLong_FromSsize_t(len);
3863}
3864
3865PyDoc_STRVAR(length_hint_doc,
3866 "Private method returning an estimate of len(list(it)).");
3867
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003868static PyObject *
3869bytearrayiter_reduce(bytesiterobject *it)
3870{
3871 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +02003872 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003873 it->it_seq, it->it_index);
3874 } else {
3875 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
3876 if (u == NULL)
3877 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02003878 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003879 }
3880}
3881
3882static PyObject *
3883bytearrayiter_setstate(bytesiterobject *it, PyObject *state)
3884{
3885 Py_ssize_t index = PyLong_AsSsize_t(state);
3886 if (index == -1 && PyErr_Occurred())
3887 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00003888 if (it->it_seq != NULL) {
3889 if (index < 0)
3890 index = 0;
3891 else if (index > PyByteArray_GET_SIZE(it->it_seq))
3892 index = PyByteArray_GET_SIZE(it->it_seq); /* iterator exhausted */
3893 it->it_index = index;
3894 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003895 Py_RETURN_NONE;
3896}
3897
3898PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
3899
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003900static PyMethodDef bytearrayiter_methods[] = {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003901 {"__length_hint__", (PyCFunction)bytearrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003902 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003903 {"__reduce__", (PyCFunction)bytearrayiter_reduce, METH_NOARGS,
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003904 bytearray_reduce__doc__},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003905 {"__setstate__", (PyCFunction)bytearrayiter_setstate, METH_O,
3906 setstate_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003907 {NULL, NULL} /* sentinel */
3908};
3909
3910PyTypeObject PyByteArrayIter_Type = {
3911 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3912 "bytearray_iterator", /* tp_name */
3913 sizeof(bytesiterobject), /* tp_basicsize */
3914 0, /* tp_itemsize */
3915 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003916 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003917 0, /* tp_print */
3918 0, /* tp_getattr */
3919 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003920 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003921 0, /* tp_repr */
3922 0, /* tp_as_number */
3923 0, /* tp_as_sequence */
3924 0, /* tp_as_mapping */
3925 0, /* tp_hash */
3926 0, /* tp_call */
3927 0, /* tp_str */
3928 PyObject_GenericGetAttr, /* tp_getattro */
3929 0, /* tp_setattro */
3930 0, /* tp_as_buffer */
3931 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
3932 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003933 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003934 0, /* tp_clear */
3935 0, /* tp_richcompare */
3936 0, /* tp_weaklistoffset */
3937 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003938 (iternextfunc)bytearrayiter_next, /* tp_iternext */
3939 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003940 0,
3941};
3942
3943static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003944bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003945{
3946 bytesiterobject *it;
3947
3948 if (!PyByteArray_Check(seq)) {
3949 PyErr_BadInternalCall();
3950 return NULL;
3951 }
3952 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
3953 if (it == NULL)
3954 return NULL;
3955 it->it_index = 0;
3956 Py_INCREF(seq);
3957 it->it_seq = (PyByteArrayObject *)seq;
3958 _PyObject_GC_TRACK(it);
3959 return (PyObject *)it;
3960}