blob: f6f370d42c3529e94b586779c39eb61911d0ef41 [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,
90 "Type %.100s doesn't support the buffer API",
91 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
183PyByteArray_Resize(PyObject *self, Py_ssize_t size)
184{
185 void *sval;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200186 PyByteArrayObject *obj = ((PyByteArrayObject *)self);
187 Py_ssize_t alloc = obj->ob_alloc;
188 Py_ssize_t logical_offset = obj->ob_start - obj->ob_bytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000189
190 assert(self != NULL);
191 assert(PyByteArray_Check(self));
192 assert(size >= 0);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200193 assert(logical_offset >= 0);
194 assert(logical_offset <= alloc);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000195
Antoine Pitrou5504e892008-12-06 21:27:53 +0000196 if (size == Py_SIZE(self)) {
197 return 0;
198 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200199 if (!_canresize(obj)) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000200 return -1;
201 }
202
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200203 if (size + logical_offset + 1 < alloc) {
204 /* Current buffer is large enough to host the requested size,
205 decide on a strategy. */
206 if (size < alloc / 2) {
207 /* Major downsize; resize down to exact size */
208 alloc = size + 1;
209 }
210 else {
211 /* Minor downsize; quick exit */
212 Py_SIZE(self) = size;
213 PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */
214 return 0;
215 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000216 }
217 else {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200218 /* Need growing, decide on a strategy */
219 if (size <= alloc * 1.125) {
220 /* Moderate upsize; overallocate similar to list_resize() */
221 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
222 }
223 else {
224 /* Major upsize; resize up to exact size */
225 alloc = size + 1;
226 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000227 }
228
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200229 if (logical_offset > 0) {
230 sval = PyObject_Malloc(alloc);
231 if (sval == NULL) {
232 PyErr_NoMemory();
233 return -1;
234 }
235 memcpy(sval, PyByteArray_AS_STRING(self), Py_MIN(size, Py_SIZE(self)));
236 PyObject_Free(obj->ob_bytes);
237 }
238 else {
239 sval = PyObject_Realloc(obj->ob_bytes, alloc);
240 if (sval == NULL) {
241 PyErr_NoMemory();
242 return -1;
243 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000244 }
245
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200246 obj->ob_bytes = obj->ob_start = sval;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000247 Py_SIZE(self) = size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200248 obj->ob_alloc = alloc;
249 obj->ob_bytes[size] = '\0'; /* Trailing null byte */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000250
251 return 0;
252}
253
254PyObject *
255PyByteArray_Concat(PyObject *a, PyObject *b)
256{
257 Py_ssize_t size;
258 Py_buffer va, vb;
259 PyByteArrayObject *result = NULL;
260
261 va.len = -1;
262 vb.len = -1;
263 if (_getbuffer(a, &va) < 0 ||
264 _getbuffer(b, &vb) < 0) {
265 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
266 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
267 goto done;
268 }
269
270 size = va.len + vb.len;
271 if (size < 0) {
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000272 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000273 goto done;
274 }
275
276 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
277 if (result != NULL) {
278 memcpy(result->ob_bytes, va.buf, va.len);
279 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
280 }
281
282 done:
283 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000284 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000285 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000286 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000287 return (PyObject *)result;
288}
289
290/* Functions stuffed into the type object */
291
292static Py_ssize_t
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000293bytearray_length(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000294{
295 return Py_SIZE(self);
296}
297
298static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000299bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000300{
301 Py_ssize_t mysize;
302 Py_ssize_t size;
303 Py_buffer vo;
304
305 if (_getbuffer(other, &vo) < 0) {
306 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
307 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
308 return NULL;
309 }
310
311 mysize = Py_SIZE(self);
312 size = mysize + vo.len;
313 if (size < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000314 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000315 return PyErr_NoMemory();
316 }
317 if (size < self->ob_alloc) {
318 Py_SIZE(self) = size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200319 PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0'; /* Trailing null byte */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000320 }
321 else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000322 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000323 return NULL;
324 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200325 memcpy(PyByteArray_AS_STRING(self) + mysize, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000326 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000327 Py_INCREF(self);
328 return (PyObject *)self;
329}
330
331static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000332bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000333{
334 PyByteArrayObject *result;
335 Py_ssize_t mysize;
336 Py_ssize_t size;
337
338 if (count < 0)
339 count = 0;
340 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000341 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000342 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000343 size = mysize * count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000344 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
345 if (result != NULL && size != 0) {
346 if (mysize == 1)
347 memset(result->ob_bytes, self->ob_bytes[0], size);
348 else {
349 Py_ssize_t i;
350 for (i = 0; i < count; i++)
351 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
352 }
353 }
354 return (PyObject *)result;
355}
356
357static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000358bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000359{
360 Py_ssize_t mysize;
361 Py_ssize_t size;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200362 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000363
364 if (count < 0)
365 count = 0;
366 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000367 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000368 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000369 size = mysize * count;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200370 if (PyByteArray_Resize((PyObject *)self, size) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000371 return NULL;
372
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200373 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000374 if (mysize == 1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200375 memset(buf, buf[0], size);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000376 else {
377 Py_ssize_t i;
378 for (i = 1; i < count; i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200379 memcpy(buf + i*mysize, buf, mysize);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000380 }
381
382 Py_INCREF(self);
383 return (PyObject *)self;
384}
385
386static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000387bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000388{
389 if (i < 0)
390 i += Py_SIZE(self);
391 if (i < 0 || i >= Py_SIZE(self)) {
392 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
393 return NULL;
394 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200395 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000396}
397
398static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000399bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000400{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000401 if (PyIndex_Check(index)) {
402 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000403
404 if (i == -1 && PyErr_Occurred())
405 return NULL;
406
407 if (i < 0)
408 i += PyByteArray_GET_SIZE(self);
409
410 if (i < 0 || i >= Py_SIZE(self)) {
411 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
412 return NULL;
413 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200414 return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i]));
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000415 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000416 else if (PySlice_Check(index)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000417 Py_ssize_t start, stop, step, slicelength, cur, i;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000418 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000419 PyByteArray_GET_SIZE(self),
420 &start, &stop, &step, &slicelength) < 0) {
421 return NULL;
422 }
423
424 if (slicelength <= 0)
425 return PyByteArray_FromStringAndSize("", 0);
426 else if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200427 return PyByteArray_FromStringAndSize(
428 PyByteArray_AS_STRING(self) + start, slicelength);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000429 }
430 else {
431 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000432 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000433 PyObject *result;
434
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000435 result = PyByteArray_FromStringAndSize(NULL, slicelength);
436 if (result == NULL)
437 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000438
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000439 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000440 for (cur = start, i = 0; i < slicelength;
441 cur += step, i++) {
442 result_buf[i] = source_buf[cur];
443 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000444 return result;
445 }
446 }
447 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400448 PyErr_Format(PyExc_TypeError,
449 "bytearray indices must be integers or slices, not %.200s",
450 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000451 return NULL;
452 }
453}
454
455static int
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200456bytearray_setslice_linear(PyByteArrayObject *self,
457 Py_ssize_t lo, Py_ssize_t hi,
458 char *bytes, Py_ssize_t bytes_len)
459{
460 Py_ssize_t avail = hi - lo;
461 char *buf = PyByteArray_AS_STRING(self);
462 Py_ssize_t growth = bytes_len - avail;
Victor Stinner84557232013-11-21 12:29:51 +0100463 int res = 0;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200464 assert(avail >= 0);
465
Victor Stinner84557232013-11-21 12:29:51 +0100466 if (growth < 0) {
467 if (!_canresize(self))
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200468 return -1;
Victor Stinner84557232013-11-21 12:29:51 +0100469
470 if (lo == 0) {
471 /* Shrink the buffer by advancing its logical start */
472 self->ob_start -= growth;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200473 /*
Victor Stinner84557232013-11-21 12:29:51 +0100474 0 lo hi old_size
475 | |<----avail----->|<-----tail------>|
476 | |<-bytes_len->|<-----tail------>|
477 0 new_lo new_hi new_size
478 */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200479 }
Victor Stinner84557232013-11-21 12:29:51 +0100480 else {
481 /*
482 0 lo hi old_size
483 | |<----avail----->|<-----tomove------>|
484 | |<-bytes_len->|<-----tomove------>|
485 0 lo new_hi new_size
486 */
487 memmove(buf + lo + bytes_len, buf + hi,
488 Py_SIZE(self) - hi);
489 }
490 if (PyByteArray_Resize((PyObject *)self,
491 Py_SIZE(self) + growth) < 0) {
492 /* Issue #19578: Handling the memory allocation failure here is
493 tricky here because the bytearray object has already been
494 modified. Depending on growth and lo, the behaviour is
495 different.
496
497 If growth < 0 and lo != 0, the operation is completed, but a
498 MemoryError is still raised and the memory block is not
499 shrinked. Otherwise, the bytearray is restored in its previous
500 state and a MemoryError is raised. */
501 if (lo == 0) {
502 self->ob_start += growth;
503 return -1;
504 }
505 /* memmove() removed bytes, the bytearray object cannot be
506 restored in its previous state. */
507 Py_SIZE(self) += growth;
508 res = -1;
509 }
510 buf = PyByteArray_AS_STRING(self);
511 }
512 else if (growth > 0) {
513 if (Py_SIZE(self) > (Py_ssize_t)PY_SSIZE_T_MAX - growth) {
514 PyErr_NoMemory();
515 return -1;
516 }
517
518 if (PyByteArray_Resize((PyObject *)self,
519 Py_SIZE(self) + growth) < 0) {
520 return -1;
521 }
522 buf = PyByteArray_AS_STRING(self);
523 /* Make the place for the additional bytes */
524 /*
525 0 lo hi old_size
526 | |<-avail->|<-----tomove------>|
527 | |<---bytes_len-->|<-----tomove------>|
528 0 lo new_hi new_size
529 */
530 memmove(buf + lo + bytes_len, buf + hi,
531 Py_SIZE(self) - lo - bytes_len);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200532 }
533
534 if (bytes_len > 0)
535 memcpy(buf + lo, bytes, bytes_len);
Victor Stinner84557232013-11-21 12:29:51 +0100536 return res;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200537}
538
539static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000540bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000541 PyObject *values)
542{
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200543 Py_ssize_t needed;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000544 void *bytes;
545 Py_buffer vbytes;
546 int res = 0;
547
548 vbytes.len = -1;
549 if (values == (PyObject *)self) {
550 /* Make a copy and call this function recursively */
551 int err;
552 values = PyByteArray_FromObject(values);
553 if (values == NULL)
554 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000555 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000556 Py_DECREF(values);
557 return err;
558 }
559 if (values == NULL) {
560 /* del b[lo:hi] */
561 bytes = NULL;
562 needed = 0;
563 }
564 else {
565 if (_getbuffer(values, &vbytes) < 0) {
566 PyErr_Format(PyExc_TypeError,
Georg Brandl3dbca812008-07-23 16:10:53 +0000567 "can't set bytearray slice from %.100s",
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000568 Py_TYPE(values)->tp_name);
569 return -1;
570 }
571 needed = vbytes.len;
572 bytes = vbytes.buf;
573 }
574
575 if (lo < 0)
576 lo = 0;
577 if (hi < lo)
578 hi = lo;
579 if (hi > Py_SIZE(self))
580 hi = Py_SIZE(self);
581
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200582 res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000583 if (vbytes.len != -1)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200584 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000585 return res;
586}
587
588static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000589bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000590{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000591 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000592
593 if (i < 0)
594 i += Py_SIZE(self);
595
596 if (i < 0 || i >= Py_SIZE(self)) {
597 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
598 return -1;
599 }
600
601 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000602 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000603
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000604 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000605 return -1;
606
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200607 PyByteArray_AS_STRING(self)[i] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000608 return 0;
609}
610
611static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000612bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000613{
614 Py_ssize_t start, stop, step, slicelen, needed;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200615 char *buf, *bytes;
616 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000617
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000618 if (PyIndex_Check(index)) {
619 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000620
621 if (i == -1 && PyErr_Occurred())
622 return -1;
623
624 if (i < 0)
625 i += PyByteArray_GET_SIZE(self);
626
627 if (i < 0 || i >= Py_SIZE(self)) {
628 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
629 return -1;
630 }
631
632 if (values == NULL) {
633 /* Fall through to slice assignment */
634 start = i;
635 stop = i + 1;
636 step = 1;
637 slicelen = 1;
638 }
639 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000640 int ival;
641 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000642 return -1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200643 buf[i] = (char)ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000644 return 0;
645 }
646 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000647 else if (PySlice_Check(index)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000648 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000649 PyByteArray_GET_SIZE(self),
650 &start, &stop, &step, &slicelen) < 0) {
651 return -1;
652 }
653 }
654 else {
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400655 PyErr_Format(PyExc_TypeError,
656 "bytearray indices must be integers or slices, not %.200s",
657 Py_TYPE(index)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000658 return -1;
659 }
660
661 if (values == NULL) {
662 bytes = NULL;
663 needed = 0;
664 }
665 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
Christian Heimes6d26ade2012-11-03 23:07:59 +0100666 int err;
Ezio Melottic64bcbe2012-11-03 21:19:06 +0200667 if (PyNumber_Check(values) || PyUnicode_Check(values)) {
668 PyErr_SetString(PyExc_TypeError,
669 "can assign only bytes, buffers, or iterables "
670 "of ints in range(0, 256)");
671 return -1;
672 }
Georg Brandlf3fa5682010-12-04 17:09:30 +0000673 /* Make a copy and call this function recursively */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000674 values = PyByteArray_FromObject(values);
675 if (values == NULL)
676 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000677 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000678 Py_DECREF(values);
679 return err;
680 }
681 else {
682 assert(PyByteArray_Check(values));
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200683 bytes = PyByteArray_AS_STRING(values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000684 needed = Py_SIZE(values);
685 }
686 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
687 if ((step < 0 && start < stop) ||
688 (step > 0 && start > stop))
689 stop = start;
690 if (step == 1) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200691 return bytearray_setslice_linear(self, start, stop, bytes, needed);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000692 }
693 else {
694 if (needed == 0) {
695 /* Delete slice */
Mark Dickinsonbc099642010-01-29 17:27:24 +0000696 size_t cur;
697 Py_ssize_t i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000698
Antoine Pitrou5504e892008-12-06 21:27:53 +0000699 if (!_canresize(self))
700 return -1;
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000701
702 if (slicelen == 0)
703 /* Nothing to do here. */
704 return 0;
705
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000706 if (step < 0) {
707 stop = start + 1;
708 start = stop + step * (slicelen - 1) - 1;
709 step = -step;
710 }
711 for (cur = start, i = 0;
712 i < slicelen; cur += step, i++) {
713 Py_ssize_t lim = step - 1;
714
Mark Dickinson66f575b2010-02-14 12:53:32 +0000715 if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000716 lim = PyByteArray_GET_SIZE(self) - cur - 1;
717
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200718 memmove(buf + cur - i,
719 buf + cur + 1, lim);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000720 }
721 /* Move the tail of the bytes, in one chunk */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000722 cur = start + (size_t)slicelen*step;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000723 if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200724 memmove(buf + cur - slicelen,
725 buf + cur,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000726 PyByteArray_GET_SIZE(self) - cur);
727 }
728 if (PyByteArray_Resize((PyObject *)self,
729 PyByteArray_GET_SIZE(self) - slicelen) < 0)
730 return -1;
731
732 return 0;
733 }
734 else {
735 /* Assign slice */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000736 Py_ssize_t i;
737 size_t cur;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000738
739 if (needed != slicelen) {
740 PyErr_Format(PyExc_ValueError,
741 "attempt to assign bytes of size %zd "
742 "to extended slice of size %zd",
743 needed, slicelen);
744 return -1;
745 }
746 for (cur = start, i = 0; i < slicelen; cur += step, i++)
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200747 buf[cur] = bytes[i];
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000748 return 0;
749 }
750 }
751}
752
753static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000754bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000755{
756 static char *kwlist[] = {"source", "encoding", "errors", 0};
757 PyObject *arg = NULL;
758 const char *encoding = NULL;
759 const char *errors = NULL;
760 Py_ssize_t count;
761 PyObject *it;
762 PyObject *(*iternext)(PyObject *);
763
764 if (Py_SIZE(self) != 0) {
765 /* Empty previous contents (yes, do this first of all!) */
766 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
767 return -1;
768 }
769
770 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000771 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000772 &arg, &encoding, &errors))
773 return -1;
774
775 /* Make a quick exit if no first argument */
776 if (arg == NULL) {
777 if (encoding != NULL || errors != NULL) {
778 PyErr_SetString(PyExc_TypeError,
779 "encoding or errors without sequence argument");
780 return -1;
781 }
782 return 0;
783 }
784
785 if (PyUnicode_Check(arg)) {
786 /* Encode via the codec registry */
787 PyObject *encoded, *new;
788 if (encoding == NULL) {
789 PyErr_SetString(PyExc_TypeError,
790 "string argument without an encoding");
791 return -1;
792 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000793 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000794 if (encoded == NULL)
795 return -1;
796 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000797 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000798 Py_DECREF(encoded);
799 if (new == NULL)
800 return -1;
801 Py_DECREF(new);
802 return 0;
803 }
804
805 /* If it's not unicode, there can't be encoding or errors */
806 if (encoding != NULL || errors != NULL) {
807 PyErr_SetString(PyExc_TypeError,
808 "encoding or errors without a string argument");
809 return -1;
810 }
811
812 /* Is it an int? */
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000813 count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
814 if (count == -1 && PyErr_Occurred()) {
815 if (PyErr_ExceptionMatches(PyExc_OverflowError))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000816 return -1;
Benjamin Peterson9c0e94f2010-04-16 23:00:53 +0000817 PyErr_Clear();
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000818 }
819 else if (count < 0) {
820 PyErr_SetString(PyExc_ValueError, "negative count");
821 return -1;
822 }
823 else {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000824 if (count > 0) {
Victor Stinner2bc4d952014-06-02 22:22:42 +0200825 if (PyByteArray_Resize((PyObject *)self, count))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000826 return -1;
Victor Stinner2bc4d952014-06-02 22:22:42 +0200827 memset(PyByteArray_AS_STRING(self), 0, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000828 }
829 return 0;
830 }
831
832 /* Use the buffer API */
833 if (PyObject_CheckBuffer(arg)) {
834 Py_ssize_t size;
835 Py_buffer view;
836 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
837 return -1;
838 size = view.len;
839 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200840 if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
841 &view, size, 'C') < 0)
Stefan Krah7d12d9d2012-07-28 12:25:55 +0200842 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000843 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000844 return 0;
845 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000846 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000847 return -1;
848 }
849
850 /* XXX Optimize this if the arguments is a list, tuple */
851
852 /* Get the iterator */
853 it = PyObject_GetIter(arg);
854 if (it == NULL)
855 return -1;
856 iternext = *Py_TYPE(it)->tp_iternext;
857
858 /* Run the iterator to exhaustion */
859 for (;;) {
860 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000861 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000862
863 /* Get the next item */
864 item = iternext(it);
865 if (item == NULL) {
866 if (PyErr_Occurred()) {
867 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
868 goto error;
869 PyErr_Clear();
870 }
871 break;
872 }
873
874 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000875 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000876 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000877 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000878 goto error;
879
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000880 /* Append the byte */
881 if (Py_SIZE(self) < self->ob_alloc)
882 Py_SIZE(self)++;
883 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
884 goto error;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200885 PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000886 }
887
888 /* Clean up and return success */
889 Py_DECREF(it);
890 return 0;
891
892 error:
893 /* Error handling when it != NULL */
894 Py_DECREF(it);
895 return -1;
896}
897
898/* Mostly copied from string_repr, but without the
899 "smart quote" functionality. */
900static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000901bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000902{
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000903 const char *quote_prefix = "bytearray(b";
904 const char *quote_postfix = ")";
905 Py_ssize_t length = Py_SIZE(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200906 /* 15 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */
Mark Dickinson66f575b2010-02-14 12:53:32 +0000907 size_t newsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000908 PyObject *v;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200909 Py_ssize_t i;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200910 char *bytes;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200911 char c;
912 char *p;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200913 int quote;
914 char *test, *start;
915 char *buffer;
916
917 if (length > (PY_SSIZE_T_MAX - 15) / 4) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000918 PyErr_SetString(PyExc_OverflowError,
919 "bytearray object is too large to make repr");
920 return NULL;
921 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200922
923 newsize = 15 + length * 4;
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100924 buffer = PyObject_Malloc(newsize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200925 if (buffer == NULL) {
926 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000927 return NULL;
928 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000929
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200930 /* Figure out which quote to use; single is preferred */
931 quote = '\'';
932 start = PyByteArray_AS_STRING(self);
933 for (test = start; test < start+length; ++test) {
934 if (*test == '"') {
935 quote = '\''; /* back to single */
936 break;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000937 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200938 else if (*test == '\'')
939 quote = '"';
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000940 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200941
942 p = buffer;
943 while (*quote_prefix)
944 *p++ = *quote_prefix++;
945 *p++ = quote;
946
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200947 bytes = PyByteArray_AS_STRING(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200948 for (i = 0; i < length; i++) {
949 /* There's at least enough room for a hex escape
950 and a closing quote. */
951 assert(newsize - (p - buffer) >= 5);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +0200952 c = bytes[i];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200953 if (c == '\'' || c == '\\')
954 *p++ = '\\', *p++ = c;
955 else if (c == '\t')
956 *p++ = '\\', *p++ = 't';
957 else if (c == '\n')
958 *p++ = '\\', *p++ = 'n';
959 else if (c == '\r')
960 *p++ = '\\', *p++ = 'r';
961 else if (c == 0)
962 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
963 else if (c < ' ' || c >= 0x7f) {
964 *p++ = '\\';
965 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +0200966 *p++ = Py_hexdigits[(c & 0xf0) >> 4];
967 *p++ = Py_hexdigits[c & 0xf];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200968 }
969 else
970 *p++ = c;
971 }
972 assert(newsize - (p - buffer) >= 1);
973 *p++ = quote;
974 while (*quote_postfix) {
975 *p++ = *quote_postfix++;
976 }
977
978 v = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrou39aba4f2011-11-12 21:15:28 +0100979 PyObject_Free(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200980 return v;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000981}
982
983static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000984bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000985{
Alexander Belopolskyf0f45142010-08-11 17:31:17 +0000986 if (Py_BytesWarningFlag) {
987 if (PyErr_WarnEx(PyExc_BytesWarning,
988 "str() on a bytearray instance", 1))
989 return NULL;
990 }
991 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000992}
993
994static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000995bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000996{
997 Py_ssize_t self_size, other_size;
998 Py_buffer self_bytes, other_bytes;
999 PyObject *res;
1000 Py_ssize_t minsize;
1001 int cmp;
1002
1003 /* Bytes can be compared to anything that supports the (binary)
1004 buffer API. Except that a comparison with Unicode is always an
1005 error, even if the comparison is for equality. */
1006 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
1007 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
Barry Warsaw9e9dcd62008-10-17 01:50:37 +00001008 if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001009 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +00001010 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001011 return NULL;
1012 }
1013
Brian Curtindfc80e32011-08-10 20:28:54 -05001014 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001015 }
1016
1017 self_size = _getbuffer(self, &self_bytes);
1018 if (self_size < 0) {
1019 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -05001020 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001021 }
1022
1023 other_size = _getbuffer(other, &other_bytes);
1024 if (other_size < 0) {
1025 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +00001026 PyBuffer_Release(&self_bytes);
Brian Curtindfc80e32011-08-10 20:28:54 -05001027 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001028 }
1029
1030 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
1031 /* Shortcut: if the lengths differ, the objects differ */
1032 cmp = (op == Py_NE);
1033 }
1034 else {
1035 minsize = self_size;
1036 if (other_size < minsize)
1037 minsize = other_size;
1038
1039 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
1040 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
1041
1042 if (cmp == 0) {
1043 if (self_size < other_size)
1044 cmp = -1;
1045 else if (self_size > other_size)
1046 cmp = 1;
1047 }
1048
1049 switch (op) {
1050 case Py_LT: cmp = cmp < 0; break;
1051 case Py_LE: cmp = cmp <= 0; break;
1052 case Py_EQ: cmp = cmp == 0; break;
1053 case Py_NE: cmp = cmp != 0; break;
1054 case Py_GT: cmp = cmp > 0; break;
1055 case Py_GE: cmp = cmp >= 0; break;
1056 }
1057 }
1058
1059 res = cmp ? Py_True : Py_False;
Martin v. Löwis423be952008-08-13 15:53:07 +00001060 PyBuffer_Release(&self_bytes);
1061 PyBuffer_Release(&other_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001062 Py_INCREF(res);
1063 return res;
1064}
1065
1066static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001067bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001068{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001069 if (self->ob_exports > 0) {
1070 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001071 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001072 PyErr_Print();
1073 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001074 if (self->ob_bytes != 0) {
Antoine Pitrou39aba4f2011-11-12 21:15:28 +01001075 PyObject_Free(self->ob_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001076 }
1077 Py_TYPE(self)->tp_free((PyObject *)self);
1078}
1079
1080
1081/* -------------------------------------------------------------------- */
1082/* Methods */
1083
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001084#define FASTSEARCH fastsearch
1085#define STRINGLIB(F) stringlib_##F
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001086#define STRINGLIB_CHAR char
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001087#define STRINGLIB_SIZEOF_CHAR 1
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001088#define STRINGLIB_LEN PyByteArray_GET_SIZE
1089#define STRINGLIB_STR PyByteArray_AS_STRING
1090#define STRINGLIB_NEW PyByteArray_FromStringAndSize
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001091#define STRINGLIB_ISSPACE Py_ISSPACE
1092#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001093#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1094#define STRINGLIB_MUTABLE 1
1095
1096#include "stringlib/fastsearch.h"
1097#include "stringlib/count.h"
1098#include "stringlib/find.h"
Antoine Pitroucfc22b42012-10-16 21:07:23 +02001099#include "stringlib/join.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001100#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001101#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001102#include "stringlib/ctype.h"
1103#include "stringlib/transmogrify.h"
1104
1105
1106/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1107were copied from the old char* style string object. */
1108
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001109/* helper macro to fixup start/end slice values */
1110#define ADJUST_INDICES(start, end, len) \
1111 if (end > len) \
1112 end = len; \
1113 else if (end < 0) { \
1114 end += len; \
1115 if (end < 0) \
1116 end = 0; \
1117 } \
1118 if (start < 0) { \
1119 start += len; \
1120 if (start < 0) \
1121 start = 0; \
1122 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001123
1124Py_LOCAL_INLINE(Py_ssize_t)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001125bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001126{
1127 PyObject *subobj;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001128 char byte;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001129 Py_buffer subbuf;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001130 const char *sub;
1131 Py_ssize_t sub_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001132 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1133 Py_ssize_t res;
1134
Antoine Pitrouac65d962011-10-20 23:54:17 +02001135 if (!stringlib_parse_args_finds_byte("find/rfind/index/rindex",
1136 args, &subobj, &byte, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001137 return -2;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001138
1139 if (subobj) {
1140 if (_getbuffer(subobj, &subbuf) < 0)
1141 return -2;
1142
1143 sub = subbuf.buf;
1144 sub_len = subbuf.len;
1145 }
1146 else {
1147 sub = &byte;
1148 sub_len = 1;
1149 }
1150
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001151 if (dir > 0)
1152 res = stringlib_find_slice(
1153 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
Antoine Pitrouac65d962011-10-20 23:54:17 +02001154 sub, sub_len, start, end);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001155 else
1156 res = stringlib_rfind_slice(
1157 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
Antoine Pitrouac65d962011-10-20 23:54:17 +02001158 sub, sub_len, start, end);
1159
1160 if (subobj)
1161 PyBuffer_Release(&subbuf);
1162
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001163 return res;
1164}
1165
1166PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001167"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001168\n\
1169Return the lowest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001170such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001171arguments start and end are interpreted as in slice notation.\n\
1172\n\
1173Return -1 on failure.");
1174
1175static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001176bytearray_find(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001177{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001178 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001179 if (result == -2)
1180 return NULL;
1181 return PyLong_FromSsize_t(result);
1182}
1183
1184PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001185"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001186\n\
1187Return the number of non-overlapping occurrences of subsection sub in\n\
1188bytes B[start:end]. Optional arguments start and end are interpreted\n\
1189as in slice notation.");
1190
1191static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001192bytearray_count(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001193{
1194 PyObject *sub_obj;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001195 const char *str = PyByteArray_AS_STRING(self), *sub;
1196 Py_ssize_t sub_len;
1197 char byte;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001198 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
Antoine Pitrouac65d962011-10-20 23:54:17 +02001199
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001200 Py_buffer vsub;
1201 PyObject *count_obj;
1202
Antoine Pitrouac65d962011-10-20 23:54:17 +02001203 if (!stringlib_parse_args_finds_byte("count", args, &sub_obj, &byte,
1204 &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001205 return NULL;
1206
Antoine Pitrouac65d962011-10-20 23:54:17 +02001207 if (sub_obj) {
1208 if (_getbuffer(sub_obj, &vsub) < 0)
1209 return NULL;
1210
1211 sub = vsub.buf;
1212 sub_len = vsub.len;
1213 }
1214 else {
1215 sub = &byte;
1216 sub_len = 1;
1217 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001218
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001219 ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001220
1221 count_obj = PyLong_FromSsize_t(
Antoine Pitrouac65d962011-10-20 23:54:17 +02001222 stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001223 );
Antoine Pitrouac65d962011-10-20 23:54:17 +02001224
1225 if (sub_obj)
1226 PyBuffer_Release(&vsub);
1227
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001228 return count_obj;
1229}
1230
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001231/*[clinic input]
1232bytearray.clear
1233
1234 self: self(type="PyByteArrayObject *")
1235
1236Remove all items from the bytearray.
1237[clinic start generated code]*/
1238
1239PyDoc_STRVAR(bytearray_clear__doc__,
1240"clear($self, /)\n"
1241"--\n"
1242"\n"
1243"Remove all items from the bytearray.");
1244
1245#define BYTEARRAY_CLEAR_METHODDEF \
1246 {"clear", (PyCFunction)bytearray_clear, METH_NOARGS, bytearray_clear__doc__},
Eli Bendersky4db28d32011-03-03 18:21:02 +00001247
Victor Stinner6430fd52011-09-29 04:02:13 +02001248static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001249bytearray_clear_impl(PyByteArrayObject *self);
1250
1251static PyObject *
1252bytearray_clear(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
1253{
1254 return bytearray_clear_impl(self);
1255}
1256
1257static PyObject *
1258bytearray_clear_impl(PyByteArrayObject *self)
1259/*[clinic end generated code: output=5344093031e2f36c input=e524fd330abcdc18]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001260{
1261 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
1262 return NULL;
1263 Py_RETURN_NONE;
1264}
1265
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001266/*[clinic input]
1267bytearray.copy
1268
1269 self: self(type="PyByteArrayObject *")
1270
1271Return a copy of B.
1272[clinic start generated code]*/
1273
1274PyDoc_STRVAR(bytearray_copy__doc__,
1275"copy($self, /)\n"
1276"--\n"
1277"\n"
1278"Return a copy of B.");
1279
1280#define BYTEARRAY_COPY_METHODDEF \
1281 {"copy", (PyCFunction)bytearray_copy, METH_NOARGS, bytearray_copy__doc__},
Eli Bendersky4db28d32011-03-03 18:21:02 +00001282
1283static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001284bytearray_copy_impl(PyByteArrayObject *self);
1285
1286static PyObject *
1287bytearray_copy(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
1288{
1289 return bytearray_copy_impl(self);
1290}
1291
1292static PyObject *
1293bytearray_copy_impl(PyByteArrayObject *self)
1294/*[clinic end generated code: output=8788ed299f7f2214 input=6d5d2975aa0f33f3]*/
Eli Bendersky4db28d32011-03-03 18:21:02 +00001295{
1296 return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
1297 PyByteArray_GET_SIZE(self));
1298}
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001299
1300PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001301"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001302\n\
1303Like B.find() but raise ValueError when the subsection is not found.");
1304
1305static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001306bytearray_index(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001307{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001308 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001309 if (result == -2)
1310 return NULL;
1311 if (result == -1) {
1312 PyErr_SetString(PyExc_ValueError,
1313 "subsection not found");
1314 return NULL;
1315 }
1316 return PyLong_FromSsize_t(result);
1317}
1318
1319
1320PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001321"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001322\n\
1323Return the highest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001324such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001325arguments start and end are interpreted as in slice notation.\n\
1326\n\
1327Return -1 on failure.");
1328
1329static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001330bytearray_rfind(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001331{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001332 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001333 if (result == -2)
1334 return NULL;
1335 return PyLong_FromSsize_t(result);
1336}
1337
1338
1339PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001340"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001341\n\
1342Like B.rfind() but raise ValueError when the subsection is not found.");
1343
1344static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001345bytearray_rindex(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001346{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001347 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001348 if (result == -2)
1349 return NULL;
1350 if (result == -1) {
1351 PyErr_SetString(PyExc_ValueError,
1352 "subsection not found");
1353 return NULL;
1354 }
1355 return PyLong_FromSsize_t(result);
1356}
1357
1358
1359static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001360bytearray_contains(PyObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001361{
1362 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1363 if (ival == -1 && PyErr_Occurred()) {
1364 Py_buffer varg;
Antoine Pitrou0010d372010-08-15 17:12:55 +00001365 Py_ssize_t pos;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001366 PyErr_Clear();
1367 if (_getbuffer(arg, &varg) < 0)
1368 return -1;
1369 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1370 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001371 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001372 return pos >= 0;
1373 }
1374 if (ival < 0 || ival >= 256) {
1375 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1376 return -1;
1377 }
1378
Antoine Pitrou0010d372010-08-15 17:12:55 +00001379 return memchr(PyByteArray_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001380}
1381
1382
1383/* Matches the end (direction >= 0) or start (direction < 0) of self
1384 * against substr, using the start and end arguments. Returns
1385 * -1 on error, 0 if not found and 1 if found.
1386 */
1387Py_LOCAL(int)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001388_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001389 Py_ssize_t end, int direction)
1390{
1391 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1392 const char* str;
1393 Py_buffer vsubstr;
1394 int rv = 0;
1395
1396 str = PyByteArray_AS_STRING(self);
1397
1398 if (_getbuffer(substr, &vsubstr) < 0)
1399 return -1;
1400
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001401 ADJUST_INDICES(start, end, len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001402
1403 if (direction < 0) {
1404 /* startswith */
1405 if (start+vsubstr.len > len) {
1406 goto done;
1407 }
1408 } else {
1409 /* endswith */
1410 if (end-start < vsubstr.len || start > len) {
1411 goto done;
1412 }
1413
1414 if (end-vsubstr.len > start)
1415 start = end - vsubstr.len;
1416 }
1417 if (end-start >= vsubstr.len)
1418 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1419
1420done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001421 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001422 return rv;
1423}
1424
1425
1426PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001427"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001428\n\
1429Return True if B starts with the specified prefix, False otherwise.\n\
1430With optional start, test B beginning at that position.\n\
1431With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001432prefix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001433
1434static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001435bytearray_startswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001436{
1437 Py_ssize_t start = 0;
1438 Py_ssize_t end = PY_SSIZE_T_MAX;
1439 PyObject *subobj;
1440 int result;
1441
Jesus Ceaac451502011-04-20 17:09:23 +02001442 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001443 return NULL;
1444 if (PyTuple_Check(subobj)) {
1445 Py_ssize_t i;
1446 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001447 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001448 PyTuple_GET_ITEM(subobj, i),
1449 start, end, -1);
1450 if (result == -1)
1451 return NULL;
1452 else if (result) {
1453 Py_RETURN_TRUE;
1454 }
1455 }
1456 Py_RETURN_FALSE;
1457 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001458 result = _bytearray_tailmatch(self, subobj, start, end, -1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001459 if (result == -1) {
1460 if (PyErr_ExceptionMatches(PyExc_TypeError))
1461 PyErr_Format(PyExc_TypeError, "startswith first arg must be bytes "
1462 "or a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001463 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001464 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001465 else
1466 return PyBool_FromLong(result);
1467}
1468
1469PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001470"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001471\n\
1472Return True if B ends with the specified suffix, False otherwise.\n\
1473With optional start, test B beginning at that position.\n\
1474With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001475suffix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001476
1477static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001478bytearray_endswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001479{
1480 Py_ssize_t start = 0;
1481 Py_ssize_t end = PY_SSIZE_T_MAX;
1482 PyObject *subobj;
1483 int result;
1484
Jesus Ceaac451502011-04-20 17:09:23 +02001485 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001486 return NULL;
1487 if (PyTuple_Check(subobj)) {
1488 Py_ssize_t i;
1489 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001490 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001491 PyTuple_GET_ITEM(subobj, i),
1492 start, end, +1);
1493 if (result == -1)
1494 return NULL;
1495 else if (result) {
1496 Py_RETURN_TRUE;
1497 }
1498 }
1499 Py_RETURN_FALSE;
1500 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001501 result = _bytearray_tailmatch(self, subobj, start, end, +1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001502 if (result == -1) {
1503 if (PyErr_ExceptionMatches(PyExc_TypeError))
1504 PyErr_Format(PyExc_TypeError, "endswith first arg must be bytes or "
1505 "a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001506 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001507 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001508 else
1509 return PyBool_FromLong(result);
1510}
1511
1512
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001513/*[clinic input]
1514bytearray.translate
1515
1516 self: self(type="PyByteArrayObject *")
1517 table: object
1518 Translation table, which must be a bytes object of length 256.
1519 [
1520 deletechars: object
1521 ]
1522 /
1523
1524Return a copy with each character mapped by the given translation table.
1525
1526All characters occurring in the optional argument deletechars are removed.
1527The remaining characters are mapped through the given translation table.
1528[clinic start generated code]*/
1529
1530PyDoc_STRVAR(bytearray_translate__doc__,
1531"translate(table, [deletechars])\n"
1532"Return a copy with each character mapped by the given translation table.\n"
1533"\n"
1534" table\n"
1535" Translation table, which must be a bytes object of length 256.\n"
1536"\n"
1537"All characters occurring in the optional argument deletechars are removed.\n"
1538"The remaining characters are mapped through the given translation table.");
1539
1540#define BYTEARRAY_TRANSLATE_METHODDEF \
1541 {"translate", (PyCFunction)bytearray_translate, METH_VARARGS, bytearray_translate__doc__},
1542
1543static PyObject *
1544bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, int group_right_1, PyObject *deletechars);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001545
1546static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001547bytearray_translate(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001548{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001549 PyObject *return_value = NULL;
1550 PyObject *table;
1551 int group_right_1 = 0;
1552 PyObject *deletechars = NULL;
1553
1554 switch (PyTuple_GET_SIZE(args)) {
1555 case 1:
1556 if (!PyArg_ParseTuple(args, "O:translate", &table))
1557 goto exit;
1558 break;
1559 case 2:
1560 if (!PyArg_ParseTuple(args, "OO:translate", &table, &deletechars))
1561 goto exit;
1562 group_right_1 = 1;
1563 break;
1564 default:
1565 PyErr_SetString(PyExc_TypeError, "bytearray.translate requires 1 to 2 arguments");
1566 goto exit;
1567 }
1568 return_value = bytearray_translate_impl(self, table, group_right_1, deletechars);
1569
1570exit:
1571 return return_value;
1572}
1573
1574static PyObject *
1575bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, int group_right_1, PyObject *deletechars)
1576/*[clinic end generated code: output=a709df81d41db4b7 input=b749ad85f4860824]*/
1577{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001578 char *input, *output;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001579 const char *table_chars;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001580 Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001581 PyObject *input_obj = (PyObject*)self;
1582 const char *output_start;
1583 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001584 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001585 int trans_table[256];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001586 Py_buffer vtable, vdel;
1587
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001588 if (table == Py_None) {
1589 table_chars = NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001590 table = NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001591 } else if (_getbuffer(table, &vtable) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001592 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001593 } else {
1594 if (vtable.len != 256) {
1595 PyErr_SetString(PyExc_ValueError,
1596 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001597 PyBuffer_Release(&vtable);
1598 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001599 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001600 table_chars = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001601 }
1602
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001603 if (deletechars != NULL) {
1604 if (_getbuffer(deletechars, &vdel) < 0) {
1605 if (table != NULL)
Georg Brandl953152f2009-07-22 12:03:59 +00001606 PyBuffer_Release(&vtable);
1607 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001608 }
1609 }
1610 else {
1611 vdel.buf = NULL;
1612 vdel.len = 0;
1613 }
1614
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001615 inlen = PyByteArray_GET_SIZE(input_obj);
1616 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1617 if (result == NULL)
1618 goto done;
1619 output_start = output = PyByteArray_AsString(result);
1620 input = PyByteArray_AS_STRING(input_obj);
1621
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001622 if (vdel.len == 0 && table_chars != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001623 /* If no deletions are required, use faster code */
1624 for (i = inlen; --i >= 0; ) {
1625 c = Py_CHARMASK(*input++);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001626 *output++ = table_chars[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001627 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001628 goto done;
1629 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001630
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001631 if (table_chars == NULL) {
Georg Brandlccc47b62008-12-28 11:44:14 +00001632 for (i = 0; i < 256; i++)
1633 trans_table[i] = Py_CHARMASK(i);
1634 } else {
1635 for (i = 0; i < 256; i++)
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001636 trans_table[i] = Py_CHARMASK(table_chars[i]);
Georg Brandlccc47b62008-12-28 11:44:14 +00001637 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001638
1639 for (i = 0; i < vdel.len; i++)
1640 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1641
1642 for (i = inlen; --i >= 0; ) {
1643 c = Py_CHARMASK(*input++);
1644 if (trans_table[c] != -1)
1645 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1646 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001647 }
1648 /* Fix the size of the resulting string */
1649 if (inlen > 0)
Christian Heimesc731bbe2013-07-21 02:04:35 +02001650 if (PyByteArray_Resize(result, output - output_start) < 0) {
1651 Py_CLEAR(result);
1652 goto done;
1653 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001654
1655done:
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001656 if (table != NULL)
Georg Brandlccc47b62008-12-28 11:44:14 +00001657 PyBuffer_Release(&vtable);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001658 if (deletechars != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001659 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001660 return result;
1661}
1662
1663
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001664/*[clinic input]
1665
1666@staticmethod
1667bytearray.maketrans
1668
1669 frm: object
1670 to: object
1671 /
1672
1673Return a translation table useable for the bytes or bytearray translate method.
1674
1675The returned table will be one where each byte in frm is mapped to the byte at
1676the same position in to.
1677
1678The bytes objects frm and to must be of the same length.
1679[clinic start generated code]*/
1680
1681PyDoc_STRVAR(bytearray_maketrans__doc__,
1682"maketrans(frm, to, /)\n"
1683"--\n"
1684"\n"
1685"Return a translation table useable for the bytes or bytearray translate method.\n"
1686"\n"
1687"The returned table will be one where each byte in frm is mapped to the byte at\n"
1688"the same position in to.\n"
1689"\n"
1690"The bytes objects frm and to must be of the same length.");
1691
1692#define BYTEARRAY_MAKETRANS_METHODDEF \
1693 {"maketrans", (PyCFunction)bytearray_maketrans, METH_VARARGS|METH_STATIC, bytearray_maketrans__doc__},
1694
Georg Brandlabc38772009-04-12 15:51:51 +00001695static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001696bytearray_maketrans_impl(PyObject *frm, PyObject *to);
1697
1698static PyObject *
1699bytearray_maketrans(void *null, PyObject *args)
Georg Brandlabc38772009-04-12 15:51:51 +00001700{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02001701 PyObject *return_value = NULL;
1702 PyObject *frm;
1703 PyObject *to;
1704
1705 if (!PyArg_UnpackTuple(args, "maketrans",
1706 2, 2,
1707 &frm, &to))
1708 goto exit;
1709 return_value = bytearray_maketrans_impl(frm, to);
1710
1711exit:
1712 return return_value;
1713}
1714
1715static PyObject *
1716bytearray_maketrans_impl(PyObject *frm, PyObject *to)
1717/*[clinic end generated code: output=307752019d9b25b5 input=ea9bdc6b328c15e2]*/
1718{
1719 return _Py_bytes_maketrans(frm, to);
Georg Brandlabc38772009-04-12 15:51:51 +00001720}
1721
1722
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001723/* find and count characters and substrings */
1724
1725#define findchar(target, target_len, c) \
1726 ((char *)memchr((const void *)(target), c, target_len))
1727
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001728
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001729/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001730Py_LOCAL(PyByteArrayObject *)
1731return_self(PyByteArrayObject *self)
1732{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001733 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001734 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1735 PyByteArray_AS_STRING(self),
1736 PyByteArray_GET_SIZE(self));
1737}
1738
1739Py_LOCAL_INLINE(Py_ssize_t)
1740countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1741{
1742 Py_ssize_t count=0;
1743 const char *start=target;
1744 const char *end=target+target_len;
1745
1746 while ( (start=findchar(start, end-start, c)) != NULL ) {
1747 count++;
1748 if (count >= maxcount)
1749 break;
1750 start += 1;
1751 }
1752 return count;
1753}
1754
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001755
1756/* Algorithms for different cases of string replacement */
1757
1758/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1759Py_LOCAL(PyByteArrayObject *)
1760replace_interleave(PyByteArrayObject *self,
1761 const char *to_s, Py_ssize_t to_len,
1762 Py_ssize_t maxcount)
1763{
1764 char *self_s, *result_s;
1765 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001766 Py_ssize_t count, i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001767 PyByteArrayObject *result;
1768
1769 self_len = PyByteArray_GET_SIZE(self);
1770
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001771 /* 1 at the end plus 1 after every character;
1772 count = min(maxcount, self_len + 1) */
1773 if (maxcount <= self_len)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001774 count = maxcount;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001775 else
1776 /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
1777 count = self_len + 1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001778
1779 /* Check for overflow */
1780 /* result_len = count * to_len + self_len; */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001781 assert(count > 0);
1782 if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001783 PyErr_SetString(PyExc_OverflowError,
1784 "replace string is too long");
1785 return NULL;
1786 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001787 result_len = count * to_len + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001788
1789 if (! (result = (PyByteArrayObject *)
1790 PyByteArray_FromStringAndSize(NULL, result_len)) )
1791 return NULL;
1792
1793 self_s = PyByteArray_AS_STRING(self);
1794 result_s = PyByteArray_AS_STRING(result);
1795
1796 /* TODO: special case single character, which doesn't need memcpy */
1797
1798 /* Lay the first one down (guaranteed this will occur) */
1799 Py_MEMCPY(result_s, to_s, to_len);
1800 result_s += to_len;
1801 count -= 1;
1802
1803 for (i=0; i<count; i++) {
1804 *result_s++ = *self_s++;
1805 Py_MEMCPY(result_s, to_s, to_len);
1806 result_s += to_len;
1807 }
1808
1809 /* Copy the rest of the original string */
1810 Py_MEMCPY(result_s, self_s, self_len-i);
1811
1812 return result;
1813}
1814
1815/* Special case for deleting a single character */
1816/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1817Py_LOCAL(PyByteArrayObject *)
1818replace_delete_single_character(PyByteArrayObject *self,
1819 char from_c, Py_ssize_t maxcount)
1820{
1821 char *self_s, *result_s;
1822 char *start, *next, *end;
1823 Py_ssize_t self_len, result_len;
1824 Py_ssize_t count;
1825 PyByteArrayObject *result;
1826
1827 self_len = PyByteArray_GET_SIZE(self);
1828 self_s = PyByteArray_AS_STRING(self);
1829
1830 count = countchar(self_s, self_len, from_c, maxcount);
1831 if (count == 0) {
1832 return return_self(self);
1833 }
1834
1835 result_len = self_len - count; /* from_len == 1 */
1836 assert(result_len>=0);
1837
1838 if ( (result = (PyByteArrayObject *)
1839 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1840 return NULL;
1841 result_s = PyByteArray_AS_STRING(result);
1842
1843 start = self_s;
1844 end = self_s + self_len;
1845 while (count-- > 0) {
1846 next = findchar(start, end-start, from_c);
1847 if (next == NULL)
1848 break;
1849 Py_MEMCPY(result_s, start, next-start);
1850 result_s += (next-start);
1851 start = next+1;
1852 }
1853 Py_MEMCPY(result_s, start, end-start);
1854
1855 return result;
1856}
1857
1858/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1859
1860Py_LOCAL(PyByteArrayObject *)
1861replace_delete_substring(PyByteArrayObject *self,
1862 const char *from_s, Py_ssize_t from_len,
1863 Py_ssize_t maxcount)
1864{
1865 char *self_s, *result_s;
1866 char *start, *next, *end;
1867 Py_ssize_t self_len, result_len;
1868 Py_ssize_t count, offset;
1869 PyByteArrayObject *result;
1870
1871 self_len = PyByteArray_GET_SIZE(self);
1872 self_s = PyByteArray_AS_STRING(self);
1873
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001874 count = stringlib_count(self_s, self_len,
1875 from_s, from_len,
1876 maxcount);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001877
1878 if (count == 0) {
1879 /* no matches */
1880 return return_self(self);
1881 }
1882
1883 result_len = self_len - (count * from_len);
1884 assert (result_len>=0);
1885
1886 if ( (result = (PyByteArrayObject *)
1887 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1888 return NULL;
1889
1890 result_s = PyByteArray_AS_STRING(result);
1891
1892 start = self_s;
1893 end = self_s + self_len;
1894 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001895 offset = stringlib_find(start, end-start,
1896 from_s, from_len,
1897 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001898 if (offset == -1)
1899 break;
1900 next = start + offset;
1901
1902 Py_MEMCPY(result_s, start, next-start);
1903
1904 result_s += (next-start);
1905 start = next+from_len;
1906 }
1907 Py_MEMCPY(result_s, start, end-start);
1908 return result;
1909}
1910
1911/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1912Py_LOCAL(PyByteArrayObject *)
1913replace_single_character_in_place(PyByteArrayObject *self,
1914 char from_c, char to_c,
1915 Py_ssize_t maxcount)
1916{
Antoine Pitroud1188562010-06-09 16:38:55 +00001917 char *self_s, *result_s, *start, *end, *next;
1918 Py_ssize_t self_len;
1919 PyByteArrayObject *result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001920
Antoine Pitroud1188562010-06-09 16:38:55 +00001921 /* The result string will be the same size */
1922 self_s = PyByteArray_AS_STRING(self);
1923 self_len = PyByteArray_GET_SIZE(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001924
Antoine Pitroud1188562010-06-09 16:38:55 +00001925 next = findchar(self_s, self_len, from_c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001926
Antoine Pitroud1188562010-06-09 16:38:55 +00001927 if (next == NULL) {
1928 /* No matches; return the original bytes */
1929 return return_self(self);
1930 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001931
Antoine Pitroud1188562010-06-09 16:38:55 +00001932 /* Need to make a new bytes */
1933 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1934 if (result == NULL)
1935 return NULL;
1936 result_s = PyByteArray_AS_STRING(result);
1937 Py_MEMCPY(result_s, self_s, self_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001938
Antoine Pitroud1188562010-06-09 16:38:55 +00001939 /* change everything in-place, starting with this one */
1940 start = result_s + (next-self_s);
1941 *start = to_c;
1942 start++;
1943 end = result_s + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001944
Antoine Pitroud1188562010-06-09 16:38:55 +00001945 while (--maxcount > 0) {
1946 next = findchar(start, end-start, from_c);
1947 if (next == NULL)
1948 break;
1949 *next = to_c;
1950 start = next+1;
1951 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001952
Antoine Pitroud1188562010-06-09 16:38:55 +00001953 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001954}
1955
1956/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1957Py_LOCAL(PyByteArrayObject *)
1958replace_substring_in_place(PyByteArrayObject *self,
1959 const char *from_s, Py_ssize_t from_len,
1960 const char *to_s, Py_ssize_t to_len,
1961 Py_ssize_t maxcount)
1962{
1963 char *result_s, *start, *end;
1964 char *self_s;
1965 Py_ssize_t self_len, offset;
1966 PyByteArrayObject *result;
1967
1968 /* The result bytes will be the same size */
1969
1970 self_s = PyByteArray_AS_STRING(self);
1971 self_len = PyByteArray_GET_SIZE(self);
1972
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001973 offset = stringlib_find(self_s, self_len,
1974 from_s, from_len,
1975 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001976 if (offset == -1) {
1977 /* No matches; return the original bytes */
1978 return return_self(self);
1979 }
1980
1981 /* Need to make a new bytes */
1982 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1983 if (result == NULL)
1984 return NULL;
1985 result_s = PyByteArray_AS_STRING(result);
1986 Py_MEMCPY(result_s, self_s, self_len);
1987
1988 /* change everything in-place, starting with this one */
1989 start = result_s + offset;
1990 Py_MEMCPY(start, to_s, from_len);
1991 start += from_len;
1992 end = result_s + self_len;
1993
1994 while ( --maxcount > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001995 offset = stringlib_find(start, end-start,
1996 from_s, from_len,
1997 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001998 if (offset==-1)
1999 break;
2000 Py_MEMCPY(start+offset, to_s, from_len);
2001 start += offset+from_len;
2002 }
2003
2004 return result;
2005}
2006
2007/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
2008Py_LOCAL(PyByteArrayObject *)
2009replace_single_character(PyByteArrayObject *self,
2010 char from_c,
2011 const char *to_s, Py_ssize_t to_len,
2012 Py_ssize_t maxcount)
2013{
2014 char *self_s, *result_s;
2015 char *start, *next, *end;
2016 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002017 Py_ssize_t count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002018 PyByteArrayObject *result;
2019
2020 self_s = PyByteArray_AS_STRING(self);
2021 self_len = PyByteArray_GET_SIZE(self);
2022
2023 count = countchar(self_s, self_len, from_c, maxcount);
2024 if (count == 0) {
2025 /* no matches, return unchanged */
2026 return return_self(self);
2027 }
2028
2029 /* use the difference between current and new, hence the "-1" */
2030 /* result_len = self_len + count * (to_len-1) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002031 assert(count > 0);
2032 if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002033 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
2034 return NULL;
2035 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002036 result_len = self_len + count * (to_len - 1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002037
2038 if ( (result = (PyByteArrayObject *)
2039 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
2040 return NULL;
2041 result_s = PyByteArray_AS_STRING(result);
2042
2043 start = self_s;
2044 end = self_s + self_len;
2045 while (count-- > 0) {
2046 next = findchar(start, end-start, from_c);
2047 if (next == NULL)
2048 break;
2049
2050 if (next == start) {
2051 /* replace with the 'to' */
2052 Py_MEMCPY(result_s, to_s, to_len);
2053 result_s += to_len;
2054 start += 1;
2055 } else {
2056 /* copy the unchanged old then the 'to' */
2057 Py_MEMCPY(result_s, start, next-start);
2058 result_s += (next-start);
2059 Py_MEMCPY(result_s, to_s, to_len);
2060 result_s += to_len;
2061 start = next+1;
2062 }
2063 }
2064 /* Copy the remainder of the remaining bytes */
2065 Py_MEMCPY(result_s, start, end-start);
2066
2067 return result;
2068}
2069
2070/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
2071Py_LOCAL(PyByteArrayObject *)
2072replace_substring(PyByteArrayObject *self,
2073 const char *from_s, Py_ssize_t from_len,
2074 const char *to_s, Py_ssize_t to_len,
2075 Py_ssize_t maxcount)
2076{
2077 char *self_s, *result_s;
2078 char *start, *next, *end;
2079 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002080 Py_ssize_t count, offset;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002081 PyByteArrayObject *result;
2082
2083 self_s = PyByteArray_AS_STRING(self);
2084 self_len = PyByteArray_GET_SIZE(self);
2085
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002086 count = stringlib_count(self_s, self_len,
2087 from_s, from_len,
2088 maxcount);
2089
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002090 if (count == 0) {
2091 /* no matches, return unchanged */
2092 return return_self(self);
2093 }
2094
2095 /* Check for overflow */
2096 /* result_len = self_len + count * (to_len-from_len) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002097 assert(count > 0);
2098 if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002099 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
2100 return NULL;
2101 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00002102 result_len = self_len + count * (to_len - from_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002103
2104 if ( (result = (PyByteArrayObject *)
2105 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
2106 return NULL;
2107 result_s = PyByteArray_AS_STRING(result);
2108
2109 start = self_s;
2110 end = self_s + self_len;
2111 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002112 offset = stringlib_find(start, end-start,
2113 from_s, from_len,
2114 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002115 if (offset == -1)
2116 break;
2117 next = start+offset;
2118 if (next == start) {
2119 /* replace with the 'to' */
2120 Py_MEMCPY(result_s, to_s, to_len);
2121 result_s += to_len;
2122 start += from_len;
2123 } else {
2124 /* copy the unchanged old then the 'to' */
2125 Py_MEMCPY(result_s, start, next-start);
2126 result_s += (next-start);
2127 Py_MEMCPY(result_s, to_s, to_len);
2128 result_s += to_len;
2129 start = next+from_len;
2130 }
2131 }
2132 /* Copy the remainder of the remaining bytes */
2133 Py_MEMCPY(result_s, start, end-start);
2134
2135 return result;
2136}
2137
2138
2139Py_LOCAL(PyByteArrayObject *)
2140replace(PyByteArrayObject *self,
2141 const char *from_s, Py_ssize_t from_len,
2142 const char *to_s, Py_ssize_t to_len,
2143 Py_ssize_t maxcount)
2144{
2145 if (maxcount < 0) {
2146 maxcount = PY_SSIZE_T_MAX;
2147 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
2148 /* nothing to do; return the original bytes */
2149 return return_self(self);
2150 }
2151
2152 if (maxcount == 0 ||
2153 (from_len == 0 && to_len == 0)) {
2154 /* nothing to do; return the original bytes */
2155 return return_self(self);
2156 }
2157
2158 /* Handle zero-length special cases */
2159
2160 if (from_len == 0) {
2161 /* insert the 'to' bytes everywhere. */
2162 /* >>> "Python".replace("", ".") */
2163 /* '.P.y.t.h.o.n.' */
2164 return replace_interleave(self, to_s, to_len, maxcount);
2165 }
2166
2167 /* Except for "".replace("", "A") == "A" there is no way beyond this */
2168 /* point for an empty self bytes to generate a non-empty bytes */
2169 /* Special case so the remaining code always gets a non-empty bytes */
2170 if (PyByteArray_GET_SIZE(self) == 0) {
2171 return return_self(self);
2172 }
2173
2174 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00002175 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002176 if (from_len == 1) {
2177 return replace_delete_single_character(
2178 self, from_s[0], maxcount);
2179 } else {
2180 return replace_delete_substring(self, from_s, from_len, maxcount);
2181 }
2182 }
2183
2184 /* Handle special case where both bytes have the same length */
2185
2186 if (from_len == to_len) {
2187 if (from_len == 1) {
2188 return replace_single_character_in_place(
2189 self,
2190 from_s[0],
2191 to_s[0],
2192 maxcount);
2193 } else {
2194 return replace_substring_in_place(
2195 self, from_s, from_len, to_s, to_len, maxcount);
2196 }
2197 }
2198
2199 /* Otherwise use the more generic algorithms */
2200 if (from_len == 1) {
2201 return replace_single_character(self, from_s[0],
2202 to_s, to_len, maxcount);
2203 } else {
2204 /* len('from')>=2, len('to')>=1 */
2205 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
2206 }
2207}
2208
2209
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002210/*[clinic input]
2211bytearray.replace
2212
2213 old: object
2214 new: object
2215 count: Py_ssize_t = -1
2216 Maximum number of occurrences to replace.
2217 -1 (the default value) means replace all occurrences.
2218 /
2219
2220Return a copy with all occurrences of substring old replaced by new.
2221
2222If the optional argument count is given, only the first count occurrences are
2223replaced.
2224[clinic start generated code]*/
2225
2226PyDoc_STRVAR(bytearray_replace__doc__,
2227"replace($self, old, new, count=-1, /)\n"
2228"--\n"
2229"\n"
2230"Return a copy with all occurrences of substring old replaced by new.\n"
2231"\n"
2232" count\n"
2233" Maximum number of occurrences to replace.\n"
2234" -1 (the default value) means replace all occurrences.\n"
2235"\n"
2236"If the optional argument count is given, only the first count occurrences are\n"
2237"replaced.");
2238
2239#define BYTEARRAY_REPLACE_METHODDEF \
2240 {"replace", (PyCFunction)bytearray_replace, METH_VARARGS, bytearray_replace__doc__},
2241
2242static PyObject *
2243bytearray_replace_impl(PyByteArrayObject *self, PyObject *old, PyObject *new, Py_ssize_t count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002244
2245static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002246bytearray_replace(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002247{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002248 PyObject *return_value = NULL;
2249 PyObject *old;
2250 PyObject *new;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002251 Py_ssize_t count = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002252
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002253 if (!PyArg_ParseTuple(args,
2254 "OO|n:replace",
2255 &old, &new, &count))
2256 goto exit;
2257 return_value = bytearray_replace_impl(self, old, new, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002258
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002259exit:
2260 return return_value;
2261}
2262
2263static PyObject *
2264bytearray_replace_impl(PyByteArrayObject *self, PyObject *old, PyObject *new, Py_ssize_t count)
2265/*[clinic end generated code: output=4d2e3c9130da0f96 input=9aaaa123608dfc1f]*/
2266{
2267 PyObject *res;
2268 Py_buffer vold, vnew;
2269
2270 if (_getbuffer(old, &vold) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002271 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002272 if (_getbuffer(new, &vnew) < 0) {
2273 PyBuffer_Release(&vold);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002274 return NULL;
2275 }
2276
2277 res = (PyObject *)replace((PyByteArrayObject *) self,
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002278 vold.buf, vold.len,
2279 vnew.buf, vnew.len, count);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002280
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002281 PyBuffer_Release(&vold);
2282 PyBuffer_Release(&vnew);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002283 return res;
2284}
2285
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002286/*[clinic input]
2287bytearray.split
2288
2289 sep: object = None
2290 The delimiter according which to split the bytearray.
2291 None (the default value) means split on ASCII whitespace characters
2292 (space, tab, return, newline, formfeed, vertical tab).
2293 maxsplit: Py_ssize_t = -1
2294 Maximum number of splits to do.
2295 -1 (the default value) means no limit.
2296
2297Return a list of the sections in the bytearray, using sep as the delimiter.
2298[clinic start generated code]*/
2299
2300PyDoc_STRVAR(bytearray_split__doc__,
2301"split($self, /, sep=None, maxsplit=-1)\n"
2302"--\n"
2303"\n"
2304"Return a list of the sections in the bytearray, using sep as the delimiter.\n"
2305"\n"
2306" sep\n"
2307" The delimiter according which to split the bytearray.\n"
2308" None (the default value) means split on ASCII whitespace characters\n"
2309" (space, tab, return, newline, formfeed, vertical tab).\n"
2310" maxsplit\n"
2311" Maximum number of splits to do.\n"
2312" -1 (the default value) means no limit.");
2313
2314#define BYTEARRAY_SPLIT_METHODDEF \
2315 {"split", (PyCFunction)bytearray_split, METH_VARARGS|METH_KEYWORDS, bytearray_split__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002316
2317static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002318bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit);
2319
2320static PyObject *
2321bytearray_split(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002322{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002323 PyObject *return_value = NULL;
2324 static char *_keywords[] = {"sep", "maxsplit", NULL};
2325 PyObject *sep = Py_None;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002326 Py_ssize_t maxsplit = -1;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002327
2328 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
2329 "|On:split", _keywords,
2330 &sep, &maxsplit))
2331 goto exit;
2332 return_value = bytearray_split_impl(self, sep, maxsplit);
2333
2334exit:
2335 return return_value;
2336}
2337
2338static PyObject *
2339bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit)
2340/*[clinic end generated code: output=062a3d87d6f918fa input=24f82669f41bf523]*/
2341{
2342 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002343 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002344 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002345 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002346
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002347 if (maxsplit < 0)
2348 maxsplit = PY_SSIZE_T_MAX;
2349
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002350 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002351 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002352
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002353 if (_getbuffer(sep, &vsub) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002354 return NULL;
2355 sub = vsub.buf;
2356 n = vsub.len;
2357
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002358 list = stringlib_split(
2359 (PyObject*) self, s, len, sub, n, maxsplit
2360 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002361 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002362 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002363}
2364
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002365/*[clinic input]
2366bytearray.partition
2367
2368 self: self(type="PyByteArrayObject *")
2369 sep: object
2370 /
2371
2372Partition the bytearray into three parts using the given separator.
2373
2374This will search for the separator sep in the bytearray. If the separator is
2375found, returns a 3-tuple containing the part before the separator, the
2376separator itself, and the part after it.
2377
2378If the separator is not found, returns a 3-tuple containing the original
2379bytearray object and two empty bytearray objects.
2380[clinic start generated code]*/
2381
2382PyDoc_STRVAR(bytearray_partition__doc__,
2383"partition($self, sep, /)\n"
2384"--\n"
2385"\n"
2386"Partition the bytearray into three parts using the given separator.\n"
2387"\n"
2388"This will search for the separator sep in the bytearray. If the separator is\n"
2389"found, returns a 3-tuple containing the part before the separator, the\n"
2390"separator itself, and the part after it.\n"
2391"\n"
2392"If the separator is not found, returns a 3-tuple containing the original\n"
2393"bytearray object and two empty bytearray objects.");
2394
2395#define BYTEARRAY_PARTITION_METHODDEF \
2396 {"partition", (PyCFunction)bytearray_partition, METH_O, bytearray_partition__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002397
2398static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002399bytearray_partition(PyByteArrayObject *self, PyObject *sep)
2400/*[clinic end generated code: output=2645138221fe6f4d input=7d7fe37b1696d506]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002401{
2402 PyObject *bytesep, *result;
2403
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002404 bytesep = PyByteArray_FromObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002405 if (! bytesep)
2406 return NULL;
2407
2408 result = stringlib_partition(
2409 (PyObject*) self,
2410 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2411 bytesep,
2412 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2413 );
2414
2415 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002416 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002417}
2418
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002419/*[clinic input]
2420bytearray.rpartition
2421
2422 self: self(type="PyByteArrayObject *")
2423 sep: object
2424 /
2425
2426Partition the bytes into three parts using the given separator.
2427
2428This will search for the separator sep in the bytearray, starting and the end.
2429If the separator is found, returns a 3-tuple containing the part before the
2430separator, the separator itself, and the part after it.
2431
2432If the separator is not found, returns a 3-tuple containing two empty bytearray
2433objects and the original bytearray object.
2434[clinic start generated code]*/
2435
2436PyDoc_STRVAR(bytearray_rpartition__doc__,
2437"rpartition($self, sep, /)\n"
2438"--\n"
2439"\n"
2440"Partition the bytes into three parts using the given separator.\n"
2441"\n"
2442"This will search for the separator sep in the bytearray, starting and the end.\n"
2443"If the separator is found, returns a 3-tuple containing the part before the\n"
2444"separator, the separator itself, and the part after it.\n"
2445"\n"
2446"If the separator is not found, returns a 3-tuple containing two empty bytearray\n"
2447"objects and the original bytearray object.");
2448
2449#define BYTEARRAY_RPARTITION_METHODDEF \
2450 {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, bytearray_rpartition__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002451
2452static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002453bytearray_rpartition(PyByteArrayObject *self, PyObject *sep)
2454/*[clinic end generated code: output=ed13e54605d007de input=9b8cd540c1b75853]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002455{
2456 PyObject *bytesep, *result;
2457
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002458 bytesep = PyByteArray_FromObject(sep);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002459 if (! bytesep)
2460 return NULL;
2461
2462 result = stringlib_rpartition(
2463 (PyObject*) self,
2464 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2465 bytesep,
2466 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2467 );
2468
2469 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002470 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002471}
2472
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002473/*[clinic input]
2474bytearray.rsplit = bytearray.split
2475
2476Return a list of the sections in the bytearray, using sep as the delimiter.
2477
2478Splitting is done starting at the end of the bytearray and working to the front.
2479[clinic start generated code]*/
2480
2481PyDoc_STRVAR(bytearray_rsplit__doc__,
2482"rsplit($self, /, sep=None, maxsplit=-1)\n"
2483"--\n"
2484"\n"
2485"Return a list of the sections in the bytearray, using sep as the delimiter.\n"
2486"\n"
2487" sep\n"
2488" The delimiter according which to split the bytearray.\n"
2489" None (the default value) means split on ASCII whitespace characters\n"
2490" (space, tab, return, newline, formfeed, vertical tab).\n"
2491" maxsplit\n"
2492" Maximum number of splits to do.\n"
2493" -1 (the default value) means no limit.\n"
2494"\n"
2495"Splitting is done starting at the end of the bytearray and working to the front.");
2496
2497#define BYTEARRAY_RSPLIT_METHODDEF \
2498 {"rsplit", (PyCFunction)bytearray_rsplit, METH_VARARGS|METH_KEYWORDS, bytearray_rsplit__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002499
2500static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002501bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit);
2502
2503static PyObject *
2504bytearray_rsplit(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002505{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002506 PyObject *return_value = NULL;
2507 static char *_keywords[] = {"sep", "maxsplit", NULL};
2508 PyObject *sep = Py_None;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002509 Py_ssize_t maxsplit = -1;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002510
2511 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
2512 "|On:rsplit", _keywords,
2513 &sep, &maxsplit))
2514 goto exit;
2515 return_value = bytearray_rsplit_impl(self, sep, maxsplit);
2516
2517exit:
2518 return return_value;
2519}
2520
2521static PyObject *
2522bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit)
2523/*[clinic end generated code: output=affaf9fc2aae8d41 input=a68286e4dd692ffe]*/
2524{
2525 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002526 const char *s = PyByteArray_AS_STRING(self), *sub;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002527 PyObject *list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002528 Py_buffer vsub;
2529
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002530 if (maxsplit < 0)
2531 maxsplit = PY_SSIZE_T_MAX;
2532
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002533 if (sep == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002534 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002535
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002536 if (_getbuffer(sep, &vsub) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002537 return NULL;
2538 sub = vsub.buf;
2539 n = vsub.len;
2540
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002541 list = stringlib_rsplit(
2542 (PyObject*) self, s, len, sub, n, maxsplit
2543 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002544 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002545 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002546}
2547
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002548/*[clinic input]
2549bytearray.reverse
2550
2551 self: self(type="PyByteArrayObject *")
2552
2553Reverse the order of the values in B in place.
2554[clinic start generated code]*/
2555
2556PyDoc_STRVAR(bytearray_reverse__doc__,
2557"reverse($self, /)\n"
2558"--\n"
2559"\n"
2560"Reverse the order of the values in B in place.");
2561
2562#define BYTEARRAY_REVERSE_METHODDEF \
2563 {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, bytearray_reverse__doc__},
2564
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002565static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002566bytearray_reverse_impl(PyByteArrayObject *self);
2567
2568static PyObject *
2569bytearray_reverse(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
2570{
2571 return bytearray_reverse_impl(self);
2572}
2573
2574static PyObject *
2575bytearray_reverse_impl(PyByteArrayObject *self)
2576/*[clinic end generated code: output=5d5e5f0bfc67f476 input=7933a499b8597bd1]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002577{
2578 char swap, *head, *tail;
2579 Py_ssize_t i, j, n = Py_SIZE(self);
2580
2581 j = n / 2;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002582 head = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002583 tail = head + n - 1;
2584 for (i = 0; i < j; i++) {
2585 swap = *head;
2586 *head++ = *tail;
2587 *tail-- = swap;
2588 }
2589
2590 Py_RETURN_NONE;
2591}
2592
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002593
2594/*[python input]
2595class bytesvalue_converter(CConverter):
2596 type = 'int'
2597 converter = '_getbytevalue'
2598[python start generated code]*/
2599/*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/
2600
2601
2602/*[clinic input]
2603bytearray.insert
2604
2605 self: self(type="PyByteArrayObject *")
2606 index: Py_ssize_t
2607 The index where the value is to be inserted.
2608 item: bytesvalue
2609 The item to be inserted.
2610 /
2611
2612Insert a single item into the bytearray before the given index.
2613[clinic start generated code]*/
2614
2615PyDoc_STRVAR(bytearray_insert__doc__,
2616"insert($self, index, item, /)\n"
2617"--\n"
2618"\n"
2619"Insert a single item into the bytearray before the given index.\n"
2620"\n"
2621" index\n"
2622" The index where the value is to be inserted.\n"
2623" item\n"
2624" The item to be inserted.");
2625
2626#define BYTEARRAY_INSERT_METHODDEF \
2627 {"insert", (PyCFunction)bytearray_insert, METH_VARARGS, bytearray_insert__doc__},
2628
2629static PyObject *
2630bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item);
2631
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002632static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002633bytearray_insert(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002634{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002635 PyObject *return_value = NULL;
2636 Py_ssize_t index;
2637 int item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002638
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002639 if (!PyArg_ParseTuple(args,
2640 "nO&:insert",
2641 &index, _getbytevalue, &item))
2642 goto exit;
2643 return_value = bytearray_insert_impl(self, index, item);
2644
2645exit:
2646 return return_value;
2647}
2648
2649static PyObject *
2650bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
2651/*[clinic end generated code: output=5ec9340d4ad19080 input=833766836ba30e1e]*/
2652{
2653 Py_ssize_t n = Py_SIZE(self);
2654 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002655
2656 if (n == PY_SSIZE_T_MAX) {
2657 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002658 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002659 return NULL;
2660 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002661 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2662 return NULL;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002663 buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002664
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002665 if (index < 0) {
2666 index += n;
2667 if (index < 0)
2668 index = 0;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002669 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002670 if (index > n)
2671 index = n;
2672 memmove(buf + index + 1, buf + index, n - index);
2673 buf[index] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002674
2675 Py_RETURN_NONE;
2676}
2677
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002678/*[clinic input]
2679bytearray.append
2680
2681 self: self(type="PyByteArrayObject *")
2682 item: bytesvalue
2683 The item to be appended.
2684 /
2685
2686Append a single item to the end of the bytearray.
2687[clinic start generated code]*/
2688
2689PyDoc_STRVAR(bytearray_append__doc__,
2690"append($self, item, /)\n"
2691"--\n"
2692"\n"
2693"Append a single item to the end of the bytearray.\n"
2694"\n"
2695" item\n"
2696" The item to be appended.");
2697
2698#define BYTEARRAY_APPEND_METHODDEF \
2699 {"append", (PyCFunction)bytearray_append, METH_VARARGS, bytearray_append__doc__},
2700
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002701static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002702bytearray_append_impl(PyByteArrayObject *self, int item);
2703
2704static PyObject *
2705bytearray_append(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002706{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002707 PyObject *return_value = NULL;
2708 int item;
2709
2710 if (!PyArg_ParseTuple(args,
2711 "O&:append",
2712 _getbytevalue, &item))
2713 goto exit;
2714 return_value = bytearray_append_impl(self, item);
2715
2716exit:
2717 return return_value;
2718}
2719
2720static PyObject *
2721bytearray_append_impl(PyByteArrayObject *self, int item)
2722/*[clinic end generated code: output=b5b3325bb3bbaf85 input=ae56ea87380407cc]*/
2723{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002724 Py_ssize_t n = Py_SIZE(self);
2725
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002726 if (n == PY_SSIZE_T_MAX) {
2727 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002728 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002729 return NULL;
2730 }
2731 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2732 return NULL;
2733
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002734 PyByteArray_AS_STRING(self)[n] = item;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002735
2736 Py_RETURN_NONE;
2737}
2738
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002739/*[clinic input]
2740bytearray.extend
2741
2742 self: self(type="PyByteArrayObject *")
2743 iterable_of_ints: object
2744 The iterable of items to append.
2745 /
2746
2747Append all the items from the iterator or sequence to the end of the bytearray.
2748[clinic start generated code]*/
2749
2750PyDoc_STRVAR(bytearray_extend__doc__,
2751"extend($self, iterable_of_ints, /)\n"
2752"--\n"
2753"\n"
2754"Append all the items from the iterator or sequence to the end of the bytearray.\n"
2755"\n"
2756" iterable_of_ints\n"
2757" The iterable of items to append.");
2758
2759#define BYTEARRAY_EXTEND_METHODDEF \
2760 {"extend", (PyCFunction)bytearray_extend, METH_O, bytearray_extend__doc__},
2761
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002762static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002763bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
2764/*[clinic end generated code: output=13b0c13ad5110dfb input=ce83a5d75b70d850]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002765{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002766 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002767 Py_ssize_t buf_size = 0, len = 0;
2768 int value;
2769 char *buf;
2770
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002771 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002772 if (PyObject_CheckBuffer(iterable_of_ints)) {
2773 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002774 return NULL;
2775
2776 Py_RETURN_NONE;
2777 }
2778
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002779 it = PyObject_GetIter(iterable_of_ints);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002780 if (it == NULL)
2781 return NULL;
2782
Ezio Melotti42da6632011-03-15 05:18:48 +02002783 /* Try to determine the length of the argument. 32 is arbitrary. */
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002784 buf_size = PyObject_LengthHint(iterable_of_ints, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002785 if (buf_size == -1) {
2786 Py_DECREF(it);
2787 return NULL;
2788 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002789
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002790 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002791 if (bytearray_obj == NULL) {
2792 Py_DECREF(it);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002793 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002794 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002795 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002796
2797 while ((item = PyIter_Next(it)) != NULL) {
2798 if (! _getbytevalue(item, &value)) {
2799 Py_DECREF(item);
2800 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002801 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002802 return NULL;
2803 }
2804 buf[len++] = value;
2805 Py_DECREF(item);
2806
2807 if (len >= buf_size) {
2808 buf_size = len + (len >> 1) + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002809 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002810 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002811 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002812 return NULL;
2813 }
2814 /* Recompute the `buf' pointer, since the resizing operation may
2815 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002816 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002817 }
2818 }
2819 Py_DECREF(it);
2820
2821 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002822 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
2823 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002824 return NULL;
2825 }
2826
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002827 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
2828 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002829 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002830 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002831 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002832
2833 Py_RETURN_NONE;
2834}
2835
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002836/*[clinic input]
2837bytearray.pop
2838
2839 self: self(type="PyByteArrayObject *")
2840 index: Py_ssize_t = -1
2841 The index from where to remove the item.
2842 -1 (the default value) means remove the last item.
2843 /
2844
2845Remove and return a single item from B.
2846
2847If no index argument is given, will pop the last item.
2848[clinic start generated code]*/
2849
2850PyDoc_STRVAR(bytearray_pop__doc__,
2851"pop($self, index=-1, /)\n"
2852"--\n"
2853"\n"
2854"Remove and return a single item from B.\n"
2855"\n"
2856" index\n"
2857" The index from where to remove the item.\n"
2858" -1 (the default value) means remove the last item.\n"
2859"\n"
2860"If no index argument is given, will pop the last item.");
2861
2862#define BYTEARRAY_POP_METHODDEF \
2863 {"pop", (PyCFunction)bytearray_pop, METH_VARARGS, bytearray_pop__doc__},
2864
2865static PyObject *
2866bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index);
2867
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002868static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002869bytearray_pop(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002870{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002871 PyObject *return_value = NULL;
2872 Py_ssize_t index = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002873
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002874 if (!PyArg_ParseTuple(args,
2875 "|n:pop",
2876 &index))
2877 goto exit;
2878 return_value = bytearray_pop_impl(self, index);
2879
2880exit:
2881 return return_value;
2882}
2883
2884static PyObject *
2885bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
2886/*[clinic end generated code: output=3b763e548e79af96 input=0797e6c0ca9d5a85]*/
2887{
2888 int value;
2889 Py_ssize_t n = Py_SIZE(self);
2890 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002891
2892 if (n == 0) {
Eli Bendersky1bc4f192011-03-04 04:55:25 +00002893 PyErr_SetString(PyExc_IndexError,
2894 "pop from empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002895 return NULL;
2896 }
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002897 if (index < 0)
2898 index += Py_SIZE(self);
2899 if (index < 0 || index >= Py_SIZE(self)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002900 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2901 return NULL;
2902 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002903 if (!_canresize(self))
2904 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002905
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002906 buf = PyByteArray_AS_STRING(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002907 value = buf[index];
2908 memmove(buf + index, buf + index + 1, n - index);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002909 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2910 return NULL;
2911
Mark Dickinson54a3db92009-09-06 10:19:23 +00002912 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002913}
2914
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002915/*[clinic input]
2916bytearray.remove
2917
2918 self: self(type="PyByteArrayObject *")
2919 value: bytesvalue
2920 The value to remove.
2921 /
2922
2923Remove the first occurrence of a value in the bytearray.
2924[clinic start generated code]*/
2925
2926PyDoc_STRVAR(bytearray_remove__doc__,
2927"remove($self, value, /)\n"
2928"--\n"
2929"\n"
2930"Remove the first occurrence of a value in the bytearray.\n"
2931"\n"
2932" value\n"
2933" The value to remove.");
2934
2935#define BYTEARRAY_REMOVE_METHODDEF \
2936 {"remove", (PyCFunction)bytearray_remove, METH_VARARGS, bytearray_remove__doc__},
2937
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002938static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002939bytearray_remove_impl(PyByteArrayObject *self, int value);
2940
2941static PyObject *
2942bytearray_remove(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002943{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002944 PyObject *return_value = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002945 int value;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02002946
2947 if (!PyArg_ParseTuple(args,
2948 "O&:remove",
2949 _getbytevalue, &value))
2950 goto exit;
2951 return_value = bytearray_remove_impl(self, value);
2952
2953exit:
2954 return return_value;
2955}
2956
2957static PyObject *
2958bytearray_remove_impl(PyByteArrayObject *self, int value)
2959/*[clinic end generated code: output=c71c8bcf4703abfc input=47560b11fd856c24]*/
2960{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002961 Py_ssize_t where, n = Py_SIZE(self);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002962 char *buf = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002963
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002964 for (where = 0; where < n; where++) {
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002965 if (buf[where] == value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002966 break;
2967 }
2968 if (where == n) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002969 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002970 return NULL;
2971 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002972 if (!_canresize(self))
2973 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002974
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02002975 memmove(buf + where, buf + where + 1, n - where);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002976 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2977 return NULL;
2978
2979 Py_RETURN_NONE;
2980}
2981
2982/* XXX These two helpers could be optimized if argsize == 1 */
2983
2984static Py_ssize_t
Antoine Pitrou5b720752013-10-05 21:24:10 +02002985lstrip_helper(char *myptr, Py_ssize_t mysize,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002986 void *argptr, Py_ssize_t argsize)
2987{
2988 Py_ssize_t i = 0;
Antoine Pitrou5b720752013-10-05 21:24:10 +02002989 while (i < mysize && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002990 i++;
2991 return i;
2992}
2993
2994static Py_ssize_t
Antoine Pitrou5b720752013-10-05 21:24:10 +02002995rstrip_helper(char *myptr, Py_ssize_t mysize,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002996 void *argptr, Py_ssize_t argsize)
2997{
2998 Py_ssize_t i = mysize - 1;
Antoine Pitrou5b720752013-10-05 21:24:10 +02002999 while (i >= 0 && memchr(argptr, (unsigned char) myptr[i], argsize))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003000 i--;
3001 return i + 1;
3002}
3003
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003004/*[clinic input]
3005bytearray.strip
3006
3007 bytes: object = None
3008 /
3009
3010Strip leading and trailing bytes contained in the argument.
3011
3012If the argument is omitted or None, strip leading and trailing ASCII whitespace.
3013[clinic start generated code]*/
3014
3015PyDoc_STRVAR(bytearray_strip__doc__,
3016"strip($self, bytes=None, /)\n"
3017"--\n"
3018"\n"
3019"Strip leading and trailing bytes contained in the argument.\n"
3020"\n"
3021"If the argument is omitted or None, strip leading and trailing ASCII whitespace.");
3022
3023#define BYTEARRAY_STRIP_METHODDEF \
3024 {"strip", (PyCFunction)bytearray_strip, METH_VARARGS, bytearray_strip__doc__},
3025
3026static PyObject *
3027bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes);
3028
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003029static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003030bytearray_strip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003031{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003032 PyObject *return_value = NULL;
3033 PyObject *bytes = Py_None;
3034
3035 if (!PyArg_UnpackTuple(args, "strip",
3036 0, 1,
3037 &bytes))
3038 goto exit;
3039 return_value = bytearray_strip_impl(self, bytes);
3040
3041exit:
3042 return return_value;
3043}
3044
3045static PyObject *
3046bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
3047/*[clinic end generated code: output=2e3d3358acc4c235 input=ef7bb59b09c21d62]*/
3048{
3049 Py_ssize_t left, right, mysize, byteslen;
3050 char *myptr, *bytesptr;
3051 Py_buffer vbytes;
3052
3053 if (bytes == Py_None) {
3054 bytesptr = "\t\n\r\f\v ";
3055 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003056 }
3057 else {
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003058 if (_getbuffer(bytes, &vbytes) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003059 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003060 bytesptr = (char *) vbytes.buf;
3061 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003062 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003063 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003064 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003065 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003066 if (left == mysize)
3067 right = left;
3068 else
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003069 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
3070 if (bytes != Py_None)
3071 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003072 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003073}
3074
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003075/*[clinic input]
3076bytearray.lstrip
3077
3078 bytes: object = None
3079 /
3080
3081Strip leading bytes contained in the argument.
3082
3083If the argument is omitted or None, strip leading ASCII whitespace.
3084[clinic start generated code]*/
3085
3086PyDoc_STRVAR(bytearray_lstrip__doc__,
3087"lstrip($self, bytes=None, /)\n"
3088"--\n"
3089"\n"
3090"Strip leading bytes contained in the argument.\n"
3091"\n"
3092"If the argument is omitted or None, strip leading ASCII whitespace.");
3093
3094#define BYTEARRAY_LSTRIP_METHODDEF \
3095 {"lstrip", (PyCFunction)bytearray_lstrip, METH_VARARGS, bytearray_lstrip__doc__},
3096
3097static PyObject *
3098bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes);
3099
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003100static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003101bytearray_lstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003102{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003103 PyObject *return_value = NULL;
3104 PyObject *bytes = Py_None;
3105
3106 if (!PyArg_UnpackTuple(args, "lstrip",
3107 0, 1,
3108 &bytes))
3109 goto exit;
3110 return_value = bytearray_lstrip_impl(self, bytes);
3111
3112exit:
3113 return return_value;
3114}
3115
3116static PyObject *
3117bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
3118/*[clinic end generated code: output=2599309808a9ec02 input=80843f975dd7c480]*/
3119{
3120 Py_ssize_t left, right, mysize, byteslen;
3121 char *myptr, *bytesptr;
3122 Py_buffer vbytes;
3123
3124 if (bytes == Py_None) {
3125 bytesptr = "\t\n\r\f\v ";
3126 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003127 }
3128 else {
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003129 if (_getbuffer(bytes, &vbytes) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003130 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003131 bytesptr = (char *) vbytes.buf;
3132 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003133 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003134 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003135 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003136 left = lstrip_helper(myptr, mysize, bytesptr, byteslen);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003137 right = mysize;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003138 if (bytes != Py_None)
3139 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003140 return PyByteArray_FromStringAndSize(myptr + left, right - left);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003141}
3142
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003143/*[clinic input]
3144bytearray.rstrip
3145
3146 bytes: object = None
3147 /
3148
3149Strip trailing bytes contained in the argument.
3150
3151If the argument is omitted or None, strip trailing ASCII whitespace.
3152[clinic start generated code]*/
3153
3154PyDoc_STRVAR(bytearray_rstrip__doc__,
3155"rstrip($self, bytes=None, /)\n"
3156"--\n"
3157"\n"
3158"Strip trailing bytes contained in the argument.\n"
3159"\n"
3160"If the argument is omitted or None, strip trailing ASCII whitespace.");
3161
3162#define BYTEARRAY_RSTRIP_METHODDEF \
3163 {"rstrip", (PyCFunction)bytearray_rstrip, METH_VARARGS, bytearray_rstrip__doc__},
3164
3165static PyObject *
3166bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes);
3167
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003168static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003169bytearray_rstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003170{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003171 PyObject *return_value = NULL;
3172 PyObject *bytes = Py_None;
3173
3174 if (!PyArg_UnpackTuple(args, "rstrip",
3175 0, 1,
3176 &bytes))
3177 goto exit;
3178 return_value = bytearray_rstrip_impl(self, bytes);
3179
3180exit:
3181 return return_value;
3182}
3183
3184static PyObject *
3185bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
3186/*[clinic end generated code: output=b5ca6259f4f4f2a3 input=e728b994954cfd91]*/
3187{
3188 Py_ssize_t right, mysize, byteslen;
3189 char *myptr, *bytesptr;
3190 Py_buffer vbytes;
3191
3192 if (bytes == Py_None) {
3193 bytesptr = "\t\n\r\f\v ";
3194 byteslen = 6;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003195 }
3196 else {
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003197 if (_getbuffer(bytes, &vbytes) < 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003198 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003199 bytesptr = (char *) vbytes.buf;
3200 byteslen = vbytes.len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003201 }
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003202 myptr = PyByteArray_AS_STRING(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003203 mysize = Py_SIZE(self);
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003204 right = rstrip_helper(myptr, mysize, bytesptr, byteslen);
3205 if (bytes != Py_None)
3206 PyBuffer_Release(&vbytes);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003207 return PyByteArray_FromStringAndSize(myptr, right);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003208}
3209
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003210/*[clinic input]
3211bytearray.decode
3212
3213 encoding: str(c_default="NULL") = 'utf-8'
3214 The encoding with which to decode the bytearray.
3215 errors: str(c_default="NULL") = 'strict'
3216 The error handling scheme to use for the handling of decoding errors.
3217 The default is 'strict' meaning that decoding errors raise a
3218 UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
3219 as well as any other name registered with codecs.register_error that
3220 can handle UnicodeDecodeErrors.
3221
3222Decode the bytearray using the codec registered for encoding.
3223[clinic start generated code]*/
3224
3225PyDoc_STRVAR(bytearray_decode__doc__,
3226"decode($self, /, encoding=\'utf-8\', errors=\'strict\')\n"
3227"--\n"
3228"\n"
3229"Decode the bytearray using the codec registered for encoding.\n"
3230"\n"
3231" encoding\n"
3232" The encoding with which to decode the bytearray.\n"
3233" errors\n"
3234" The error handling scheme to use for the handling of decoding errors.\n"
3235" The default is \'strict\' meaning that decoding errors raise a\n"
3236" UnicodeDecodeError. Other possible values are \'ignore\' and \'replace\'\n"
3237" as well as any other name registered with codecs.register_error that\n"
3238" can handle UnicodeDecodeErrors.");
3239
3240#define BYTEARRAY_DECODE_METHODDEF \
3241 {"decode", (PyCFunction)bytearray_decode, METH_VARARGS|METH_KEYWORDS, bytearray_decode__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003242
3243static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003244bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors);
3245
3246static PyObject *
3247bytearray_decode(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003248{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003249 PyObject *return_value = NULL;
3250 static char *_keywords[] = {"encoding", "errors", NULL};
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003251 const char *encoding = NULL;
3252 const char *errors = NULL;
3253
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003254 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
3255 "|ss:decode", _keywords,
3256 &encoding, &errors))
3257 goto exit;
3258 return_value = bytearray_decode_impl(self, encoding, errors);
3259
3260exit:
3261 return return_value;
3262}
3263
3264static PyObject *
3265bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors)
3266/*[clinic end generated code: output=38b83681f1e38a6c input=f28d8f903020257b]*/
3267{
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003268 if (encoding == NULL)
3269 encoding = PyUnicode_GetDefaultEncoding();
Martin v. Löwis0efea322014-07-27 17:29:17 +02003270 return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003271}
3272
3273PyDoc_STRVAR(alloc_doc,
3274"B.__alloc__() -> int\n\
3275\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00003276Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003277
3278static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003279bytearray_alloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003280{
3281 return PyLong_FromSsize_t(self->ob_alloc);
3282}
3283
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003284/*[clinic input]
3285bytearray.join
3286
3287 iterable_of_bytes: object
3288 /
3289
3290Concatenate any number of bytes/bytearray objects.
3291
3292The bytearray whose method is called is inserted in between each pair.
3293
3294The result is returned as a new bytearray object.
3295[clinic start generated code]*/
3296
3297PyDoc_STRVAR(bytearray_join__doc__,
3298"join($self, iterable_of_bytes, /)\n"
3299"--\n"
3300"\n"
3301"Concatenate any number of bytes/bytearray objects.\n"
3302"\n"
3303"The bytearray whose method is called is inserted in between each pair.\n"
3304"\n"
3305"The result is returned as a new bytearray object.");
3306
3307#define BYTEARRAY_JOIN_METHODDEF \
3308 {"join", (PyCFunction)bytearray_join, METH_O, bytearray_join__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003309
3310static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003311bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes)
3312/*[clinic end generated code: output=544e7430032dfdf4 input=aba6b1f9b30fcb8e]*/
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003313{
Martin v. Löwis0efea322014-07-27 17:29:17 +02003314 return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003315}
3316
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003317/*[clinic input]
3318bytearray.splitlines
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003319
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003320 keepends: int(py_default="False") = 0
3321
3322Return a list of the lines in the bytearray, breaking at line boundaries.
3323
3324Line breaks are not included in the resulting list unless keepends is given and
3325true.
3326[clinic start generated code]*/
3327
3328PyDoc_STRVAR(bytearray_splitlines__doc__,
3329"splitlines($self, /, keepends=False)\n"
3330"--\n"
3331"\n"
3332"Return a list of the lines in the bytearray, breaking at line boundaries.\n"
3333"\n"
3334"Line breaks are not included in the resulting list unless keepends is given and\n"
3335"true.");
3336
3337#define BYTEARRAY_SPLITLINES_METHODDEF \
3338 {"splitlines", (PyCFunction)bytearray_splitlines, METH_VARARGS|METH_KEYWORDS, bytearray_splitlines__doc__},
3339
3340static PyObject *
3341bytearray_splitlines_impl(PyByteArrayObject *self, int keepends);
3342
3343static PyObject *
3344bytearray_splitlines(PyByteArrayObject *self, PyObject *args, PyObject *kwargs)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003345{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003346 PyObject *return_value = NULL;
3347 static char *_keywords[] = {"keepends", NULL};
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003348 int keepends = 0;
3349
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003350 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
3351 "|i:splitlines", _keywords,
3352 &keepends))
3353 goto exit;
3354 return_value = bytearray_splitlines_impl(self, keepends);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003355
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003356exit:
3357 return return_value;
3358}
3359
3360static PyObject *
3361bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
3362/*[clinic end generated code: output=a837fd0512ad46ff input=36f0b25bc792f6c0]*/
3363{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00003364 return stringlib_splitlines(
3365 (PyObject*) self, PyByteArray_AS_STRING(self),
3366 PyByteArray_GET_SIZE(self), keepends
3367 );
3368}
3369
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003370static int
Victor Stinner6430fd52011-09-29 04:02:13 +02003371hex_digit_to_int(Py_UCS4 c)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003372{
3373 if (c >= 128)
3374 return -1;
Eric Smith6dc46f52009-04-27 20:39:49 +00003375 if (Py_ISDIGIT(c))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003376 return c - '0';
3377 else {
Eric Smith6dc46f52009-04-27 20:39:49 +00003378 if (Py_ISUPPER(c))
3379 c = Py_TOLOWER(c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003380 if (c >= 'a' && c <= 'f')
3381 return c - 'a' + 10;
3382 }
3383 return -1;
3384}
3385
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003386/*[clinic input]
3387@classmethod
3388bytearray.fromhex
3389
3390 cls: self(type="PyObject*")
3391 string: unicode
3392 /
3393
3394Create a bytearray object from a string of hexadecimal numbers.
3395
3396Spaces between two numbers are accepted.
3397Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
3398[clinic start generated code]*/
3399
3400PyDoc_STRVAR(bytearray_fromhex__doc__,
3401"fromhex($type, string, /)\n"
3402"--\n"
3403"\n"
3404"Create a bytearray object from a string of hexadecimal numbers.\n"
3405"\n"
3406"Spaces between two numbers are accepted.\n"
3407"Example: bytearray.fromhex(\'B9 01EF\') -> bytearray(b\'\\\\xb9\\\\x01\\\\xef\')");
3408
3409#define BYTEARRAY_FROMHEX_METHODDEF \
3410 {"fromhex", (PyCFunction)bytearray_fromhex, METH_VARARGS|METH_CLASS, bytearray_fromhex__doc__},
3411
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003412static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003413bytearray_fromhex_impl(PyObject*cls, PyObject *string);
3414
3415static PyObject *
3416bytearray_fromhex(PyTypeObject *cls, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003417{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003418 PyObject *return_value = NULL;
3419 PyObject *string;
3420
3421 if (!PyArg_ParseTuple(args,
3422 "U:fromhex",
3423 &string))
3424 goto exit;
3425 return_value = bytearray_fromhex_impl((PyObject*)cls, string);
3426
3427exit:
3428 return return_value;
3429}
3430
3431static PyObject *
3432bytearray_fromhex_impl(PyObject*cls, PyObject *string)
3433/*[clinic end generated code: output=adc3c804a74e56d4 input=907bbd2d34d9367a]*/
3434{
3435 PyObject *newbytes;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003436 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003437 Py_ssize_t hexlen, byteslen, i, j;
3438 int top, bot;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003439 void *data;
3440 unsigned int kind;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003441
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003442 assert(PyUnicode_Check(string));
3443 if (PyUnicode_READY(string))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003444 return NULL;
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003445 kind = PyUnicode_KIND(string);
3446 data = PyUnicode_DATA(string);
3447 hexlen = PyUnicode_GET_LENGTH(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003448
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003449 byteslen = hexlen/2; /* This overestimates if there are spaces */
3450 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
3451 if (!newbytes)
3452 return NULL;
3453 buf = PyByteArray_AS_STRING(newbytes);
3454 for (i = j = 0; i < hexlen; i += 2) {
3455 /* skip over spaces in the input */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003456 while (PyUnicode_READ(kind, data, i) == ' ')
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003457 i++;
3458 if (i >= hexlen)
3459 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003460 top = hex_digit_to_int(PyUnicode_READ(kind, data, i));
3461 bot = hex_digit_to_int(PyUnicode_READ(kind, data, i+1));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003462 if (top == -1 || bot == -1) {
3463 PyErr_Format(PyExc_ValueError,
3464 "non-hexadecimal number found in "
3465 "fromhex() arg at position %zd", i);
3466 goto error;
3467 }
3468 buf[j++] = (top << 4) + bot;
3469 }
3470 if (PyByteArray_Resize(newbytes, j) < 0)
3471 goto error;
3472 return newbytes;
3473
3474 error:
3475 Py_DECREF(newbytes);
3476 return NULL;
3477}
3478
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003479
3480static PyObject *
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003481_common_reduce(PyByteArrayObject *self, int proto)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003482{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003483 PyObject *dict;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003484 _Py_IDENTIFIER(__dict__);
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003485 char *buf;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003486
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003487 dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003488 if (dict == NULL) {
3489 PyErr_Clear();
3490 dict = Py_None;
3491 Py_INCREF(dict);
3492 }
3493
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003494 buf = PyByteArray_AS_STRING(self);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003495 if (proto < 3) {
3496 /* use str based reduction for backwards compatibility with Python 2.x */
3497 PyObject *latin1;
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003498 if (Py_SIZE(self))
3499 latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003500 else
3501 latin1 = PyUnicode_FromString("");
3502 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
3503 }
3504 else {
3505 /* use more efficient byte based reduction */
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003506 if (Py_SIZE(self)) {
3507 return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), dict);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003508 }
3509 else {
3510 return Py_BuildValue("(O()N)", Py_TYPE(self), dict);
3511 }
3512 }
3513}
3514
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003515/*[clinic input]
3516bytearray.__reduce__ as bytearray_reduce
3517
3518 self: self(type="PyByteArrayObject *")
3519
3520Return state information for pickling.
3521[clinic start generated code]*/
3522
3523PyDoc_STRVAR(bytearray_reduce__doc__,
3524"__reduce__($self, /)\n"
3525"--\n"
3526"\n"
3527"Return state information for pickling.");
3528
3529#define BYTEARRAY_REDUCE_METHODDEF \
3530 {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, bytearray_reduce__doc__},
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003531
3532static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003533bytearray_reduce_impl(PyByteArrayObject *self);
3534
3535static PyObject *
3536bytearray_reduce(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
3537{
3538 return bytearray_reduce_impl(self);
3539}
3540
3541static PyObject *
3542bytearray_reduce_impl(PyByteArrayObject *self)
3543/*[clinic end generated code: output=b1b56fe87bf30fb0 input=fbb07de4d102a03a]*/
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003544{
3545 return _common_reduce(self, 2);
3546}
3547
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003548/*[clinic input]
3549bytearray.__reduce_ex__ as bytearray_reduce_ex
3550
3551 self: self(type="PyByteArrayObject *")
3552 proto: int = 0
3553 /
3554
3555Return state information for pickling.
3556[clinic start generated code]*/
3557
3558PyDoc_STRVAR(bytearray_reduce_ex__doc__,
3559"__reduce_ex__($self, proto=0, /)\n"
3560"--\n"
3561"\n"
3562"Return state information for pickling.");
3563
3564#define BYTEARRAY_REDUCE_EX_METHODDEF \
3565 {"__reduce_ex__", (PyCFunction)bytearray_reduce_ex, METH_VARARGS, bytearray_reduce_ex__doc__},
3566
3567static PyObject *
3568bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003569
3570static PyObject *
3571bytearray_reduce_ex(PyByteArrayObject *self, PyObject *args)
3572{
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003573 PyObject *return_value = NULL;
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003574 int proto = 0;
3575
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003576 if (!PyArg_ParseTuple(args,
3577 "|i:__reduce_ex__",
3578 &proto))
3579 goto exit;
3580 return_value = bytearray_reduce_ex_impl(self, proto);
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003581
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003582exit:
3583 return return_value;
3584}
3585
3586static PyObject *
3587bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
3588/*[clinic end generated code: output=bbd9afb2f5953dc1 input=0e091a42ca6dbd91]*/
3589{
Antoine Pitroub0e1f8b2011-12-05 20:40:08 +01003590 return _common_reduce(self, proto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003591}
3592
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003593/*[clinic input]
3594bytearray.__sizeof__ as bytearray_sizeof
3595
3596 self: self(type="PyByteArrayObject *")
3597
3598Returns the size of the bytearray object in memory, in bytes.
3599[clinic start generated code]*/
3600
3601PyDoc_STRVAR(bytearray_sizeof__doc__,
3602"__sizeof__($self, /)\n"
3603"--\n"
3604"\n"
3605"Returns the size of the bytearray object in memory, in bytes.");
3606
3607#define BYTEARRAY_SIZEOF_METHODDEF \
3608 {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, bytearray_sizeof__doc__},
3609
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003610static PyObject *
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003611bytearray_sizeof_impl(PyByteArrayObject *self);
3612
3613static PyObject *
3614bytearray_sizeof(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored))
3615{
3616 return bytearray_sizeof_impl(self);
3617}
3618
3619static PyObject *
3620bytearray_sizeof_impl(PyByteArrayObject *self)
3621/*[clinic end generated code: output=4a2254b0a85630c6 input=6b23d305362b462b]*/
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003622{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00003623 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003624
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00003625 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
3626 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003627}
3628
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003629static PySequenceMethods bytearray_as_sequence = {
3630 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003631 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003632 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
3633 (ssizeargfunc)bytearray_getitem, /* sq_item */
3634 0, /* sq_slice */
3635 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
3636 0, /* sq_ass_slice */
3637 (objobjproc)bytearray_contains, /* sq_contains */
3638 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
3639 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003640};
3641
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003642static PyMappingMethods bytearray_as_mapping = {
3643 (lenfunc)bytearray_length,
3644 (binaryfunc)bytearray_subscript,
3645 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003646};
3647
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003648static PyBufferProcs bytearray_as_buffer = {
3649 (getbufferproc)bytearray_getbuffer,
3650 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003651};
3652
3653static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003654bytearray_methods[] = {
3655 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003656 BYTEARRAY_REDUCE_METHODDEF
3657 BYTEARRAY_REDUCE_EX_METHODDEF
3658 BYTEARRAY_SIZEOF_METHODDEF
3659 BYTEARRAY_APPEND_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003660 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
3661 _Py_capitalize__doc__},
3662 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003663 BYTEARRAY_CLEAR_METHODDEF
3664 BYTEARRAY_COPY_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003665 {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003666 BYTEARRAY_DECODE_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003667 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +02003668 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS | METH_KEYWORDS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003669 expandtabs__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003670 BYTEARRAY_EXTEND_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003671 {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003672 BYTEARRAY_FROMHEX_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003673 {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003674 BYTEARRAY_INSERT_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003675 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
3676 _Py_isalnum__doc__},
3677 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
3678 _Py_isalpha__doc__},
3679 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
3680 _Py_isdigit__doc__},
3681 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
3682 _Py_islower__doc__},
3683 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
3684 _Py_isspace__doc__},
3685 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
3686 _Py_istitle__doc__},
3687 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
3688 _Py_isupper__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003689 BYTEARRAY_JOIN_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003690 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
3691 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003692 BYTEARRAY_LSTRIP_METHODDEF
3693 BYTEARRAY_MAKETRANS_METHODDEF
3694 BYTEARRAY_PARTITION_METHODDEF
3695 BYTEARRAY_POP_METHODDEF
3696 BYTEARRAY_REMOVE_METHODDEF
3697 BYTEARRAY_REPLACE_METHODDEF
3698 BYTEARRAY_REVERSE_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003699 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
3700 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003701 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003702 BYTEARRAY_RPARTITION_METHODDEF
3703 BYTEARRAY_RSPLIT_METHODDEF
3704 BYTEARRAY_RSTRIP_METHODDEF
3705 BYTEARRAY_SPLIT_METHODDEF
3706 BYTEARRAY_SPLITLINES_METHODDEF
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003707 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003708 startswith__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003709 BYTEARRAY_STRIP_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003710 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
3711 _Py_swapcase__doc__},
3712 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003713 BYTEARRAY_TRANSLATE_METHODDEF
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003714 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
3715 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
3716 {NULL}
3717};
3718
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003719PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00003720"bytearray(iterable_of_ints) -> bytearray\n\
3721bytearray(string, encoding[, errors]) -> bytearray\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003722bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
3723bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
3724bytearray() -> empty bytes array\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003725\n\
3726Construct an mutable bytearray object from:\n\
3727 - an iterable yielding integers in range(256)\n\
3728 - a text string encoded using the specified encoding\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003729 - a bytes or a buffer object\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003730 - any object implementing the buffer API.\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01003731 - an integer");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003732
3733
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003734static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003735
3736PyTypeObject PyByteArray_Type = {
3737 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3738 "bytearray",
3739 sizeof(PyByteArrayObject),
3740 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003741 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003742 0, /* tp_print */
3743 0, /* tp_getattr */
3744 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003745 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003746 (reprfunc)bytearray_repr, /* tp_repr */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003747 0, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003748 &bytearray_as_sequence, /* tp_as_sequence */
3749 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003750 0, /* tp_hash */
3751 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003752 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003753 PyObject_GenericGetAttr, /* tp_getattro */
3754 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003755 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003756 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003757 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003758 0, /* tp_traverse */
3759 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003760 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003761 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003762 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003763 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003764 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003765 0, /* tp_members */
3766 0, /* tp_getset */
3767 0, /* tp_base */
3768 0, /* tp_dict */
3769 0, /* tp_descr_get */
3770 0, /* tp_descr_set */
3771 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003772 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003773 PyType_GenericAlloc, /* tp_alloc */
3774 PyType_GenericNew, /* tp_new */
3775 PyObject_Del, /* tp_free */
3776};
3777
3778/*********************** Bytes Iterator ****************************/
3779
3780typedef struct {
3781 PyObject_HEAD
3782 Py_ssize_t it_index;
3783 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
3784} bytesiterobject;
3785
3786static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003787bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003788{
3789 _PyObject_GC_UNTRACK(it);
3790 Py_XDECREF(it->it_seq);
3791 PyObject_GC_Del(it);
3792}
3793
3794static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003795bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003796{
3797 Py_VISIT(it->it_seq);
3798 return 0;
3799}
3800
3801static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003802bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003803{
3804 PyByteArrayObject *seq;
3805 PyObject *item;
3806
3807 assert(it != NULL);
3808 seq = it->it_seq;
3809 if (seq == NULL)
3810 return NULL;
3811 assert(PyByteArray_Check(seq));
3812
3813 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
3814 item = PyLong_FromLong(
Antoine Pitrou5df8a8a2013-10-05 21:12:18 +02003815 (unsigned char)PyByteArray_AS_STRING(seq)[it->it_index]);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003816 if (item != NULL)
3817 ++it->it_index;
3818 return item;
3819 }
3820
3821 Py_DECREF(seq);
3822 it->it_seq = NULL;
3823 return NULL;
3824}
3825
3826static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003827bytearrayiter_length_hint(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003828{
3829 Py_ssize_t len = 0;
3830 if (it->it_seq)
3831 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
3832 return PyLong_FromSsize_t(len);
3833}
3834
3835PyDoc_STRVAR(length_hint_doc,
3836 "Private method returning an estimate of len(list(it)).");
3837
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003838static PyObject *
3839bytearrayiter_reduce(bytesiterobject *it)
3840{
3841 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +02003842 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003843 it->it_seq, it->it_index);
3844 } else {
3845 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
3846 if (u == NULL)
3847 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02003848 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003849 }
3850}
3851
3852static PyObject *
3853bytearrayiter_setstate(bytesiterobject *it, PyObject *state)
3854{
3855 Py_ssize_t index = PyLong_AsSsize_t(state);
3856 if (index == -1 && PyErr_Occurred())
3857 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00003858 if (it->it_seq != NULL) {
3859 if (index < 0)
3860 index = 0;
3861 else if (index > PyByteArray_GET_SIZE(it->it_seq))
3862 index = PyByteArray_GET_SIZE(it->it_seq); /* iterator exhausted */
3863 it->it_index = index;
3864 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003865 Py_RETURN_NONE;
3866}
3867
3868PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
3869
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003870static PyMethodDef bytearrayiter_methods[] = {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003871 {"__length_hint__", (PyCFunction)bytearrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003872 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003873 {"__reduce__", (PyCFunction)bytearrayiter_reduce, METH_NOARGS,
Martin v. Löwis7252a6e2014-07-27 16:25:09 +02003874 bytearray_reduce__doc__},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003875 {"__setstate__", (PyCFunction)bytearrayiter_setstate, METH_O,
3876 setstate_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003877 {NULL, NULL} /* sentinel */
3878};
3879
3880PyTypeObject PyByteArrayIter_Type = {
3881 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3882 "bytearray_iterator", /* tp_name */
3883 sizeof(bytesiterobject), /* tp_basicsize */
3884 0, /* tp_itemsize */
3885 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003886 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003887 0, /* tp_print */
3888 0, /* tp_getattr */
3889 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003890 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003891 0, /* tp_repr */
3892 0, /* tp_as_number */
3893 0, /* tp_as_sequence */
3894 0, /* tp_as_mapping */
3895 0, /* tp_hash */
3896 0, /* tp_call */
3897 0, /* tp_str */
3898 PyObject_GenericGetAttr, /* tp_getattro */
3899 0, /* tp_setattro */
3900 0, /* tp_as_buffer */
3901 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
3902 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003903 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003904 0, /* tp_clear */
3905 0, /* tp_richcompare */
3906 0, /* tp_weaklistoffset */
3907 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003908 (iternextfunc)bytearrayiter_next, /* tp_iternext */
3909 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003910 0,
3911};
3912
3913static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003914bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003915{
3916 bytesiterobject *it;
3917
3918 if (!PyByteArray_Check(seq)) {
3919 PyErr_BadInternalCall();
3920 return NULL;
3921 }
3922 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
3923 if (it == NULL)
3924 return NULL;
3925 it->it_index = 0;
3926 Py_INCREF(seq);
3927 it->it_seq = (PyByteArrayObject *)seq;
3928 _PyObject_GC_TRACK(it);
3929 return (PyObject *)it;
3930}