blob: 7d5dbd0587b5abdacda887dc60f5e2db6146a6f6 [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
Antoine Pitroufc8d6f42010-01-17 12:38:54 +00008char _PyByteArray_empty_string[] = "";
Christian Heimes2c9c7a52008-05-26 13:42:13 +00009
10void
11PyByteArray_Fini(void)
12{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000013}
14
15int
16PyByteArray_Init(void)
17{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000018 return 1;
19}
20
21/* end nullbytes support */
22
23/* Helpers */
24
25static int
26_getbytevalue(PyObject* arg, int *value)
27{
28 long face_value;
29
30 if (PyLong_Check(arg)) {
31 face_value = PyLong_AsLong(arg);
Georg Brandl9a54d7c2008-07-16 23:15:30 +000032 } else {
33 PyObject *index = PyNumber_Index(arg);
34 if (index == NULL) {
35 PyErr_Format(PyExc_TypeError, "an integer is required");
Mark Dickinson10de93a2010-07-09 19:25:48 +000036 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000037 return 0;
38 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +000039 face_value = PyLong_AsLong(index);
40 Py_DECREF(index);
41 }
42
43 if (face_value < 0 || face_value >= 256) {
44 /* this includes the OverflowError in case the long is too large */
45 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
Mark Dickinson10de93a2010-07-09 19:25:48 +000046 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000047 return 0;
48 }
49
50 *value = face_value;
51 return 1;
52}
53
54static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +000055bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000056{
57 int ret;
58 void *ptr;
59 if (view == NULL) {
60 obj->ob_exports++;
61 return 0;
62 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000063 ptr = (void *) PyByteArray_AS_STRING(obj);
Martin v. Löwis423be952008-08-13 15:53:07 +000064 ret = PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
Christian Heimes2c9c7a52008-05-26 13:42:13 +000065 if (ret >= 0) {
66 obj->ob_exports++;
67 }
68 return ret;
69}
70
71static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +000072bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000073{
74 obj->ob_exports--;
75}
76
77static Py_ssize_t
78_getbuffer(PyObject *obj, Py_buffer *view)
79{
80 PyBufferProcs *buffer = Py_TYPE(obj)->tp_as_buffer;
81
82 if (buffer == NULL || buffer->bf_getbuffer == NULL)
83 {
84 PyErr_Format(PyExc_TypeError,
85 "Type %.100s doesn't support the buffer API",
86 Py_TYPE(obj)->tp_name);
87 return -1;
88 }
89
90 if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0)
91 return -1;
92 return view->len;
93}
94
Antoine Pitrou5504e892008-12-06 21:27:53 +000095static int
96_canresize(PyByteArrayObject *self)
97{
98 if (self->ob_exports > 0) {
99 PyErr_SetString(PyExc_BufferError,
100 "Existing exports of data: object cannot be re-sized");
101 return 0;
102 }
103 return 1;
104}
105
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000106/* Direct API functions */
107
108PyObject *
109PyByteArray_FromObject(PyObject *input)
110{
111 return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
112 input, NULL);
113}
114
115PyObject *
116PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
117{
118 PyByteArrayObject *new;
119 Py_ssize_t alloc;
120
121 if (size < 0) {
122 PyErr_SetString(PyExc_SystemError,
123 "Negative size passed to PyByteArray_FromStringAndSize");
124 return NULL;
125 }
126
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000127 /* Prevent buffer overflow when setting alloc to size+1. */
128 if (size == PY_SSIZE_T_MAX) {
129 return PyErr_NoMemory();
130 }
131
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000132 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
133 if (new == NULL)
134 return NULL;
135
136 if (size == 0) {
137 new->ob_bytes = NULL;
138 alloc = 0;
139 }
140 else {
141 alloc = size + 1;
142 new->ob_bytes = PyMem_Malloc(alloc);
143 if (new->ob_bytes == NULL) {
144 Py_DECREF(new);
145 return PyErr_NoMemory();
146 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +0000147 if (bytes != NULL && size > 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000148 memcpy(new->ob_bytes, bytes, size);
149 new->ob_bytes[size] = '\0'; /* Trailing null byte */
150 }
151 Py_SIZE(new) = size;
152 new->ob_alloc = alloc;
153 new->ob_exports = 0;
154
155 return (PyObject *)new;
156}
157
158Py_ssize_t
159PyByteArray_Size(PyObject *self)
160{
161 assert(self != NULL);
162 assert(PyByteArray_Check(self));
163
164 return PyByteArray_GET_SIZE(self);
165}
166
167char *
168PyByteArray_AsString(PyObject *self)
169{
170 assert(self != NULL);
171 assert(PyByteArray_Check(self));
172
173 return PyByteArray_AS_STRING(self);
174}
175
176int
177PyByteArray_Resize(PyObject *self, Py_ssize_t size)
178{
179 void *sval;
180 Py_ssize_t alloc = ((PyByteArrayObject *)self)->ob_alloc;
181
182 assert(self != NULL);
183 assert(PyByteArray_Check(self));
184 assert(size >= 0);
185
Antoine Pitrou5504e892008-12-06 21:27:53 +0000186 if (size == Py_SIZE(self)) {
187 return 0;
188 }
189 if (!_canresize((PyByteArrayObject *)self)) {
190 return -1;
191 }
192
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000193 if (size < alloc / 2) {
194 /* Major downsize; resize down to exact size */
195 alloc = size + 1;
196 }
197 else if (size < alloc) {
198 /* Within allocated size; quick exit */
199 Py_SIZE(self) = size;
200 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null */
201 return 0;
202 }
203 else if (size <= alloc * 1.125) {
204 /* Moderate upsize; overallocate similar to list_resize() */
205 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
206 }
207 else {
208 /* Major upsize; resize up to exact size */
209 alloc = size + 1;
210 }
211
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000212 sval = PyMem_Realloc(((PyByteArrayObject *)self)->ob_bytes, alloc);
213 if (sval == NULL) {
214 PyErr_NoMemory();
215 return -1;
216 }
217
218 ((PyByteArrayObject *)self)->ob_bytes = sval;
219 Py_SIZE(self) = size;
220 ((PyByteArrayObject *)self)->ob_alloc = alloc;
221 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null byte */
222
223 return 0;
224}
225
226PyObject *
227PyByteArray_Concat(PyObject *a, PyObject *b)
228{
229 Py_ssize_t size;
230 Py_buffer va, vb;
231 PyByteArrayObject *result = NULL;
232
233 va.len = -1;
234 vb.len = -1;
235 if (_getbuffer(a, &va) < 0 ||
236 _getbuffer(b, &vb) < 0) {
237 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
238 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
239 goto done;
240 }
241
242 size = va.len + vb.len;
243 if (size < 0) {
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000244 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000245 goto done;
246 }
247
248 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
249 if (result != NULL) {
250 memcpy(result->ob_bytes, va.buf, va.len);
251 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
252 }
253
254 done:
255 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000256 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000257 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000258 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000259 return (PyObject *)result;
260}
261
262/* Functions stuffed into the type object */
263
264static Py_ssize_t
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000265bytearray_length(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000266{
267 return Py_SIZE(self);
268}
269
270static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000271bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000272{
273 Py_ssize_t mysize;
274 Py_ssize_t size;
275 Py_buffer vo;
276
277 if (_getbuffer(other, &vo) < 0) {
278 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
279 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
280 return NULL;
281 }
282
283 mysize = Py_SIZE(self);
284 size = mysize + vo.len;
285 if (size < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000286 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000287 return PyErr_NoMemory();
288 }
289 if (size < self->ob_alloc) {
290 Py_SIZE(self) = size;
291 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
292 }
293 else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000294 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000295 return NULL;
296 }
297 memcpy(self->ob_bytes + mysize, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000298 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000299 Py_INCREF(self);
300 return (PyObject *)self;
301}
302
303static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000304bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000305{
306 PyByteArrayObject *result;
307 Py_ssize_t mysize;
308 Py_ssize_t size;
309
310 if (count < 0)
311 count = 0;
312 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000313 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000314 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000315 size = mysize * count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000316 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
317 if (result != NULL && size != 0) {
318 if (mysize == 1)
319 memset(result->ob_bytes, self->ob_bytes[0], size);
320 else {
321 Py_ssize_t i;
322 for (i = 0; i < count; i++)
323 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
324 }
325 }
326 return (PyObject *)result;
327}
328
329static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000330bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000331{
332 Py_ssize_t mysize;
333 Py_ssize_t size;
334
335 if (count < 0)
336 count = 0;
337 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000338 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000339 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000340 size = mysize * count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000341 if (size < self->ob_alloc) {
342 Py_SIZE(self) = size;
343 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
344 }
345 else if (PyByteArray_Resize((PyObject *)self, size) < 0)
346 return NULL;
347
348 if (mysize == 1)
349 memset(self->ob_bytes, self->ob_bytes[0], size);
350 else {
351 Py_ssize_t i;
352 for (i = 1; i < count; i++)
353 memcpy(self->ob_bytes + i*mysize, self->ob_bytes, mysize);
354 }
355
356 Py_INCREF(self);
357 return (PyObject *)self;
358}
359
360static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000361bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000362{
363 if (i < 0)
364 i += Py_SIZE(self);
365 if (i < 0 || i >= Py_SIZE(self)) {
366 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
367 return NULL;
368 }
369 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
370}
371
372static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000373bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000374{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000375 if (PyIndex_Check(index)) {
376 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000377
378 if (i == -1 && PyErr_Occurred())
379 return NULL;
380
381 if (i < 0)
382 i += PyByteArray_GET_SIZE(self);
383
384 if (i < 0 || i >= Py_SIZE(self)) {
385 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
386 return NULL;
387 }
388 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
389 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000390 else if (PySlice_Check(index)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000391 Py_ssize_t start, stop, step, slicelength, cur, i;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000392 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000393 PyByteArray_GET_SIZE(self),
394 &start, &stop, &step, &slicelength) < 0) {
395 return NULL;
396 }
397
398 if (slicelength <= 0)
399 return PyByteArray_FromStringAndSize("", 0);
400 else if (step == 1) {
401 return PyByteArray_FromStringAndSize(self->ob_bytes + start,
402 slicelength);
403 }
404 else {
405 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000406 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000407 PyObject *result;
408
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000409 result = PyByteArray_FromStringAndSize(NULL, slicelength);
410 if (result == NULL)
411 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000412
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000413 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000414 for (cur = start, i = 0; i < slicelength;
415 cur += step, i++) {
416 result_buf[i] = source_buf[cur];
417 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000418 return result;
419 }
420 }
421 else {
422 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integers");
423 return NULL;
424 }
425}
426
427static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000428bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000429 PyObject *values)
430{
431 Py_ssize_t avail, needed;
432 void *bytes;
433 Py_buffer vbytes;
434 int res = 0;
435
436 vbytes.len = -1;
437 if (values == (PyObject *)self) {
438 /* Make a copy and call this function recursively */
439 int err;
440 values = PyByteArray_FromObject(values);
441 if (values == NULL)
442 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000443 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000444 Py_DECREF(values);
445 return err;
446 }
447 if (values == NULL) {
448 /* del b[lo:hi] */
449 bytes = NULL;
450 needed = 0;
451 }
452 else {
453 if (_getbuffer(values, &vbytes) < 0) {
454 PyErr_Format(PyExc_TypeError,
Georg Brandl3dbca812008-07-23 16:10:53 +0000455 "can't set bytearray slice from %.100s",
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000456 Py_TYPE(values)->tp_name);
457 return -1;
458 }
459 needed = vbytes.len;
460 bytes = vbytes.buf;
461 }
462
463 if (lo < 0)
464 lo = 0;
465 if (hi < lo)
466 hi = lo;
467 if (hi > Py_SIZE(self))
468 hi = Py_SIZE(self);
469
470 avail = hi - lo;
471 if (avail < 0)
472 lo = hi = avail = 0;
473
474 if (avail != needed) {
475 if (avail > needed) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000476 if (!_canresize(self)) {
477 res = -1;
478 goto finish;
479 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000480 /*
481 0 lo hi old_size
482 | |<----avail----->|<-----tomove------>|
483 | |<-needed->|<-----tomove------>|
484 0 lo new_hi new_size
485 */
486 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
487 Py_SIZE(self) - hi);
488 }
489 /* XXX(nnorwitz): need to verify this can't overflow! */
490 if (PyByteArray_Resize((PyObject *)self,
491 Py_SIZE(self) + needed - avail) < 0) {
492 res = -1;
493 goto finish;
494 }
495 if (avail < needed) {
496 /*
497 0 lo hi old_size
498 | |<-avail->|<-----tomove------>|
499 | |<----needed---->|<-----tomove------>|
500 0 lo new_hi new_size
501 */
502 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
503 Py_SIZE(self) - lo - needed);
504 }
505 }
506
507 if (needed > 0)
508 memcpy(self->ob_bytes + lo, bytes, needed);
509
510
511 finish:
512 if (vbytes.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000513 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000514 return res;
515}
516
517static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000518bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000519{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000520 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000521
522 if (i < 0)
523 i += Py_SIZE(self);
524
525 if (i < 0 || i >= Py_SIZE(self)) {
526 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
527 return -1;
528 }
529
530 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000531 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000532
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000533 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000534 return -1;
535
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000536 self->ob_bytes[i] = ival;
537 return 0;
538}
539
540static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000541bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000542{
543 Py_ssize_t start, stop, step, slicelen, needed;
544 char *bytes;
545
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000546 if (PyIndex_Check(index)) {
547 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000548
549 if (i == -1 && PyErr_Occurred())
550 return -1;
551
552 if (i < 0)
553 i += PyByteArray_GET_SIZE(self);
554
555 if (i < 0 || i >= Py_SIZE(self)) {
556 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
557 return -1;
558 }
559
560 if (values == NULL) {
561 /* Fall through to slice assignment */
562 start = i;
563 stop = i + 1;
564 step = 1;
565 slicelen = 1;
566 }
567 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000568 int ival;
569 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000570 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000571 self->ob_bytes[i] = (char)ival;
572 return 0;
573 }
574 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000575 else if (PySlice_Check(index)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000576 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000577 PyByteArray_GET_SIZE(self),
578 &start, &stop, &step, &slicelen) < 0) {
579 return -1;
580 }
581 }
582 else {
583 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integer");
584 return -1;
585 }
586
587 if (values == NULL) {
588 bytes = NULL;
589 needed = 0;
590 }
591 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
Christian Heimes6d26ade2012-11-03 23:07:59 +0100592 int err;
Ezio Melottic64bcbe2012-11-03 21:19:06 +0200593 if (PyNumber_Check(values) || PyUnicode_Check(values)) {
594 PyErr_SetString(PyExc_TypeError,
595 "can assign only bytes, buffers, or iterables "
596 "of ints in range(0, 256)");
597 return -1;
598 }
Georg Brandlf3fa5682010-12-04 17:09:30 +0000599 /* Make a copy and call this function recursively */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000600 values = PyByteArray_FromObject(values);
601 if (values == NULL)
602 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000603 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000604 Py_DECREF(values);
605 return err;
606 }
607 else {
608 assert(PyByteArray_Check(values));
609 bytes = ((PyByteArrayObject *)values)->ob_bytes;
610 needed = Py_SIZE(values);
611 }
612 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
613 if ((step < 0 && start < stop) ||
614 (step > 0 && start > stop))
615 stop = start;
616 if (step == 1) {
617 if (slicelen != needed) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000618 if (!_canresize(self))
619 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000620 if (slicelen > needed) {
621 /*
622 0 start stop old_size
623 | |<---slicelen--->|<-----tomove------>|
624 | |<-needed->|<-----tomove------>|
625 0 lo new_hi new_size
626 */
627 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
628 Py_SIZE(self) - stop);
629 }
630 if (PyByteArray_Resize((PyObject *)self,
631 Py_SIZE(self) + needed - slicelen) < 0)
632 return -1;
633 if (slicelen < needed) {
634 /*
635 0 lo hi old_size
636 | |<-avail->|<-----tomove------>|
637 | |<----needed---->|<-----tomove------>|
638 0 lo new_hi new_size
639 */
640 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
641 Py_SIZE(self) - start - needed);
642 }
643 }
644
645 if (needed > 0)
646 memcpy(self->ob_bytes + start, bytes, needed);
647
648 return 0;
649 }
650 else {
651 if (needed == 0) {
652 /* Delete slice */
Mark Dickinsonbc099642010-01-29 17:27:24 +0000653 size_t cur;
654 Py_ssize_t i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000655
Antoine Pitrou5504e892008-12-06 21:27:53 +0000656 if (!_canresize(self))
657 return -1;
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000658
659 if (slicelen == 0)
660 /* Nothing to do here. */
661 return 0;
662
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000663 if (step < 0) {
664 stop = start + 1;
665 start = stop + step * (slicelen - 1) - 1;
666 step = -step;
667 }
668 for (cur = start, i = 0;
669 i < slicelen; cur += step, i++) {
670 Py_ssize_t lim = step - 1;
671
Mark Dickinson66f575b2010-02-14 12:53:32 +0000672 if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000673 lim = PyByteArray_GET_SIZE(self) - cur - 1;
674
675 memmove(self->ob_bytes + cur - i,
676 self->ob_bytes + cur + 1, lim);
677 }
678 /* Move the tail of the bytes, in one chunk */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000679 cur = start + (size_t)slicelen*step;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000680 if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000681 memmove(self->ob_bytes + cur - slicelen,
682 self->ob_bytes + cur,
683 PyByteArray_GET_SIZE(self) - cur);
684 }
685 if (PyByteArray_Resize((PyObject *)self,
686 PyByteArray_GET_SIZE(self) - slicelen) < 0)
687 return -1;
688
689 return 0;
690 }
691 else {
692 /* Assign slice */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000693 Py_ssize_t i;
694 size_t cur;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000695
696 if (needed != slicelen) {
697 PyErr_Format(PyExc_ValueError,
698 "attempt to assign bytes of size %zd "
699 "to extended slice of size %zd",
700 needed, slicelen);
701 return -1;
702 }
703 for (cur = start, i = 0; i < slicelen; cur += step, i++)
704 self->ob_bytes[cur] = bytes[i];
705 return 0;
706 }
707 }
708}
709
710static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000711bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000712{
713 static char *kwlist[] = {"source", "encoding", "errors", 0};
714 PyObject *arg = NULL;
715 const char *encoding = NULL;
716 const char *errors = NULL;
717 Py_ssize_t count;
718 PyObject *it;
719 PyObject *(*iternext)(PyObject *);
720
721 if (Py_SIZE(self) != 0) {
722 /* Empty previous contents (yes, do this first of all!) */
723 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
724 return -1;
725 }
726
727 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000728 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000729 &arg, &encoding, &errors))
730 return -1;
731
732 /* Make a quick exit if no first argument */
733 if (arg == NULL) {
734 if (encoding != NULL || errors != NULL) {
735 PyErr_SetString(PyExc_TypeError,
736 "encoding or errors without sequence argument");
737 return -1;
738 }
739 return 0;
740 }
741
742 if (PyUnicode_Check(arg)) {
743 /* Encode via the codec registry */
744 PyObject *encoded, *new;
745 if (encoding == NULL) {
746 PyErr_SetString(PyExc_TypeError,
747 "string argument without an encoding");
748 return -1;
749 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000750 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000751 if (encoded == NULL)
752 return -1;
753 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000754 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000755 Py_DECREF(encoded);
756 if (new == NULL)
757 return -1;
758 Py_DECREF(new);
759 return 0;
760 }
761
762 /* If it's not unicode, there can't be encoding or errors */
763 if (encoding != NULL || errors != NULL) {
764 PyErr_SetString(PyExc_TypeError,
765 "encoding or errors without a string argument");
766 return -1;
767 }
768
769 /* Is it an int? */
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000770 count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
771 if (count == -1 && PyErr_Occurred()) {
772 if (PyErr_ExceptionMatches(PyExc_OverflowError))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000773 return -1;
Benjamin Peterson9c0e94f2010-04-16 23:00:53 +0000774 PyErr_Clear();
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000775 }
776 else if (count < 0) {
777 PyErr_SetString(PyExc_ValueError, "negative count");
778 return -1;
779 }
780 else {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000781 if (count > 0) {
782 if (PyByteArray_Resize((PyObject *)self, count))
783 return -1;
784 memset(self->ob_bytes, 0, count);
785 }
786 return 0;
787 }
788
789 /* Use the buffer API */
790 if (PyObject_CheckBuffer(arg)) {
791 Py_ssize_t size;
792 Py_buffer view;
793 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
794 return -1;
795 size = view.len;
796 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
797 if (PyBuffer_ToContiguous(self->ob_bytes, &view, size, 'C') < 0)
798 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000799 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000800 return 0;
801 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000802 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000803 return -1;
804 }
805
806 /* XXX Optimize this if the arguments is a list, tuple */
807
808 /* Get the iterator */
809 it = PyObject_GetIter(arg);
810 if (it == NULL)
811 return -1;
812 iternext = *Py_TYPE(it)->tp_iternext;
813
814 /* Run the iterator to exhaustion */
815 for (;;) {
816 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000817 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000818
819 /* Get the next item */
820 item = iternext(it);
821 if (item == NULL) {
822 if (PyErr_Occurred()) {
823 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
824 goto error;
825 PyErr_Clear();
826 }
827 break;
828 }
829
830 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000831 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000832 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000833 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000834 goto error;
835
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000836 /* Append the byte */
837 if (Py_SIZE(self) < self->ob_alloc)
838 Py_SIZE(self)++;
839 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
840 goto error;
841 self->ob_bytes[Py_SIZE(self)-1] = value;
842 }
843
844 /* Clean up and return success */
845 Py_DECREF(it);
846 return 0;
847
848 error:
849 /* Error handling when it != NULL */
850 Py_DECREF(it);
851 return -1;
852}
853
854/* Mostly copied from string_repr, but without the
855 "smart quote" functionality. */
856static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000857bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000858{
859 static const char *hexdigits = "0123456789abcdef";
860 const char *quote_prefix = "bytearray(b";
861 const char *quote_postfix = ")";
862 Py_ssize_t length = Py_SIZE(self);
863 /* 14 == strlen(quote_prefix) + 2 + strlen(quote_postfix) */
Mark Dickinson66f575b2010-02-14 12:53:32 +0000864 size_t newsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000865 PyObject *v;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000866 if (length > (PY_SSIZE_T_MAX - 14) / 4) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000867 PyErr_SetString(PyExc_OverflowError,
868 "bytearray object is too large to make repr");
869 return NULL;
870 }
Mark Dickinson66f575b2010-02-14 12:53:32 +0000871 newsize = 14 + 4 * length;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000872 v = PyUnicode_FromUnicode(NULL, newsize);
873 if (v == NULL) {
874 return NULL;
875 }
876 else {
877 register Py_ssize_t i;
878 register Py_UNICODE c;
879 register Py_UNICODE *p;
880 int quote;
881
882 /* Figure out which quote to use; single is preferred */
883 quote = '\'';
884 {
885 char *test, *start;
886 start = PyByteArray_AS_STRING(self);
887 for (test = start; test < start+length; ++test) {
888 if (*test == '"') {
889 quote = '\''; /* back to single */
890 goto decided;
891 }
892 else if (*test == '\'')
893 quote = '"';
894 }
895 decided:
896 ;
897 }
898
899 p = PyUnicode_AS_UNICODE(v);
900 while (*quote_prefix)
901 *p++ = *quote_prefix++;
902 *p++ = quote;
903
904 for (i = 0; i < length; i++) {
905 /* There's at least enough room for a hex escape
906 and a closing quote. */
907 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5);
908 c = self->ob_bytes[i];
909 if (c == '\'' || c == '\\')
910 *p++ = '\\', *p++ = c;
911 else if (c == '\t')
912 *p++ = '\\', *p++ = 't';
913 else if (c == '\n')
914 *p++ = '\\', *p++ = 'n';
915 else if (c == '\r')
916 *p++ = '\\', *p++ = 'r';
917 else if (c == 0)
918 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
919 else if (c < ' ' || c >= 0x7f) {
920 *p++ = '\\';
921 *p++ = 'x';
922 *p++ = hexdigits[(c & 0xf0) >> 4];
923 *p++ = hexdigits[c & 0xf];
924 }
925 else
926 *p++ = c;
927 }
928 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1);
929 *p++ = quote;
930 while (*quote_postfix) {
931 *p++ = *quote_postfix++;
932 }
933 *p = '\0';
934 if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) {
935 Py_DECREF(v);
936 return NULL;
937 }
938 return v;
939 }
940}
941
942static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000943bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000944{
Alexander Belopolskyf0f45142010-08-11 17:31:17 +0000945 if (Py_BytesWarningFlag) {
946 if (PyErr_WarnEx(PyExc_BytesWarning,
947 "str() on a bytearray instance", 1))
948 return NULL;
949 }
950 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000951}
952
953static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000954bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000955{
956 Py_ssize_t self_size, other_size;
957 Py_buffer self_bytes, other_bytes;
958 PyObject *res;
959 Py_ssize_t minsize;
960 int cmp;
961
962 /* Bytes can be compared to anything that supports the (binary)
963 buffer API. Except that a comparison with Unicode is always an
964 error, even if the comparison is for equality. */
965 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
966 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
Barry Warsaw9e9dcd62008-10-17 01:50:37 +0000967 if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000968 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +0000969 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000970 return NULL;
971 }
972
973 Py_INCREF(Py_NotImplemented);
974 return Py_NotImplemented;
975 }
976
977 self_size = _getbuffer(self, &self_bytes);
978 if (self_size < 0) {
979 PyErr_Clear();
980 Py_INCREF(Py_NotImplemented);
981 return Py_NotImplemented;
982 }
983
984 other_size = _getbuffer(other, &other_bytes);
985 if (other_size < 0) {
986 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +0000987 PyBuffer_Release(&self_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000988 Py_INCREF(Py_NotImplemented);
989 return Py_NotImplemented;
990 }
991
992 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
993 /* Shortcut: if the lengths differ, the objects differ */
994 cmp = (op == Py_NE);
995 }
996 else {
997 minsize = self_size;
998 if (other_size < minsize)
999 minsize = other_size;
1000
1001 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
1002 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
1003
1004 if (cmp == 0) {
1005 if (self_size < other_size)
1006 cmp = -1;
1007 else if (self_size > other_size)
1008 cmp = 1;
1009 }
1010
1011 switch (op) {
1012 case Py_LT: cmp = cmp < 0; break;
1013 case Py_LE: cmp = cmp <= 0; break;
1014 case Py_EQ: cmp = cmp == 0; break;
1015 case Py_NE: cmp = cmp != 0; break;
1016 case Py_GT: cmp = cmp > 0; break;
1017 case Py_GE: cmp = cmp >= 0; break;
1018 }
1019 }
1020
1021 res = cmp ? Py_True : Py_False;
Martin v. Löwis423be952008-08-13 15:53:07 +00001022 PyBuffer_Release(&self_bytes);
1023 PyBuffer_Release(&other_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001024 Py_INCREF(res);
1025 return res;
1026}
1027
1028static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001029bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001030{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001031 if (self->ob_exports > 0) {
1032 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001033 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001034 PyErr_Print();
1035 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001036 if (self->ob_bytes != 0) {
1037 PyMem_Free(self->ob_bytes);
1038 }
1039 Py_TYPE(self)->tp_free((PyObject *)self);
1040}
1041
1042
1043/* -------------------------------------------------------------------- */
1044/* Methods */
1045
1046#define STRINGLIB_CHAR char
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001047#define STRINGLIB_LEN PyByteArray_GET_SIZE
1048#define STRINGLIB_STR PyByteArray_AS_STRING
1049#define STRINGLIB_NEW PyByteArray_FromStringAndSize
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001050#define STRINGLIB_ISSPACE Py_ISSPACE
1051#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001052#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1053#define STRINGLIB_MUTABLE 1
1054
1055#include "stringlib/fastsearch.h"
1056#include "stringlib/count.h"
1057#include "stringlib/find.h"
1058#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001059#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001060#include "stringlib/ctype.h"
1061#include "stringlib/transmogrify.h"
1062
1063
1064/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1065were copied from the old char* style string object. */
1066
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001067/* helper macro to fixup start/end slice values */
1068#define ADJUST_INDICES(start, end, len) \
1069 if (end > len) \
1070 end = len; \
1071 else if (end < 0) { \
1072 end += len; \
1073 if (end < 0) \
1074 end = 0; \
1075 } \
1076 if (start < 0) { \
1077 start += len; \
1078 if (start < 0) \
1079 start = 0; \
1080 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001081
1082Py_LOCAL_INLINE(Py_ssize_t)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001083bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001084{
1085 PyObject *subobj;
1086 Py_buffer subbuf;
1087 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1088 Py_ssize_t res;
1089
Jesus Ceaac451502011-04-20 17:09:23 +02001090 if (!stringlib_parse_args_finds("find/rfind/index/rindex",
1091 args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001092 return -2;
1093 if (_getbuffer(subobj, &subbuf) < 0)
1094 return -2;
1095 if (dir > 0)
1096 res = stringlib_find_slice(
1097 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1098 subbuf.buf, subbuf.len, start, end);
1099 else
1100 res = stringlib_rfind_slice(
1101 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1102 subbuf.buf, subbuf.len, start, end);
Martin v. Löwis423be952008-08-13 15:53:07 +00001103 PyBuffer_Release(&subbuf);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001104 return res;
1105}
1106
1107PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001108"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001109\n\
1110Return the lowest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001111such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001112arguments start and end are interpreted as in slice notation.\n\
1113\n\
1114Return -1 on failure.");
1115
1116static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001117bytearray_find(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001118{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001119 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001120 if (result == -2)
1121 return NULL;
1122 return PyLong_FromSsize_t(result);
1123}
1124
1125PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001126"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001127\n\
1128Return the number of non-overlapping occurrences of subsection sub in\n\
1129bytes B[start:end]. Optional arguments start and end are interpreted\n\
1130as in slice notation.");
1131
1132static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001133bytearray_count(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001134{
1135 PyObject *sub_obj;
1136 const char *str = PyByteArray_AS_STRING(self);
1137 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
1138 Py_buffer vsub;
1139 PyObject *count_obj;
1140
Jesus Ceaac451502011-04-20 17:09:23 +02001141 if (!stringlib_parse_args_finds("count", args, &sub_obj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001142 return NULL;
1143
1144 if (_getbuffer(sub_obj, &vsub) < 0)
1145 return NULL;
1146
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001147 ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001148
1149 count_obj = PyLong_FromSsize_t(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001150 stringlib_count(str + start, end - start, vsub.buf, vsub.len, PY_SSIZE_T_MAX)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001151 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001152 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001153 return count_obj;
1154}
1155
1156
1157PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001158"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001159\n\
1160Like B.find() but raise ValueError when the subsection is not found.");
1161
1162static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001163bytearray_index(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001164{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001165 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001166 if (result == -2)
1167 return NULL;
1168 if (result == -1) {
1169 PyErr_SetString(PyExc_ValueError,
1170 "subsection not found");
1171 return NULL;
1172 }
1173 return PyLong_FromSsize_t(result);
1174}
1175
1176
1177PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001178"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001179\n\
1180Return the highest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001181such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001182arguments start and end are interpreted as in slice notation.\n\
1183\n\
1184Return -1 on failure.");
1185
1186static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001187bytearray_rfind(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001188{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001189 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001190 if (result == -2)
1191 return NULL;
1192 return PyLong_FromSsize_t(result);
1193}
1194
1195
1196PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001197"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001198\n\
1199Like B.rfind() but raise ValueError when the subsection is not found.");
1200
1201static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001202bytearray_rindex(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001203{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001204 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001205 if (result == -2)
1206 return NULL;
1207 if (result == -1) {
1208 PyErr_SetString(PyExc_ValueError,
1209 "subsection not found");
1210 return NULL;
1211 }
1212 return PyLong_FromSsize_t(result);
1213}
1214
1215
1216static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001217bytearray_contains(PyObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001218{
1219 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1220 if (ival == -1 && PyErr_Occurred()) {
1221 Py_buffer varg;
Antoine Pitrou0010d372010-08-15 17:12:55 +00001222 Py_ssize_t pos;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001223 PyErr_Clear();
1224 if (_getbuffer(arg, &varg) < 0)
1225 return -1;
1226 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1227 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001228 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001229 return pos >= 0;
1230 }
1231 if (ival < 0 || ival >= 256) {
1232 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1233 return -1;
1234 }
1235
Antoine Pitrou0010d372010-08-15 17:12:55 +00001236 return memchr(PyByteArray_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001237}
1238
1239
1240/* Matches the end (direction >= 0) or start (direction < 0) of self
1241 * against substr, using the start and end arguments. Returns
1242 * -1 on error, 0 if not found and 1 if found.
1243 */
1244Py_LOCAL(int)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001245_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001246 Py_ssize_t end, int direction)
1247{
1248 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1249 const char* str;
1250 Py_buffer vsubstr;
1251 int rv = 0;
1252
1253 str = PyByteArray_AS_STRING(self);
1254
1255 if (_getbuffer(substr, &vsubstr) < 0)
1256 return -1;
1257
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001258 ADJUST_INDICES(start, end, len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001259
1260 if (direction < 0) {
1261 /* startswith */
1262 if (start+vsubstr.len > len) {
1263 goto done;
1264 }
1265 } else {
1266 /* endswith */
1267 if (end-start < vsubstr.len || start > len) {
1268 goto done;
1269 }
1270
1271 if (end-vsubstr.len > start)
1272 start = end - vsubstr.len;
1273 }
1274 if (end-start >= vsubstr.len)
1275 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1276
1277done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001278 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001279 return rv;
1280}
1281
1282
1283PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001284"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001285\n\
1286Return True if B starts with the specified prefix, False otherwise.\n\
1287With optional start, test B beginning at that position.\n\
1288With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001289prefix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001290
1291static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001292bytearray_startswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001293{
1294 Py_ssize_t start = 0;
1295 Py_ssize_t end = PY_SSIZE_T_MAX;
1296 PyObject *subobj;
1297 int result;
1298
Jesus Ceaac451502011-04-20 17:09:23 +02001299 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001300 return NULL;
1301 if (PyTuple_Check(subobj)) {
1302 Py_ssize_t i;
1303 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001304 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001305 PyTuple_GET_ITEM(subobj, i),
1306 start, end, -1);
1307 if (result == -1)
1308 return NULL;
1309 else if (result) {
1310 Py_RETURN_TRUE;
1311 }
1312 }
1313 Py_RETURN_FALSE;
1314 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001315 result = _bytearray_tailmatch(self, subobj, start, end, -1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001316 if (result == -1) {
1317 if (PyErr_ExceptionMatches(PyExc_TypeError))
1318 PyErr_Format(PyExc_TypeError, "startswith first arg must be bytes "
1319 "or a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001320 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001321 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001322 else
1323 return PyBool_FromLong(result);
1324}
1325
1326PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001327"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001328\n\
1329Return True if B ends with the specified suffix, False otherwise.\n\
1330With optional start, test B beginning at that position.\n\
1331With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001332suffix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001333
1334static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001335bytearray_endswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001336{
1337 Py_ssize_t start = 0;
1338 Py_ssize_t end = PY_SSIZE_T_MAX;
1339 PyObject *subobj;
1340 int result;
1341
Jesus Ceaac451502011-04-20 17:09:23 +02001342 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001343 return NULL;
1344 if (PyTuple_Check(subobj)) {
1345 Py_ssize_t i;
1346 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001347 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001348 PyTuple_GET_ITEM(subobj, i),
1349 start, end, +1);
1350 if (result == -1)
1351 return NULL;
1352 else if (result) {
1353 Py_RETURN_TRUE;
1354 }
1355 }
1356 Py_RETURN_FALSE;
1357 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001358 result = _bytearray_tailmatch(self, subobj, start, end, +1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001359 if (result == -1) {
1360 if (PyErr_ExceptionMatches(PyExc_TypeError))
1361 PyErr_Format(PyExc_TypeError, "endswith first arg must be bytes or "
1362 "a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001363 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001364 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001365 else
1366 return PyBool_FromLong(result);
1367}
1368
1369
1370PyDoc_STRVAR(translate__doc__,
1371"B.translate(table[, deletechars]) -> bytearray\n\
1372\n\
1373Return a copy of B, where all characters occurring in the\n\
1374optional argument deletechars are removed, and the remaining\n\
1375characters have been mapped through the given translation\n\
1376table, which must be a bytes object of length 256.");
1377
1378static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001379bytearray_translate(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001380{
1381 register char *input, *output;
1382 register const char *table;
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001383 register Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001384 PyObject *input_obj = (PyObject*)self;
1385 const char *output_start;
1386 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001387 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001388 int trans_table[256];
Georg Brandlccc47b62008-12-28 11:44:14 +00001389 PyObject *tableobj = NULL, *delobj = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001390 Py_buffer vtable, vdel;
1391
1392 if (!PyArg_UnpackTuple(args, "translate", 1, 2,
1393 &tableobj, &delobj))
1394 return NULL;
1395
Georg Brandlccc47b62008-12-28 11:44:14 +00001396 if (tableobj == Py_None) {
1397 table = NULL;
1398 tableobj = NULL;
1399 } else if (_getbuffer(tableobj, &vtable) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001400 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001401 } else {
1402 if (vtable.len != 256) {
1403 PyErr_SetString(PyExc_ValueError,
1404 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001405 PyBuffer_Release(&vtable);
1406 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001407 }
1408 table = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001409 }
1410
1411 if (delobj != NULL) {
1412 if (_getbuffer(delobj, &vdel) < 0) {
Georg Brandl953152f2009-07-22 12:03:59 +00001413 if (tableobj != NULL)
1414 PyBuffer_Release(&vtable);
1415 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001416 }
1417 }
1418 else {
1419 vdel.buf = NULL;
1420 vdel.len = 0;
1421 }
1422
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001423 inlen = PyByteArray_GET_SIZE(input_obj);
1424 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1425 if (result == NULL)
1426 goto done;
1427 output_start = output = PyByteArray_AsString(result);
1428 input = PyByteArray_AS_STRING(input_obj);
1429
Georg Brandlccc47b62008-12-28 11:44:14 +00001430 if (vdel.len == 0 && table != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001431 /* If no deletions are required, use faster code */
1432 for (i = inlen; --i >= 0; ) {
1433 c = Py_CHARMASK(*input++);
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001434 *output++ = table[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001435 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001436 goto done;
1437 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001438
1439 if (table == NULL) {
1440 for (i = 0; i < 256; i++)
1441 trans_table[i] = Py_CHARMASK(i);
1442 } else {
1443 for (i = 0; i < 256; i++)
1444 trans_table[i] = Py_CHARMASK(table[i]);
1445 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001446
1447 for (i = 0; i < vdel.len; i++)
1448 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1449
1450 for (i = inlen; --i >= 0; ) {
1451 c = Py_CHARMASK(*input++);
1452 if (trans_table[c] != -1)
1453 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1454 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001455 }
1456 /* Fix the size of the resulting string */
1457 if (inlen > 0)
1458 PyByteArray_Resize(result, output - output_start);
1459
1460done:
Georg Brandlccc47b62008-12-28 11:44:14 +00001461 if (tableobj != NULL)
1462 PyBuffer_Release(&vtable);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001463 if (delobj != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001464 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001465 return result;
1466}
1467
1468
Georg Brandlabc38772009-04-12 15:51:51 +00001469static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001470bytearray_maketrans(PyObject *null, PyObject *args)
Georg Brandlabc38772009-04-12 15:51:51 +00001471{
Alexander Belopolskyf0f45142010-08-11 17:31:17 +00001472 return _Py_bytes_maketrans(args);
Georg Brandlabc38772009-04-12 15:51:51 +00001473}
1474
1475
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001476/* find and count characters and substrings */
1477
1478#define findchar(target, target_len, c) \
1479 ((char *)memchr((const void *)(target), c, target_len))
1480
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001481
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001482/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001483Py_LOCAL(PyByteArrayObject *)
1484return_self(PyByteArrayObject *self)
1485{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001486 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001487 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1488 PyByteArray_AS_STRING(self),
1489 PyByteArray_GET_SIZE(self));
1490}
1491
1492Py_LOCAL_INLINE(Py_ssize_t)
1493countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1494{
1495 Py_ssize_t count=0;
1496 const char *start=target;
1497 const char *end=target+target_len;
1498
1499 while ( (start=findchar(start, end-start, c)) != NULL ) {
1500 count++;
1501 if (count >= maxcount)
1502 break;
1503 start += 1;
1504 }
1505 return count;
1506}
1507
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001508
1509/* Algorithms for different cases of string replacement */
1510
1511/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1512Py_LOCAL(PyByteArrayObject *)
1513replace_interleave(PyByteArrayObject *self,
1514 const char *to_s, Py_ssize_t to_len,
1515 Py_ssize_t maxcount)
1516{
1517 char *self_s, *result_s;
1518 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001519 Py_ssize_t count, i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001520 PyByteArrayObject *result;
1521
1522 self_len = PyByteArray_GET_SIZE(self);
1523
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001524 /* 1 at the end plus 1 after every character;
1525 count = min(maxcount, self_len + 1) */
1526 if (maxcount <= self_len)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001527 count = maxcount;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001528 else
1529 /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
1530 count = self_len + 1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001531
1532 /* Check for overflow */
1533 /* result_len = count * to_len + self_len; */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001534 assert(count > 0);
1535 if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001536 PyErr_SetString(PyExc_OverflowError,
1537 "replace string is too long");
1538 return NULL;
1539 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001540 result_len = count * to_len + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001541
1542 if (! (result = (PyByteArrayObject *)
1543 PyByteArray_FromStringAndSize(NULL, result_len)) )
1544 return NULL;
1545
1546 self_s = PyByteArray_AS_STRING(self);
1547 result_s = PyByteArray_AS_STRING(result);
1548
1549 /* TODO: special case single character, which doesn't need memcpy */
1550
1551 /* Lay the first one down (guaranteed this will occur) */
1552 Py_MEMCPY(result_s, to_s, to_len);
1553 result_s += to_len;
1554 count -= 1;
1555
1556 for (i=0; i<count; i++) {
1557 *result_s++ = *self_s++;
1558 Py_MEMCPY(result_s, to_s, to_len);
1559 result_s += to_len;
1560 }
1561
1562 /* Copy the rest of the original string */
1563 Py_MEMCPY(result_s, self_s, self_len-i);
1564
1565 return result;
1566}
1567
1568/* Special case for deleting a single character */
1569/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1570Py_LOCAL(PyByteArrayObject *)
1571replace_delete_single_character(PyByteArrayObject *self,
1572 char from_c, Py_ssize_t maxcount)
1573{
1574 char *self_s, *result_s;
1575 char *start, *next, *end;
1576 Py_ssize_t self_len, result_len;
1577 Py_ssize_t count;
1578 PyByteArrayObject *result;
1579
1580 self_len = PyByteArray_GET_SIZE(self);
1581 self_s = PyByteArray_AS_STRING(self);
1582
1583 count = countchar(self_s, self_len, from_c, maxcount);
1584 if (count == 0) {
1585 return return_self(self);
1586 }
1587
1588 result_len = self_len - count; /* from_len == 1 */
1589 assert(result_len>=0);
1590
1591 if ( (result = (PyByteArrayObject *)
1592 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1593 return NULL;
1594 result_s = PyByteArray_AS_STRING(result);
1595
1596 start = self_s;
1597 end = self_s + self_len;
1598 while (count-- > 0) {
1599 next = findchar(start, end-start, from_c);
1600 if (next == NULL)
1601 break;
1602 Py_MEMCPY(result_s, start, next-start);
1603 result_s += (next-start);
1604 start = next+1;
1605 }
1606 Py_MEMCPY(result_s, start, end-start);
1607
1608 return result;
1609}
1610
1611/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1612
1613Py_LOCAL(PyByteArrayObject *)
1614replace_delete_substring(PyByteArrayObject *self,
1615 const char *from_s, Py_ssize_t from_len,
1616 Py_ssize_t maxcount)
1617{
1618 char *self_s, *result_s;
1619 char *start, *next, *end;
1620 Py_ssize_t self_len, result_len;
1621 Py_ssize_t count, offset;
1622 PyByteArrayObject *result;
1623
1624 self_len = PyByteArray_GET_SIZE(self);
1625 self_s = PyByteArray_AS_STRING(self);
1626
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001627 count = stringlib_count(self_s, self_len,
1628 from_s, from_len,
1629 maxcount);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001630
1631 if (count == 0) {
1632 /* no matches */
1633 return return_self(self);
1634 }
1635
1636 result_len = self_len - (count * from_len);
1637 assert (result_len>=0);
1638
1639 if ( (result = (PyByteArrayObject *)
1640 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1641 return NULL;
1642
1643 result_s = PyByteArray_AS_STRING(result);
1644
1645 start = self_s;
1646 end = self_s + self_len;
1647 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001648 offset = stringlib_find(start, end-start,
1649 from_s, from_len,
1650 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001651 if (offset == -1)
1652 break;
1653 next = start + offset;
1654
1655 Py_MEMCPY(result_s, start, next-start);
1656
1657 result_s += (next-start);
1658 start = next+from_len;
1659 }
1660 Py_MEMCPY(result_s, start, end-start);
1661 return result;
1662}
1663
1664/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1665Py_LOCAL(PyByteArrayObject *)
1666replace_single_character_in_place(PyByteArrayObject *self,
1667 char from_c, char to_c,
1668 Py_ssize_t maxcount)
1669{
Antoine Pitroud1188562010-06-09 16:38:55 +00001670 char *self_s, *result_s, *start, *end, *next;
1671 Py_ssize_t self_len;
1672 PyByteArrayObject *result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001673
Antoine Pitroud1188562010-06-09 16:38:55 +00001674 /* The result string will be the same size */
1675 self_s = PyByteArray_AS_STRING(self);
1676 self_len = PyByteArray_GET_SIZE(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001677
Antoine Pitroud1188562010-06-09 16:38:55 +00001678 next = findchar(self_s, self_len, from_c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001679
Antoine Pitroud1188562010-06-09 16:38:55 +00001680 if (next == NULL) {
1681 /* No matches; return the original bytes */
1682 return return_self(self);
1683 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001684
Antoine Pitroud1188562010-06-09 16:38:55 +00001685 /* Need to make a new bytes */
1686 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1687 if (result == NULL)
1688 return NULL;
1689 result_s = PyByteArray_AS_STRING(result);
1690 Py_MEMCPY(result_s, self_s, self_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001691
Antoine Pitroud1188562010-06-09 16:38:55 +00001692 /* change everything in-place, starting with this one */
1693 start = result_s + (next-self_s);
1694 *start = to_c;
1695 start++;
1696 end = result_s + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001697
Antoine Pitroud1188562010-06-09 16:38:55 +00001698 while (--maxcount > 0) {
1699 next = findchar(start, end-start, from_c);
1700 if (next == NULL)
1701 break;
1702 *next = to_c;
1703 start = next+1;
1704 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001705
Antoine Pitroud1188562010-06-09 16:38:55 +00001706 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001707}
1708
1709/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1710Py_LOCAL(PyByteArrayObject *)
1711replace_substring_in_place(PyByteArrayObject *self,
1712 const char *from_s, Py_ssize_t from_len,
1713 const char *to_s, Py_ssize_t to_len,
1714 Py_ssize_t maxcount)
1715{
1716 char *result_s, *start, *end;
1717 char *self_s;
1718 Py_ssize_t self_len, offset;
1719 PyByteArrayObject *result;
1720
1721 /* The result bytes will be the same size */
1722
1723 self_s = PyByteArray_AS_STRING(self);
1724 self_len = PyByteArray_GET_SIZE(self);
1725
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001726 offset = stringlib_find(self_s, self_len,
1727 from_s, from_len,
1728 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001729 if (offset == -1) {
1730 /* No matches; return the original bytes */
1731 return return_self(self);
1732 }
1733
1734 /* Need to make a new bytes */
1735 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1736 if (result == NULL)
1737 return NULL;
1738 result_s = PyByteArray_AS_STRING(result);
1739 Py_MEMCPY(result_s, self_s, self_len);
1740
1741 /* change everything in-place, starting with this one */
1742 start = result_s + offset;
1743 Py_MEMCPY(start, to_s, from_len);
1744 start += from_len;
1745 end = result_s + self_len;
1746
1747 while ( --maxcount > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001748 offset = stringlib_find(start, end-start,
1749 from_s, from_len,
1750 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001751 if (offset==-1)
1752 break;
1753 Py_MEMCPY(start+offset, to_s, from_len);
1754 start += offset+from_len;
1755 }
1756
1757 return result;
1758}
1759
1760/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
1761Py_LOCAL(PyByteArrayObject *)
1762replace_single_character(PyByteArrayObject *self,
1763 char from_c,
1764 const char *to_s, Py_ssize_t to_len,
1765 Py_ssize_t maxcount)
1766{
1767 char *self_s, *result_s;
1768 char *start, *next, *end;
1769 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001770 Py_ssize_t count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001771 PyByteArrayObject *result;
1772
1773 self_s = PyByteArray_AS_STRING(self);
1774 self_len = PyByteArray_GET_SIZE(self);
1775
1776 count = countchar(self_s, self_len, from_c, maxcount);
1777 if (count == 0) {
1778 /* no matches, return unchanged */
1779 return return_self(self);
1780 }
1781
1782 /* use the difference between current and new, hence the "-1" */
1783 /* result_len = self_len + count * (to_len-1) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001784 assert(count > 0);
1785 if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001786 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1787 return NULL;
1788 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001789 result_len = self_len + count * (to_len - 1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001790
1791 if ( (result = (PyByteArrayObject *)
1792 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1793 return NULL;
1794 result_s = PyByteArray_AS_STRING(result);
1795
1796 start = self_s;
1797 end = self_s + self_len;
1798 while (count-- > 0) {
1799 next = findchar(start, end-start, from_c);
1800 if (next == NULL)
1801 break;
1802
1803 if (next == start) {
1804 /* replace with the 'to' */
1805 Py_MEMCPY(result_s, to_s, to_len);
1806 result_s += to_len;
1807 start += 1;
1808 } else {
1809 /* copy the unchanged old then the 'to' */
1810 Py_MEMCPY(result_s, start, next-start);
1811 result_s += (next-start);
1812 Py_MEMCPY(result_s, to_s, to_len);
1813 result_s += to_len;
1814 start = next+1;
1815 }
1816 }
1817 /* Copy the remainder of the remaining bytes */
1818 Py_MEMCPY(result_s, start, end-start);
1819
1820 return result;
1821}
1822
1823/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
1824Py_LOCAL(PyByteArrayObject *)
1825replace_substring(PyByteArrayObject *self,
1826 const char *from_s, Py_ssize_t from_len,
1827 const char *to_s, Py_ssize_t to_len,
1828 Py_ssize_t maxcount)
1829{
1830 char *self_s, *result_s;
1831 char *start, *next, *end;
1832 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001833 Py_ssize_t count, offset;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001834 PyByteArrayObject *result;
1835
1836 self_s = PyByteArray_AS_STRING(self);
1837 self_len = PyByteArray_GET_SIZE(self);
1838
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001839 count = stringlib_count(self_s, self_len,
1840 from_s, from_len,
1841 maxcount);
1842
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001843 if (count == 0) {
1844 /* no matches, return unchanged */
1845 return return_self(self);
1846 }
1847
1848 /* Check for overflow */
1849 /* result_len = self_len + count * (to_len-from_len) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001850 assert(count > 0);
1851 if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001852 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1853 return NULL;
1854 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001855 result_len = self_len + count * (to_len - from_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001856
1857 if ( (result = (PyByteArrayObject *)
1858 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1859 return NULL;
1860 result_s = PyByteArray_AS_STRING(result);
1861
1862 start = self_s;
1863 end = self_s + self_len;
1864 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001865 offset = stringlib_find(start, end-start,
1866 from_s, from_len,
1867 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001868 if (offset == -1)
1869 break;
1870 next = start+offset;
1871 if (next == start) {
1872 /* replace with the 'to' */
1873 Py_MEMCPY(result_s, to_s, to_len);
1874 result_s += to_len;
1875 start += from_len;
1876 } else {
1877 /* copy the unchanged old then the 'to' */
1878 Py_MEMCPY(result_s, start, next-start);
1879 result_s += (next-start);
1880 Py_MEMCPY(result_s, to_s, to_len);
1881 result_s += to_len;
1882 start = next+from_len;
1883 }
1884 }
1885 /* Copy the remainder of the remaining bytes */
1886 Py_MEMCPY(result_s, start, end-start);
1887
1888 return result;
1889}
1890
1891
1892Py_LOCAL(PyByteArrayObject *)
1893replace(PyByteArrayObject *self,
1894 const char *from_s, Py_ssize_t from_len,
1895 const char *to_s, Py_ssize_t to_len,
1896 Py_ssize_t maxcount)
1897{
1898 if (maxcount < 0) {
1899 maxcount = PY_SSIZE_T_MAX;
1900 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
1901 /* nothing to do; return the original bytes */
1902 return return_self(self);
1903 }
1904
1905 if (maxcount == 0 ||
1906 (from_len == 0 && to_len == 0)) {
1907 /* nothing to do; return the original bytes */
1908 return return_self(self);
1909 }
1910
1911 /* Handle zero-length special cases */
1912
1913 if (from_len == 0) {
1914 /* insert the 'to' bytes everywhere. */
1915 /* >>> "Python".replace("", ".") */
1916 /* '.P.y.t.h.o.n.' */
1917 return replace_interleave(self, to_s, to_len, maxcount);
1918 }
1919
1920 /* Except for "".replace("", "A") == "A" there is no way beyond this */
1921 /* point for an empty self bytes to generate a non-empty bytes */
1922 /* Special case so the remaining code always gets a non-empty bytes */
1923 if (PyByteArray_GET_SIZE(self) == 0) {
1924 return return_self(self);
1925 }
1926
1927 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00001928 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001929 if (from_len == 1) {
1930 return replace_delete_single_character(
1931 self, from_s[0], maxcount);
1932 } else {
1933 return replace_delete_substring(self, from_s, from_len, maxcount);
1934 }
1935 }
1936
1937 /* Handle special case where both bytes have the same length */
1938
1939 if (from_len == to_len) {
1940 if (from_len == 1) {
1941 return replace_single_character_in_place(
1942 self,
1943 from_s[0],
1944 to_s[0],
1945 maxcount);
1946 } else {
1947 return replace_substring_in_place(
1948 self, from_s, from_len, to_s, to_len, maxcount);
1949 }
1950 }
1951
1952 /* Otherwise use the more generic algorithms */
1953 if (from_len == 1) {
1954 return replace_single_character(self, from_s[0],
1955 to_s, to_len, maxcount);
1956 } else {
1957 /* len('from')>=2, len('to')>=1 */
1958 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
1959 }
1960}
1961
1962
1963PyDoc_STRVAR(replace__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001964"B.replace(old, new[, count]) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001965\n\
1966Return a copy of B with all occurrences of subsection\n\
1967old replaced by new. If the optional argument count is\n\
1968given, only the first count occurrences are replaced.");
1969
1970static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001971bytearray_replace(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001972{
1973 Py_ssize_t count = -1;
1974 PyObject *from, *to, *res;
1975 Py_buffer vfrom, vto;
1976
1977 if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
1978 return NULL;
1979
1980 if (_getbuffer(from, &vfrom) < 0)
1981 return NULL;
1982 if (_getbuffer(to, &vto) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +00001983 PyBuffer_Release(&vfrom);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001984 return NULL;
1985 }
1986
1987 res = (PyObject *)replace((PyByteArrayObject *) self,
1988 vfrom.buf, vfrom.len,
1989 vto.buf, vto.len, count);
1990
Martin v. Löwis423be952008-08-13 15:53:07 +00001991 PyBuffer_Release(&vfrom);
1992 PyBuffer_Release(&vto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001993 return res;
1994}
1995
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001996PyDoc_STRVAR(split__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001997"B.split([sep[, maxsplit]]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001998\n\
1999Return a list of the sections in B, using sep as the delimiter.\n\
2000If sep is not given, B is split on ASCII whitespace characters\n\
2001(space, tab, return, newline, formfeed, vertical tab).\n\
2002If maxsplit is given, at most maxsplit splits are done.");
2003
2004static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002005bytearray_split(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002006{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002007 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
2008 Py_ssize_t maxsplit = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002009 const char *s = PyByteArray_AS_STRING(self), *sub;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002010 PyObject *list, *subobj = Py_None;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002011 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002012
2013 if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
2014 return NULL;
2015 if (maxsplit < 0)
2016 maxsplit = PY_SSIZE_T_MAX;
2017
2018 if (subobj == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002019 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002020
2021 if (_getbuffer(subobj, &vsub) < 0)
2022 return NULL;
2023 sub = vsub.buf;
2024 n = vsub.len;
2025
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002026 list = stringlib_split(
2027 (PyObject*) self, s, len, sub, n, maxsplit
2028 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002029 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002030 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002031}
2032
2033PyDoc_STRVAR(partition__doc__,
2034"B.partition(sep) -> (head, sep, tail)\n\
2035\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002036Search for the separator sep in B, and return the part before it,\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002037the separator itself, and the part after it. If the separator is not\n\
2038found, returns B and two empty bytearray objects.");
2039
2040static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002041bytearray_partition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002042{
2043 PyObject *bytesep, *result;
2044
2045 bytesep = PyByteArray_FromObject(sep_obj);
2046 if (! bytesep)
2047 return NULL;
2048
2049 result = stringlib_partition(
2050 (PyObject*) self,
2051 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2052 bytesep,
2053 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2054 );
2055
2056 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002057 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002058}
2059
2060PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +00002061"B.rpartition(sep) -> (head, sep, tail)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002062\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002063Search for the separator sep in B, starting at the end of B,\n\
2064and return the part before it, the separator itself, and the\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002065part after it. If the separator is not found, returns two empty\n\
2066bytearray objects and B.");
2067
2068static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002069bytearray_rpartition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002070{
2071 PyObject *bytesep, *result;
2072
2073 bytesep = PyByteArray_FromObject(sep_obj);
2074 if (! bytesep)
2075 return NULL;
2076
2077 result = stringlib_rpartition(
2078 (PyObject*) self,
2079 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2080 bytesep,
2081 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2082 );
2083
2084 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002085 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002086}
2087
2088PyDoc_STRVAR(rsplit__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002089"B.rsplit(sep[, maxsplit]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002090\n\
2091Return a list of the sections in B, using sep as the delimiter,\n\
2092starting at the end of B and working to the front.\n\
2093If sep is not given, B is split on ASCII whitespace characters\n\
2094(space, tab, return, newline, formfeed, vertical tab).\n\
2095If maxsplit is given, at most maxsplit splits are done.");
2096
2097static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002098bytearray_rsplit(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002099{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002100 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
2101 Py_ssize_t maxsplit = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002102 const char *s = PyByteArray_AS_STRING(self), *sub;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002103 PyObject *list, *subobj = Py_None;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002104 Py_buffer vsub;
2105
2106 if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
2107 return NULL;
2108 if (maxsplit < 0)
2109 maxsplit = PY_SSIZE_T_MAX;
2110
2111 if (subobj == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002112 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002113
2114 if (_getbuffer(subobj, &vsub) < 0)
2115 return NULL;
2116 sub = vsub.buf;
2117 n = vsub.len;
2118
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002119 list = stringlib_rsplit(
2120 (PyObject*) self, s, len, sub, n, maxsplit
2121 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002122 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002123 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002124}
2125
2126PyDoc_STRVAR(reverse__doc__,
2127"B.reverse() -> None\n\
2128\n\
2129Reverse the order of the values in B in place.");
2130static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002131bytearray_reverse(PyByteArrayObject *self, PyObject *unused)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002132{
2133 char swap, *head, *tail;
2134 Py_ssize_t i, j, n = Py_SIZE(self);
2135
2136 j = n / 2;
2137 head = self->ob_bytes;
2138 tail = head + n - 1;
2139 for (i = 0; i < j; i++) {
2140 swap = *head;
2141 *head++ = *tail;
2142 *tail-- = swap;
2143 }
2144
2145 Py_RETURN_NONE;
2146}
2147
2148PyDoc_STRVAR(insert__doc__,
2149"B.insert(index, int) -> None\n\
2150\n\
2151Insert a single item into the bytearray before the given index.");
2152static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002153bytearray_insert(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002154{
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002155 PyObject *value;
2156 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002157 Py_ssize_t where, n = Py_SIZE(self);
2158
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002159 if (!PyArg_ParseTuple(args, "nO:insert", &where, &value))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002160 return NULL;
2161
2162 if (n == PY_SSIZE_T_MAX) {
2163 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002164 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002165 return NULL;
2166 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002167 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002168 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002169 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2170 return NULL;
2171
2172 if (where < 0) {
2173 where += n;
2174 if (where < 0)
2175 where = 0;
2176 }
2177 if (where > n)
2178 where = n;
2179 memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where);
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002180 self->ob_bytes[where] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002181
2182 Py_RETURN_NONE;
2183}
2184
2185PyDoc_STRVAR(append__doc__,
2186"B.append(int) -> None\n\
2187\n\
2188Append a single item to the end of B.");
2189static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002190bytearray_append(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002191{
2192 int value;
2193 Py_ssize_t n = Py_SIZE(self);
2194
2195 if (! _getbytevalue(arg, &value))
2196 return NULL;
2197 if (n == PY_SSIZE_T_MAX) {
2198 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002199 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002200 return NULL;
2201 }
2202 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2203 return NULL;
2204
2205 self->ob_bytes[n] = value;
2206
2207 Py_RETURN_NONE;
2208}
2209
2210PyDoc_STRVAR(extend__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002211"B.extend(iterable_of_ints) -> None\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002212\n\
2213Append all the elements from the iterator or sequence to the\n\
2214end of B.");
2215static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002216bytearray_extend(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002217{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002218 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002219 Py_ssize_t buf_size = 0, len = 0;
2220 int value;
2221 char *buf;
2222
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002223 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002224 if (PyObject_CheckBuffer(arg)) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002225 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), arg) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002226 return NULL;
2227
2228 Py_RETURN_NONE;
2229 }
2230
2231 it = PyObject_GetIter(arg);
2232 if (it == NULL)
2233 return NULL;
2234
Ezio Melotti42da6632011-03-15 05:18:48 +02002235 /* Try to determine the length of the argument. 32 is arbitrary. */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002236 buf_size = _PyObject_LengthHint(arg, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002237 if (buf_size == -1) {
2238 Py_DECREF(it);
2239 return NULL;
2240 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002241
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002242 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002243 if (bytearray_obj == NULL) {
2244 Py_DECREF(it);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002245 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002246 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002247 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002248
2249 while ((item = PyIter_Next(it)) != NULL) {
2250 if (! _getbytevalue(item, &value)) {
2251 Py_DECREF(item);
2252 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002253 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002254 return NULL;
2255 }
2256 buf[len++] = value;
2257 Py_DECREF(item);
2258
2259 if (len >= buf_size) {
2260 buf_size = len + (len >> 1) + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002261 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002262 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002263 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002264 return NULL;
2265 }
2266 /* Recompute the `buf' pointer, since the resizing operation may
2267 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002268 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002269 }
2270 }
2271 Py_DECREF(it);
2272
2273 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002274 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
2275 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002276 return NULL;
2277 }
2278
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002279 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
2280 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002281 return NULL;
Antoine Pitrou58bb82e2012-04-01 16:05:46 +02002282 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002283 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002284
2285 Py_RETURN_NONE;
2286}
2287
2288PyDoc_STRVAR(pop__doc__,
2289"B.pop([index]) -> int\n\
2290\n\
2291Remove and return a single item from B. If no index\n\
Benjamin Petersondcf97b92008-07-02 17:30:14 +00002292argument is given, will pop the last value.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002293static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002294bytearray_pop(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002295{
2296 int value;
2297 Py_ssize_t where = -1, n = Py_SIZE(self);
2298
2299 if (!PyArg_ParseTuple(args, "|n:pop", &where))
2300 return NULL;
2301
2302 if (n == 0) {
Eli Benderskye0c8635d82011-03-04 05:10:57 +00002303 PyErr_SetString(PyExc_IndexError,
2304 "pop from empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002305 return NULL;
2306 }
2307 if (where < 0)
2308 where += Py_SIZE(self);
2309 if (where < 0 || where >= Py_SIZE(self)) {
2310 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2311 return NULL;
2312 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002313 if (!_canresize(self))
2314 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002315
2316 value = self->ob_bytes[where];
2317 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2318 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2319 return NULL;
2320
Mark Dickinson54a3db92009-09-06 10:19:23 +00002321 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002322}
2323
2324PyDoc_STRVAR(remove__doc__,
2325"B.remove(int) -> None\n\
2326\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002327Remove the first occurrence of a value in B.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002328static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002329bytearray_remove(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002330{
2331 int value;
2332 Py_ssize_t where, n = Py_SIZE(self);
2333
2334 if (! _getbytevalue(arg, &value))
2335 return NULL;
2336
2337 for (where = 0; where < n; where++) {
2338 if (self->ob_bytes[where] == value)
2339 break;
2340 }
2341 if (where == n) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002342 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002343 return NULL;
2344 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002345 if (!_canresize(self))
2346 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002347
2348 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2349 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2350 return NULL;
2351
2352 Py_RETURN_NONE;
2353}
2354
2355/* XXX These two helpers could be optimized if argsize == 1 */
2356
2357static Py_ssize_t
2358lstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2359 void *argptr, Py_ssize_t argsize)
2360{
2361 Py_ssize_t i = 0;
2362 while (i < mysize && memchr(argptr, myptr[i], argsize))
2363 i++;
2364 return i;
2365}
2366
2367static Py_ssize_t
2368rstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2369 void *argptr, Py_ssize_t argsize)
2370{
2371 Py_ssize_t i = mysize - 1;
2372 while (i >= 0 && memchr(argptr, myptr[i], argsize))
2373 i--;
2374 return i + 1;
2375}
2376
2377PyDoc_STRVAR(strip__doc__,
2378"B.strip([bytes]) -> bytearray\n\
2379\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002380Strip leading and trailing bytes contained in the argument\n\
2381and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002382If the argument is omitted, strip ASCII whitespace.");
2383static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002384bytearray_strip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002385{
2386 Py_ssize_t left, right, mysize, argsize;
2387 void *myptr, *argptr;
2388 PyObject *arg = Py_None;
2389 Py_buffer varg;
2390 if (!PyArg_ParseTuple(args, "|O:strip", &arg))
2391 return NULL;
2392 if (arg == Py_None) {
2393 argptr = "\t\n\r\f\v ";
2394 argsize = 6;
2395 }
2396 else {
2397 if (_getbuffer(arg, &varg) < 0)
2398 return NULL;
2399 argptr = varg.buf;
2400 argsize = varg.len;
2401 }
2402 myptr = self->ob_bytes;
2403 mysize = Py_SIZE(self);
2404 left = lstrip_helper(myptr, mysize, argptr, argsize);
2405 if (left == mysize)
2406 right = left;
2407 else
2408 right = rstrip_helper(myptr, mysize, argptr, argsize);
2409 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002410 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002411 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2412}
2413
2414PyDoc_STRVAR(lstrip__doc__,
2415"B.lstrip([bytes]) -> bytearray\n\
2416\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002417Strip leading bytes contained in the argument\n\
2418and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002419If the argument is omitted, strip leading ASCII whitespace.");
2420static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002421bytearray_lstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002422{
2423 Py_ssize_t left, right, mysize, argsize;
2424 void *myptr, *argptr;
2425 PyObject *arg = Py_None;
2426 Py_buffer varg;
2427 if (!PyArg_ParseTuple(args, "|O:lstrip", &arg))
2428 return NULL;
2429 if (arg == Py_None) {
2430 argptr = "\t\n\r\f\v ";
2431 argsize = 6;
2432 }
2433 else {
2434 if (_getbuffer(arg, &varg) < 0)
2435 return NULL;
2436 argptr = varg.buf;
2437 argsize = varg.len;
2438 }
2439 myptr = self->ob_bytes;
2440 mysize = Py_SIZE(self);
2441 left = lstrip_helper(myptr, mysize, argptr, argsize);
2442 right = mysize;
2443 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002444 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002445 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2446}
2447
2448PyDoc_STRVAR(rstrip__doc__,
2449"B.rstrip([bytes]) -> bytearray\n\
2450\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002451Strip trailing bytes contained in the argument\n\
2452and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002453If the argument is omitted, strip trailing ASCII whitespace.");
2454static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002455bytearray_rstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002456{
2457 Py_ssize_t left, right, mysize, argsize;
2458 void *myptr, *argptr;
2459 PyObject *arg = Py_None;
2460 Py_buffer varg;
2461 if (!PyArg_ParseTuple(args, "|O:rstrip", &arg))
2462 return NULL;
2463 if (arg == Py_None) {
2464 argptr = "\t\n\r\f\v ";
2465 argsize = 6;
2466 }
2467 else {
2468 if (_getbuffer(arg, &varg) < 0)
2469 return NULL;
2470 argptr = varg.buf;
2471 argsize = varg.len;
2472 }
2473 myptr = self->ob_bytes;
2474 mysize = Py_SIZE(self);
2475 left = 0;
2476 right = rstrip_helper(myptr, mysize, argptr, argsize);
2477 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002478 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002479 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2480}
2481
2482PyDoc_STRVAR(decode_doc,
Victor Stinnerc911bbf2010-11-07 19:04:46 +00002483"B.decode(encoding='utf-8', errors='strict') -> str\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002484\n\
Victor Stinnere14e2122010-11-07 18:41:46 +00002485Decode B using the codec registered for encoding. Default encoding\n\
2486is 'utf-8'. errors may be given to set a different error\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002487handling scheme. Default is 'strict' meaning that encoding errors raise\n\
2488a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
2489as well as any other name registered with codecs.register_error that is\n\
2490able to handle UnicodeDecodeErrors.");
2491
2492static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00002493bytearray_decode(PyObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002494{
2495 const char *encoding = NULL;
2496 const char *errors = NULL;
Benjamin Peterson308d6372009-09-18 21:42:35 +00002497 static char *kwlist[] = {"encoding", "errors", 0};
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002498
Benjamin Peterson308d6372009-09-18 21:42:35 +00002499 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode", kwlist, &encoding, &errors))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002500 return NULL;
2501 if (encoding == NULL)
2502 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002503 return PyUnicode_FromEncodedObject(self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002504}
2505
2506PyDoc_STRVAR(alloc_doc,
2507"B.__alloc__() -> int\n\
2508\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002509Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002510
2511static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002512bytearray_alloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002513{
2514 return PyLong_FromSsize_t(self->ob_alloc);
2515}
2516
2517PyDoc_STRVAR(join_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002518"B.join(iterable_of_bytes) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002519\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002520Concatenate any number of bytes/bytearray objects, with B\n\
2521in between each pair, and return the result as a new bytearray.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002522
2523static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002524bytearray_join(PyByteArrayObject *self, PyObject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002525{
2526 PyObject *seq;
2527 Py_ssize_t mysize = Py_SIZE(self);
2528 Py_ssize_t i;
2529 Py_ssize_t n;
2530 PyObject **items;
2531 Py_ssize_t totalsize = 0;
2532 PyObject *result;
2533 char *dest;
2534
2535 seq = PySequence_Fast(it, "can only join an iterable");
2536 if (seq == NULL)
2537 return NULL;
2538 n = PySequence_Fast_GET_SIZE(seq);
2539 items = PySequence_Fast_ITEMS(seq);
2540
2541 /* Compute the total size, and check that they are all bytes */
2542 /* XXX Shouldn't we use _getbuffer() on these items instead? */
2543 for (i = 0; i < n; i++) {
2544 PyObject *obj = items[i];
2545 if (!PyByteArray_Check(obj) && !PyBytes_Check(obj)) {
2546 PyErr_Format(PyExc_TypeError,
2547 "can only join an iterable of bytes "
2548 "(item %ld has type '%.100s')",
2549 /* XXX %ld isn't right on Win64 */
2550 (long)i, Py_TYPE(obj)->tp_name);
2551 goto error;
2552 }
2553 if (i > 0)
2554 totalsize += mysize;
2555 totalsize += Py_SIZE(obj);
2556 if (totalsize < 0) {
2557 PyErr_NoMemory();
2558 goto error;
2559 }
2560 }
2561
2562 /* Allocate the result, and copy the bytes */
2563 result = PyByteArray_FromStringAndSize(NULL, totalsize);
2564 if (result == NULL)
2565 goto error;
2566 dest = PyByteArray_AS_STRING(result);
2567 for (i = 0; i < n; i++) {
2568 PyObject *obj = items[i];
2569 Py_ssize_t size = Py_SIZE(obj);
2570 char *buf;
2571 if (PyByteArray_Check(obj))
2572 buf = PyByteArray_AS_STRING(obj);
2573 else
2574 buf = PyBytes_AS_STRING(obj);
2575 if (i) {
2576 memcpy(dest, self->ob_bytes, mysize);
2577 dest += mysize;
2578 }
2579 memcpy(dest, buf, size);
2580 dest += size;
2581 }
2582
2583 /* Done */
2584 Py_DECREF(seq);
2585 return result;
2586
2587 /* Error handling */
2588 error:
2589 Py_DECREF(seq);
2590 return NULL;
2591}
2592
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002593PyDoc_STRVAR(splitlines__doc__,
2594"B.splitlines([keepends]) -> list of lines\n\
2595\n\
2596Return a list of the lines in B, breaking at line boundaries.\n\
2597Line breaks are not included in the resulting list unless keepends\n\
2598is given and true.");
2599
2600static PyObject*
2601bytearray_splitlines(PyObject *self, PyObject *args)
2602{
2603 int keepends = 0;
2604
2605 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
2606 return NULL;
2607
2608 return stringlib_splitlines(
2609 (PyObject*) self, PyByteArray_AS_STRING(self),
2610 PyByteArray_GET_SIZE(self), keepends
2611 );
2612}
2613
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002614PyDoc_STRVAR(fromhex_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002615"bytearray.fromhex(string) -> bytearray (static method)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002616\n\
2617Create a bytearray object from a string of hexadecimal numbers.\n\
2618Spaces between two numbers are accepted.\n\
2619Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef').");
2620
2621static int
2622hex_digit_to_int(Py_UNICODE c)
2623{
2624 if (c >= 128)
2625 return -1;
Eric Smith6dc46f52009-04-27 20:39:49 +00002626 if (Py_ISDIGIT(c))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002627 return c - '0';
2628 else {
Eric Smith6dc46f52009-04-27 20:39:49 +00002629 if (Py_ISUPPER(c))
2630 c = Py_TOLOWER(c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002631 if (c >= 'a' && c <= 'f')
2632 return c - 'a' + 10;
2633 }
2634 return -1;
2635}
2636
2637static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002638bytearray_fromhex(PyObject *cls, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002639{
2640 PyObject *newbytes, *hexobj;
2641 char *buf;
2642 Py_UNICODE *hex;
2643 Py_ssize_t hexlen, byteslen, i, j;
2644 int top, bot;
2645
2646 if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj))
2647 return NULL;
2648 assert(PyUnicode_Check(hexobj));
2649 hexlen = PyUnicode_GET_SIZE(hexobj);
2650 hex = PyUnicode_AS_UNICODE(hexobj);
2651 byteslen = hexlen/2; /* This overestimates if there are spaces */
2652 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
2653 if (!newbytes)
2654 return NULL;
2655 buf = PyByteArray_AS_STRING(newbytes);
2656 for (i = j = 0; i < hexlen; i += 2) {
2657 /* skip over spaces in the input */
2658 while (hex[i] == ' ')
2659 i++;
2660 if (i >= hexlen)
2661 break;
2662 top = hex_digit_to_int(hex[i]);
2663 bot = hex_digit_to_int(hex[i+1]);
2664 if (top == -1 || bot == -1) {
2665 PyErr_Format(PyExc_ValueError,
2666 "non-hexadecimal number found in "
2667 "fromhex() arg at position %zd", i);
2668 goto error;
2669 }
2670 buf[j++] = (top << 4) + bot;
2671 }
2672 if (PyByteArray_Resize(newbytes, j) < 0)
2673 goto error;
2674 return newbytes;
2675
2676 error:
2677 Py_DECREF(newbytes);
2678 return NULL;
2679}
2680
2681PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2682
2683static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002684bytearray_reduce(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002685{
2686 PyObject *latin1, *dict;
2687 if (self->ob_bytes)
2688 latin1 = PyUnicode_DecodeLatin1(self->ob_bytes,
2689 Py_SIZE(self), NULL);
2690 else
2691 latin1 = PyUnicode_FromString("");
2692
2693 dict = PyObject_GetAttrString((PyObject *)self, "__dict__");
2694 if (dict == NULL) {
2695 PyErr_Clear();
2696 dict = Py_None;
2697 Py_INCREF(dict);
2698 }
2699
2700 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
2701}
2702
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002703PyDoc_STRVAR(sizeof_doc,
2704"B.__sizeof__() -> int\n\
2705 \n\
2706Returns the size of B in memory, in bytes");
2707static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002708bytearray_sizeof(PyByteArrayObject *self)
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002709{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002710 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002711
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002712 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
2713 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002714}
2715
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002716static PySequenceMethods bytearray_as_sequence = {
2717 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002718 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002719 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
2720 (ssizeargfunc)bytearray_getitem, /* sq_item */
2721 0, /* sq_slice */
2722 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
2723 0, /* sq_ass_slice */
2724 (objobjproc)bytearray_contains, /* sq_contains */
2725 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
2726 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002727};
2728
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002729static PyMappingMethods bytearray_as_mapping = {
2730 (lenfunc)bytearray_length,
2731 (binaryfunc)bytearray_subscript,
2732 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002733};
2734
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002735static PyBufferProcs bytearray_as_buffer = {
2736 (getbufferproc)bytearray_getbuffer,
2737 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002738};
2739
2740static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002741bytearray_methods[] = {
2742 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
2743 {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, reduce_doc},
2744 {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, sizeof_doc},
2745 {"append", (PyCFunction)bytearray_append, METH_O, append__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002746 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
2747 _Py_capitalize__doc__},
2748 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002749 {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
Benjamin Peterson308d6372009-09-18 21:42:35 +00002750 {"decode", (PyCFunction)bytearray_decode, METH_VARARGS | METH_KEYWORDS, decode_doc},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002751 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002752 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS,
2753 expandtabs__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002754 {"extend", (PyCFunction)bytearray_extend, METH_O, extend__doc__},
2755 {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
2756 {"fromhex", (PyCFunction)bytearray_fromhex, METH_VARARGS|METH_CLASS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002757 fromhex_doc},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002758 {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
2759 {"insert", (PyCFunction)bytearray_insert, METH_VARARGS, insert__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002760 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
2761 _Py_isalnum__doc__},
2762 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
2763 _Py_isalpha__doc__},
2764 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
2765 _Py_isdigit__doc__},
2766 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
2767 _Py_islower__doc__},
2768 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
2769 _Py_isspace__doc__},
2770 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
2771 _Py_istitle__doc__},
2772 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
2773 _Py_isupper__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002774 {"join", (PyCFunction)bytearray_join, METH_O, join_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002775 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
2776 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002777 {"lstrip", (PyCFunction)bytearray_lstrip, METH_VARARGS, lstrip__doc__},
2778 {"maketrans", (PyCFunction)bytearray_maketrans, METH_VARARGS|METH_STATIC,
Georg Brandlabc38772009-04-12 15:51:51 +00002779 _Py_maketrans__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002780 {"partition", (PyCFunction)bytearray_partition, METH_O, partition__doc__},
2781 {"pop", (PyCFunction)bytearray_pop, METH_VARARGS, pop__doc__},
2782 {"remove", (PyCFunction)bytearray_remove, METH_O, remove__doc__},
2783 {"replace", (PyCFunction)bytearray_replace, METH_VARARGS, replace__doc__},
2784 {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, reverse__doc__},
2785 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
2786 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002787 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002788 {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, rpartition__doc__},
2789 {"rsplit", (PyCFunction)bytearray_rsplit, METH_VARARGS, rsplit__doc__},
2790 {"rstrip", (PyCFunction)bytearray_rstrip, METH_VARARGS, rstrip__doc__},
2791 {"split", (PyCFunction)bytearray_split, METH_VARARGS, split__doc__},
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002792 {"splitlines", (PyCFunction)bytearray_splitlines, METH_VARARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002793 splitlines__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002794 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002795 startswith__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002796 {"strip", (PyCFunction)bytearray_strip, METH_VARARGS, strip__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002797 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
2798 _Py_swapcase__doc__},
2799 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002800 {"translate", (PyCFunction)bytearray_translate, METH_VARARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002801 translate__doc__},
2802 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
2803 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
2804 {NULL}
2805};
2806
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002807PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002808"bytearray(iterable_of_ints) -> bytearray\n\
2809bytearray(string, encoding[, errors]) -> bytearray\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01002810bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
2811bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
2812bytearray() -> empty bytes array\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002813\n\
2814Construct an mutable bytearray object from:\n\
2815 - an iterable yielding integers in range(256)\n\
2816 - a text string encoded using the specified encoding\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01002817 - a bytes or a buffer object\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002818 - any object implementing the buffer API.\n\
Victor Stinnerbb2e9c42011-12-17 23:18:07 +01002819 - an integer");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002820
2821
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002822static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002823
2824PyTypeObject PyByteArray_Type = {
2825 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2826 "bytearray",
2827 sizeof(PyByteArrayObject),
2828 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002829 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002830 0, /* tp_print */
2831 0, /* tp_getattr */
2832 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002833 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002834 (reprfunc)bytearray_repr, /* tp_repr */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002835 0, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002836 &bytearray_as_sequence, /* tp_as_sequence */
2837 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002838 0, /* tp_hash */
2839 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002840 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002841 PyObject_GenericGetAttr, /* tp_getattro */
2842 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002843 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002844 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002845 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002846 0, /* tp_traverse */
2847 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002848 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002849 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002850 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002851 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002852 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002853 0, /* tp_members */
2854 0, /* tp_getset */
2855 0, /* tp_base */
2856 0, /* tp_dict */
2857 0, /* tp_descr_get */
2858 0, /* tp_descr_set */
2859 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002860 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002861 PyType_GenericAlloc, /* tp_alloc */
2862 PyType_GenericNew, /* tp_new */
2863 PyObject_Del, /* tp_free */
2864};
2865
2866/*********************** Bytes Iterator ****************************/
2867
2868typedef struct {
2869 PyObject_HEAD
2870 Py_ssize_t it_index;
2871 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
2872} bytesiterobject;
2873
2874static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002875bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002876{
2877 _PyObject_GC_UNTRACK(it);
2878 Py_XDECREF(it->it_seq);
2879 PyObject_GC_Del(it);
2880}
2881
2882static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002883bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002884{
2885 Py_VISIT(it->it_seq);
2886 return 0;
2887}
2888
2889static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002890bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002891{
2892 PyByteArrayObject *seq;
2893 PyObject *item;
2894
2895 assert(it != NULL);
2896 seq = it->it_seq;
2897 if (seq == NULL)
2898 return NULL;
2899 assert(PyByteArray_Check(seq));
2900
2901 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
2902 item = PyLong_FromLong(
2903 (unsigned char)seq->ob_bytes[it->it_index]);
2904 if (item != NULL)
2905 ++it->it_index;
2906 return item;
2907 }
2908
2909 Py_DECREF(seq);
2910 it->it_seq = NULL;
2911 return NULL;
2912}
2913
2914static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002915bytesarrayiter_length_hint(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002916{
2917 Py_ssize_t len = 0;
2918 if (it->it_seq)
2919 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
2920 return PyLong_FromSsize_t(len);
2921}
2922
2923PyDoc_STRVAR(length_hint_doc,
2924 "Private method returning an estimate of len(list(it)).");
2925
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002926static PyMethodDef bytearrayiter_methods[] = {
2927 {"__length_hint__", (PyCFunction)bytesarrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002928 length_hint_doc},
2929 {NULL, NULL} /* sentinel */
2930};
2931
2932PyTypeObject PyByteArrayIter_Type = {
2933 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2934 "bytearray_iterator", /* tp_name */
2935 sizeof(bytesiterobject), /* tp_basicsize */
2936 0, /* tp_itemsize */
2937 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002938 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002939 0, /* tp_print */
2940 0, /* tp_getattr */
2941 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002942 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002943 0, /* tp_repr */
2944 0, /* tp_as_number */
2945 0, /* tp_as_sequence */
2946 0, /* tp_as_mapping */
2947 0, /* tp_hash */
2948 0, /* tp_call */
2949 0, /* tp_str */
2950 PyObject_GenericGetAttr, /* tp_getattro */
2951 0, /* tp_setattro */
2952 0, /* tp_as_buffer */
2953 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2954 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002955 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002956 0, /* tp_clear */
2957 0, /* tp_richcompare */
2958 0, /* tp_weaklistoffset */
2959 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002960 (iternextfunc)bytearrayiter_next, /* tp_iternext */
2961 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002962 0,
2963};
2964
2965static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002966bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002967{
2968 bytesiterobject *it;
2969
2970 if (!PyByteArray_Check(seq)) {
2971 PyErr_BadInternalCall();
2972 return NULL;
2973 }
2974 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
2975 if (it == NULL)
2976 return NULL;
2977 it->it_index = 0;
2978 Py_INCREF(seq);
2979 it->it_seq = (PyByteArrayObject *)seq;
2980 _PyObject_GC_TRACK(it);
2981 return (PyObject *)it;
2982}