blob: 47d480f61782909ea2a808eb99f1b81bd91af216 [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"
7
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02008/*[clinic input]
9class bytearray "PyByteArrayObject *" "&PyByteArray_Type"
10[clinic start generated code]*/
11/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5535b77c37a119e0]*/
12
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000013char _PyByteArray_empty_string[] = "";
Christian Heimes2c9c7a52008-05-26 13:42:13 +000014
15void
16PyByteArray_Fini(void)
17{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000018}
19
20int
21PyByteArray_Init(void)
22{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000023 return 1;
24}
25
26/* end nullbytes support */
27
28/* Helpers */
29
30static int
31_getbytevalue(PyObject* arg, int *value)
32{
33 long face_value;
34
35 if (PyLong_Check(arg)) {
36 face_value = PyLong_AsLong(arg);
Georg Brandl9a54d7c2008-07-16 23:15:30 +000037 } else {
38 PyObject *index = PyNumber_Index(arg);
39 if (index == NULL) {
40 PyErr_Format(PyExc_TypeError, "an integer is required");
Mark Dickinson10de93a2010-07-09 19:25:48 +000041 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000042 return 0;
43 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +000044 face_value = PyLong_AsLong(index);
45 Py_DECREF(index);
46 }
47
48 if (face_value < 0 || face_value >= 256) {
49 /* this includes the OverflowError in case the long is too large */
50 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
Mark Dickinson10de93a2010-07-09 19:25:48 +000051 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000052 return 0;
53 }
54
55 *value = face_value;
56 return 1;
57}
58
59static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +000060bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000061{
62 int ret;
63 void *ptr;
64 if (view == NULL) {
65 obj->ob_exports++;
66 return 0;
67 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000068 ptr = (void *) PyByteArray_AS_STRING(obj);
Martin v. Löwis423be952008-08-13 15:53:07 +000069 ret = PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
Christian Heimes2c9c7a52008-05-26 13:42:13 +000070 if (ret >= 0) {
71 obj->ob_exports++;
72 }
73 return ret;
74}
75
76static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +000077bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000078{
79 obj->ob_exports--;
80}
81
82static Py_ssize_t
83_getbuffer(PyObject *obj, Py_buffer *view)
84{
85 PyBufferProcs *buffer = Py_TYPE(obj)->tp_as_buffer;
86
87 if (buffer == NULL || buffer->bf_getbuffer == NULL)
88 {
89 PyErr_Format(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -040090 "a bytes-like object is required, not '%.100s'",
Christian Heimes2c9c7a52008-05-26 13:42:13 +000091 Py_TYPE(obj)->tp_name);
92 return -1;
93 }
94
95 if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0)
96 return -1;
97 return view->len;
98}
99
Antoine Pitrou5504e892008-12-06 21:27:53 +0000100static int
101_canresize(PyByteArrayObject *self)
102{
103 if (self->ob_exports > 0) {
104 PyErr_SetString(PyExc_BufferError,
105 "Existing exports of data: object cannot be re-sized");
106 return 0;
107 }
108 return 1;
109}
110
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000111/* Direct API functions */
112
113PyObject *
114PyByteArray_FromObject(PyObject *input)
115{
116 return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
117 input, NULL);
118}
119
120PyObject *
121PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
122{
123 PyByteArrayObject *new;
124 Py_ssize_t alloc;
125
126 if (size < 0) {
127 PyErr_SetString(PyExc_SystemError,
128 "Negative size passed to PyByteArray_FromStringAndSize");
129 return NULL;
130 }
131
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000132 /* Prevent buffer overflow when setting alloc to size+1. */
133 if (size == PY_SSIZE_T_MAX) {
134 return PyErr_NoMemory();
135 }
136
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000137 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
138 if (new == NULL)
139 return NULL;
140
141 if (size == 0) {
142 new->ob_bytes = NULL;
143 alloc = 0;
144 }
145 else {
146 alloc = size + 1;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100147 new->ob_bytes = PyObject_Malloc(alloc);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000148 if (new->ob_bytes == NULL) {
149 Py_DECREF(new);
150 return PyErr_NoMemory();
151 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +0000152 if (bytes != NULL && size > 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000153 memcpy(new->ob_bytes, bytes, size);
154 new->ob_bytes[size] = '\0'; /* Trailing null byte */
155 }
156 Py_SIZE(new) = size;
157 new->ob_alloc = alloc;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200158 new->ob_start = new->ob_bytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000159 new->ob_exports = 0;
160
161 return (PyObject *)new;
162}
163
164Py_ssize_t
165PyByteArray_Size(PyObject *self)
166{
167 assert(self != NULL);
168 assert(PyByteArray_Check(self));
169
170 return PyByteArray_GET_SIZE(self);
171}
172
173char *
174PyByteArray_AsString(PyObject *self)
175{
176 assert(self != NULL);
177 assert(PyByteArray_Check(self));
178
179 return PyByteArray_AS_STRING(self);
180}
181
182int
Antoine Pitroucc231542014-11-02 18:40:09 +0100183PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000184{
185 void *sval;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200186 PyByteArrayObject *obj = ((PyByteArrayObject *)self);
Antoine Pitroucc231542014-11-02 18:40:09 +0100187 /* All computations are done unsigned to avoid integer overflows
188 (see issue #22335). */
189 size_t alloc = (size_t) obj->ob_alloc;
190 size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes);
191 size_t size = (size_t) requested_size;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000192
193 assert(self != NULL);
194 assert(PyByteArray_Check(self));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200195 assert(logical_offset <= alloc);
Antoine Pitroucc231542014-11-02 18:40:09 +0100196 assert(requested_size >= 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000197
Antoine Pitroucc231542014-11-02 18:40:09 +0100198 if (requested_size == Py_SIZE(self)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000199 return 0;
200 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200201 if (!_canresize(obj)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000202 return -1;
203 }
204
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200205 if (size + logical_offset + 1 < alloc) {
206 /* Current buffer is large enough to host the requested size,
207 decide on a strategy. */
208 if (size < alloc / 2) {
209 /* Major downsize; resize down to exact size */
210 alloc = size + 1;
211 }
212 else {
213 /* Minor downsize; quick exit */
214 Py_SIZE(self) = size;
215 PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */
216 return 0;
217 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000218 }
219 else {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200220 /* Need growing, decide on a strategy */
221 if (size <= alloc * 1.125) {
222 /* Moderate upsize; overallocate similar to list_resize() */
223 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
224 }
225 else {
226 /* Major upsize; resize up to exact size */
227 alloc = size + 1;
228 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000229 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100230 if (alloc > PY_SSIZE_T_MAX) {
231 PyErr_NoMemory();
232 return -1;
233 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000234
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200235 if (logical_offset > 0) {
236 sval = PyObject_Malloc(alloc);
237 if (sval == NULL) {
238 PyErr_NoMemory();
239 return -1;
240 }
Antoine Pitroucc231542014-11-02 18:40:09 +0100241 memcpy(sval, PyByteArray_AS_STRING(self),
242 Py_MIN(requested_size, Py_SIZE(self)));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200243 PyObject_Free(obj->ob_bytes);
244 }
245 else {
246 sval = PyObject_Realloc(obj->ob_bytes, alloc);
247 if (sval == NULL) {
248 PyErr_NoMemory();
249 return -1;
250 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000251 }
252
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200253 obj->ob_bytes = obj->ob_start = sval;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000254 Py_SIZE(self) = size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200255 obj->ob_alloc = alloc;
256 obj->ob_bytes[size] = '\0'; /* Trailing null byte */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000257
258 return 0;
259}
260
261PyObject *
262PyByteArray_Concat(PyObject *a, PyObject *b)
263{
264 Py_ssize_t size;
265 Py_buffer va, vb;
266 PyByteArrayObject *result = NULL;
267
268 va.len = -1;
269 vb.len = -1;
270 if (_getbuffer(a, &va) < 0 ||
271 _getbuffer(b, &vb) < 0) {
272 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
273 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
274 goto done;
275 }
276
277 size = va.len + vb.len;
278 if (size < 0) {
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000279 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000280 goto done;
281 }
282
283 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
284 if (result != NULL) {
285 memcpy(result->ob_bytes, va.buf, va.len);
286 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
287 }
288
289 done:
290 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000291 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000292 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000293 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000294 return (PyObject *)result;
295}
296
297/* Functions stuffed into the type object */
298
299static Py_ssize_t
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000300bytearray_length(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000301{
302 return Py_SIZE(self);
303}
304
305static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000306bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000307{
308 Py_ssize_t mysize;
309 Py_ssize_t size;
310 Py_buffer vo;
311
312 if (_getbuffer(other, &vo) < 0) {
313 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
314 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
315 return NULL;
316 }
317
318 mysize = Py_SIZE(self);
319 size = mysize + vo.len;
320 if (size < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000321 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000322 return PyErr_NoMemory();
323 }
324 if (size < self->ob_alloc) {
325 Py_SIZE(self) = size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200326 PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0'; /* Trailing null byte */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000327 }
328 else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000329 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000330 return NULL;
331 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200332 memcpy(PyByteArray_AS_STRING(self) + mysize, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000333 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000334 Py_INCREF(self);
335 return (PyObject *)self;
336}
337
338static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000339bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000340{
341 PyByteArrayObject *result;
342 Py_ssize_t mysize;
343 Py_ssize_t size;
344
345 if (count < 0)
346 count = 0;
347 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000348 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000349 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000350 size = mysize * count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000351 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
352 if (result != NULL && size != 0) {
353 if (mysize == 1)
354 memset(result->ob_bytes, self->ob_bytes[0], size);
355 else {
356 Py_ssize_t i;
357 for (i = 0; i < count; i++)
358 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
359 }
360 }
361 return (PyObject *)result;
362}
363
364static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000365bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000366{
367 Py_ssize_t mysize;
368 Py_ssize_t size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200369 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000370
371 if (count < 0)
372 count = 0;
373 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000374 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000375 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000376 size = mysize * count;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200377 if (PyByteArray_Resize((PyObject *)self, size) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000378 return NULL;
379
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200380 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000381 if (mysize == 1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200382 memset(buf, buf[0], size);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000383 else {
384 Py_ssize_t i;
385 for (i = 1; i < count; i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200386 memcpy(buf + i*mysize, buf, mysize);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000387 }
388
389 Py_INCREF(self);
390 return (PyObject *)self;
391}
392
393static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000394bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000395{
396 if (i < 0)
397 i += Py_SIZE(self);
398 if (i < 0 || i >= Py_SIZE(self)) {
399 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
400 return NULL;
401 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200402 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000403}
404
405static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000406bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000407{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000408 if (PyIndex_Check(index)) {
409 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000410
411 if (i == -1 && PyErr_Occurred())
412 return NULL;
413
414 if (i < 0)
415 i += PyByteArray_GET_SIZE(self);
416
417 if (i < 0 || i >= Py_SIZE(self)) {
418 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
419 return NULL;
420 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200421 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000422 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000423 else if (PySlice_Check(index)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000424 Py_ssize_t start, stop, step, slicelength, cur, i;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000425 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000426 PyByteArray_GET_SIZE(self),
427 &start, &stop, &step, &slicelength) < 0) {
428 return NULL;
429 }
430
431 if (slicelength <= 0)
432 return PyByteArray_FromStringAndSize("", 0);
433 else if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200434 return PyByteArray_FromStringAndSize(
435 PyByteArray_AS_STRING(self) + start, slicelength);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000436 }
437 else {
438 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000439 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000440 PyObject *result;
441
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000442 result = PyByteArray_FromStringAndSize(NULL, slicelength);
443 if (result == NULL)
444 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000445
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000446 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000447 for (cur = start, i = 0; i < slicelength;
448 cur += step, i++) {
449 result_buf[i] = source_buf[cur];
450 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000451 return result;
452 }
453 }
454 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400455 PyErr_Format(PyExc_TypeError,
456 "bytearray indices must be integers or slices, not %.200s",
457 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000458 return NULL;
459 }
460}
461
462static int
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200463bytearray_setslice_linear(PyByteArrayObject *self,
464 Py_ssize_t lo, Py_ssize_t hi,
465 char *bytes, Py_ssize_t bytes_len)
466{
467 Py_ssize_t avail = hi - lo;
468 char *buf = PyByteArray_AS_STRING(self);
469 Py_ssize_t growth = bytes_len - avail;
Victor Stinner84557232013-11-21 12:29:51 +0100470 int res = 0;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200471 assert(avail >= 0);
472
Victor Stinner84557232013-11-21 12:29:51 +0100473 if (growth < 0) {
474 if (!_canresize(self))
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200475 return -1;
Victor Stinner84557232013-11-21 12:29:51 +0100476
477 if (lo == 0) {
478 /* Shrink the buffer by advancing its logical start */
479 self->ob_start -= growth;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200480 /*
Victor Stinner84557232013-11-21 12:29:51 +0100481 0 lo hi old_size
482 | |<----avail----->|<-----tail------>|
483 | |<-bytes_len->|<-----tail------>|
484 0 new_lo new_hi new_size
485 */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200486 }
Victor Stinner84557232013-11-21 12:29:51 +0100487 else {
488 /*
489 0 lo hi old_size
490 | |<----avail----->|<-----tomove------>|
491 | |<-bytes_len->|<-----tomove------>|
492 0 lo new_hi new_size
493 */
494 memmove(buf + lo + bytes_len, buf + hi,
495 Py_SIZE(self) - hi);
496 }
497 if (PyByteArray_Resize((PyObject *)self,
498 Py_SIZE(self) + growth) < 0) {
499 /* Issue #19578: Handling the memory allocation failure here is
500 tricky here because the bytearray object has already been
501 modified. Depending on growth and lo, the behaviour is
502 different.
503
504 If growth < 0 and lo != 0, the operation is completed, but a
505 MemoryError is still raised and the memory block is not
506 shrinked. Otherwise, the bytearray is restored in its previous
507 state and a MemoryError is raised. */
508 if (lo == 0) {
509 self->ob_start += growth;
510 return -1;
511 }
512 /* memmove() removed bytes, the bytearray object cannot be
513 restored in its previous state. */
514 Py_SIZE(self) += growth;
515 res = -1;
516 }
517 buf = PyByteArray_AS_STRING(self);
518 }
519 else if (growth > 0) {
520 if (Py_SIZE(self) > (Py_ssize_t)PY_SSIZE_T_MAX - growth) {
521 PyErr_NoMemory();
522 return -1;
523 }
524
525 if (PyByteArray_Resize((PyObject *)self,
526 Py_SIZE(self) + growth) < 0) {
527 return -1;
528 }
529 buf = PyByteArray_AS_STRING(self);
530 /* Make the place for the additional bytes */
531 /*
532 0 lo hi old_size
533 | |<-avail->|<-----tomove------>|
534 | |<---bytes_len-->|<-----tomove------>|
535 0 lo new_hi new_size
536 */
537 memmove(buf + lo + bytes_len, buf + hi,
538 Py_SIZE(self) - lo - bytes_len);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200539 }
540
541 if (bytes_len > 0)
542 memcpy(buf + lo, bytes, bytes_len);
Victor Stinner84557232013-11-21 12:29:51 +0100543 return res;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200544}
545
546static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000547bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000548 PyObject *values)
549{
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200550 Py_ssize_t needed;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000551 void *bytes;
552 Py_buffer vbytes;
553 int res = 0;
554
555 vbytes.len = -1;
556 if (values == (PyObject *)self) {
557 /* Make a copy and call this function recursively */
558 int err;
559 values = PyByteArray_FromObject(values);
560 if (values == NULL)
561 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000562 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000563 Py_DECREF(values);
564 return err;
565 }
566 if (values == NULL) {
567 /* del b[lo:hi] */
568 bytes = NULL;
569 needed = 0;
570 }
571 else {
572 if (_getbuffer(values, &vbytes) < 0) {
573 PyErr_Format(PyExc_TypeError,
Georg Brandl3dbca812008-07-23 16:10:53 +0000574 "can't set bytearray slice from %.100s",
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000575 Py_TYPE(values)->tp_name);
576 return -1;
577 }
578 needed = vbytes.len;
579 bytes = vbytes.buf;
580 }
581
582 if (lo < 0)
583 lo = 0;
584 if (hi < lo)
585 hi = lo;
586 if (hi > Py_SIZE(self))
587 hi = Py_SIZE(self);
588
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200589 res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000590 if (vbytes.len != -1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200591 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000592 return res;
593}
594
595static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000596bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000597{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000598 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000599
600 if (i < 0)
601 i += Py_SIZE(self);
602
603 if (i < 0 || i >= Py_SIZE(self)) {
604 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
605 return -1;
606 }
607
608 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000609 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000610
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000611 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000612 return -1;
613
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200614 PyByteArray_AS_STRING(self)[i] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000615 return 0;
616}
617
618static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000619bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000620{
621 Py_ssize_t start, stop, step, slicelen, needed;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200622 char *buf, *bytes;
623 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000624
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000625 if (PyIndex_Check(index)) {
626 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000627
628 if (i == -1 && PyErr_Occurred())
629 return -1;
630
631 if (i < 0)
632 i += PyByteArray_GET_SIZE(self);
633
634 if (i < 0 || i >= Py_SIZE(self)) {
635 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
636 return -1;
637 }
638
639 if (values == NULL) {
640 /* Fall through to slice assignment */
641 start = i;
642 stop = i + 1;
643 step = 1;
644 slicelen = 1;
645 }
646 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000647 int ival;
648 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000649 return -1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200650 buf[i] = (char)ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000651 return 0;
652 }
653 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000654 else if (PySlice_Check(index)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000655 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000656 PyByteArray_GET_SIZE(self),
657 &start, &stop, &step, &slicelen) < 0) {
658 return -1;
659 }
660 }
661 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400662 PyErr_Format(PyExc_TypeError,
663 "bytearray indices must be integers or slices, not %.200s",
664 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000665 return -1;
666 }
667
668 if (values == NULL) {
669 bytes = NULL;
670 needed = 0;
671 }
672 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
Christian Heimes6d26ade2012-11-03 23:07:59 +0100673 int err;
Ezio Melottic64bcbe2012-11-03 21:19:06 +0200674 if (PyNumber_Check(values) || PyUnicode_Check(values)) {
675 PyErr_SetString(PyExc_TypeError,
676 "can assign only bytes, buffers, or iterables "
677 "of ints in range(0, 256)");
678 return -1;
679 }
Georg Brandlf3fa5682010-12-04 17:09:30 +0000680 /* Make a copy and call this function recursively */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000681 values = PyByteArray_FromObject(values);
682 if (values == NULL)
683 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000684 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000685 Py_DECREF(values);
686 return err;
687 }
688 else {
689 assert(PyByteArray_Check(values));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200690 bytes = PyByteArray_AS_STRING(values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000691 needed = Py_SIZE(values);
692 }
693 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
694 if ((step < 0 && start < stop) ||
695 (step > 0 && start > stop))
696 stop = start;
697 if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200698 return bytearray_setslice_linear(self, start, stop, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000699 }
700 else {
701 if (needed == 0) {
702 /* Delete slice */
Mark Dickinsonbc099642010-01-29 17:27:24 +0000703 size_t cur;
704 Py_ssize_t i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000705
Antoine Pitrou5504e892008-12-06 21:27:53 +0000706 if (!_canresize(self))
707 return -1;
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000708
709 if (slicelen == 0)
710 /* Nothing to do here. */
711 return 0;
712
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000713 if (step < 0) {
714 stop = start + 1;
715 start = stop + step * (slicelen - 1) - 1;
716 step = -step;
717 }
718 for (cur = start, i = 0;
719 i < slicelen; cur += step, i++) {
720 Py_ssize_t lim = step - 1;
721
Mark Dickinson66f575b2010-02-14 12:53:32 +0000722 if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000723 lim = PyByteArray_GET_SIZE(self) - cur - 1;
724
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200725 memmove(buf + cur - i,
726 buf + cur + 1, lim);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000727 }
728 /* Move the tail of the bytes, in one chunk */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000729 cur = start + (size_t)slicelen*step;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000730 if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200731 memmove(buf + cur - slicelen,
732 buf + cur,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000733 PyByteArray_GET_SIZE(self) - cur);
734 }
735 if (PyByteArray_Resize((PyObject *)self,
736 PyByteArray_GET_SIZE(self) - slicelen) < 0)
737 return -1;
738
739 return 0;
740 }
741 else {
742 /* Assign slice */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000743 Py_ssize_t i;
744 size_t cur;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000745
746 if (needed != slicelen) {
747 PyErr_Format(PyExc_ValueError,
748 "attempt to assign bytes of size %zd "
749 "to extended slice of size %zd",
750 needed, slicelen);
751 return -1;
752 }
753 for (cur = start, i = 0; i < slicelen; cur += step, i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200754 buf[cur] = bytes[i];
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000755 return 0;
756 }
757 }
758}
759
760static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000761bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000762{
763 static char *kwlist[] = {"source", "encoding", "errors", 0};
764 PyObject *arg = NULL;
765 const char *encoding = NULL;
766 const char *errors = NULL;
767 Py_ssize_t count;
768 PyObject *it;
769 PyObject *(*iternext)(PyObject *);
770
771 if (Py_SIZE(self) != 0) {
772 /* Empty previous contents (yes, do this first of all!) */
773 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
774 return -1;
775 }
776
777 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000778 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000779 &arg, &encoding, &errors))
780 return -1;
781
782 /* Make a quick exit if no first argument */
783 if (arg == NULL) {
784 if (encoding != NULL || errors != NULL) {
785 PyErr_SetString(PyExc_TypeError,
786 "encoding or errors without sequence argument");
787 return -1;
788 }
789 return 0;
790 }
791
792 if (PyUnicode_Check(arg)) {
793 /* Encode via the codec registry */
794 PyObject *encoded, *new;
795 if (encoding == NULL) {
796 PyErr_SetString(PyExc_TypeError,
797 "string argument without an encoding");
798 return -1;
799 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000800 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000801 if (encoded == NULL)
802 return -1;
803 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000804 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000805 Py_DECREF(encoded);
806 if (new == NULL)
807 return -1;
808 Py_DECREF(new);
809 return 0;
810 }
811
812 /* If it's not unicode, there can't be encoding or errors */
813 if (encoding != NULL || errors != NULL) {
814 PyErr_SetString(PyExc_TypeError,
815 "encoding or errors without a string argument");
816 return -1;
817 }
818
819 /* Is it an int? */
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000820 count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
821 if (count == -1 && PyErr_Occurred()) {
822 if (PyErr_ExceptionMatches(PyExc_OverflowError))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000823 return -1;
Benjamin Peterson9c0e94f2010-04-16 23:00:53 +0000824 PyErr_Clear();
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000825 }
826 else if (count < 0) {
827 PyErr_SetString(PyExc_ValueError, "negative count");
828 return -1;
829 }
830 else {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000831 if (count > 0) {
Victor Stinner2bc4d952014-06-02 22:22:42 +0200832 if (PyByteArray_Resize((PyObject *)self, count))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000833 return -1;
Victor Stinner2bc4d952014-06-02 22:22:42 +0200834 memset(PyByteArray_AS_STRING(self), 0, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000835 }
836 return 0;
837 }
838
839 /* Use the buffer API */
840 if (PyObject_CheckBuffer(arg)) {
841 Py_ssize_t size;
842 Py_buffer view;
843 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
844 return -1;
845 size = view.len;
846 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200847 if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
848 &view, size, 'C') < 0)
Stefan Krah7d12d9d2012-07-28 12:25:55 +0200849 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000850 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000851 return 0;
852 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000853 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000854 return -1;
855 }
856
857 /* XXX Optimize this if the arguments is a list, tuple */
858
859 /* Get the iterator */
860 it = PyObject_GetIter(arg);
861 if (it == NULL)
862 return -1;
863 iternext = *Py_TYPE(it)->tp_iternext;
864
865 /* Run the iterator to exhaustion */
866 for (;;) {
867 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000868 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000869
870 /* Get the next item */
871 item = iternext(it);
872 if (item == NULL) {
873 if (PyErr_Occurred()) {
874 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
875 goto error;
876 PyErr_Clear();
877 }
878 break;
879 }
880
881 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000882 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000883 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000884 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000885 goto error;
886
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000887 /* Append the byte */
888 if (Py_SIZE(self) < self->ob_alloc)
889 Py_SIZE(self)++;
890 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
891 goto error;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200892 PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000893 }
894
895 /* Clean up and return success */
896 Py_DECREF(it);
897 return 0;
898
899 error:
900 /* Error handling when it != NULL */
901 Py_DECREF(it);
902 return -1;
903}
904
905/* Mostly copied from string_repr, but without the
906 "smart quote" functionality. */
907static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000908bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000909{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000910 const char *quote_prefix = "bytearray(b";
911 const char *quote_postfix = ")";
912 Py_ssize_t length = Py_SIZE(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200913 /* 15 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */
Mark Dickinson66f575b2010-02-14 12:53:32 +0000914 size_t newsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000915 PyObject *v;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200916 Py_ssize_t i;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200917 char *bytes;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200918 char c;
919 char *p;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200920 int quote;
921 char *test, *start;
922 char *buffer;
923
924 if (length > (PY_SSIZE_T_MAX - 15) / 4) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000925 PyErr_SetString(PyExc_OverflowError,
926 "bytearray object is too large to make repr");
927 return NULL;
928 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200929
930 newsize = 15 + length * 4;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100931 buffer = PyObject_Malloc(newsize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200932 if (buffer == NULL) {
933 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000934 return NULL;
935 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000936
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200937 /* Figure out which quote to use; single is preferred */
938 quote = '\'';
939 start = PyByteArray_AS_STRING(self);
940 for (test = start; test < start+length; ++test) {
941 if (*test == '"') {
942 quote = '\''; /* back to single */
943 break;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000944 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200945 else if (*test == '\'')
946 quote = '"';
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000947 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200948
949 p = buffer;
950 while (*quote_prefix)
951 *p++ = *quote_prefix++;
952 *p++ = quote;
953
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200954 bytes = PyByteArray_AS_STRING(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200955 for (i = 0; i < length; i++) {
956 /* There's at least enough room for a hex escape
957 and a closing quote. */
958 assert(newsize - (p - buffer) >= 5);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200959 c = bytes[i];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200960 if (c == '\'' || c == '\\')
961 *p++ = '\\', *p++ = c;
962 else if (c == '\t')
963 *p++ = '\\', *p++ = 't';
964 else if (c == '\n')
965 *p++ = '\\', *p++ = 'n';
966 else if (c == '\r')
967 *p++ = '\\', *p++ = 'r';
968 else if (c == 0)
969 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
970 else if (c < ' ' || c >= 0x7f) {
971 *p++ = '\\';
972 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +0200973 *p++ = Py_hexdigits[(c & 0xf0) >> 4];
974 *p++ = Py_hexdigits[c & 0xf];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975 }
976 else
977 *p++ = c;
978 }
979 assert(newsize - (p - buffer) >= 1);
980 *p++ = quote;
981 while (*quote_postfix) {
982 *p++ = *quote_postfix++;
983 }
984
985 v = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100986 PyObject_Free(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987 return v;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000988}
989
990static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000991bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000992{
Alexander Belopolskyf0f45142010-08-11 17:31:17 +0000993 if (Py_BytesWarningFlag) {
994 if (PyErr_WarnEx(PyExc_BytesWarning,
995 "str() on a bytearray instance", 1))
996 return NULL;
997 }
998 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000999}
1000
1001static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001002bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001003{
1004 Py_ssize_t self_size, other_size;
1005 Py_buffer self_bytes, other_bytes;
1006 PyObject *res;
1007 Py_ssize_t minsize;
1008 int cmp;
1009
1010 /* Bytes can be compared to anything that supports the (binary)
1011 buffer API. Except that a comparison with Unicode is always an
1012 error, even if the comparison is for equality. */
1013 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
1014 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
Barry Warsaw9e9dcd62008-10-17 01:50:37 +00001015 if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001016 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +00001017 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001018 return NULL;
1019 }
1020
Brian Curtindfc80e32011-08-10 20:28:54 -05001021 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001022 }
1023
1024 self_size = _getbuffer(self, &self_bytes);
1025 if (self_size < 0) {
1026 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05001027 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001028 }
1029
1030 other_size = _getbuffer(other, &other_bytes);
1031 if (other_size < 0) {
1032 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +00001033 PyBuffer_Release(&self_bytes);
Brian Curtindfc80e32011-08-10 20:28:54 -05001034 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001035 }
1036
1037 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
1038 /* Shortcut: if the lengths differ, the objects differ */
1039 cmp = (op == Py_NE);
1040 }
1041 else {
1042 minsize = self_size;
1043 if (other_size < minsize)
1044 minsize = other_size;
1045
1046 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
1047 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
1048
1049 if (cmp == 0) {
1050 if (self_size < other_size)
1051 cmp = -1;
1052 else if (self_size > other_size)
1053 cmp = 1;
1054 }
1055
1056 switch (op) {
1057 case Py_LT: cmp = cmp < 0; break;
1058 case Py_LE: cmp = cmp <= 0; break;
1059 case Py_EQ: cmp = cmp == 0; break;
1060 case Py_NE: cmp = cmp != 0; break;
1061 case Py_GT: cmp = cmp > 0; break;
1062 case Py_GE: cmp = cmp >= 0; break;
1063 }
1064 }
1065
1066 res = cmp ? Py_True : Py_False;
Martin v. Löwis423be952008-08-13 15:53:07 +00001067 PyBuffer_Release(&self_bytes);
1068 PyBuffer_Release(&other_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001069 Py_INCREF(res);
1070 return res;
1071}
1072
1073static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001074bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001075{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001076 if (self->ob_exports > 0) {
1077 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001078 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001079 PyErr_Print();
1080 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001081 if (self->ob_bytes != 0) {
Antoine Pitrou39aba4f2011-11-12 21:15:28 +01001082 PyObject_Free(self->ob_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001083 }
1084 Py_TYPE(self)->tp_free((PyObject *)self);
1085}
1086
1087
1088/* -------------------------------------------------------------------- */
1089/* Methods */
1090
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001091#define FASTSEARCH fastsearch
1092#define STRINGLIB(F) stringlib_##F
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001093#define STRINGLIB_CHAR char
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001094#define STRINGLIB_SIZEOF_CHAR 1
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001095#define STRINGLIB_LEN PyByteArray_GET_SIZE
1096#define STRINGLIB_STR PyByteArray_AS_STRING
1097#define STRINGLIB_NEW PyByteArray_FromStringAndSize
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001098#define STRINGLIB_ISSPACE Py_ISSPACE
1099#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001100#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1101#define STRINGLIB_MUTABLE 1
1102
1103#include "stringlib/fastsearch.h"
1104#include "stringlib/count.h"
1105#include "stringlib/find.h"
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001106#include "stringlib/join.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001107#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001108#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001109#include "stringlib/ctype.h"
1110#include "stringlib/transmogrify.h"
1111
1112
1113/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1114were copied from the old char* style string object. */
1115
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001116/* helper macro to fixup start/end slice values */
1117#define ADJUST_INDICES(start, end, len) \
1118 if (end > len) \
1119 end = len; \
1120 else if (end < 0) { \
1121 end += len; \
1122 if (end < 0) \
1123 end = 0; \
1124 } \
1125 if (start < 0) { \
1126 start += len; \
1127 if (start < 0) \
1128 start = 0; \
1129 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001130
1131Py_LOCAL_INLINE(Py_ssize_t)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001132bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001133{
1134 PyObject *subobj;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001135 char byte;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001136 Py_buffer subbuf;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001137 const char *sub;
1138 Py_ssize_t sub_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001139 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1140 Py_ssize_t res;
1141
Antoine Pitrouac65d962011-10-20 23:54:17 +02001142 if (!stringlib_parse_args_finds_byte("find/rfind/index/rindex",
1143 args, &subobj, &byte, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001144 return -2;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001145
1146 if (subobj) {
1147 if (_getbuffer(subobj, &subbuf) < 0)
1148 return -2;
1149
1150 sub = subbuf.buf;
1151 sub_len = subbuf.len;
1152 }
1153 else {
1154 sub = &byte;
1155 sub_len = 1;
1156 }
1157
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001158 if (dir > 0)
1159 res = stringlib_find_slice(
1160 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
Antoine Pitrouac65d962011-10-20 23:54:17 +02001161 sub, sub_len, start, end);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001162 else
1163 res = stringlib_rfind_slice(
1164 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
Antoine Pitrouac65d962011-10-20 23:54:17 +02001165 sub, sub_len, start, end);
1166
1167 if (subobj)
1168 PyBuffer_Release(&subbuf);
1169
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001170 return res;
1171}
1172
1173PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001174"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001175\n\
1176Return the lowest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001177such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001178arguments start and end are interpreted as in slice notation.\n\
1179\n\
1180Return -1 on failure.");
1181
1182static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001183bytearray_find(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001184{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001185 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001186 if (result == -2)
1187 return NULL;
1188 return PyLong_FromSsize_t(result);
1189}
1190
1191PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001192"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001193\n\
1194Return the number of non-overlapping occurrences of subsection sub in\n\
1195bytes B[start:end]. Optional arguments start and end are interpreted\n\
1196as in slice notation.");
1197
1198static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001199bytearray_count(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001200{
1201 PyObject *sub_obj;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001202 const char *str = PyByteArray_AS_STRING(self), *sub;
1203 Py_ssize_t sub_len;
1204 char byte;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001205 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001206
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001207 Py_buffer vsub;
1208 PyObject *count_obj;
1209
Antoine Pitrouac65d962011-10-20 23:54:17 +02001210 if (!stringlib_parse_args_finds_byte("count", args, &sub_obj, &byte,
1211 &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001212 return NULL;
1213
Antoine Pitrouac65d962011-10-20 23:54:17 +02001214 if (sub_obj) {
1215 if (_getbuffer(sub_obj, &vsub) < 0)
1216 return NULL;
1217
1218 sub = vsub.buf;
1219 sub_len = vsub.len;
1220 }
1221 else {
1222 sub = &byte;
1223 sub_len = 1;
1224 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001225
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001226 ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001227
1228 count_obj = PyLong_FromSsize_t(
Antoine Pitrouac65d962011-10-20 23:54:17 +02001229 stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001230 );
Antoine Pitrouac65d962011-10-20 23:54:17 +02001231
1232 if (sub_obj)
1233 PyBuffer_Release(&vsub);
1234
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001235 return count_obj;
1236}
1237
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001238/*[clinic input]
1239bytearray.clear
1240
1241 self: self(type="PyByteArrayObject *")
1242
1243Remove all items from the bytearray.
1244[clinic start generated code]*/
1245
1246PyDoc_STRVAR(bytearray_clear__doc__,
1247"clear($self, /)\n"
1248"--\n"
1249"\n"
1250"Remove all items from the bytearray.");
1251
1252#define BYTEARRAY_CLEAR_METHODDEF \
1253 {"clear", (PyCFunction)bytearray_clear, METH_NOARGS, bytearray_clear__doc__},
Eli Bendersky4db28d32011-03-03 18:21:02 +00001254
Victor Stinner6430fd52011-09-29 04:02:13 +02001255static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001256bytearray_clear_impl(PyByteArrayObject *self);
1257
1258static PyObject *
1259bytearray_clear(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
1260{
1261 return bytearray_clear_impl(self);
1262}
1263
1264static PyObject *
1265bytearray_clear_impl(PyByteArrayObject *self)
1266/*[clinic end generated code: output=5344093031e2f36c input=e524fd330abcdc18]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001267{
1268 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
1269 return NULL;
1270 Py_RETURN_NONE;
1271}
1272
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001273/*[clinic input]
1274bytearray.copy
1275
1276 self: self(type="PyByteArrayObject *")
1277
1278Return a copy of B.
1279[clinic start generated code]*/
1280
1281PyDoc_STRVAR(bytearray_copy__doc__,
1282"copy($self, /)\n"
1283"--\n"
1284"\n"
1285"Return a copy of B.");
1286
1287#define BYTEARRAY_COPY_METHODDEF \
1288 {"copy", (PyCFunction)bytearray_copy, METH_NOARGS, bytearray_copy__doc__},
Eli Bendersky4db28d32011-03-03 18:21:02 +00001289
1290static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001291bytearray_copy_impl(PyByteArrayObject *self);
1292
1293static PyObject *
1294bytearray_copy(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
1295{
1296 return bytearray_copy_impl(self);
1297}
1298
1299static PyObject *
1300bytearray_copy_impl(PyByteArrayObject *self)
1301/*[clinic end generated code: output=8788ed299f7f2214 input=6d5d2975aa0f33f3]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001302{
1303 return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
1304 PyByteArray_GET_SIZE(self));
1305}
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001306
1307PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001308"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001309\n\
1310Like B.find() but raise ValueError when the subsection is not found.");
1311
1312static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001313bytearray_index(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001314{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001315 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001316 if (result == -2)
1317 return NULL;
1318 if (result == -1) {
1319 PyErr_SetString(PyExc_ValueError,
1320 "subsection not found");
1321 return NULL;
1322 }
1323 return PyLong_FromSsize_t(result);
1324}
1325
1326
1327PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001328"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001329\n\
1330Return the highest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001331such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001332arguments start and end are interpreted as in slice notation.\n\
1333\n\
1334Return -1 on failure.");
1335
1336static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001337bytearray_rfind(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001338{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001339 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001340 if (result == -2)
1341 return NULL;
1342 return PyLong_FromSsize_t(result);
1343}
1344
1345
1346PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001347"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001348\n\
1349Like B.rfind() but raise ValueError when the subsection is not found.");
1350
1351static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001352bytearray_rindex(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001353{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001354 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001355 if (result == -2)
1356 return NULL;
1357 if (result == -1) {
1358 PyErr_SetString(PyExc_ValueError,
1359 "subsection not found");
1360 return NULL;
1361 }
1362 return PyLong_FromSsize_t(result);
1363}
1364
1365
1366static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001367bytearray_contains(PyObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001368{
1369 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1370 if (ival == -1 && PyErr_Occurred()) {
1371 Py_buffer varg;
Antoine Pitrou0010d372010-08-15 17:12:55 +00001372 Py_ssize_t pos;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001373 PyErr_Clear();
1374 if (_getbuffer(arg, &varg) < 0)
1375 return -1;
1376 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1377 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001378 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001379 return pos >= 0;
1380 }
1381 if (ival < 0 || ival >= 256) {
1382 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1383 return -1;
1384 }
1385
Antoine Pitrou0010d372010-08-15 17:12:55 +00001386 return memchr(PyByteArray_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001387}
1388
1389
1390/* Matches the end (direction >= 0) or start (direction < 0) of self
1391 * against substr, using the start and end arguments. Returns
1392 * -1 on error, 0 if not found and 1 if found.
1393 */
1394Py_LOCAL(int)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001395_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001396 Py_ssize_t end, int direction)
1397{
1398 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1399 const char* str;
1400 Py_buffer vsubstr;
1401 int rv = 0;
1402
1403 str = PyByteArray_AS_STRING(self);
1404
1405 if (_getbuffer(substr, &vsubstr) < 0)
1406 return -1;
1407
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001408 ADJUST_INDICES(start, end, len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001409
1410 if (direction < 0) {
1411 /* startswith */
1412 if (start+vsubstr.len > len) {
1413 goto done;
1414 }
1415 } else {
1416 /* endswith */
1417 if (end-start < vsubstr.len || start > len) {
1418 goto done;
1419 }
1420
1421 if (end-vsubstr.len > start)
1422 start = end - vsubstr.len;
1423 }
1424 if (end-start >= vsubstr.len)
1425 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1426
1427done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001428 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001429 return rv;
1430}
1431
1432
1433PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001434"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001435\n\
1436Return True if B starts with the specified prefix, False otherwise.\n\
1437With optional start, test B beginning at that position.\n\
1438With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001439prefix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001440
1441static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001442bytearray_startswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001443{
1444 Py_ssize_t start = 0;
1445 Py_ssize_t end = PY_SSIZE_T_MAX;
1446 PyObject *subobj;
1447 int result;
1448
Jesus Ceaac451502011-04-20 17:09:23 +02001449 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001450 return NULL;
1451 if (PyTuple_Check(subobj)) {
1452 Py_ssize_t i;
1453 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001454 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001455 PyTuple_GET_ITEM(subobj, i),
1456 start, end, -1);
1457 if (result == -1)
1458 return NULL;
1459 else if (result) {
1460 Py_RETURN_TRUE;
1461 }
1462 }
1463 Py_RETURN_FALSE;
1464 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001465 result = _bytearray_tailmatch(self, subobj, start, end, -1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001466 if (result == -1) {
1467 if (PyErr_ExceptionMatches(PyExc_TypeError))
1468 PyErr_Format(PyExc_TypeError, "startswith first arg must be bytes "
1469 "or a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001470 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001471 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001472 else
1473 return PyBool_FromLong(result);
1474}
1475
1476PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001477"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001478\n\
1479Return True if B ends with the specified suffix, False otherwise.\n\
1480With optional start, test B beginning at that position.\n\
1481With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001482suffix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001483
1484static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001485bytearray_endswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001486{
1487 Py_ssize_t start = 0;
1488 Py_ssize_t end = PY_SSIZE_T_MAX;
1489 PyObject *subobj;
1490 int result;
1491
Jesus Ceaac451502011-04-20 17:09:23 +02001492 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001493 return NULL;
1494 if (PyTuple_Check(subobj)) {
1495 Py_ssize_t i;
1496 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001497 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001498 PyTuple_GET_ITEM(subobj, i),
1499 start, end, +1);
1500 if (result == -1)
1501 return NULL;
1502 else if (result) {
1503 Py_RETURN_TRUE;
1504 }
1505 }
1506 Py_RETURN_FALSE;
1507 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001508 result = _bytearray_tailmatch(self, subobj, start, end, +1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001509 if (result == -1) {
1510 if (PyErr_ExceptionMatches(PyExc_TypeError))
1511 PyErr_Format(PyExc_TypeError, "endswith first arg must be bytes or "
1512 "a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001513 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001514 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001515 else
1516 return PyBool_FromLong(result);
1517}
1518
1519
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001520/*[clinic input]
1521bytearray.translate
1522
1523 self: self(type="PyByteArrayObject *")
1524 table: object
1525 Translation table, which must be a bytes object of length 256.
1526 [
1527 deletechars: object
1528 ]
1529 /
1530
1531Return a copy with each character mapped by the given translation table.
1532
1533All characters occurring in the optional argument deletechars are removed.
1534The remaining characters are mapped through the given translation table.
1535[clinic start generated code]*/
1536
1537PyDoc_STRVAR(bytearray_translate__doc__,
1538"translate(table, [deletechars])\n"
1539"Return a copy with each character mapped by the given translation table.\n"
1540"\n"
1541" table\n"
1542" Translation table, which must be a bytes object of length 256.\n"
1543"\n"
1544"All characters occurring in the optional argument deletechars are removed.\n"
1545"The remaining characters are mapped through the given translation table.");
1546
1547#define BYTEARRAY_TRANSLATE_METHODDEF \
1548 {"translate", (PyCFunction)bytearray_translate, METH_VARARGS, bytearray_translate__doc__},
1549
1550static PyObject *
1551bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, int group_right_1, PyObject *deletechars);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001552
1553static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001554bytearray_translate(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001555{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001556 PyObject *return_value = NULL;
1557 PyObject *table;
1558 int group_right_1 = 0;
1559 PyObject *deletechars = NULL;
1560
1561 switch (PyTuple_GET_SIZE(args)) {
1562 case 1:
1563 if (!PyArg_ParseTuple(args, "O:translate", &table))
1564 goto exit;
1565 break;
1566 case 2:
1567 if (!PyArg_ParseTuple(args, "OO:translate", &table, &deletechars))
1568 goto exit;
1569 group_right_1 = 1;
1570 break;
1571 default:
1572 PyErr_SetString(PyExc_TypeError, "bytearray.translate requires 1 to 2 arguments");
1573 goto exit;
1574 }
1575 return_value = bytearray_translate_impl(self, table, group_right_1, deletechars);
1576
1577exit:
1578 return return_value;
1579}
1580
1581static PyObject *
1582bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, int group_right_1, PyObject *deletechars)
1583/*[clinic end generated code: output=a709df81d41db4b7 input=b749ad85f4860824]*/
1584{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001585 char *input, *output;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001586 const char *table_chars;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001587 Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001588 PyObject *input_obj = (PyObject*)self;
1589 const char *output_start;
1590 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001591 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001592 int trans_table[256];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001593 Py_buffer vtable, vdel;
1594
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001595 if (table == Py_None) {
1596 table_chars = NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001597 table = NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001598 } else if (_getbuffer(table, &vtable) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001599 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001600 } else {
1601 if (vtable.len != 256) {
1602 PyErr_SetString(PyExc_ValueError,
1603 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001604 PyBuffer_Release(&vtable);
1605 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001606 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001607 table_chars = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001608 }
1609
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001610 if (deletechars != NULL) {
1611 if (_getbuffer(deletechars, &vdel) < 0) {
1612 if (table != NULL)
Georg Brandl953152f2009-07-22 12:03:59 +00001613 PyBuffer_Release(&vtable);
1614 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001615 }
1616 }
1617 else {
1618 vdel.buf = NULL;
1619 vdel.len = 0;
1620 }
1621
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001622 inlen = PyByteArray_GET_SIZE(input_obj);
1623 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1624 if (result == NULL)
1625 goto done;
1626 output_start = output = PyByteArray_AsString(result);
1627 input = PyByteArray_AS_STRING(input_obj);
1628
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001629 if (vdel.len == 0 && table_chars != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001630 /* If no deletions are required, use faster code */
1631 for (i = inlen; --i >= 0; ) {
1632 c = Py_CHARMASK(*input++);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001633 *output++ = table_chars[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001634 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001635 goto done;
1636 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001637
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001638 if (table_chars == NULL) {
Georg Brandlccc47b62008-12-28 11:44:14 +00001639 for (i = 0; i < 256; i++)
1640 trans_table[i] = Py_CHARMASK(i);
1641 } else {
1642 for (i = 0; i < 256; i++)
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001643 trans_table[i] = Py_CHARMASK(table_chars[i]);
Georg Brandlccc47b62008-12-28 11:44:14 +00001644 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001645
1646 for (i = 0; i < vdel.len; i++)
1647 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1648
1649 for (i = inlen; --i >= 0; ) {
1650 c = Py_CHARMASK(*input++);
1651 if (trans_table[c] != -1)
1652 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1653 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001654 }
1655 /* Fix the size of the resulting string */
1656 if (inlen > 0)
Christian Heimesc731bbe2013-07-21 02:04:35 +02001657 if (PyByteArray_Resize(result, output - output_start) < 0) {
1658 Py_CLEAR(result);
1659 goto done;
1660 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001661
1662done:
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001663 if (table != NULL)
Georg Brandlccc47b62008-12-28 11:44:14 +00001664 PyBuffer_Release(&vtable);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001665 if (deletechars != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001666 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001667 return result;
1668}
1669
1670
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001671/*[clinic input]
1672
1673@staticmethod
1674bytearray.maketrans
1675
1676 frm: object
1677 to: object
1678 /
1679
1680Return a translation table useable for the bytes or bytearray translate method.
1681
1682The returned table will be one where each byte in frm is mapped to the byte at
1683the same position in to.
1684
1685The bytes objects frm and to must be of the same length.
1686[clinic start generated code]*/
1687
1688PyDoc_STRVAR(bytearray_maketrans__doc__,
1689"maketrans(frm, to, /)\n"
1690"--\n"
1691"\n"
1692"Return a translation table useable for the bytes or bytearray translate method.\n"
1693"\n"
1694"The returned table will be one where each byte in frm is mapped to the byte at\n"
1695"the same position in to.\n"
1696"\n"
1697"The bytes objects frm and to must be of the same length.");
1698
1699#define BYTEARRAY_MAKETRANS_METHODDEF \
1700 {"maketrans", (PyCFunction)bytearray_maketrans, METH_VARARGS|METH_STATIC, bytearray_maketrans__doc__},
1701
Georg Brandlabc38772009-04-12 15:51:51 +00001702static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001703bytearray_maketrans_impl(PyObject *frm, PyObject *to);
1704
1705static PyObject *
1706bytearray_maketrans(void *null, PyObject *args)
Georg Brandlabc38772009-04-12 15:51:51 +00001707{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001708 PyObject *return_value = NULL;
1709 PyObject *frm;
1710 PyObject *to;
1711
1712 if (!PyArg_UnpackTuple(args, "maketrans",
1713 2, 2,
1714 &frm, &to))
1715 goto exit;
1716 return_value = bytearray_maketrans_impl(frm, to);
1717
1718exit:
1719 return return_value;
1720}
1721
1722static PyObject *
1723bytearray_maketrans_impl(PyObject *frm, PyObject *to)
1724/*[clinic end generated code: output=307752019d9b25b5 input=ea9bdc6b328c15e2]*/
1725{
1726 return _Py_bytes_maketrans(frm, to);
Georg Brandlabc38772009-04-12 15:51:51 +00001727}
1728
1729
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001730/* find and count characters and substrings */
1731
1732#define findchar(target, target_len, c) \
1733 ((char *)memchr((const void *)(target), c, target_len))
1734
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001735
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001736/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001737Py_LOCAL(PyByteArrayObject *)
1738return_self(PyByteArrayObject *self)
1739{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001740 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001741 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1742 PyByteArray_AS_STRING(self),
1743 PyByteArray_GET_SIZE(self));
1744}
1745
1746Py_LOCAL_INLINE(Py_ssize_t)
1747countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1748{
1749 Py_ssize_t count=0;
1750 const char *start=target;
1751 const char *end=target+target_len;
1752
1753 while ( (start=findchar(start, end-start, c)) != NULL ) {
1754 count++;
1755 if (count >= maxcount)
1756 break;
1757 start += 1;
1758 }
1759 return count;
1760}
1761
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001762
1763/* Algorithms for different cases of string replacement */
1764
1765/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1766Py_LOCAL(PyByteArrayObject *)
1767replace_interleave(PyByteArrayObject *self,
1768 const char *to_s, Py_ssize_t to_len,
1769 Py_ssize_t maxcount)
1770{
1771 char *self_s, *result_s;
1772 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001773 Py_ssize_t count, i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001774 PyByteArrayObject *result;
1775
1776 self_len = PyByteArray_GET_SIZE(self);
1777
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001778 /* 1 at the end plus 1 after every character;
1779 count = min(maxcount, self_len + 1) */
1780 if (maxcount <= self_len)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001781 count = maxcount;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001782 else
1783 /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
1784 count = self_len + 1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001785
1786 /* Check for overflow */
1787 /* result_len = count * to_len + self_len; */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001788 assert(count > 0);
1789 if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001790 PyErr_SetString(PyExc_OverflowError,
1791 "replace string is too long");
1792 return NULL;
1793 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001794 result_len = count * to_len + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001795
1796 if (! (result = (PyByteArrayObject *)
1797 PyByteArray_FromStringAndSize(NULL, result_len)) )
1798 return NULL;
1799
1800 self_s = PyByteArray_AS_STRING(self);
1801 result_s = PyByteArray_AS_STRING(result);
1802
1803 /* TODO: special case single character, which doesn't need memcpy */
1804
1805 /* Lay the first one down (guaranteed this will occur) */
1806 Py_MEMCPY(result_s, to_s, to_len);
1807 result_s += to_len;
1808 count -= 1;
1809
1810 for (i=0; i<count; i++) {
1811 *result_s++ = *self_s++;
1812 Py_MEMCPY(result_s, to_s, to_len);
1813 result_s += to_len;
1814 }
1815
1816 /* Copy the rest of the original string */
1817 Py_MEMCPY(result_s, self_s, self_len-i);
1818
1819 return result;
1820}
1821
1822/* Special case for deleting a single character */
1823/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1824Py_LOCAL(PyByteArrayObject *)
1825replace_delete_single_character(PyByteArrayObject *self,
1826 char from_c, Py_ssize_t maxcount)
1827{
1828 char *self_s, *result_s;
1829 char *start, *next, *end;
1830 Py_ssize_t self_len, result_len;
1831 Py_ssize_t count;
1832 PyByteArrayObject *result;
1833
1834 self_len = PyByteArray_GET_SIZE(self);
1835 self_s = PyByteArray_AS_STRING(self);
1836
1837 count = countchar(self_s, self_len, from_c, maxcount);
1838 if (count == 0) {
1839 return return_self(self);
1840 }
1841
1842 result_len = self_len - count; /* from_len == 1 */
1843 assert(result_len>=0);
1844
1845 if ( (result = (PyByteArrayObject *)
1846 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1847 return NULL;
1848 result_s = PyByteArray_AS_STRING(result);
1849
1850 start = self_s;
1851 end = self_s + self_len;
1852 while (count-- > 0) {
1853 next = findchar(start, end-start, from_c);
1854 if (next == NULL)
1855 break;
1856 Py_MEMCPY(result_s, start, next-start);
1857 result_s += (next-start);
1858 start = next+1;
1859 }
1860 Py_MEMCPY(result_s, start, end-start);
1861
1862 return result;
1863}
1864
1865/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1866
1867Py_LOCAL(PyByteArrayObject *)
1868replace_delete_substring(PyByteArrayObject *self,
1869 const char *from_s, Py_ssize_t from_len,
1870 Py_ssize_t maxcount)
1871{
1872 char *self_s, *result_s;
1873 char *start, *next, *end;
1874 Py_ssize_t self_len, result_len;
1875 Py_ssize_t count, offset;
1876 PyByteArrayObject *result;
1877
1878 self_len = PyByteArray_GET_SIZE(self);
1879 self_s = PyByteArray_AS_STRING(self);
1880
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001881 count = stringlib_count(self_s, self_len,
1882 from_s, from_len,
1883 maxcount);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001884
1885 if (count == 0) {
1886 /* no matches */
1887 return return_self(self);
1888 }
1889
1890 result_len = self_len - (count * from_len);
1891 assert (result_len>=0);
1892
1893 if ( (result = (PyByteArrayObject *)
1894 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1895 return NULL;
1896
1897 result_s = PyByteArray_AS_STRING(result);
1898
1899 start = self_s;
1900 end = self_s + self_len;
1901 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001902 offset = stringlib_find(start, end-start,
1903 from_s, from_len,
1904 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001905 if (offset == -1)
1906 break;
1907 next = start + offset;
1908
1909 Py_MEMCPY(result_s, start, next-start);
1910
1911 result_s += (next-start);
1912 start = next+from_len;
1913 }
1914 Py_MEMCPY(result_s, start, end-start);
1915 return result;
1916}
1917
1918/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1919Py_LOCAL(PyByteArrayObject *)
1920replace_single_character_in_place(PyByteArrayObject *self,
1921 char from_c, char to_c,
1922 Py_ssize_t maxcount)
1923{
Antoine Pitroud1188562010-06-09 16:38:55 +00001924 char *self_s, *result_s, *start, *end, *next;
1925 Py_ssize_t self_len;
1926 PyByteArrayObject *result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001927
Antoine Pitroud1188562010-06-09 16:38:55 +00001928 /* The result string will be the same size */
1929 self_s = PyByteArray_AS_STRING(self);
1930 self_len = PyByteArray_GET_SIZE(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001931
Antoine Pitroud1188562010-06-09 16:38:55 +00001932 next = findchar(self_s, self_len, from_c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001933
Antoine Pitroud1188562010-06-09 16:38:55 +00001934 if (next == NULL) {
1935 /* No matches; return the original bytes */
1936 return return_self(self);
1937 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001938
Antoine Pitroud1188562010-06-09 16:38:55 +00001939 /* Need to make a new bytes */
1940 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1941 if (result == NULL)
1942 return NULL;
1943 result_s = PyByteArray_AS_STRING(result);
1944 Py_MEMCPY(result_s, self_s, self_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001945
Antoine Pitroud1188562010-06-09 16:38:55 +00001946 /* change everything in-place, starting with this one */
1947 start = result_s + (next-self_s);
1948 *start = to_c;
1949 start++;
1950 end = result_s + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001951
Antoine Pitroud1188562010-06-09 16:38:55 +00001952 while (--maxcount > 0) {
1953 next = findchar(start, end-start, from_c);
1954 if (next == NULL)
1955 break;
1956 *next = to_c;
1957 start = next+1;
1958 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001959
Antoine Pitroud1188562010-06-09 16:38:55 +00001960 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001961}
1962
1963/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1964Py_LOCAL(PyByteArrayObject *)
1965replace_substring_in_place(PyByteArrayObject *self,
1966 const char *from_s, Py_ssize_t from_len,
1967 const char *to_s, Py_ssize_t to_len,
1968 Py_ssize_t maxcount)
1969{
1970 char *result_s, *start, *end;
1971 char *self_s;
1972 Py_ssize_t self_len, offset;
1973 PyByteArrayObject *result;
1974
1975 /* The result bytes will be the same size */
1976
1977 self_s = PyByteArray_AS_STRING(self);
1978 self_len = PyByteArray_GET_SIZE(self);
1979
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001980 offset = stringlib_find(self_s, self_len,
1981 from_s, from_len,
1982 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001983 if (offset == -1) {
1984 /* No matches; return the original bytes */
1985 return return_self(self);
1986 }
1987
1988 /* Need to make a new bytes */
1989 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1990 if (result == NULL)
1991 return NULL;
1992 result_s = PyByteArray_AS_STRING(result);
1993 Py_MEMCPY(result_s, self_s, self_len);
1994
1995 /* change everything in-place, starting with this one */
1996 start = result_s + offset;
1997 Py_MEMCPY(start, to_s, from_len);
1998 start += from_len;
1999 end = result_s + self_len;
2000
2001 while ( --maxcount > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002002 offset = stringlib_find(start, end-start,
2003 from_s, from_len,
2004 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002005 if (offset==-1)
2006 break;
2007 Py_MEMCPY(start+offset, to_s, from_len);
2008 start += offset+from_len;
2009 }
2010
2011 return result;
2012}
2013
2014/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
2015Py_LOCAL(PyByteArrayObject *)
2016replace_single_character(PyByteArrayObject *self,
2017 char from_c,
2018 const char *to_s, Py_ssize_t to_len,
2019 Py_ssize_t maxcount)
2020{
2021 char *self_s, *result_s;
2022 char *start, *next, *end;
2023 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002024 Py_ssize_t count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002025 PyByteArrayObject *result;
2026
2027 self_s = PyByteArray_AS_STRING(self);
2028 self_len = PyByteArray_GET_SIZE(self);
2029
2030 count = countchar(self_s, self_len, from_c, maxcount);
2031 if (count == 0) {
2032 /* no matches, return unchanged */
2033 return return_self(self);
2034 }
2035
2036 /* use the difference between current and new, hence the "-1" */
2037 /* result_len = self_len + count * (to_len-1) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002038 assert(count > 0);
2039 if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002040 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
2041 return NULL;
2042 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002043 result_len = self_len + count * (to_len - 1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002044
2045 if ( (result = (PyByteArrayObject *)
2046 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
2047 return NULL;
2048 result_s = PyByteArray_AS_STRING(result);
2049
2050 start = self_s;
2051 end = self_s + self_len;
2052 while (count-- > 0) {
2053 next = findchar(start, end-start, from_c);
2054 if (next == NULL)
2055 break;
2056
2057 if (next == start) {
2058 /* replace with the 'to' */
2059 Py_MEMCPY(result_s, to_s, to_len);
2060 result_s += to_len;
2061 start += 1;
2062 } else {
2063 /* copy the unchanged old then the 'to' */
2064 Py_MEMCPY(result_s, start, next-start);
2065 result_s += (next-start);
2066 Py_MEMCPY(result_s, to_s, to_len);
2067 result_s += to_len;
2068 start = next+1;
2069 }
2070 }
2071 /* Copy the remainder of the remaining bytes */
2072 Py_MEMCPY(result_s, start, end-start);
2073
2074 return result;
2075}
2076
2077/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
2078Py_LOCAL(PyByteArrayObject *)
2079replace_substring(PyByteArrayObject *self,
2080 const char *from_s, Py_ssize_t from_len,
2081 const char *to_s, Py_ssize_t to_len,
2082 Py_ssize_t maxcount)
2083{
2084 char *self_s, *result_s;
2085 char *start, *next, *end;
2086 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002087 Py_ssize_t count, offset;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002088 PyByteArrayObject *result;
2089
2090 self_s = PyByteArray_AS_STRING(self);
2091 self_len = PyByteArray_GET_SIZE(self);
2092
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002093 count = stringlib_count(self_s, self_len,
2094 from_s, from_len,
2095 maxcount);
2096
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002097 if (count == 0) {
2098 /* no matches, return unchanged */
2099 return return_self(self);
2100 }
2101
2102 /* Check for overflow */
2103 /* result_len = self_len + count * (to_len-from_len) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002104 assert(count > 0);
2105 if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002106 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
2107 return NULL;
2108 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002109 result_len = self_len + count * (to_len - from_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002110
2111 if ( (result = (PyByteArrayObject *)
2112 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
2113 return NULL;
2114 result_s = PyByteArray_AS_STRING(result);
2115
2116 start = self_s;
2117 end = self_s + self_len;
2118 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002119 offset = stringlib_find(start, end-start,
2120 from_s, from_len,
2121 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002122 if (offset == -1)
2123 break;
2124 next = start+offset;
2125 if (next == start) {
2126 /* replace with the 'to' */
2127 Py_MEMCPY(result_s, to_s, to_len);
2128 result_s += to_len;
2129 start += from_len;
2130 } else {
2131 /* copy the unchanged old then the 'to' */
2132 Py_MEMCPY(result_s, start, next-start);
2133 result_s += (next-start);
2134 Py_MEMCPY(result_s, to_s, to_len);
2135 result_s += to_len;
2136 start = next+from_len;
2137 }
2138 }
2139 /* Copy the remainder of the remaining bytes */
2140 Py_MEMCPY(result_s, start, end-start);
2141
2142 return result;
2143}
2144
2145
2146Py_LOCAL(PyByteArrayObject *)
2147replace(PyByteArrayObject *self,
2148 const char *from_s, Py_ssize_t from_len,
2149 const char *to_s, Py_ssize_t to_len,
2150 Py_ssize_t maxcount)
2151{
2152 if (maxcount < 0) {
2153 maxcount = PY_SSIZE_T_MAX;
2154 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
2155 /* nothing to do; return the original bytes */
2156 return return_self(self);
2157 }
2158
2159 if (maxcount == 0 ||
2160 (from_len == 0 && to_len == 0)) {
2161 /* nothing to do; return the original bytes */
2162 return return_self(self);
2163 }
2164
2165 /* Handle zero-length special cases */
2166
2167 if (from_len == 0) {
2168 /* insert the 'to' bytes everywhere. */
2169 /* >>> "Python".replace("", ".") */
2170 /* '.P.y.t.h.o.n.' */
2171 return replace_interleave(self, to_s, to_len, maxcount);
2172 }
2173
2174 /* Except for "".replace("", "A") == "A" there is no way beyond this */
2175 /* point for an empty self bytes to generate a non-empty bytes */
2176 /* Special case so the remaining code always gets a non-empty bytes */
2177 if (PyByteArray_GET_SIZE(self) == 0) {
2178 return return_self(self);
2179 }
2180
2181 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00002182 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002183 if (from_len == 1) {
2184 return replace_delete_single_character(
2185 self, from_s[0], maxcount);
2186 } else {
2187 return replace_delete_substring(self, from_s, from_len, maxcount);
2188 }
2189 }
2190
2191 /* Handle special case where both bytes have the same length */
2192
2193 if (from_len == to_len) {
2194 if (from_len == 1) {
2195 return replace_single_character_in_place(
2196 self,
2197 from_s[0],
2198 to_s[0],
2199 maxcount);
2200 } else {
2201 return replace_substring_in_place(
2202 self, from_s, from_len, to_s, to_len, maxcount);
2203 }
2204 }
2205
2206 /* Otherwise use the more generic algorithms */
2207 if (from_len == 1) {
2208 return replace_single_character(self, from_s[0],
2209 to_s, to_len, maxcount);
2210 } else {
2211 /* len('from')>=2, len('to')>=1 */
2212 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
2213 }
2214}
2215
2216
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002217/*[clinic input]
2218bytearray.replace
2219
2220 old: object
2221 new: object
2222 count: Py_ssize_t = -1
2223 Maximum number of occurrences to replace.
2224 -1 (the default value) means replace all occurrences.
2225 /
2226
2227Return a copy with all occurrences of substring old replaced by new.
2228
2229If the optional argument count is given, only the first count occurrences are
2230replaced.
2231[clinic start generated code]*/
2232
2233PyDoc_STRVAR(bytearray_replace__doc__,
2234"replace($self, old, new, count=-1, /)\n"
2235"--\n"
2236"\n"
2237"Return a copy with all occurrences of substring old replaced by new.\n"
2238"\n"
2239" count\n"
2240" Maximum number of occurrences to replace.\n"
2241" -1 (the default value) means replace all occurrences.\n"
2242"\n"
2243"If the optional argument count is given, only the first count occurrences are\n"
2244"replaced.");
2245
2246#define BYTEARRAY_REPLACE_METHODDEF \
2247 {"replace", (PyCFunction)bytearray_replace, METH_VARARGS, bytearray_replace__doc__},
2248
2249static PyObject *
2250bytearray_replace_impl(PyByteArrayObject *self, PyObject *old, PyObject *new, Py_ssize_t count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002251
2252static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002253bytearray_replace(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002254{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002255 PyObject *return_value = NULL;
2256 PyObject *old;
2257 PyObject *new;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002258 Py_ssize_t count = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002259
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002260 if (!PyArg_ParseTuple(args,
2261 "OO|n:replace",
2262 &old, &new, &count))
2263 goto exit;
2264 return_value = bytearray_replace_impl(self, old, new, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002265
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002266exit:
2267 return return_value;
2268}
2269
2270static PyObject *
2271bytearray_replace_impl(PyByteArrayObject *self, PyObject *old, PyObject *new, Py_ssize_t count)
2272/*[clinic end generated code: output=4d2e3c9130da0f96 input=9aaaa123608dfc1f]*/
2273{
2274 PyObject *res;
2275 Py_buffer vold, vnew;
2276
2277 if (_getbuffer(old, &vold) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002278 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002279 if (_getbuffer(new, &vnew) < 0) {
2280 PyBuffer_Release(&vold);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002281 return NULL;
2282 }
2283
2284 res = (PyObject *)replace((PyByteArrayObject *) self,
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002285 vold.buf, vold.len,
2286 vnew.buf, vnew.len, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002287
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002288 PyBuffer_Release(&vold);
2289 PyBuffer_Release(&vnew);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002290 return res;
2291}
2292
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002293/*[clinic input]
2294bytearray.split
2295
2296 sep: object = None
2297 The delimiter according which to split the bytearray.
2298 None (the default value) means split on ASCII whitespace characters
2299 (space, tab, return, newline, formfeed, vertical tab).
2300 maxsplit: Py_ssize_t = -1
2301 Maximum number of splits to do.
2302 -1 (the default value) means no limit.
2303
2304Return a list of the sections in the bytearray, using sep as the delimiter.
2305[clinic start generated code]*/
2306
2307PyDoc_STRVAR(bytearray_split__doc__,
2308"split($self, /, sep=None, maxsplit=-1)\n"
2309"--\n"
2310"\n"
2311"Return a list of the sections in the bytearray, using sep as the delimiter.\n"
2312"\n"
2313" sep\n"
2314" The delimiter according which to split the bytearray.\n"
2315" None (the default value) means split on ASCII whitespace characters\n"
2316" (space, tab, return, newline, formfeed, vertical tab).\n"
2317" maxsplit\n"
2318" Maximum number of splits to do.\n"
2319" -1 (the default value) means no limit.");
2320
2321#define BYTEARRAY_SPLIT_METHODDEF \
2322 {"split", (PyCFunction)bytearray_split, METH_VARARGS|METH_KEYWORDS, bytearray_split__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002323
2324static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002325bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit);
2326
2327static PyObject *
2328bytearray_split(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002329{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002330 PyObject *return_value = NULL;
2331 static char *_keywords[] = {"sep", "maxsplit", NULL};
2332 PyObject *sep = Py_None;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002333 Py_ssize_t maxsplit = -1;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002334
2335 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
2336 "|On:split", _keywords,
2337 &sep, &maxsplit))
2338 goto exit;
2339 return_value = bytearray_split_impl(self, sep, maxsplit);
2340
2341exit:
2342 return return_value;
2343}
2344
2345static PyObject *
2346bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit)
2347/*[clinic end generated code: output=062a3d87d6f918fa input=24f82669f41bf523]*/
2348{
2349 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002350 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002351 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002352 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002353
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002354 if (maxsplit < 0)
2355 maxsplit = PY_SSIZE_T_MAX;
2356
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002357 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002358 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002359
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002360 if (_getbuffer(sep, &vsub) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002361 return NULL;
2362 sub = vsub.buf;
2363 n = vsub.len;
2364
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002365 list = stringlib_split(
2366 (PyObject*) self, s, len, sub, n, maxsplit
2367 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002368 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002369 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002370}
2371
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002372/*[clinic input]
2373bytearray.partition
2374
2375 self: self(type="PyByteArrayObject *")
2376 sep: object
2377 /
2378
2379Partition the bytearray into three parts using the given separator.
2380
2381This will search for the separator sep in the bytearray. If the separator is
2382found, returns a 3-tuple containing the part before the separator, the
2383separator itself, and the part after it.
2384
2385If the separator is not found, returns a 3-tuple containing the original
2386bytearray object and two empty bytearray objects.
2387[clinic start generated code]*/
2388
2389PyDoc_STRVAR(bytearray_partition__doc__,
2390"partition($self, sep, /)\n"
2391"--\n"
2392"\n"
2393"Partition the bytearray into three parts using the given separator.\n"
2394"\n"
2395"This will search for the separator sep in the bytearray. If the separator is\n"
2396"found, returns a 3-tuple containing the part before the separator, the\n"
2397"separator itself, and the part after it.\n"
2398"\n"
2399"If the separator is not found, returns a 3-tuple containing the original\n"
2400"bytearray object and two empty bytearray objects.");
2401
2402#define BYTEARRAY_PARTITION_METHODDEF \
2403 {"partition", (PyCFunction)bytearray_partition, METH_O, bytearray_partition__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002404
2405static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002406bytearray_partition(PyByteArrayObject *self, PyObject *sep)
2407/*[clinic end generated code: output=2645138221fe6f4d input=7d7fe37b1696d506]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002408{
2409 PyObject *bytesep, *result;
2410
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002411 bytesep = PyByteArray_FromObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002412 if (! bytesep)
2413 return NULL;
2414
2415 result = stringlib_partition(
2416 (PyObject*) self,
2417 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2418 bytesep,
2419 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2420 );
2421
2422 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002423 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002424}
2425
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002426/*[clinic input]
2427bytearray.rpartition
2428
2429 self: self(type="PyByteArrayObject *")
2430 sep: object
2431 /
2432
2433Partition the bytes into three parts using the given separator.
2434
2435This will search for the separator sep in the bytearray, starting and the end.
2436If the separator is found, returns a 3-tuple containing the part before the
2437separator, the separator itself, and the part after it.
2438
2439If the separator is not found, returns a 3-tuple containing two empty bytearray
2440objects and the original bytearray object.
2441[clinic start generated code]*/
2442
2443PyDoc_STRVAR(bytearray_rpartition__doc__,
2444"rpartition($self, sep, /)\n"
2445"--\n"
2446"\n"
2447"Partition the bytes into three parts using the given separator.\n"
2448"\n"
2449"This will search for the separator sep in the bytearray, starting and the end.\n"
2450"If the separator is found, returns a 3-tuple containing the part before the\n"
2451"separator, the separator itself, and the part after it.\n"
2452"\n"
2453"If the separator is not found, returns a 3-tuple containing two empty bytearray\n"
2454"objects and the original bytearray object.");
2455
2456#define BYTEARRAY_RPARTITION_METHODDEF \
2457 {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, bytearray_rpartition__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002458
2459static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002460bytearray_rpartition(PyByteArrayObject *self, PyObject *sep)
2461/*[clinic end generated code: output=ed13e54605d007de input=9b8cd540c1b75853]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002462{
2463 PyObject *bytesep, *result;
2464
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002465 bytesep = PyByteArray_FromObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002466 if (! bytesep)
2467 return NULL;
2468
2469 result = stringlib_rpartition(
2470 (PyObject*) self,
2471 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2472 bytesep,
2473 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2474 );
2475
2476 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002477 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002478}
2479
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002480/*[clinic input]
2481bytearray.rsplit = bytearray.split
2482
2483Return a list of the sections in the bytearray, using sep as the delimiter.
2484
2485Splitting is done starting at the end of the bytearray and working to the front.
2486[clinic start generated code]*/
2487
2488PyDoc_STRVAR(bytearray_rsplit__doc__,
2489"rsplit($self, /, sep=None, maxsplit=-1)\n"
2490"--\n"
2491"\n"
2492"Return a list of the sections in the bytearray, using sep as the delimiter.\n"
2493"\n"
2494" sep\n"
2495" The delimiter according which to split the bytearray.\n"
2496" None (the default value) means split on ASCII whitespace characters\n"
2497" (space, tab, return, newline, formfeed, vertical tab).\n"
2498" maxsplit\n"
2499" Maximum number of splits to do.\n"
2500" -1 (the default value) means no limit.\n"
2501"\n"
2502"Splitting is done starting at the end of the bytearray and working to the front.");
2503
2504#define BYTEARRAY_RSPLIT_METHODDEF \
2505 {"rsplit", (PyCFunction)bytearray_rsplit, METH_VARARGS|METH_KEYWORDS, bytearray_rsplit__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002506
2507static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002508bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit);
2509
2510static PyObject *
2511bytearray_rsplit(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002512{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002513 PyObject *return_value = NULL;
2514 static char *_keywords[] = {"sep", "maxsplit", NULL};
2515 PyObject *sep = Py_None;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002516 Py_ssize_t maxsplit = -1;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002517
2518 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
2519 "|On:rsplit", _keywords,
2520 &sep, &maxsplit))
2521 goto exit;
2522 return_value = bytearray_rsplit_impl(self, sep, maxsplit);
2523
2524exit:
2525 return return_value;
2526}
2527
2528static PyObject *
2529bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit)
2530/*[clinic end generated code: output=affaf9fc2aae8d41 input=a68286e4dd692ffe]*/
2531{
2532 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002533 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002534 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002535 Py_buffer vsub;
2536
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002537 if (maxsplit < 0)
2538 maxsplit = PY_SSIZE_T_MAX;
2539
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002540 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002541 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002542
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002543 if (_getbuffer(sep, &vsub) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002544 return NULL;
2545 sub = vsub.buf;
2546 n = vsub.len;
2547
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002548 list = stringlib_rsplit(
2549 (PyObject*) self, s, len, sub, n, maxsplit
2550 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002551 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002552 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002553}
2554
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002555/*[clinic input]
2556bytearray.reverse
2557
2558 self: self(type="PyByteArrayObject *")
2559
2560Reverse the order of the values in B in place.
2561[clinic start generated code]*/
2562
2563PyDoc_STRVAR(bytearray_reverse__doc__,
2564"reverse($self, /)\n"
2565"--\n"
2566"\n"
2567"Reverse the order of the values in B in place.");
2568
2569#define BYTEARRAY_REVERSE_METHODDEF \
2570 {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, bytearray_reverse__doc__},
2571
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002572static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002573bytearray_reverse_impl(PyByteArrayObject *self);
2574
2575static PyObject *
2576bytearray_reverse(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
2577{
2578 return bytearray_reverse_impl(self);
2579}
2580
2581static PyObject *
2582bytearray_reverse_impl(PyByteArrayObject *self)
2583/*[clinic end generated code: output=5d5e5f0bfc67f476 input=7933a499b8597bd1]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002584{
2585 char swap, *head, *tail;
2586 Py_ssize_t i, j, n = Py_SIZE(self);
2587
2588 j = n / 2;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002589 head = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002590 tail = head + n - 1;
2591 for (i = 0; i < j; i++) {
2592 swap = *head;
2593 *head++ = *tail;
2594 *tail-- = swap;
2595 }
2596
2597 Py_RETURN_NONE;
2598}
2599
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002600
2601/*[python input]
2602class bytesvalue_converter(CConverter):
2603 type = 'int'
2604 converter = '_getbytevalue'
2605[python start generated code]*/
2606/*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/
2607
2608
2609/*[clinic input]
2610bytearray.insert
2611
2612 self: self(type="PyByteArrayObject *")
2613 index: Py_ssize_t
2614 The index where the value is to be inserted.
2615 item: bytesvalue
2616 The item to be inserted.
2617 /
2618
2619Insert a single item into the bytearray before the given index.
2620[clinic start generated code]*/
2621
2622PyDoc_STRVAR(bytearray_insert__doc__,
2623"insert($self, index, item, /)\n"
2624"--\n"
2625"\n"
2626"Insert a single item into the bytearray before the given index.\n"
2627"\n"
2628" index\n"
2629" The index where the value is to be inserted.\n"
2630" item\n"
2631" The item to be inserted.");
2632
2633#define BYTEARRAY_INSERT_METHODDEF \
2634 {"insert", (PyCFunction)bytearray_insert, METH_VARARGS, bytearray_insert__doc__},
2635
2636static PyObject *
2637bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item);
2638
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002639static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002640bytearray_insert(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002641{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002642 PyObject *return_value = NULL;
2643 Py_ssize_t index;
2644 int item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002645
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002646 if (!PyArg_ParseTuple(args,
2647 "nO&:insert",
2648 &index, _getbytevalue, &item))
2649 goto exit;
2650 return_value = bytearray_insert_impl(self, index, item);
2651
2652exit:
2653 return return_value;
2654}
2655
2656static PyObject *
2657bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
2658/*[clinic end generated code: output=5ec9340d4ad19080 input=833766836ba30e1e]*/
2659{
2660 Py_ssize_t n = Py_SIZE(self);
2661 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002662
2663 if (n == PY_SSIZE_T_MAX) {
2664 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002665 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002666 return NULL;
2667 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002668 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2669 return NULL;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002670 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002671
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002672 if (index < 0) {
2673 index += n;
2674 if (index < 0)
2675 index = 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002676 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002677 if (index > n)
2678 index = n;
2679 memmove(buf + index + 1, buf + index, n - index);
2680 buf[index] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002681
2682 Py_RETURN_NONE;
2683}
2684
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002685/*[clinic input]
2686bytearray.append
2687
2688 self: self(type="PyByteArrayObject *")
2689 item: bytesvalue
2690 The item to be appended.
2691 /
2692
2693Append a single item to the end of the bytearray.
2694[clinic start generated code]*/
2695
2696PyDoc_STRVAR(bytearray_append__doc__,
2697"append($self, item, /)\n"
2698"--\n"
2699"\n"
2700"Append a single item to the end of the bytearray.\n"
2701"\n"
2702" item\n"
2703" The item to be appended.");
2704
2705#define BYTEARRAY_APPEND_METHODDEF \
2706 {"append", (PyCFunction)bytearray_append, METH_VARARGS, bytearray_append__doc__},
2707
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002708static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002709bytearray_append_impl(PyByteArrayObject *self, int item);
2710
2711static PyObject *
2712bytearray_append(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002713{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002714 PyObject *return_value = NULL;
2715 int item;
2716
2717 if (!PyArg_ParseTuple(args,
2718 "O&:append",
2719 _getbytevalue, &item))
2720 goto exit;
2721 return_value = bytearray_append_impl(self, item);
2722
2723exit:
2724 return return_value;
2725}
2726
2727static PyObject *
2728bytearray_append_impl(PyByteArrayObject *self, int item)
2729/*[clinic end generated code: output=b5b3325bb3bbaf85 input=ae56ea87380407cc]*/
2730{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002731 Py_ssize_t n = Py_SIZE(self);
2732
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002733 if (n == PY_SSIZE_T_MAX) {
2734 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002735 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002736 return NULL;
2737 }
2738 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2739 return NULL;
2740
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002741 PyByteArray_AS_STRING(self)[n] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002742
2743 Py_RETURN_NONE;
2744}
2745
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002746/*[clinic input]
2747bytearray.extend
2748
2749 self: self(type="PyByteArrayObject *")
2750 iterable_of_ints: object
2751 The iterable of items to append.
2752 /
2753
2754Append all the items from the iterator or sequence to the end of the bytearray.
2755[clinic start generated code]*/
2756
2757PyDoc_STRVAR(bytearray_extend__doc__,
2758"extend($self, iterable_of_ints, /)\n"
2759"--\n"
2760"\n"
2761"Append all the items from the iterator or sequence to the end of the bytearray.\n"
2762"\n"
2763" iterable_of_ints\n"
2764" The iterable of items to append.");
2765
2766#define BYTEARRAY_EXTEND_METHODDEF \
2767 {"extend", (PyCFunction)bytearray_extend, METH_O, bytearray_extend__doc__},
2768
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002769static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002770bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
2771/*[clinic end generated code: output=13b0c13ad5110dfb input=ce83a5d75b70d850]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002772{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002773 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002774 Py_ssize_t buf_size = 0, len = 0;
2775 int value;
2776 char *buf;
2777
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002778 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002779 if (PyObject_CheckBuffer(iterable_of_ints)) {
2780 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002781 return NULL;
2782
2783 Py_RETURN_NONE;
2784 }
2785
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002786 it = PyObject_GetIter(iterable_of_ints);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002787 if (it == NULL)
2788 return NULL;
2789
Ezio Melotti42da6632011-03-15 05:18:48 +02002790 /* Try to determine the length of the argument. 32 is arbitrary. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002791 buf_size = PyObject_LengthHint(iterable_of_ints, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002792 if (buf_size == -1) {
2793 Py_DECREF(it);
2794 return NULL;
2795 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002796
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002797 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002798 if (bytearray_obj == NULL) {
2799 Py_DECREF(it);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002800 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002801 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002802 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002803
2804 while ((item = PyIter_Next(it)) != NULL) {
2805 if (! _getbytevalue(item, &value)) {
2806 Py_DECREF(item);
2807 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002808 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002809 return NULL;
2810 }
2811 buf[len++] = value;
2812 Py_DECREF(item);
2813
2814 if (len >= buf_size) {
2815 buf_size = len + (len >> 1) + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002816 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002817 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002818 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002819 return NULL;
2820 }
2821 /* Recompute the `buf' pointer, since the resizing operation may
2822 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002823 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002824 }
2825 }
2826 Py_DECREF(it);
2827
2828 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002829 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
2830 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002831 return NULL;
2832 }
2833
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002834 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
2835 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002836 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002837 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002838 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002839
2840 Py_RETURN_NONE;
2841}
2842
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002843/*[clinic input]
2844bytearray.pop
2845
2846 self: self(type="PyByteArrayObject *")
2847 index: Py_ssize_t = -1
2848 The index from where to remove the item.
2849 -1 (the default value) means remove the last item.
2850 /
2851
2852Remove and return a single item from B.
2853
2854If no index argument is given, will pop the last item.
2855[clinic start generated code]*/
2856
2857PyDoc_STRVAR(bytearray_pop__doc__,
2858"pop($self, index=-1, /)\n"
2859"--\n"
2860"\n"
2861"Remove and return a single item from B.\n"
2862"\n"
2863" index\n"
2864" The index from where to remove the item.\n"
2865" -1 (the default value) means remove the last item.\n"
2866"\n"
2867"If no index argument is given, will pop the last item.");
2868
2869#define BYTEARRAY_POP_METHODDEF \
2870 {"pop", (PyCFunction)bytearray_pop, METH_VARARGS, bytearray_pop__doc__},
2871
2872static PyObject *
2873bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index);
2874
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002875static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002876bytearray_pop(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002877{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002878 PyObject *return_value = NULL;
2879 Py_ssize_t index = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002880
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002881 if (!PyArg_ParseTuple(args,
2882 "|n:pop",
2883 &index))
2884 goto exit;
2885 return_value = bytearray_pop_impl(self, index);
2886
2887exit:
2888 return return_value;
2889}
2890
2891static PyObject *
2892bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
2893/*[clinic end generated code: output=3b763e548e79af96 input=0797e6c0ca9d5a85]*/
2894{
2895 int value;
2896 Py_ssize_t n = Py_SIZE(self);
2897 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002898
2899 if (n == 0) {
Eli Bendersky1bc4f192011-03-04 04:55:25 +00002900 PyErr_SetString(PyExc_IndexError,
2901 "pop from empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002902 return NULL;
2903 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002904 if (index < 0)
2905 index += Py_SIZE(self);
2906 if (index < 0 || index >= Py_SIZE(self)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002907 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2908 return NULL;
2909 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002910 if (!_canresize(self))
2911 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002912
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002913 buf = PyByteArray_AS_STRING(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002914 value = buf[index];
2915 memmove(buf + index, buf + index + 1, n - index);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002916 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2917 return NULL;
2918
Mark Dickinson54a3db92009-09-06 10:19:23 +00002919 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002920}
2921
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002922/*[clinic input]
2923bytearray.remove
2924
2925 self: self(type="PyByteArrayObject *")
2926 value: bytesvalue
2927 The value to remove.
2928 /
2929
2930Remove the first occurrence of a value in the bytearray.
2931[clinic start generated code]*/
2932
2933PyDoc_STRVAR(bytearray_remove__doc__,
2934"remove($self, value, /)\n"
2935"--\n"
2936"\n"
2937"Remove the first occurrence of a value in the bytearray.\n"
2938"\n"
2939" value\n"
2940" The value to remove.");
2941
2942#define BYTEARRAY_REMOVE_METHODDEF \
2943 {"remove", (PyCFunction)bytearray_remove, METH_VARARGS, bytearray_remove__doc__},
2944
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002945static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002946bytearray_remove_impl(PyByteArrayObject *self, int value);
2947
2948static PyObject *
2949bytearray_remove(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002950{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002951 PyObject *return_value = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002952 int value;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002953
2954 if (!PyArg_ParseTuple(args,
2955 "O&:remove",
2956 _getbytevalue, &value))
2957 goto exit;
2958 return_value = bytearray_remove_impl(self, value);
2959
2960exit:
2961 return return_value;
2962}
2963
2964static PyObject *
2965bytearray_remove_impl(PyByteArrayObject *self, int value)
2966/*[clinic end generated code: output=c71c8bcf4703abfc input=47560b11fd856c24]*/
2967{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002968 Py_ssize_t where, n = Py_SIZE(self);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002969 char *buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002970
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002971 for (where = 0; where < n; where++) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002972 if (buf[where] == value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002973 break;
2974 }
2975 if (where == n) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002976 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002977 return NULL;
2978 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002979 if (!_canresize(self))
2980 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002981
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002982 memmove(buf + where, buf + where + 1, n - where);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002983 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2984 return NULL;
2985
2986 Py_RETURN_NONE;
2987}
2988
2989/* XXX These two helpers could be optimized if argsize == 1 */
2990
2991static Py_ssize_t
Antoine Pitrou5b720752013-10-05 21:24:10 +02002992lstrip_helper(char *myptr, Py_ssize_t mysize,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002993 void *argptr, Py_ssize_t argsize)
2994{
2995 Py_ssize_t i = 0;
Antoine Pitrou5b720752013-10-05 21:24:10 +02002996 while (i < mysize && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002997 i++;
2998 return i;
2999}
3000
3001static Py_ssize_t
Antoine Pitrou5b720752013-10-05 21:24:10 +02003002rstrip_helper(char *myptr, Py_ssize_t mysize,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003003 void *argptr, Py_ssize_t argsize)
3004{
3005 Py_ssize_t i = mysize - 1;
Antoine Pitrou5b720752013-10-05 21:24:10 +02003006 while (i >= 0 && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003007 i--;
3008 return i + 1;
3009}
3010
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003011/*[clinic input]
3012bytearray.strip
3013
3014 bytes: object = None
3015 /
3016
3017Strip leading and trailing bytes contained in the argument.
3018
3019If the argument is omitted or None, strip leading and trailing ASCII whitespace.
3020[clinic start generated code]*/
3021
3022PyDoc_STRVAR(bytearray_strip__doc__,
3023"strip($self, bytes=None, /)\n"
3024"--\n"
3025"\n"
3026"Strip leading and trailing bytes contained in the argument.\n"
3027"\n"
3028"If the argument is omitted or None, strip leading and trailing ASCII whitespace.");
3029
3030#define BYTEARRAY_STRIP_METHODDEF \
3031 {"strip", (PyCFunction)bytearray_strip, METH_VARARGS, bytearray_strip__doc__},
3032
3033static PyObject *
3034bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes);
3035
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003036static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003037bytearray_strip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003038{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003039 PyObject *return_value = NULL;
3040 PyObject *bytes = Py_None;
3041
3042 if (!PyArg_UnpackTuple(args, "strip",
3043 0, 1,
3044 &bytes))
3045 goto exit;
3046 return_value = bytearray_strip_impl(self, bytes);
3047
3048exit:
3049 return return_value;
3050}
3051
3052static PyObject *
3053bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
3054/*[clinic end generated code: output=2e3d3358acc4c235 input=ef7bb59b09c21d62]*/
3055{
3056 Py_ssize_t left, right, mysize, byteslen;
3057 char *myptr, *bytesptr;
3058 Py_buffer vbytes;
3059
3060 if (bytes == Py_None) {
3061 bytesptr = "\t\n\r\f\v ";
3062 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003063 }
3064 else {
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003065 if (_getbuffer(bytes, &vbytes) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003066 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003067 bytesptr = (char *) vbytes.buf;
3068 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003069 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003070 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003071 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003072 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003073 if (left == mysize)
3074 right = left;
3075 else
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003076 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
3077 if (bytes != Py_None)
3078 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003079 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003080}
3081
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003082/*[clinic input]
3083bytearray.lstrip
3084
3085 bytes: object = None
3086 /
3087
3088Strip leading bytes contained in the argument.
3089
3090If the argument is omitted or None, strip leading ASCII whitespace.
3091[clinic start generated code]*/
3092
3093PyDoc_STRVAR(bytearray_lstrip__doc__,
3094"lstrip($self, bytes=None, /)\n"
3095"--\n"
3096"\n"
3097"Strip leading bytes contained in the argument.\n"
3098"\n"
3099"If the argument is omitted or None, strip leading ASCII whitespace.");
3100
3101#define BYTEARRAY_LSTRIP_METHODDEF \
3102 {"lstrip", (PyCFunction)bytearray_lstrip, METH_VARARGS, bytearray_lstrip__doc__},
3103
3104static PyObject *
3105bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes);
3106
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003107static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003108bytearray_lstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003109{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003110 PyObject *return_value = NULL;
3111 PyObject *bytes = Py_None;
3112
3113 if (!PyArg_UnpackTuple(args, "lstrip",
3114 0, 1,
3115 &bytes))
3116 goto exit;
3117 return_value = bytearray_lstrip_impl(self, bytes);
3118
3119exit:
3120 return return_value;
3121}
3122
3123static PyObject *
3124bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
3125/*[clinic end generated code: output=2599309808a9ec02 input=80843f975dd7c480]*/
3126{
3127 Py_ssize_t left, right, mysize, byteslen;
3128 char *myptr, *bytesptr;
3129 Py_buffer vbytes;
3130
3131 if (bytes == Py_None) {
3132 bytesptr = "\t\n\r\f\v ";
3133 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003134 }
3135 else {
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003136 if (_getbuffer(bytes, &vbytes) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003137 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003138 bytesptr = (char *) vbytes.buf;
3139 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003140 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003141 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003142 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003143 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003144 right = mysize;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003145 if (bytes != Py_None)
3146 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003147 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003148}
3149
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003150/*[clinic input]
3151bytearray.rstrip
3152
3153 bytes: object = None
3154 /
3155
3156Strip trailing bytes contained in the argument.
3157
3158If the argument is omitted or None, strip trailing ASCII whitespace.
3159[clinic start generated code]*/
3160
3161PyDoc_STRVAR(bytearray_rstrip__doc__,
3162"rstrip($self, bytes=None, /)\n"
3163"--\n"
3164"\n"
3165"Strip trailing bytes contained in the argument.\n"
3166"\n"
3167"If the argument is omitted or None, strip trailing ASCII whitespace.");
3168
3169#define BYTEARRAY_RSTRIP_METHODDEF \
3170 {"rstrip", (PyCFunction)bytearray_rstrip, METH_VARARGS, bytearray_rstrip__doc__},
3171
3172static PyObject *
3173bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes);
3174
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003175static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003176bytearray_rstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003177{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003178 PyObject *return_value = NULL;
3179 PyObject *bytes = Py_None;
3180
3181 if (!PyArg_UnpackTuple(args, "rstrip",
3182 0, 1,
3183 &bytes))
3184 goto exit;
3185 return_value = bytearray_rstrip_impl(self, bytes);
3186
3187exit:
3188 return return_value;
3189}
3190
3191static PyObject *
3192bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
3193/*[clinic end generated code: output=b5ca6259f4f4f2a3 input=e728b994954cfd91]*/
3194{
3195 Py_ssize_t right, mysize, byteslen;
3196 char *myptr, *bytesptr;
3197 Py_buffer vbytes;
3198
3199 if (bytes == Py_None) {
3200 bytesptr = "\t\n\r\f\v ";
3201 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003202 }
3203 else {
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003204 if (_getbuffer(bytes, &vbytes) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003205 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003206 bytesptr = (char *) vbytes.buf;
3207 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003208 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003209 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003210 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003211 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
3212 if (bytes != Py_None)
3213 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003214 return PyByteArray_FromStringAndSize(myptr, right);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003215}
3216
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003217/*[clinic input]
3218bytearray.decode
3219
3220 encoding: str(c_default="NULL") = 'utf-8'
3221 The encoding with which to decode the bytearray.
3222 errors: str(c_default="NULL") = 'strict'
3223 The error handling scheme to use for the handling of decoding errors.
3224 The default is 'strict' meaning that decoding errors raise a
3225 UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
3226 as well as any other name registered with codecs.register_error that
3227 can handle UnicodeDecodeErrors.
3228
3229Decode the bytearray using the codec registered for encoding.
3230[clinic start generated code]*/
3231
3232PyDoc_STRVAR(bytearray_decode__doc__,
3233"decode($self, /, encoding=\'utf-8\', errors=\'strict\')\n"
3234"--\n"
3235"\n"
3236"Decode the bytearray using the codec registered for encoding.\n"
3237"\n"
3238" encoding\n"
3239" The encoding with which to decode the bytearray.\n"
3240" errors\n"
3241" The error handling scheme to use for the handling of decoding errors.\n"
3242" The default is \'strict\' meaning that decoding errors raise a\n"
3243" UnicodeDecodeError. Other possible values are \'ignore\' and \'replace\'\n"
3244" as well as any other name registered with codecs.register_error that\n"
3245" can handle UnicodeDecodeErrors.");
3246
3247#define BYTEARRAY_DECODE_METHODDEF \
3248 {"decode", (PyCFunction)bytearray_decode, METH_VARARGS|METH_KEYWORDS, bytearray_decode__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003249
3250static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003251bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors);
3252
3253static PyObject *
3254bytearray_decode(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003255{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003256 PyObject *return_value = NULL;
3257 static char *_keywords[] = {"encoding", "errors", NULL};
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003258 const char *encoding = NULL;
3259 const char *errors = NULL;
3260
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003261 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
3262 "|ss:decode", _keywords,
3263 &encoding, &errors))
3264 goto exit;
3265 return_value = bytearray_decode_impl(self, encoding, errors);
3266
3267exit:
3268 return return_value;
3269}
3270
3271static PyObject *
3272bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors)
3273/*[clinic end generated code: output=38b83681f1e38a6c input=f28d8f903020257b]*/
3274{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003275 if (encoding == NULL)
3276 encoding = PyUnicode_GetDefaultEncoding();
Martin v. Löwis0efea322014-07-27 17:29:17 +02003277 return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003278}
3279
3280PyDoc_STRVAR(alloc_doc,
3281"B.__alloc__() -> int\n\
3282\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00003283Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003284
3285static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003286bytearray_alloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003287{
3288 return PyLong_FromSsize_t(self->ob_alloc);
3289}
3290
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003291/*[clinic input]
3292bytearray.join
3293
3294 iterable_of_bytes: object
3295 /
3296
3297Concatenate any number of bytes/bytearray objects.
3298
3299The bytearray whose method is called is inserted in between each pair.
3300
3301The result is returned as a new bytearray object.
3302[clinic start generated code]*/
3303
3304PyDoc_STRVAR(bytearray_join__doc__,
3305"join($self, iterable_of_bytes, /)\n"
3306"--\n"
3307"\n"
3308"Concatenate any number of bytes/bytearray objects.\n"
3309"\n"
3310"The bytearray whose method is called is inserted in between each pair.\n"
3311"\n"
3312"The result is returned as a new bytearray object.");
3313
3314#define BYTEARRAY_JOIN_METHODDEF \
3315 {"join", (PyCFunction)bytearray_join, METH_O, bytearray_join__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003316
3317static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003318bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes)
3319/*[clinic end generated code: output=544e7430032dfdf4 input=aba6b1f9b30fcb8e]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003320{
Martin v. Löwis0efea322014-07-27 17:29:17 +02003321 return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003322}
3323
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003324/*[clinic input]
3325bytearray.splitlines
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003326
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003327 keepends: int(py_default="False") = 0
3328
3329Return a list of the lines in the bytearray, breaking at line boundaries.
3330
3331Line breaks are not included in the resulting list unless keepends is given and
3332true.
3333[clinic start generated code]*/
3334
3335PyDoc_STRVAR(bytearray_splitlines__doc__,
3336"splitlines($self, /, keepends=False)\n"
3337"--\n"
3338"\n"
3339"Return a list of the lines in the bytearray, breaking at line boundaries.\n"
3340"\n"
3341"Line breaks are not included in the resulting list unless keepends is given and\n"
3342"true.");
3343
3344#define BYTEARRAY_SPLITLINES_METHODDEF \
3345 {"splitlines", (PyCFunction)bytearray_splitlines, METH_VARARGS|METH_KEYWORDS, bytearray_splitlines__doc__},
3346
3347static PyObject *
3348bytearray_splitlines_impl(PyByteArrayObject *self, int keepends);
3349
3350static PyObject *
3351bytearray_splitlines(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003352{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003353 PyObject *return_value = NULL;
3354 static char *_keywords[] = {"keepends", NULL};
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003355 int keepends = 0;
3356
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003357 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
3358 "|i:splitlines", _keywords,
3359 &keepends))
3360 goto exit;
3361 return_value = bytearray_splitlines_impl(self, keepends);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003362
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003363exit:
3364 return return_value;
3365}
3366
3367static PyObject *
3368bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
3369/*[clinic end generated code: output=a837fd0512ad46ff input=36f0b25bc792f6c0]*/
3370{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003371 return stringlib_splitlines(
3372 (PyObject*) self, PyByteArray_AS_STRING(self),
3373 PyByteArray_GET_SIZE(self), keepends
3374 );
3375}
3376
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003377static int
Victor Stinner6430fd52011-09-29 04:02:13 +02003378hex_digit_to_int(Py_UCS4 c)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003379{
3380 if (c >= 128)
3381 return -1;
Eric Smith6dc46f52009-04-27 20:39:49 +00003382 if (Py_ISDIGIT(c))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003383 return c - '0';
3384 else {
Eric Smith6dc46f52009-04-27 20:39:49 +00003385 if (Py_ISUPPER(c))
3386 c = Py_TOLOWER(c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003387 if (c >= 'a' && c <= 'f')
3388 return c - 'a' + 10;
3389 }
3390 return -1;
3391}
3392
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003393/*[clinic input]
3394@classmethod
3395bytearray.fromhex
3396
3397 cls: self(type="PyObject*")
3398 string: unicode
3399 /
3400
3401Create a bytearray object from a string of hexadecimal numbers.
3402
3403Spaces between two numbers are accepted.
3404Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
3405[clinic start generated code]*/
3406
3407PyDoc_STRVAR(bytearray_fromhex__doc__,
3408"fromhex($type, string, /)\n"
3409"--\n"
3410"\n"
3411"Create a bytearray object from a string of hexadecimal numbers.\n"
3412"\n"
3413"Spaces between two numbers are accepted.\n"
3414"Example: bytearray.fromhex(\'B9 01EF\') -> bytearray(b\'\\\\xb9\\\\x01\\\\xef\')");
3415
3416#define BYTEARRAY_FROMHEX_METHODDEF \
3417 {"fromhex", (PyCFunction)bytearray_fromhex, METH_VARARGS|METH_CLASS, bytearray_fromhex__doc__},
3418
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003419static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003420bytearray_fromhex_impl(PyObject*cls, PyObject *string);
3421
3422static PyObject *
3423bytearray_fromhex(PyTypeObject *cls, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003424{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003425 PyObject *return_value = NULL;
3426 PyObject *string;
3427
3428 if (!PyArg_ParseTuple(args,
3429 "U:fromhex",
3430 &string))
3431 goto exit;
3432 return_value = bytearray_fromhex_impl((PyObject*)cls, string);
3433
3434exit:
3435 return return_value;
3436}
3437
3438static PyObject *
3439bytearray_fromhex_impl(PyObject*cls, PyObject *string)
3440/*[clinic end generated code: output=adc3c804a74e56d4 input=907bbd2d34d9367a]*/
3441{
3442 PyObject *newbytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003443 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003444 Py_ssize_t hexlen, byteslen, i, j;
3445 int top, bot;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003446 void *data;
3447 unsigned int kind;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003448
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003449 assert(PyUnicode_Check(string));
3450 if (PyUnicode_READY(string))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003451 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003452 kind = PyUnicode_KIND(string);
3453 data = PyUnicode_DATA(string);
3454 hexlen = PyUnicode_GET_LENGTH(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003455
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003456 byteslen = hexlen/2; /* This overestimates if there are spaces */
3457 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
3458 if (!newbytes)
3459 return NULL;
3460 buf = PyByteArray_AS_STRING(newbytes);
3461 for (i = j = 0; i < hexlen; i += 2) {
3462 /* skip over spaces in the input */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003463 while (PyUnicode_READ(kind, data, i) == ' ')
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003464 i++;
3465 if (i >= hexlen)
3466 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003467 top = hex_digit_to_int(PyUnicode_READ(kind, data, i));
3468 bot = hex_digit_to_int(PyUnicode_READ(kind, data, i+1));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003469 if (top == -1 || bot == -1) {
3470 PyErr_Format(PyExc_ValueError,
3471 "non-hexadecimal number found in "
3472 "fromhex() arg at position %zd", i);
3473 goto error;
3474 }
3475 buf[j++] = (top << 4) + bot;
3476 }
3477 if (PyByteArray_Resize(newbytes, j) < 0)
3478 goto error;
3479 return newbytes;
3480
3481 error:
3482 Py_DECREF(newbytes);
3483 return NULL;
3484}
3485
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003486
3487static PyObject *
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003488_common_reduce(PyByteArrayObject *self, int proto)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003489{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003490 PyObject *dict;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003491 _Py_IDENTIFIER(__dict__);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003492 char *buf;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003493
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003494 dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003495 if (dict == NULL) {
3496 PyErr_Clear();
3497 dict = Py_None;
3498 Py_INCREF(dict);
3499 }
3500
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003501 buf = PyByteArray_AS_STRING(self);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003502 if (proto < 3) {
3503 /* use str based reduction for backwards compatibility with Python 2.x */
3504 PyObject *latin1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003505 if (Py_SIZE(self))
3506 latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003507 else
3508 latin1 = PyUnicode_FromString("");
3509 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
3510 }
3511 else {
3512 /* use more efficient byte based reduction */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003513 if (Py_SIZE(self)) {
3514 return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), dict);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003515 }
3516 else {
3517 return Py_BuildValue("(O()N)", Py_TYPE(self), dict);
3518 }
3519 }
3520}
3521
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003522/*[clinic input]
3523bytearray.__reduce__ as bytearray_reduce
3524
3525 self: self(type="PyByteArrayObject *")
3526
3527Return state information for pickling.
3528[clinic start generated code]*/
3529
3530PyDoc_STRVAR(bytearray_reduce__doc__,
3531"__reduce__($self, /)\n"
3532"--\n"
3533"\n"
3534"Return state information for pickling.");
3535
3536#define BYTEARRAY_REDUCE_METHODDEF \
3537 {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, bytearray_reduce__doc__},
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003538
3539static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003540bytearray_reduce_impl(PyByteArrayObject *self);
3541
3542static PyObject *
3543bytearray_reduce(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
3544{
3545 return bytearray_reduce_impl(self);
3546}
3547
3548static PyObject *
3549bytearray_reduce_impl(PyByteArrayObject *self)
3550/*[clinic end generated code: output=b1b56fe87bf30fb0 input=fbb07de4d102a03a]*/
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003551{
3552 return _common_reduce(self, 2);
3553}
3554
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003555/*[clinic input]
3556bytearray.__reduce_ex__ as bytearray_reduce_ex
3557
3558 self: self(type="PyByteArrayObject *")
3559 proto: int = 0
3560 /
3561
3562Return state information for pickling.
3563[clinic start generated code]*/
3564
3565PyDoc_STRVAR(bytearray_reduce_ex__doc__,
3566"__reduce_ex__($self, proto=0, /)\n"
3567"--\n"
3568"\n"
3569"Return state information for pickling.");
3570
3571#define BYTEARRAY_REDUCE_EX_METHODDEF \
3572 {"__reduce_ex__", (PyCFunction)bytearray_reduce_ex, METH_VARARGS, bytearray_reduce_ex__doc__},
3573
3574static PyObject *
3575bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003576
3577static PyObject *
3578bytearray_reduce_ex(PyByteArrayObject *self, PyObject *args)
3579{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003580 PyObject *return_value = NULL;
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003581 int proto = 0;
3582
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003583 if (!PyArg_ParseTuple(args,
3584 "|i:__reduce_ex__",
3585 &proto))
3586 goto exit;
3587 return_value = bytearray_reduce_ex_impl(self, proto);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003588
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003589exit:
3590 return return_value;
3591}
3592
3593static PyObject *
3594bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
3595/*[clinic end generated code: output=bbd9afb2f5953dc1 input=0e091a42ca6dbd91]*/
3596{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003597 return _common_reduce(self, proto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003598}
3599
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003600/*[clinic input]
3601bytearray.__sizeof__ as bytearray_sizeof
3602
3603 self: self(type="PyByteArrayObject *")
3604
3605Returns the size of the bytearray object in memory, in bytes.
3606[clinic start generated code]*/
3607
3608PyDoc_STRVAR(bytearray_sizeof__doc__,
3609"__sizeof__($self, /)\n"
3610"--\n"
3611"\n"
3612"Returns the size of the bytearray object in memory, in bytes.");
3613
3614#define BYTEARRAY_SIZEOF_METHODDEF \
3615 {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, bytearray_sizeof__doc__},
3616
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003617static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003618bytearray_sizeof_impl(PyByteArrayObject *self);
3619
3620static PyObject *
3621bytearray_sizeof(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
3622{
3623 return bytearray_sizeof_impl(self);
3624}
3625
3626static PyObject *
3627bytearray_sizeof_impl(PyByteArrayObject *self)
3628/*[clinic end generated code: output=4a2254b0a85630c6 input=6b23d305362b462b]*/
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003629{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00003630 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003631
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00003632 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
3633 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003634}
3635
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003636static PySequenceMethods bytearray_as_sequence = {
3637 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003638 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003639 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
3640 (ssizeargfunc)bytearray_getitem, /* sq_item */
3641 0, /* sq_slice */
3642 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
3643 0, /* sq_ass_slice */
3644 (objobjproc)bytearray_contains, /* sq_contains */
3645 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
3646 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003647};
3648
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003649static PyMappingMethods bytearray_as_mapping = {
3650 (lenfunc)bytearray_length,
3651 (binaryfunc)bytearray_subscript,
3652 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003653};
3654
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003655static PyBufferProcs bytearray_as_buffer = {
3656 (getbufferproc)bytearray_getbuffer,
3657 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003658};
3659
3660static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003661bytearray_methods[] = {
3662 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003663 BYTEARRAY_REDUCE_METHODDEF
3664 BYTEARRAY_REDUCE_EX_METHODDEF
3665 BYTEARRAY_SIZEOF_METHODDEF
3666 BYTEARRAY_APPEND_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003667 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
3668 _Py_capitalize__doc__},
3669 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003670 BYTEARRAY_CLEAR_METHODDEF
3671 BYTEARRAY_COPY_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003672 {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003673 BYTEARRAY_DECODE_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003674 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +02003675 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS | METH_KEYWORDS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003676 expandtabs__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003677 BYTEARRAY_EXTEND_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003678 {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003679 BYTEARRAY_FROMHEX_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003680 {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003681 BYTEARRAY_INSERT_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003682 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
3683 _Py_isalnum__doc__},
3684 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
3685 _Py_isalpha__doc__},
3686 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
3687 _Py_isdigit__doc__},
3688 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
3689 _Py_islower__doc__},
3690 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
3691 _Py_isspace__doc__},
3692 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
3693 _Py_istitle__doc__},
3694 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
3695 _Py_isupper__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003696 BYTEARRAY_JOIN_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003697 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
3698 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003699 BYTEARRAY_LSTRIP_METHODDEF
3700 BYTEARRAY_MAKETRANS_METHODDEF
3701 BYTEARRAY_PARTITION_METHODDEF
3702 BYTEARRAY_POP_METHODDEF
3703 BYTEARRAY_REMOVE_METHODDEF
3704 BYTEARRAY_REPLACE_METHODDEF
3705 BYTEARRAY_REVERSE_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003706 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
3707 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003708 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003709 BYTEARRAY_RPARTITION_METHODDEF
3710 BYTEARRAY_RSPLIT_METHODDEF
3711 BYTEARRAY_RSTRIP_METHODDEF
3712 BYTEARRAY_SPLIT_METHODDEF
3713 BYTEARRAY_SPLITLINES_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003714 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003715 startswith__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003716 BYTEARRAY_STRIP_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003717 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
3718 _Py_swapcase__doc__},
3719 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003720 BYTEARRAY_TRANSLATE_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003721 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
3722 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
3723 {NULL}
3724};
3725
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003726PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00003727"bytearray(iterable_of_ints) -> bytearray\n\
3728bytearray(string, encoding[, errors]) -> bytearray\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003729bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
3730bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
3731bytearray() -> empty bytes array\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003732\n\
3733Construct an mutable bytearray object from:\n\
3734 - an iterable yielding integers in range(256)\n\
3735 - a text string encoded using the specified encoding\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003736 - a bytes or a buffer object\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003737 - any object implementing the buffer API.\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003738 - an integer");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003739
3740
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003741static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003742
3743PyTypeObject PyByteArray_Type = {
3744 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3745 "bytearray",
3746 sizeof(PyByteArrayObject),
3747 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003748 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003749 0, /* tp_print */
3750 0, /* tp_getattr */
3751 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003752 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003753 (reprfunc)bytearray_repr, /* tp_repr */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003754 0, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003755 &bytearray_as_sequence, /* tp_as_sequence */
3756 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003757 0, /* tp_hash */
3758 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003759 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003760 PyObject_GenericGetAttr, /* tp_getattro */
3761 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003762 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003763 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003764 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003765 0, /* tp_traverse */
3766 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003767 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003768 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003769 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003770 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003771 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003772 0, /* tp_members */
3773 0, /* tp_getset */
3774 0, /* tp_base */
3775 0, /* tp_dict */
3776 0, /* tp_descr_get */
3777 0, /* tp_descr_set */
3778 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003779 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003780 PyType_GenericAlloc, /* tp_alloc */
3781 PyType_GenericNew, /* tp_new */
3782 PyObject_Del, /* tp_free */
3783};
3784
3785/*********************** Bytes Iterator ****************************/
3786
3787typedef struct {
3788 PyObject_HEAD
3789 Py_ssize_t it_index;
3790 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
3791} bytesiterobject;
3792
3793static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003794bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003795{
3796 _PyObject_GC_UNTRACK(it);
3797 Py_XDECREF(it->it_seq);
3798 PyObject_GC_Del(it);
3799}
3800
3801static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003802bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003803{
3804 Py_VISIT(it->it_seq);
3805 return 0;
3806}
3807
3808static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003809bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003810{
3811 PyByteArrayObject *seq;
3812 PyObject *item;
3813
3814 assert(it != NULL);
3815 seq = it->it_seq;
3816 if (seq == NULL)
3817 return NULL;
3818 assert(PyByteArray_Check(seq));
3819
3820 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
3821 item = PyLong_FromLong(
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003822 (unsigned char)PyByteArray_AS_STRING(seq)[it->it_index]);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003823 if (item != NULL)
3824 ++it->it_index;
3825 return item;
3826 }
3827
3828 Py_DECREF(seq);
3829 it->it_seq = NULL;
3830 return NULL;
3831}
3832
3833static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003834bytearrayiter_length_hint(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003835{
3836 Py_ssize_t len = 0;
3837 if (it->it_seq)
3838 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
3839 return PyLong_FromSsize_t(len);
3840}
3841
3842PyDoc_STRVAR(length_hint_doc,
3843 "Private method returning an estimate of len(list(it)).");
3844
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003845static PyObject *
3846bytearrayiter_reduce(bytesiterobject *it)
3847{
3848 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +02003849 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003850 it->it_seq, it->it_index);
3851 } else {
3852 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
3853 if (u == NULL)
3854 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02003855 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003856 }
3857}
3858
3859static PyObject *
3860bytearrayiter_setstate(bytesiterobject *it, PyObject *state)
3861{
3862 Py_ssize_t index = PyLong_AsSsize_t(state);
3863 if (index == -1 && PyErr_Occurred())
3864 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00003865 if (it->it_seq != NULL) {
3866 if (index < 0)
3867 index = 0;
3868 else if (index > PyByteArray_GET_SIZE(it->it_seq))
3869 index = PyByteArray_GET_SIZE(it->it_seq); /* iterator exhausted */
3870 it->it_index = index;
3871 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003872 Py_RETURN_NONE;
3873}
3874
3875PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
3876
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003877static PyMethodDef bytearrayiter_methods[] = {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003878 {"__length_hint__", (PyCFunction)bytearrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003879 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003880 {"__reduce__", (PyCFunction)bytearrayiter_reduce, METH_NOARGS,
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003881 bytearray_reduce__doc__},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003882 {"__setstate__", (PyCFunction)bytearrayiter_setstate, METH_O,
3883 setstate_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003884 {NULL, NULL} /* sentinel */
3885};
3886
3887PyTypeObject PyByteArrayIter_Type = {
3888 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3889 "bytearray_iterator", /* tp_name */
3890 sizeof(bytesiterobject), /* tp_basicsize */
3891 0, /* tp_itemsize */
3892 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003893 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003894 0, /* tp_print */
3895 0, /* tp_getattr */
3896 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003897 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003898 0, /* tp_repr */
3899 0, /* tp_as_number */
3900 0, /* tp_as_sequence */
3901 0, /* tp_as_mapping */
3902 0, /* tp_hash */
3903 0, /* tp_call */
3904 0, /* tp_str */
3905 PyObject_GenericGetAttr, /* tp_getattro */
3906 0, /* tp_setattro */
3907 0, /* tp_as_buffer */
3908 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
3909 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003910 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003911 0, /* tp_clear */
3912 0, /* tp_richcompare */
3913 0, /* tp_weaklistoffset */
3914 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003915 (iternextfunc)bytearrayiter_next, /* tp_iternext */
3916 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003917 0,
3918};
3919
3920static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003921bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003922{
3923 bytesiterobject *it;
3924
3925 if (!PyByteArray_Check(seq)) {
3926 PyErr_BadInternalCall();
3927 return NULL;
3928 }
3929 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
3930 if (it == NULL)
3931 return NULL;
3932 it->it_index = 0;
3933 Py_INCREF(seq);
3934 it->it_seq = (PyByteArrayObject *)seq;
3935 _PyObject_GC_TRACK(it);
3936 return (PyObject *)it;
3937}