blob: fba575879fd6781c7b792a41d5aaf0e9621ba7db [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)) {
Georg Brandlf3fa5682010-12-04 17:09:30 +0000592 /* Make a copy and call this function recursively */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000593 int err;
594 values = PyByteArray_FromObject(values);
595 if (values == NULL)
596 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000597 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000598 Py_DECREF(values);
599 return err;
600 }
601 else {
602 assert(PyByteArray_Check(values));
603 bytes = ((PyByteArrayObject *)values)->ob_bytes;
604 needed = Py_SIZE(values);
605 }
606 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
607 if ((step < 0 && start < stop) ||
608 (step > 0 && start > stop))
609 stop = start;
610 if (step == 1) {
611 if (slicelen != needed) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000612 if (!_canresize(self))
613 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000614 if (slicelen > needed) {
615 /*
616 0 start stop old_size
617 | |<---slicelen--->|<-----tomove------>|
618 | |<-needed->|<-----tomove------>|
619 0 lo new_hi new_size
620 */
621 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
622 Py_SIZE(self) - stop);
623 }
624 if (PyByteArray_Resize((PyObject *)self,
625 Py_SIZE(self) + needed - slicelen) < 0)
626 return -1;
627 if (slicelen < needed) {
628 /*
629 0 lo hi old_size
630 | |<-avail->|<-----tomove------>|
631 | |<----needed---->|<-----tomove------>|
632 0 lo new_hi new_size
633 */
634 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
635 Py_SIZE(self) - start - needed);
636 }
637 }
638
639 if (needed > 0)
640 memcpy(self->ob_bytes + start, bytes, needed);
641
642 return 0;
643 }
644 else {
645 if (needed == 0) {
646 /* Delete slice */
Mark Dickinsonbc099642010-01-29 17:27:24 +0000647 size_t cur;
648 Py_ssize_t i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000649
Antoine Pitrou5504e892008-12-06 21:27:53 +0000650 if (!_canresize(self))
651 return -1;
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000652
653 if (slicelen == 0)
654 /* Nothing to do here. */
655 return 0;
656
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000657 if (step < 0) {
658 stop = start + 1;
659 start = stop + step * (slicelen - 1) - 1;
660 step = -step;
661 }
662 for (cur = start, i = 0;
663 i < slicelen; cur += step, i++) {
664 Py_ssize_t lim = step - 1;
665
Mark Dickinson66f575b2010-02-14 12:53:32 +0000666 if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000667 lim = PyByteArray_GET_SIZE(self) - cur - 1;
668
669 memmove(self->ob_bytes + cur - i,
670 self->ob_bytes + cur + 1, lim);
671 }
672 /* Move the tail of the bytes, in one chunk */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000673 cur = start + (size_t)slicelen*step;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000674 if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000675 memmove(self->ob_bytes + cur - slicelen,
676 self->ob_bytes + cur,
677 PyByteArray_GET_SIZE(self) - cur);
678 }
679 if (PyByteArray_Resize((PyObject *)self,
680 PyByteArray_GET_SIZE(self) - slicelen) < 0)
681 return -1;
682
683 return 0;
684 }
685 else {
686 /* Assign slice */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000687 Py_ssize_t i;
688 size_t cur;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000689
690 if (needed != slicelen) {
691 PyErr_Format(PyExc_ValueError,
692 "attempt to assign bytes of size %zd "
693 "to extended slice of size %zd",
694 needed, slicelen);
695 return -1;
696 }
697 for (cur = start, i = 0; i < slicelen; cur += step, i++)
698 self->ob_bytes[cur] = bytes[i];
699 return 0;
700 }
701 }
702}
703
704static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000705bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000706{
707 static char *kwlist[] = {"source", "encoding", "errors", 0};
708 PyObject *arg = NULL;
709 const char *encoding = NULL;
710 const char *errors = NULL;
711 Py_ssize_t count;
712 PyObject *it;
713 PyObject *(*iternext)(PyObject *);
714
715 if (Py_SIZE(self) != 0) {
716 /* Empty previous contents (yes, do this first of all!) */
717 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
718 return -1;
719 }
720
721 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000722 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000723 &arg, &encoding, &errors))
724 return -1;
725
726 /* Make a quick exit if no first argument */
727 if (arg == NULL) {
728 if (encoding != NULL || errors != NULL) {
729 PyErr_SetString(PyExc_TypeError,
730 "encoding or errors without sequence argument");
731 return -1;
732 }
733 return 0;
734 }
735
736 if (PyUnicode_Check(arg)) {
737 /* Encode via the codec registry */
738 PyObject *encoded, *new;
739 if (encoding == NULL) {
740 PyErr_SetString(PyExc_TypeError,
741 "string argument without an encoding");
742 return -1;
743 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000744 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000745 if (encoded == NULL)
746 return -1;
747 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000748 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000749 Py_DECREF(encoded);
750 if (new == NULL)
751 return -1;
752 Py_DECREF(new);
753 return 0;
754 }
755
756 /* If it's not unicode, there can't be encoding or errors */
757 if (encoding != NULL || errors != NULL) {
758 PyErr_SetString(PyExc_TypeError,
759 "encoding or errors without a string argument");
760 return -1;
761 }
762
763 /* Is it an int? */
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000764 count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
765 if (count == -1 && PyErr_Occurred()) {
766 if (PyErr_ExceptionMatches(PyExc_OverflowError))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000767 return -1;
Benjamin Peterson9c0e94f2010-04-16 23:00:53 +0000768 PyErr_Clear();
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000769 }
770 else if (count < 0) {
771 PyErr_SetString(PyExc_ValueError, "negative count");
772 return -1;
773 }
774 else {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000775 if (count > 0) {
776 if (PyByteArray_Resize((PyObject *)self, count))
777 return -1;
778 memset(self->ob_bytes, 0, count);
779 }
780 return 0;
781 }
782
783 /* Use the buffer API */
784 if (PyObject_CheckBuffer(arg)) {
785 Py_ssize_t size;
786 Py_buffer view;
787 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
788 return -1;
789 size = view.len;
790 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
791 if (PyBuffer_ToContiguous(self->ob_bytes, &view, size, 'C') < 0)
792 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000793 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000794 return 0;
795 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000796 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000797 return -1;
798 }
799
800 /* XXX Optimize this if the arguments is a list, tuple */
801
802 /* Get the iterator */
803 it = PyObject_GetIter(arg);
804 if (it == NULL)
805 return -1;
806 iternext = *Py_TYPE(it)->tp_iternext;
807
808 /* Run the iterator to exhaustion */
809 for (;;) {
810 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000811 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000812
813 /* Get the next item */
814 item = iternext(it);
815 if (item == NULL) {
816 if (PyErr_Occurred()) {
817 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
818 goto error;
819 PyErr_Clear();
820 }
821 break;
822 }
823
824 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000825 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000826 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000827 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000828 goto error;
829
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000830 /* Append the byte */
831 if (Py_SIZE(self) < self->ob_alloc)
832 Py_SIZE(self)++;
833 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
834 goto error;
835 self->ob_bytes[Py_SIZE(self)-1] = value;
836 }
837
838 /* Clean up and return success */
839 Py_DECREF(it);
840 return 0;
841
842 error:
843 /* Error handling when it != NULL */
844 Py_DECREF(it);
845 return -1;
846}
847
848/* Mostly copied from string_repr, but without the
849 "smart quote" functionality. */
850static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000851bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000852{
853 static const char *hexdigits = "0123456789abcdef";
854 const char *quote_prefix = "bytearray(b";
855 const char *quote_postfix = ")";
856 Py_ssize_t length = Py_SIZE(self);
857 /* 14 == strlen(quote_prefix) + 2 + strlen(quote_postfix) */
Mark Dickinson66f575b2010-02-14 12:53:32 +0000858 size_t newsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000859 PyObject *v;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000860 if (length > (PY_SSIZE_T_MAX - 14) / 4) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000861 PyErr_SetString(PyExc_OverflowError,
862 "bytearray object is too large to make repr");
863 return NULL;
864 }
Mark Dickinson66f575b2010-02-14 12:53:32 +0000865 newsize = 14 + 4 * length;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000866 v = PyUnicode_FromUnicode(NULL, newsize);
867 if (v == NULL) {
868 return NULL;
869 }
870 else {
871 register Py_ssize_t i;
872 register Py_UNICODE c;
873 register Py_UNICODE *p;
874 int quote;
875
876 /* Figure out which quote to use; single is preferred */
877 quote = '\'';
878 {
879 char *test, *start;
880 start = PyByteArray_AS_STRING(self);
881 for (test = start; test < start+length; ++test) {
882 if (*test == '"') {
883 quote = '\''; /* back to single */
884 goto decided;
885 }
886 else if (*test == '\'')
887 quote = '"';
888 }
889 decided:
890 ;
891 }
892
893 p = PyUnicode_AS_UNICODE(v);
894 while (*quote_prefix)
895 *p++ = *quote_prefix++;
896 *p++ = quote;
897
898 for (i = 0; i < length; i++) {
899 /* There's at least enough room for a hex escape
900 and a closing quote. */
901 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5);
902 c = self->ob_bytes[i];
903 if (c == '\'' || c == '\\')
904 *p++ = '\\', *p++ = c;
905 else if (c == '\t')
906 *p++ = '\\', *p++ = 't';
907 else if (c == '\n')
908 *p++ = '\\', *p++ = 'n';
909 else if (c == '\r')
910 *p++ = '\\', *p++ = 'r';
911 else if (c == 0)
912 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
913 else if (c < ' ' || c >= 0x7f) {
914 *p++ = '\\';
915 *p++ = 'x';
916 *p++ = hexdigits[(c & 0xf0) >> 4];
917 *p++ = hexdigits[c & 0xf];
918 }
919 else
920 *p++ = c;
921 }
922 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1);
923 *p++ = quote;
924 while (*quote_postfix) {
925 *p++ = *quote_postfix++;
926 }
927 *p = '\0';
928 if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) {
929 Py_DECREF(v);
930 return NULL;
931 }
932 return v;
933 }
934}
935
936static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000937bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000938{
Alexander Belopolskyf0f45142010-08-11 17:31:17 +0000939 if (Py_BytesWarningFlag) {
940 if (PyErr_WarnEx(PyExc_BytesWarning,
941 "str() on a bytearray instance", 1))
942 return NULL;
943 }
944 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000945}
946
947static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000948bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000949{
950 Py_ssize_t self_size, other_size;
951 Py_buffer self_bytes, other_bytes;
952 PyObject *res;
953 Py_ssize_t minsize;
954 int cmp;
955
956 /* Bytes can be compared to anything that supports the (binary)
957 buffer API. Except that a comparison with Unicode is always an
958 error, even if the comparison is for equality. */
959 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
960 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
Barry Warsaw9e9dcd62008-10-17 01:50:37 +0000961 if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000962 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +0000963 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000964 return NULL;
965 }
966
967 Py_INCREF(Py_NotImplemented);
968 return Py_NotImplemented;
969 }
970
971 self_size = _getbuffer(self, &self_bytes);
972 if (self_size < 0) {
973 PyErr_Clear();
974 Py_INCREF(Py_NotImplemented);
975 return Py_NotImplemented;
976 }
977
978 other_size = _getbuffer(other, &other_bytes);
979 if (other_size < 0) {
980 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +0000981 PyBuffer_Release(&self_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000982 Py_INCREF(Py_NotImplemented);
983 return Py_NotImplemented;
984 }
985
986 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
987 /* Shortcut: if the lengths differ, the objects differ */
988 cmp = (op == Py_NE);
989 }
990 else {
991 minsize = self_size;
992 if (other_size < minsize)
993 minsize = other_size;
994
995 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
996 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
997
998 if (cmp == 0) {
999 if (self_size < other_size)
1000 cmp = -1;
1001 else if (self_size > other_size)
1002 cmp = 1;
1003 }
1004
1005 switch (op) {
1006 case Py_LT: cmp = cmp < 0; break;
1007 case Py_LE: cmp = cmp <= 0; break;
1008 case Py_EQ: cmp = cmp == 0; break;
1009 case Py_NE: cmp = cmp != 0; break;
1010 case Py_GT: cmp = cmp > 0; break;
1011 case Py_GE: cmp = cmp >= 0; break;
1012 }
1013 }
1014
1015 res = cmp ? Py_True : Py_False;
Martin v. Löwis423be952008-08-13 15:53:07 +00001016 PyBuffer_Release(&self_bytes);
1017 PyBuffer_Release(&other_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001018 Py_INCREF(res);
1019 return res;
1020}
1021
1022static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001023bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001024{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001025 if (self->ob_exports > 0) {
1026 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001027 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001028 PyErr_Print();
1029 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001030 if (self->ob_bytes != 0) {
1031 PyMem_Free(self->ob_bytes);
1032 }
1033 Py_TYPE(self)->tp_free((PyObject *)self);
1034}
1035
1036
1037/* -------------------------------------------------------------------- */
1038/* Methods */
1039
1040#define STRINGLIB_CHAR char
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001041#define STRINGLIB_LEN PyByteArray_GET_SIZE
1042#define STRINGLIB_STR PyByteArray_AS_STRING
1043#define STRINGLIB_NEW PyByteArray_FromStringAndSize
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001044#define STRINGLIB_ISSPACE Py_ISSPACE
1045#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001046#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1047#define STRINGLIB_MUTABLE 1
1048
1049#include "stringlib/fastsearch.h"
1050#include "stringlib/count.h"
1051#include "stringlib/find.h"
1052#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001053#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001054#include "stringlib/ctype.h"
1055#include "stringlib/transmogrify.h"
1056
1057
1058/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1059were copied from the old char* style string object. */
1060
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001061/* helper macro to fixup start/end slice values */
1062#define ADJUST_INDICES(start, end, len) \
1063 if (end > len) \
1064 end = len; \
1065 else if (end < 0) { \
1066 end += len; \
1067 if (end < 0) \
1068 end = 0; \
1069 } \
1070 if (start < 0) { \
1071 start += len; \
1072 if (start < 0) \
1073 start = 0; \
1074 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001075
1076Py_LOCAL_INLINE(Py_ssize_t)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001077bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001078{
1079 PyObject *subobj;
1080 Py_buffer subbuf;
1081 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1082 Py_ssize_t res;
1083
Jesus Ceaac451502011-04-20 17:09:23 +02001084 if (!stringlib_parse_args_finds("find/rfind/index/rindex",
1085 args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001086 return -2;
1087 if (_getbuffer(subobj, &subbuf) < 0)
1088 return -2;
1089 if (dir > 0)
1090 res = stringlib_find_slice(
1091 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1092 subbuf.buf, subbuf.len, start, end);
1093 else
1094 res = stringlib_rfind_slice(
1095 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1096 subbuf.buf, subbuf.len, start, end);
Martin v. Löwis423be952008-08-13 15:53:07 +00001097 PyBuffer_Release(&subbuf);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001098 return res;
1099}
1100
1101PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001102"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001103\n\
1104Return the lowest index in B where subsection sub is found,\n\
1105such that sub is contained within s[start,end]. Optional\n\
1106arguments start and end are interpreted as in slice notation.\n\
1107\n\
1108Return -1 on failure.");
1109
1110static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001111bytearray_find(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001112{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001113 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001114 if (result == -2)
1115 return NULL;
1116 return PyLong_FromSsize_t(result);
1117}
1118
1119PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001120"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001121\n\
1122Return the number of non-overlapping occurrences of subsection sub in\n\
1123bytes B[start:end]. Optional arguments start and end are interpreted\n\
1124as in slice notation.");
1125
1126static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001127bytearray_count(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001128{
1129 PyObject *sub_obj;
1130 const char *str = PyByteArray_AS_STRING(self);
1131 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
1132 Py_buffer vsub;
1133 PyObject *count_obj;
1134
Jesus Ceaac451502011-04-20 17:09:23 +02001135 if (!stringlib_parse_args_finds("count", args, &sub_obj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001136 return NULL;
1137
1138 if (_getbuffer(sub_obj, &vsub) < 0)
1139 return NULL;
1140
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001141 ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001142
1143 count_obj = PyLong_FromSsize_t(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001144 stringlib_count(str + start, end - start, vsub.buf, vsub.len, PY_SSIZE_T_MAX)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001145 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001146 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001147 return count_obj;
1148}
1149
Eli Bendersky4db28d32011-03-03 18:21:02 +00001150PyDoc_STRVAR(clear__doc__,
1151"B.clear() -> None\n\
1152\n\
1153Remove all items from B.");
1154
1155static PyObject *
1156bytearray_clear(PyByteArrayObject *self)
1157{
1158 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
1159 return NULL;
1160 Py_RETURN_NONE;
1161}
1162
1163PyDoc_STRVAR(copy__doc__,
1164"B.copy() -> bytearray\n\
1165\n\
1166Return a copy of B.");
1167
1168static PyObject *
1169bytearray_copy(PyByteArrayObject *self)
1170{
1171 return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
1172 PyByteArray_GET_SIZE(self));
1173}
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001174
1175PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001176"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001177\n\
1178Like B.find() but raise ValueError when the subsection is not found.");
1179
1180static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001181bytearray_index(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001182{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001183 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001184 if (result == -2)
1185 return NULL;
1186 if (result == -1) {
1187 PyErr_SetString(PyExc_ValueError,
1188 "subsection not found");
1189 return NULL;
1190 }
1191 return PyLong_FromSsize_t(result);
1192}
1193
1194
1195PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001196"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001197\n\
1198Return the highest index in B where subsection sub is found,\n\
1199such that sub is contained within s[start,end]. Optional\n\
1200arguments start and end are interpreted as in slice notation.\n\
1201\n\
1202Return -1 on failure.");
1203
1204static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001205bytearray_rfind(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001206{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001207 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001208 if (result == -2)
1209 return NULL;
1210 return PyLong_FromSsize_t(result);
1211}
1212
1213
1214PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001215"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001216\n\
1217Like B.rfind() but raise ValueError when the subsection is not found.");
1218
1219static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001220bytearray_rindex(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001221{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001222 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001223 if (result == -2)
1224 return NULL;
1225 if (result == -1) {
1226 PyErr_SetString(PyExc_ValueError,
1227 "subsection not found");
1228 return NULL;
1229 }
1230 return PyLong_FromSsize_t(result);
1231}
1232
1233
1234static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001235bytearray_contains(PyObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001236{
1237 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1238 if (ival == -1 && PyErr_Occurred()) {
1239 Py_buffer varg;
Antoine Pitrou0010d372010-08-15 17:12:55 +00001240 Py_ssize_t pos;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001241 PyErr_Clear();
1242 if (_getbuffer(arg, &varg) < 0)
1243 return -1;
1244 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1245 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001246 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001247 return pos >= 0;
1248 }
1249 if (ival < 0 || ival >= 256) {
1250 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1251 return -1;
1252 }
1253
Antoine Pitrou0010d372010-08-15 17:12:55 +00001254 return memchr(PyByteArray_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001255}
1256
1257
1258/* Matches the end (direction >= 0) or start (direction < 0) of self
1259 * against substr, using the start and end arguments. Returns
1260 * -1 on error, 0 if not found and 1 if found.
1261 */
1262Py_LOCAL(int)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001263_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001264 Py_ssize_t end, int direction)
1265{
1266 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1267 const char* str;
1268 Py_buffer vsubstr;
1269 int rv = 0;
1270
1271 str = PyByteArray_AS_STRING(self);
1272
1273 if (_getbuffer(substr, &vsubstr) < 0)
1274 return -1;
1275
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001276 ADJUST_INDICES(start, end, len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001277
1278 if (direction < 0) {
1279 /* startswith */
1280 if (start+vsubstr.len > len) {
1281 goto done;
1282 }
1283 } else {
1284 /* endswith */
1285 if (end-start < vsubstr.len || start > len) {
1286 goto done;
1287 }
1288
1289 if (end-vsubstr.len > start)
1290 start = end - vsubstr.len;
1291 }
1292 if (end-start >= vsubstr.len)
1293 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1294
1295done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001296 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001297 return rv;
1298}
1299
1300
1301PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001302"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001303\n\
1304Return True if B starts with the specified prefix, False otherwise.\n\
1305With optional start, test B beginning at that position.\n\
1306With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001307prefix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001308
1309static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001310bytearray_startswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001311{
1312 Py_ssize_t start = 0;
1313 Py_ssize_t end = PY_SSIZE_T_MAX;
1314 PyObject *subobj;
1315 int result;
1316
Jesus Ceaac451502011-04-20 17:09:23 +02001317 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001318 return NULL;
1319 if (PyTuple_Check(subobj)) {
1320 Py_ssize_t i;
1321 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001322 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001323 PyTuple_GET_ITEM(subobj, i),
1324 start, end, -1);
1325 if (result == -1)
1326 return NULL;
1327 else if (result) {
1328 Py_RETURN_TRUE;
1329 }
1330 }
1331 Py_RETURN_FALSE;
1332 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001333 result = _bytearray_tailmatch(self, subobj, start, end, -1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001334 if (result == -1) {
1335 if (PyErr_ExceptionMatches(PyExc_TypeError))
1336 PyErr_Format(PyExc_TypeError, "startswith first arg must be bytes "
1337 "or a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001338 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001339 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001340 else
1341 return PyBool_FromLong(result);
1342}
1343
1344PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001345"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001346\n\
1347Return True if B ends with the specified suffix, False otherwise.\n\
1348With optional start, test B beginning at that position.\n\
1349With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001350suffix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001351
1352static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001353bytearray_endswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001354{
1355 Py_ssize_t start = 0;
1356 Py_ssize_t end = PY_SSIZE_T_MAX;
1357 PyObject *subobj;
1358 int result;
1359
Jesus Ceaac451502011-04-20 17:09:23 +02001360 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001361 return NULL;
1362 if (PyTuple_Check(subobj)) {
1363 Py_ssize_t i;
1364 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001365 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001366 PyTuple_GET_ITEM(subobj, i),
1367 start, end, +1);
1368 if (result == -1)
1369 return NULL;
1370 else if (result) {
1371 Py_RETURN_TRUE;
1372 }
1373 }
1374 Py_RETURN_FALSE;
1375 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001376 result = _bytearray_tailmatch(self, subobj, start, end, +1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001377 if (result == -1) {
1378 if (PyErr_ExceptionMatches(PyExc_TypeError))
1379 PyErr_Format(PyExc_TypeError, "endswith first arg must be bytes or "
1380 "a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001381 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001382 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001383 else
1384 return PyBool_FromLong(result);
1385}
1386
1387
1388PyDoc_STRVAR(translate__doc__,
1389"B.translate(table[, deletechars]) -> bytearray\n\
1390\n\
1391Return a copy of B, where all characters occurring in the\n\
1392optional argument deletechars are removed, and the remaining\n\
1393characters have been mapped through the given translation\n\
1394table, which must be a bytes object of length 256.");
1395
1396static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001397bytearray_translate(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001398{
1399 register char *input, *output;
1400 register const char *table;
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001401 register Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001402 PyObject *input_obj = (PyObject*)self;
1403 const char *output_start;
1404 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001405 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001406 int trans_table[256];
Georg Brandlccc47b62008-12-28 11:44:14 +00001407 PyObject *tableobj = NULL, *delobj = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001408 Py_buffer vtable, vdel;
1409
1410 if (!PyArg_UnpackTuple(args, "translate", 1, 2,
1411 &tableobj, &delobj))
1412 return NULL;
1413
Georg Brandlccc47b62008-12-28 11:44:14 +00001414 if (tableobj == Py_None) {
1415 table = NULL;
1416 tableobj = NULL;
1417 } else if (_getbuffer(tableobj, &vtable) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001418 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001419 } else {
1420 if (vtable.len != 256) {
1421 PyErr_SetString(PyExc_ValueError,
1422 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001423 PyBuffer_Release(&vtable);
1424 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001425 }
1426 table = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001427 }
1428
1429 if (delobj != NULL) {
1430 if (_getbuffer(delobj, &vdel) < 0) {
Georg Brandl953152f2009-07-22 12:03:59 +00001431 if (tableobj != NULL)
1432 PyBuffer_Release(&vtable);
1433 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001434 }
1435 }
1436 else {
1437 vdel.buf = NULL;
1438 vdel.len = 0;
1439 }
1440
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001441 inlen = PyByteArray_GET_SIZE(input_obj);
1442 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1443 if (result == NULL)
1444 goto done;
1445 output_start = output = PyByteArray_AsString(result);
1446 input = PyByteArray_AS_STRING(input_obj);
1447
Georg Brandlccc47b62008-12-28 11:44:14 +00001448 if (vdel.len == 0 && table != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001449 /* If no deletions are required, use faster code */
1450 for (i = inlen; --i >= 0; ) {
1451 c = Py_CHARMASK(*input++);
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001452 *output++ = table[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001453 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001454 goto done;
1455 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001456
1457 if (table == NULL) {
1458 for (i = 0; i < 256; i++)
1459 trans_table[i] = Py_CHARMASK(i);
1460 } else {
1461 for (i = 0; i < 256; i++)
1462 trans_table[i] = Py_CHARMASK(table[i]);
1463 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001464
1465 for (i = 0; i < vdel.len; i++)
1466 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1467
1468 for (i = inlen; --i >= 0; ) {
1469 c = Py_CHARMASK(*input++);
1470 if (trans_table[c] != -1)
1471 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1472 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001473 }
1474 /* Fix the size of the resulting string */
1475 if (inlen > 0)
1476 PyByteArray_Resize(result, output - output_start);
1477
1478done:
Georg Brandlccc47b62008-12-28 11:44:14 +00001479 if (tableobj != NULL)
1480 PyBuffer_Release(&vtable);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001481 if (delobj != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001482 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001483 return result;
1484}
1485
1486
Georg Brandlabc38772009-04-12 15:51:51 +00001487static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001488bytearray_maketrans(PyObject *null, PyObject *args)
Georg Brandlabc38772009-04-12 15:51:51 +00001489{
Alexander Belopolskyf0f45142010-08-11 17:31:17 +00001490 return _Py_bytes_maketrans(args);
Georg Brandlabc38772009-04-12 15:51:51 +00001491}
1492
1493
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001494/* find and count characters and substrings */
1495
1496#define findchar(target, target_len, c) \
1497 ((char *)memchr((const void *)(target), c, target_len))
1498
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001499
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001500/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001501Py_LOCAL(PyByteArrayObject *)
1502return_self(PyByteArrayObject *self)
1503{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001504 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001505 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1506 PyByteArray_AS_STRING(self),
1507 PyByteArray_GET_SIZE(self));
1508}
1509
1510Py_LOCAL_INLINE(Py_ssize_t)
1511countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1512{
1513 Py_ssize_t count=0;
1514 const char *start=target;
1515 const char *end=target+target_len;
1516
1517 while ( (start=findchar(start, end-start, c)) != NULL ) {
1518 count++;
1519 if (count >= maxcount)
1520 break;
1521 start += 1;
1522 }
1523 return count;
1524}
1525
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001526
1527/* Algorithms for different cases of string replacement */
1528
1529/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1530Py_LOCAL(PyByteArrayObject *)
1531replace_interleave(PyByteArrayObject *self,
1532 const char *to_s, Py_ssize_t to_len,
1533 Py_ssize_t maxcount)
1534{
1535 char *self_s, *result_s;
1536 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001537 Py_ssize_t count, i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001538 PyByteArrayObject *result;
1539
1540 self_len = PyByteArray_GET_SIZE(self);
1541
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001542 /* 1 at the end plus 1 after every character;
1543 count = min(maxcount, self_len + 1) */
1544 if (maxcount <= self_len)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001545 count = maxcount;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001546 else
1547 /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
1548 count = self_len + 1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001549
1550 /* Check for overflow */
1551 /* result_len = count * to_len + self_len; */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001552 assert(count > 0);
1553 if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001554 PyErr_SetString(PyExc_OverflowError,
1555 "replace string is too long");
1556 return NULL;
1557 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001558 result_len = count * to_len + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001559
1560 if (! (result = (PyByteArrayObject *)
1561 PyByteArray_FromStringAndSize(NULL, result_len)) )
1562 return NULL;
1563
1564 self_s = PyByteArray_AS_STRING(self);
1565 result_s = PyByteArray_AS_STRING(result);
1566
1567 /* TODO: special case single character, which doesn't need memcpy */
1568
1569 /* Lay the first one down (guaranteed this will occur) */
1570 Py_MEMCPY(result_s, to_s, to_len);
1571 result_s += to_len;
1572 count -= 1;
1573
1574 for (i=0; i<count; i++) {
1575 *result_s++ = *self_s++;
1576 Py_MEMCPY(result_s, to_s, to_len);
1577 result_s += to_len;
1578 }
1579
1580 /* Copy the rest of the original string */
1581 Py_MEMCPY(result_s, self_s, self_len-i);
1582
1583 return result;
1584}
1585
1586/* Special case for deleting a single character */
1587/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1588Py_LOCAL(PyByteArrayObject *)
1589replace_delete_single_character(PyByteArrayObject *self,
1590 char from_c, Py_ssize_t maxcount)
1591{
1592 char *self_s, *result_s;
1593 char *start, *next, *end;
1594 Py_ssize_t self_len, result_len;
1595 Py_ssize_t count;
1596 PyByteArrayObject *result;
1597
1598 self_len = PyByteArray_GET_SIZE(self);
1599 self_s = PyByteArray_AS_STRING(self);
1600
1601 count = countchar(self_s, self_len, from_c, maxcount);
1602 if (count == 0) {
1603 return return_self(self);
1604 }
1605
1606 result_len = self_len - count; /* from_len == 1 */
1607 assert(result_len>=0);
1608
1609 if ( (result = (PyByteArrayObject *)
1610 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1611 return NULL;
1612 result_s = PyByteArray_AS_STRING(result);
1613
1614 start = self_s;
1615 end = self_s + self_len;
1616 while (count-- > 0) {
1617 next = findchar(start, end-start, from_c);
1618 if (next == NULL)
1619 break;
1620 Py_MEMCPY(result_s, start, next-start);
1621 result_s += (next-start);
1622 start = next+1;
1623 }
1624 Py_MEMCPY(result_s, start, end-start);
1625
1626 return result;
1627}
1628
1629/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1630
1631Py_LOCAL(PyByteArrayObject *)
1632replace_delete_substring(PyByteArrayObject *self,
1633 const char *from_s, Py_ssize_t from_len,
1634 Py_ssize_t maxcount)
1635{
1636 char *self_s, *result_s;
1637 char *start, *next, *end;
1638 Py_ssize_t self_len, result_len;
1639 Py_ssize_t count, offset;
1640 PyByteArrayObject *result;
1641
1642 self_len = PyByteArray_GET_SIZE(self);
1643 self_s = PyByteArray_AS_STRING(self);
1644
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001645 count = stringlib_count(self_s, self_len,
1646 from_s, from_len,
1647 maxcount);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001648
1649 if (count == 0) {
1650 /* no matches */
1651 return return_self(self);
1652 }
1653
1654 result_len = self_len - (count * from_len);
1655 assert (result_len>=0);
1656
1657 if ( (result = (PyByteArrayObject *)
1658 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1659 return NULL;
1660
1661 result_s = PyByteArray_AS_STRING(result);
1662
1663 start = self_s;
1664 end = self_s + self_len;
1665 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001666 offset = stringlib_find(start, end-start,
1667 from_s, from_len,
1668 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001669 if (offset == -1)
1670 break;
1671 next = start + offset;
1672
1673 Py_MEMCPY(result_s, start, next-start);
1674
1675 result_s += (next-start);
1676 start = next+from_len;
1677 }
1678 Py_MEMCPY(result_s, start, end-start);
1679 return result;
1680}
1681
1682/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1683Py_LOCAL(PyByteArrayObject *)
1684replace_single_character_in_place(PyByteArrayObject *self,
1685 char from_c, char to_c,
1686 Py_ssize_t maxcount)
1687{
Antoine Pitroud1188562010-06-09 16:38:55 +00001688 char *self_s, *result_s, *start, *end, *next;
1689 Py_ssize_t self_len;
1690 PyByteArrayObject *result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001691
Antoine Pitroud1188562010-06-09 16:38:55 +00001692 /* The result string will be the same size */
1693 self_s = PyByteArray_AS_STRING(self);
1694 self_len = PyByteArray_GET_SIZE(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001695
Antoine Pitroud1188562010-06-09 16:38:55 +00001696 next = findchar(self_s, self_len, from_c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001697
Antoine Pitroud1188562010-06-09 16:38:55 +00001698 if (next == NULL) {
1699 /* No matches; return the original bytes */
1700 return return_self(self);
1701 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001702
Antoine Pitroud1188562010-06-09 16:38:55 +00001703 /* Need to make a new bytes */
1704 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1705 if (result == NULL)
1706 return NULL;
1707 result_s = PyByteArray_AS_STRING(result);
1708 Py_MEMCPY(result_s, self_s, self_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001709
Antoine Pitroud1188562010-06-09 16:38:55 +00001710 /* change everything in-place, starting with this one */
1711 start = result_s + (next-self_s);
1712 *start = to_c;
1713 start++;
1714 end = result_s + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001715
Antoine Pitroud1188562010-06-09 16:38:55 +00001716 while (--maxcount > 0) {
1717 next = findchar(start, end-start, from_c);
1718 if (next == NULL)
1719 break;
1720 *next = to_c;
1721 start = next+1;
1722 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001723
Antoine Pitroud1188562010-06-09 16:38:55 +00001724 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001725}
1726
1727/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1728Py_LOCAL(PyByteArrayObject *)
1729replace_substring_in_place(PyByteArrayObject *self,
1730 const char *from_s, Py_ssize_t from_len,
1731 const char *to_s, Py_ssize_t to_len,
1732 Py_ssize_t maxcount)
1733{
1734 char *result_s, *start, *end;
1735 char *self_s;
1736 Py_ssize_t self_len, offset;
1737 PyByteArrayObject *result;
1738
1739 /* The result bytes will be the same size */
1740
1741 self_s = PyByteArray_AS_STRING(self);
1742 self_len = PyByteArray_GET_SIZE(self);
1743
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001744 offset = stringlib_find(self_s, self_len,
1745 from_s, from_len,
1746 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001747 if (offset == -1) {
1748 /* No matches; return the original bytes */
1749 return return_self(self);
1750 }
1751
1752 /* Need to make a new bytes */
1753 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1754 if (result == NULL)
1755 return NULL;
1756 result_s = PyByteArray_AS_STRING(result);
1757 Py_MEMCPY(result_s, self_s, self_len);
1758
1759 /* change everything in-place, starting with this one */
1760 start = result_s + offset;
1761 Py_MEMCPY(start, to_s, from_len);
1762 start += from_len;
1763 end = result_s + self_len;
1764
1765 while ( --maxcount > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001766 offset = stringlib_find(start, end-start,
1767 from_s, from_len,
1768 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001769 if (offset==-1)
1770 break;
1771 Py_MEMCPY(start+offset, to_s, from_len);
1772 start += offset+from_len;
1773 }
1774
1775 return result;
1776}
1777
1778/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
1779Py_LOCAL(PyByteArrayObject *)
1780replace_single_character(PyByteArrayObject *self,
1781 char from_c,
1782 const char *to_s, Py_ssize_t to_len,
1783 Py_ssize_t maxcount)
1784{
1785 char *self_s, *result_s;
1786 char *start, *next, *end;
1787 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001788 Py_ssize_t count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001789 PyByteArrayObject *result;
1790
1791 self_s = PyByteArray_AS_STRING(self);
1792 self_len = PyByteArray_GET_SIZE(self);
1793
1794 count = countchar(self_s, self_len, from_c, maxcount);
1795 if (count == 0) {
1796 /* no matches, return unchanged */
1797 return return_self(self);
1798 }
1799
1800 /* use the difference between current and new, hence the "-1" */
1801 /* result_len = self_len + count * (to_len-1) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001802 assert(count > 0);
1803 if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001804 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1805 return NULL;
1806 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001807 result_len = self_len + count * (to_len - 1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001808
1809 if ( (result = (PyByteArrayObject *)
1810 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1811 return NULL;
1812 result_s = PyByteArray_AS_STRING(result);
1813
1814 start = self_s;
1815 end = self_s + self_len;
1816 while (count-- > 0) {
1817 next = findchar(start, end-start, from_c);
1818 if (next == NULL)
1819 break;
1820
1821 if (next == start) {
1822 /* replace with the 'to' */
1823 Py_MEMCPY(result_s, to_s, to_len);
1824 result_s += to_len;
1825 start += 1;
1826 } else {
1827 /* copy the unchanged old then the 'to' */
1828 Py_MEMCPY(result_s, start, next-start);
1829 result_s += (next-start);
1830 Py_MEMCPY(result_s, to_s, to_len);
1831 result_s += to_len;
1832 start = next+1;
1833 }
1834 }
1835 /* Copy the remainder of the remaining bytes */
1836 Py_MEMCPY(result_s, start, end-start);
1837
1838 return result;
1839}
1840
1841/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
1842Py_LOCAL(PyByteArrayObject *)
1843replace_substring(PyByteArrayObject *self,
1844 const char *from_s, Py_ssize_t from_len,
1845 const char *to_s, Py_ssize_t to_len,
1846 Py_ssize_t maxcount)
1847{
1848 char *self_s, *result_s;
1849 char *start, *next, *end;
1850 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001851 Py_ssize_t count, offset;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001852 PyByteArrayObject *result;
1853
1854 self_s = PyByteArray_AS_STRING(self);
1855 self_len = PyByteArray_GET_SIZE(self);
1856
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001857 count = stringlib_count(self_s, self_len,
1858 from_s, from_len,
1859 maxcount);
1860
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001861 if (count == 0) {
1862 /* no matches, return unchanged */
1863 return return_self(self);
1864 }
1865
1866 /* Check for overflow */
1867 /* result_len = self_len + count * (to_len-from_len) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001868 assert(count > 0);
1869 if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001870 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1871 return NULL;
1872 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001873 result_len = self_len + count * (to_len - from_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001874
1875 if ( (result = (PyByteArrayObject *)
1876 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1877 return NULL;
1878 result_s = PyByteArray_AS_STRING(result);
1879
1880 start = self_s;
1881 end = self_s + self_len;
1882 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001883 offset = stringlib_find(start, end-start,
1884 from_s, from_len,
1885 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001886 if (offset == -1)
1887 break;
1888 next = start+offset;
1889 if (next == start) {
1890 /* replace with the 'to' */
1891 Py_MEMCPY(result_s, to_s, to_len);
1892 result_s += to_len;
1893 start += from_len;
1894 } else {
1895 /* copy the unchanged old then the 'to' */
1896 Py_MEMCPY(result_s, start, next-start);
1897 result_s += (next-start);
1898 Py_MEMCPY(result_s, to_s, to_len);
1899 result_s += to_len;
1900 start = next+from_len;
1901 }
1902 }
1903 /* Copy the remainder of the remaining bytes */
1904 Py_MEMCPY(result_s, start, end-start);
1905
1906 return result;
1907}
1908
1909
1910Py_LOCAL(PyByteArrayObject *)
1911replace(PyByteArrayObject *self,
1912 const char *from_s, Py_ssize_t from_len,
1913 const char *to_s, Py_ssize_t to_len,
1914 Py_ssize_t maxcount)
1915{
1916 if (maxcount < 0) {
1917 maxcount = PY_SSIZE_T_MAX;
1918 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
1919 /* nothing to do; return the original bytes */
1920 return return_self(self);
1921 }
1922
1923 if (maxcount == 0 ||
1924 (from_len == 0 && to_len == 0)) {
1925 /* nothing to do; return the original bytes */
1926 return return_self(self);
1927 }
1928
1929 /* Handle zero-length special cases */
1930
1931 if (from_len == 0) {
1932 /* insert the 'to' bytes everywhere. */
1933 /* >>> "Python".replace("", ".") */
1934 /* '.P.y.t.h.o.n.' */
1935 return replace_interleave(self, to_s, to_len, maxcount);
1936 }
1937
1938 /* Except for "".replace("", "A") == "A" there is no way beyond this */
1939 /* point for an empty self bytes to generate a non-empty bytes */
1940 /* Special case so the remaining code always gets a non-empty bytes */
1941 if (PyByteArray_GET_SIZE(self) == 0) {
1942 return return_self(self);
1943 }
1944
1945 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00001946 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001947 if (from_len == 1) {
1948 return replace_delete_single_character(
1949 self, from_s[0], maxcount);
1950 } else {
1951 return replace_delete_substring(self, from_s, from_len, maxcount);
1952 }
1953 }
1954
1955 /* Handle special case where both bytes have the same length */
1956
1957 if (from_len == to_len) {
1958 if (from_len == 1) {
1959 return replace_single_character_in_place(
1960 self,
1961 from_s[0],
1962 to_s[0],
1963 maxcount);
1964 } else {
1965 return replace_substring_in_place(
1966 self, from_s, from_len, to_s, to_len, maxcount);
1967 }
1968 }
1969
1970 /* Otherwise use the more generic algorithms */
1971 if (from_len == 1) {
1972 return replace_single_character(self, from_s[0],
1973 to_s, to_len, maxcount);
1974 } else {
1975 /* len('from')>=2, len('to')>=1 */
1976 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
1977 }
1978}
1979
1980
1981PyDoc_STRVAR(replace__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001982"B.replace(old, new[, count]) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001983\n\
1984Return a copy of B with all occurrences of subsection\n\
1985old replaced by new. If the optional argument count is\n\
1986given, only the first count occurrences are replaced.");
1987
1988static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001989bytearray_replace(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001990{
1991 Py_ssize_t count = -1;
1992 PyObject *from, *to, *res;
1993 Py_buffer vfrom, vto;
1994
1995 if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
1996 return NULL;
1997
1998 if (_getbuffer(from, &vfrom) < 0)
1999 return NULL;
2000 if (_getbuffer(to, &vto) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +00002001 PyBuffer_Release(&vfrom);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002002 return NULL;
2003 }
2004
2005 res = (PyObject *)replace((PyByteArrayObject *) self,
2006 vfrom.buf, vfrom.len,
2007 vto.buf, vto.len, count);
2008
Martin v. Löwis423be952008-08-13 15:53:07 +00002009 PyBuffer_Release(&vfrom);
2010 PyBuffer_Release(&vto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002011 return res;
2012}
2013
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002014PyDoc_STRVAR(split__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002015"B.split([sep[, maxsplit]]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002016\n\
2017Return a list of the sections in B, using sep as the delimiter.\n\
2018If sep is not given, B is split on ASCII whitespace characters\n\
2019(space, tab, return, newline, formfeed, vertical tab).\n\
2020If maxsplit is given, at most maxsplit splits are done.");
2021
2022static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002023bytearray_split(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002024{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002025 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
2026 Py_ssize_t maxsplit = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002027 const char *s = PyByteArray_AS_STRING(self), *sub;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002028 PyObject *list, *subobj = Py_None;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002029 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002030
2031 if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
2032 return NULL;
2033 if (maxsplit < 0)
2034 maxsplit = PY_SSIZE_T_MAX;
2035
2036 if (subobj == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002037 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002038
2039 if (_getbuffer(subobj, &vsub) < 0)
2040 return NULL;
2041 sub = vsub.buf;
2042 n = vsub.len;
2043
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002044 list = stringlib_split(
2045 (PyObject*) self, s, len, sub, n, maxsplit
2046 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002047 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002048 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002049}
2050
2051PyDoc_STRVAR(partition__doc__,
2052"B.partition(sep) -> (head, sep, tail)\n\
2053\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002054Search for the separator sep in B, and return the part before it,\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002055the separator itself, and the part after it. If the separator is not\n\
2056found, returns B and two empty bytearray objects.");
2057
2058static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002059bytearray_partition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002060{
2061 PyObject *bytesep, *result;
2062
2063 bytesep = PyByteArray_FromObject(sep_obj);
2064 if (! bytesep)
2065 return NULL;
2066
2067 result = stringlib_partition(
2068 (PyObject*) self,
2069 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2070 bytesep,
2071 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2072 );
2073
2074 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002075 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002076}
2077
2078PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +00002079"B.rpartition(sep) -> (head, sep, tail)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002080\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002081Search for the separator sep in B, starting at the end of B,\n\
2082and return the part before it, the separator itself, and the\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002083part after it. If the separator is not found, returns two empty\n\
2084bytearray objects and B.");
2085
2086static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002087bytearray_rpartition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002088{
2089 PyObject *bytesep, *result;
2090
2091 bytesep = PyByteArray_FromObject(sep_obj);
2092 if (! bytesep)
2093 return NULL;
2094
2095 result = stringlib_rpartition(
2096 (PyObject*) self,
2097 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2098 bytesep,
2099 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2100 );
2101
2102 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002103 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002104}
2105
2106PyDoc_STRVAR(rsplit__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002107"B.rsplit(sep[, maxsplit]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002108\n\
2109Return a list of the sections in B, using sep as the delimiter,\n\
2110starting at the end of B and working to the front.\n\
2111If sep is not given, B is split on ASCII whitespace characters\n\
2112(space, tab, return, newline, formfeed, vertical tab).\n\
2113If maxsplit is given, at most maxsplit splits are done.");
2114
2115static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002116bytearray_rsplit(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002117{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002118 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
2119 Py_ssize_t maxsplit = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002120 const char *s = PyByteArray_AS_STRING(self), *sub;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002121 PyObject *list, *subobj = Py_None;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002122 Py_buffer vsub;
2123
2124 if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
2125 return NULL;
2126 if (maxsplit < 0)
2127 maxsplit = PY_SSIZE_T_MAX;
2128
2129 if (subobj == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002130 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002131
2132 if (_getbuffer(subobj, &vsub) < 0)
2133 return NULL;
2134 sub = vsub.buf;
2135 n = vsub.len;
2136
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002137 list = stringlib_rsplit(
2138 (PyObject*) self, s, len, sub, n, maxsplit
2139 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002140 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002141 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002142}
2143
2144PyDoc_STRVAR(reverse__doc__,
2145"B.reverse() -> None\n\
2146\n\
2147Reverse the order of the values in B in place.");
2148static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002149bytearray_reverse(PyByteArrayObject *self, PyObject *unused)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002150{
2151 char swap, *head, *tail;
2152 Py_ssize_t i, j, n = Py_SIZE(self);
2153
2154 j = n / 2;
2155 head = self->ob_bytes;
2156 tail = head + n - 1;
2157 for (i = 0; i < j; i++) {
2158 swap = *head;
2159 *head++ = *tail;
2160 *tail-- = swap;
2161 }
2162
2163 Py_RETURN_NONE;
2164}
2165
2166PyDoc_STRVAR(insert__doc__,
2167"B.insert(index, int) -> None\n\
2168\n\
2169Insert a single item into the bytearray before the given index.");
2170static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002171bytearray_insert(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002172{
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002173 PyObject *value;
2174 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002175 Py_ssize_t where, n = Py_SIZE(self);
2176
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002177 if (!PyArg_ParseTuple(args, "nO:insert", &where, &value))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002178 return NULL;
2179
2180 if (n == PY_SSIZE_T_MAX) {
2181 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002182 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002183 return NULL;
2184 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002185 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002186 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002187 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2188 return NULL;
2189
2190 if (where < 0) {
2191 where += n;
2192 if (where < 0)
2193 where = 0;
2194 }
2195 if (where > n)
2196 where = n;
2197 memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where);
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002198 self->ob_bytes[where] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002199
2200 Py_RETURN_NONE;
2201}
2202
2203PyDoc_STRVAR(append__doc__,
2204"B.append(int) -> None\n\
2205\n\
2206Append a single item to the end of B.");
2207static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002208bytearray_append(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002209{
2210 int value;
2211 Py_ssize_t n = Py_SIZE(self);
2212
2213 if (! _getbytevalue(arg, &value))
2214 return NULL;
2215 if (n == PY_SSIZE_T_MAX) {
2216 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002217 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002218 return NULL;
2219 }
2220 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2221 return NULL;
2222
2223 self->ob_bytes[n] = value;
2224
2225 Py_RETURN_NONE;
2226}
2227
2228PyDoc_STRVAR(extend__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002229"B.extend(iterable_of_ints) -> None\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002230\n\
2231Append all the elements from the iterator or sequence to the\n\
2232end of B.");
2233static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002234bytearray_extend(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002235{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002236 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002237 Py_ssize_t buf_size = 0, len = 0;
2238 int value;
2239 char *buf;
2240
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002241 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002242 if (PyObject_CheckBuffer(arg)) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002243 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), arg) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002244 return NULL;
2245
2246 Py_RETURN_NONE;
2247 }
2248
2249 it = PyObject_GetIter(arg);
2250 if (it == NULL)
2251 return NULL;
2252
Ezio Melotti42da6632011-03-15 05:18:48 +02002253 /* Try to determine the length of the argument. 32 is arbitrary. */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002254 buf_size = _PyObject_LengthHint(arg, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002255 if (buf_size == -1) {
2256 Py_DECREF(it);
2257 return NULL;
2258 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002259
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002260 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
2261 if (bytearray_obj == NULL)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002262 return NULL;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002263 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002264
2265 while ((item = PyIter_Next(it)) != NULL) {
2266 if (! _getbytevalue(item, &value)) {
2267 Py_DECREF(item);
2268 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002269 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002270 return NULL;
2271 }
2272 buf[len++] = value;
2273 Py_DECREF(item);
2274
2275 if (len >= buf_size) {
2276 buf_size = len + (len >> 1) + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002277 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002278 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002279 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002280 return NULL;
2281 }
2282 /* Recompute the `buf' pointer, since the resizing operation may
2283 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002284 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002285 }
2286 }
2287 Py_DECREF(it);
2288
2289 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002290 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
2291 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002292 return NULL;
2293 }
2294
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002295 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002296 return NULL;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002297 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002298
2299 Py_RETURN_NONE;
2300}
2301
2302PyDoc_STRVAR(pop__doc__,
2303"B.pop([index]) -> int\n\
2304\n\
2305Remove and return a single item from B. If no index\n\
Benjamin Petersondcf97b92008-07-02 17:30:14 +00002306argument is given, will pop the last value.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002307static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002308bytearray_pop(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002309{
2310 int value;
2311 Py_ssize_t where = -1, n = Py_SIZE(self);
2312
2313 if (!PyArg_ParseTuple(args, "|n:pop", &where))
2314 return NULL;
2315
2316 if (n == 0) {
Eli Bendersky1bc4f192011-03-04 04:55:25 +00002317 PyErr_SetString(PyExc_IndexError,
2318 "pop from empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002319 return NULL;
2320 }
2321 if (where < 0)
2322 where += Py_SIZE(self);
2323 if (where < 0 || where >= Py_SIZE(self)) {
2324 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2325 return NULL;
2326 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002327 if (!_canresize(self))
2328 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002329
2330 value = self->ob_bytes[where];
2331 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2332 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2333 return NULL;
2334
Mark Dickinson54a3db92009-09-06 10:19:23 +00002335 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002336}
2337
2338PyDoc_STRVAR(remove__doc__,
2339"B.remove(int) -> None\n\
2340\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002341Remove the first occurrence of a value in B.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002342static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002343bytearray_remove(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002344{
2345 int value;
2346 Py_ssize_t where, n = Py_SIZE(self);
2347
2348 if (! _getbytevalue(arg, &value))
2349 return NULL;
2350
2351 for (where = 0; where < n; where++) {
2352 if (self->ob_bytes[where] == value)
2353 break;
2354 }
2355 if (where == n) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002356 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002357 return NULL;
2358 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002359 if (!_canresize(self))
2360 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002361
2362 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2363 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2364 return NULL;
2365
2366 Py_RETURN_NONE;
2367}
2368
2369/* XXX These two helpers could be optimized if argsize == 1 */
2370
2371static Py_ssize_t
2372lstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2373 void *argptr, Py_ssize_t argsize)
2374{
2375 Py_ssize_t i = 0;
2376 while (i < mysize && memchr(argptr, myptr[i], argsize))
2377 i++;
2378 return i;
2379}
2380
2381static Py_ssize_t
2382rstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2383 void *argptr, Py_ssize_t argsize)
2384{
2385 Py_ssize_t i = mysize - 1;
2386 while (i >= 0 && memchr(argptr, myptr[i], argsize))
2387 i--;
2388 return i + 1;
2389}
2390
2391PyDoc_STRVAR(strip__doc__,
2392"B.strip([bytes]) -> bytearray\n\
2393\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002394Strip leading and trailing bytes contained in the argument\n\
2395and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002396If the argument is omitted, strip ASCII whitespace.");
2397static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002398bytearray_strip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002399{
2400 Py_ssize_t left, right, mysize, argsize;
2401 void *myptr, *argptr;
2402 PyObject *arg = Py_None;
2403 Py_buffer varg;
2404 if (!PyArg_ParseTuple(args, "|O:strip", &arg))
2405 return NULL;
2406 if (arg == Py_None) {
2407 argptr = "\t\n\r\f\v ";
2408 argsize = 6;
2409 }
2410 else {
2411 if (_getbuffer(arg, &varg) < 0)
2412 return NULL;
2413 argptr = varg.buf;
2414 argsize = varg.len;
2415 }
2416 myptr = self->ob_bytes;
2417 mysize = Py_SIZE(self);
2418 left = lstrip_helper(myptr, mysize, argptr, argsize);
2419 if (left == mysize)
2420 right = left;
2421 else
2422 right = rstrip_helper(myptr, mysize, argptr, argsize);
2423 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002424 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002425 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2426}
2427
2428PyDoc_STRVAR(lstrip__doc__,
2429"B.lstrip([bytes]) -> bytearray\n\
2430\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002431Strip leading bytes contained in the argument\n\
2432and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002433If the argument is omitted, strip leading ASCII whitespace.");
2434static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002435bytearray_lstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002436{
2437 Py_ssize_t left, right, mysize, argsize;
2438 void *myptr, *argptr;
2439 PyObject *arg = Py_None;
2440 Py_buffer varg;
2441 if (!PyArg_ParseTuple(args, "|O:lstrip", &arg))
2442 return NULL;
2443 if (arg == Py_None) {
2444 argptr = "\t\n\r\f\v ";
2445 argsize = 6;
2446 }
2447 else {
2448 if (_getbuffer(arg, &varg) < 0)
2449 return NULL;
2450 argptr = varg.buf;
2451 argsize = varg.len;
2452 }
2453 myptr = self->ob_bytes;
2454 mysize = Py_SIZE(self);
2455 left = lstrip_helper(myptr, mysize, argptr, argsize);
2456 right = mysize;
2457 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002458 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002459 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2460}
2461
2462PyDoc_STRVAR(rstrip__doc__,
2463"B.rstrip([bytes]) -> bytearray\n\
2464\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002465Strip trailing bytes contained in the argument\n\
2466and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002467If the argument is omitted, strip trailing ASCII whitespace.");
2468static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002469bytearray_rstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002470{
Brett Cannonb94767f2011-02-22 20:15:44 +00002471 Py_ssize_t right, mysize, argsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002472 void *myptr, *argptr;
2473 PyObject *arg = Py_None;
2474 Py_buffer varg;
2475 if (!PyArg_ParseTuple(args, "|O:rstrip", &arg))
2476 return NULL;
2477 if (arg == Py_None) {
2478 argptr = "\t\n\r\f\v ";
2479 argsize = 6;
2480 }
2481 else {
2482 if (_getbuffer(arg, &varg) < 0)
2483 return NULL;
2484 argptr = varg.buf;
2485 argsize = varg.len;
2486 }
2487 myptr = self->ob_bytes;
2488 mysize = Py_SIZE(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002489 right = rstrip_helper(myptr, mysize, argptr, argsize);
2490 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002491 PyBuffer_Release(&varg);
Brett Cannonb94767f2011-02-22 20:15:44 +00002492 return PyByteArray_FromStringAndSize(self->ob_bytes, right);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002493}
2494
2495PyDoc_STRVAR(decode_doc,
Victor Stinnerc911bbf2010-11-07 19:04:46 +00002496"B.decode(encoding='utf-8', errors='strict') -> str\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002497\n\
Victor Stinnere14e2122010-11-07 18:41:46 +00002498Decode B using the codec registered for encoding. Default encoding\n\
2499is 'utf-8'. errors may be given to set a different error\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002500handling scheme. Default is 'strict' meaning that encoding errors raise\n\
2501a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
2502as well as any other name registered with codecs.register_error that is\n\
2503able to handle UnicodeDecodeErrors.");
2504
2505static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00002506bytearray_decode(PyObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002507{
2508 const char *encoding = NULL;
2509 const char *errors = NULL;
Benjamin Peterson308d6372009-09-18 21:42:35 +00002510 static char *kwlist[] = {"encoding", "errors", 0};
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002511
Benjamin Peterson308d6372009-09-18 21:42:35 +00002512 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode", kwlist, &encoding, &errors))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002513 return NULL;
2514 if (encoding == NULL)
2515 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002516 return PyUnicode_FromEncodedObject(self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002517}
2518
2519PyDoc_STRVAR(alloc_doc,
2520"B.__alloc__() -> int\n\
2521\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002522Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002523
2524static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002525bytearray_alloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002526{
2527 return PyLong_FromSsize_t(self->ob_alloc);
2528}
2529
2530PyDoc_STRVAR(join_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002531"B.join(iterable_of_bytes) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002532\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002533Concatenate any number of bytes/bytearray objects, with B\n\
2534in between each pair, and return the result as a new bytearray.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002535
2536static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002537bytearray_join(PyByteArrayObject *self, PyObject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002538{
2539 PyObject *seq;
2540 Py_ssize_t mysize = Py_SIZE(self);
2541 Py_ssize_t i;
2542 Py_ssize_t n;
2543 PyObject **items;
2544 Py_ssize_t totalsize = 0;
2545 PyObject *result;
2546 char *dest;
2547
2548 seq = PySequence_Fast(it, "can only join an iterable");
2549 if (seq == NULL)
2550 return NULL;
2551 n = PySequence_Fast_GET_SIZE(seq);
2552 items = PySequence_Fast_ITEMS(seq);
2553
2554 /* Compute the total size, and check that they are all bytes */
2555 /* XXX Shouldn't we use _getbuffer() on these items instead? */
2556 for (i = 0; i < n; i++) {
2557 PyObject *obj = items[i];
2558 if (!PyByteArray_Check(obj) && !PyBytes_Check(obj)) {
2559 PyErr_Format(PyExc_TypeError,
2560 "can only join an iterable of bytes "
2561 "(item %ld has type '%.100s')",
2562 /* XXX %ld isn't right on Win64 */
2563 (long)i, Py_TYPE(obj)->tp_name);
2564 goto error;
2565 }
2566 if (i > 0)
2567 totalsize += mysize;
2568 totalsize += Py_SIZE(obj);
2569 if (totalsize < 0) {
2570 PyErr_NoMemory();
2571 goto error;
2572 }
2573 }
2574
2575 /* Allocate the result, and copy the bytes */
2576 result = PyByteArray_FromStringAndSize(NULL, totalsize);
2577 if (result == NULL)
2578 goto error;
2579 dest = PyByteArray_AS_STRING(result);
2580 for (i = 0; i < n; i++) {
2581 PyObject *obj = items[i];
2582 Py_ssize_t size = Py_SIZE(obj);
2583 char *buf;
2584 if (PyByteArray_Check(obj))
2585 buf = PyByteArray_AS_STRING(obj);
2586 else
2587 buf = PyBytes_AS_STRING(obj);
2588 if (i) {
2589 memcpy(dest, self->ob_bytes, mysize);
2590 dest += mysize;
2591 }
2592 memcpy(dest, buf, size);
2593 dest += size;
2594 }
2595
2596 /* Done */
2597 Py_DECREF(seq);
2598 return result;
2599
2600 /* Error handling */
2601 error:
2602 Py_DECREF(seq);
2603 return NULL;
2604}
2605
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002606PyDoc_STRVAR(splitlines__doc__,
2607"B.splitlines([keepends]) -> list of lines\n\
2608\n\
2609Return a list of the lines in B, breaking at line boundaries.\n\
2610Line breaks are not included in the resulting list unless keepends\n\
2611is given and true.");
2612
2613static PyObject*
2614bytearray_splitlines(PyObject *self, PyObject *args)
2615{
2616 int keepends = 0;
2617
2618 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
2619 return NULL;
2620
2621 return stringlib_splitlines(
2622 (PyObject*) self, PyByteArray_AS_STRING(self),
2623 PyByteArray_GET_SIZE(self), keepends
2624 );
2625}
2626
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002627PyDoc_STRVAR(fromhex_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002628"bytearray.fromhex(string) -> bytearray (static method)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002629\n\
2630Create a bytearray object from a string of hexadecimal numbers.\n\
2631Spaces between two numbers are accepted.\n\
2632Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef').");
2633
2634static int
2635hex_digit_to_int(Py_UNICODE c)
2636{
2637 if (c >= 128)
2638 return -1;
Eric Smith6dc46f52009-04-27 20:39:49 +00002639 if (Py_ISDIGIT(c))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002640 return c - '0';
2641 else {
Eric Smith6dc46f52009-04-27 20:39:49 +00002642 if (Py_ISUPPER(c))
2643 c = Py_TOLOWER(c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002644 if (c >= 'a' && c <= 'f')
2645 return c - 'a' + 10;
2646 }
2647 return -1;
2648}
2649
2650static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002651bytearray_fromhex(PyObject *cls, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002652{
2653 PyObject *newbytes, *hexobj;
2654 char *buf;
2655 Py_UNICODE *hex;
2656 Py_ssize_t hexlen, byteslen, i, j;
2657 int top, bot;
2658
2659 if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj))
2660 return NULL;
2661 assert(PyUnicode_Check(hexobj));
2662 hexlen = PyUnicode_GET_SIZE(hexobj);
2663 hex = PyUnicode_AS_UNICODE(hexobj);
2664 byteslen = hexlen/2; /* This overestimates if there are spaces */
2665 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
2666 if (!newbytes)
2667 return NULL;
2668 buf = PyByteArray_AS_STRING(newbytes);
2669 for (i = j = 0; i < hexlen; i += 2) {
2670 /* skip over spaces in the input */
2671 while (hex[i] == ' ')
2672 i++;
2673 if (i >= hexlen)
2674 break;
2675 top = hex_digit_to_int(hex[i]);
2676 bot = hex_digit_to_int(hex[i+1]);
2677 if (top == -1 || bot == -1) {
2678 PyErr_Format(PyExc_ValueError,
2679 "non-hexadecimal number found in "
2680 "fromhex() arg at position %zd", i);
2681 goto error;
2682 }
2683 buf[j++] = (top << 4) + bot;
2684 }
2685 if (PyByteArray_Resize(newbytes, j) < 0)
2686 goto error;
2687 return newbytes;
2688
2689 error:
2690 Py_DECREF(newbytes);
2691 return NULL;
2692}
2693
2694PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2695
2696static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002697bytearray_reduce(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002698{
2699 PyObject *latin1, *dict;
2700 if (self->ob_bytes)
2701 latin1 = PyUnicode_DecodeLatin1(self->ob_bytes,
2702 Py_SIZE(self), NULL);
2703 else
2704 latin1 = PyUnicode_FromString("");
2705
2706 dict = PyObject_GetAttrString((PyObject *)self, "__dict__");
2707 if (dict == NULL) {
2708 PyErr_Clear();
2709 dict = Py_None;
2710 Py_INCREF(dict);
2711 }
2712
2713 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
2714}
2715
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002716PyDoc_STRVAR(sizeof_doc,
2717"B.__sizeof__() -> int\n\
2718 \n\
2719Returns the size of B in memory, in bytes");
2720static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002721bytearray_sizeof(PyByteArrayObject *self)
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002722{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002723 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002724
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002725 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
2726 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002727}
2728
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002729static PySequenceMethods bytearray_as_sequence = {
2730 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002731 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002732 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
2733 (ssizeargfunc)bytearray_getitem, /* sq_item */
2734 0, /* sq_slice */
2735 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
2736 0, /* sq_ass_slice */
2737 (objobjproc)bytearray_contains, /* sq_contains */
2738 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
2739 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002740};
2741
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002742static PyMappingMethods bytearray_as_mapping = {
2743 (lenfunc)bytearray_length,
2744 (binaryfunc)bytearray_subscript,
2745 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002746};
2747
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002748static PyBufferProcs bytearray_as_buffer = {
2749 (getbufferproc)bytearray_getbuffer,
2750 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002751};
2752
2753static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002754bytearray_methods[] = {
2755 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
2756 {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, reduce_doc},
2757 {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, sizeof_doc},
2758 {"append", (PyCFunction)bytearray_append, METH_O, append__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002759 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
2760 _Py_capitalize__doc__},
2761 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
Eli Bendersky4db28d32011-03-03 18:21:02 +00002762 {"clear", (PyCFunction)bytearray_clear, METH_NOARGS, clear__doc__},
2763 {"copy", (PyCFunction)bytearray_copy, METH_NOARGS, copy__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002764 {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
Benjamin Peterson308d6372009-09-18 21:42:35 +00002765 {"decode", (PyCFunction)bytearray_decode, METH_VARARGS | METH_KEYWORDS, decode_doc},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002766 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002767 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS,
2768 expandtabs__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002769 {"extend", (PyCFunction)bytearray_extend, METH_O, extend__doc__},
2770 {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
2771 {"fromhex", (PyCFunction)bytearray_fromhex, METH_VARARGS|METH_CLASS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002772 fromhex_doc},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002773 {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
2774 {"insert", (PyCFunction)bytearray_insert, METH_VARARGS, insert__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002775 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
2776 _Py_isalnum__doc__},
2777 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
2778 _Py_isalpha__doc__},
2779 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
2780 _Py_isdigit__doc__},
2781 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
2782 _Py_islower__doc__},
2783 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
2784 _Py_isspace__doc__},
2785 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
2786 _Py_istitle__doc__},
2787 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
2788 _Py_isupper__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002789 {"join", (PyCFunction)bytearray_join, METH_O, join_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002790 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
2791 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002792 {"lstrip", (PyCFunction)bytearray_lstrip, METH_VARARGS, lstrip__doc__},
2793 {"maketrans", (PyCFunction)bytearray_maketrans, METH_VARARGS|METH_STATIC,
Georg Brandlabc38772009-04-12 15:51:51 +00002794 _Py_maketrans__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002795 {"partition", (PyCFunction)bytearray_partition, METH_O, partition__doc__},
2796 {"pop", (PyCFunction)bytearray_pop, METH_VARARGS, pop__doc__},
2797 {"remove", (PyCFunction)bytearray_remove, METH_O, remove__doc__},
2798 {"replace", (PyCFunction)bytearray_replace, METH_VARARGS, replace__doc__},
2799 {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, reverse__doc__},
2800 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
2801 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002802 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002803 {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, rpartition__doc__},
2804 {"rsplit", (PyCFunction)bytearray_rsplit, METH_VARARGS, rsplit__doc__},
2805 {"rstrip", (PyCFunction)bytearray_rstrip, METH_VARARGS, rstrip__doc__},
2806 {"split", (PyCFunction)bytearray_split, METH_VARARGS, split__doc__},
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002807 {"splitlines", (PyCFunction)bytearray_splitlines, METH_VARARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002808 splitlines__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002809 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002810 startswith__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002811 {"strip", (PyCFunction)bytearray_strip, METH_VARARGS, strip__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002812 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
2813 _Py_swapcase__doc__},
2814 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002815 {"translate", (PyCFunction)bytearray_translate, METH_VARARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002816 translate__doc__},
2817 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
2818 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
2819 {NULL}
2820};
2821
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002822PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002823"bytearray(iterable_of_ints) -> bytearray\n\
2824bytearray(string, encoding[, errors]) -> bytearray\n\
2825bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray\n\
2826bytearray(memory_view) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002827\n\
2828Construct an mutable bytearray object from:\n\
2829 - an iterable yielding integers in range(256)\n\
2830 - a text string encoded using the specified encoding\n\
2831 - a bytes or a bytearray object\n\
2832 - any object implementing the buffer API.\n\
2833\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002834bytearray(int) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002835\n\
2836Construct a zero-initialized bytearray of the given length.");
2837
2838
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002839static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002840
2841PyTypeObject PyByteArray_Type = {
2842 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2843 "bytearray",
2844 sizeof(PyByteArrayObject),
2845 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002846 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002847 0, /* tp_print */
2848 0, /* tp_getattr */
2849 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002850 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002851 (reprfunc)bytearray_repr, /* tp_repr */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002852 0, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002853 &bytearray_as_sequence, /* tp_as_sequence */
2854 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002855 0, /* tp_hash */
2856 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002857 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002858 PyObject_GenericGetAttr, /* tp_getattro */
2859 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002860 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002861 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002862 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002863 0, /* tp_traverse */
2864 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002865 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002866 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002867 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002868 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002869 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002870 0, /* tp_members */
2871 0, /* tp_getset */
2872 0, /* tp_base */
2873 0, /* tp_dict */
2874 0, /* tp_descr_get */
2875 0, /* tp_descr_set */
2876 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002877 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002878 PyType_GenericAlloc, /* tp_alloc */
2879 PyType_GenericNew, /* tp_new */
2880 PyObject_Del, /* tp_free */
2881};
2882
2883/*********************** Bytes Iterator ****************************/
2884
2885typedef struct {
2886 PyObject_HEAD
2887 Py_ssize_t it_index;
2888 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
2889} bytesiterobject;
2890
2891static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002892bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002893{
2894 _PyObject_GC_UNTRACK(it);
2895 Py_XDECREF(it->it_seq);
2896 PyObject_GC_Del(it);
2897}
2898
2899static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002900bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002901{
2902 Py_VISIT(it->it_seq);
2903 return 0;
2904}
2905
2906static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002907bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002908{
2909 PyByteArrayObject *seq;
2910 PyObject *item;
2911
2912 assert(it != NULL);
2913 seq = it->it_seq;
2914 if (seq == NULL)
2915 return NULL;
2916 assert(PyByteArray_Check(seq));
2917
2918 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
2919 item = PyLong_FromLong(
2920 (unsigned char)seq->ob_bytes[it->it_index]);
2921 if (item != NULL)
2922 ++it->it_index;
2923 return item;
2924 }
2925
2926 Py_DECREF(seq);
2927 it->it_seq = NULL;
2928 return NULL;
2929}
2930
2931static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002932bytesarrayiter_length_hint(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002933{
2934 Py_ssize_t len = 0;
2935 if (it->it_seq)
2936 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
2937 return PyLong_FromSsize_t(len);
2938}
2939
2940PyDoc_STRVAR(length_hint_doc,
2941 "Private method returning an estimate of len(list(it)).");
2942
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002943static PyMethodDef bytearrayiter_methods[] = {
2944 {"__length_hint__", (PyCFunction)bytesarrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002945 length_hint_doc},
2946 {NULL, NULL} /* sentinel */
2947};
2948
2949PyTypeObject PyByteArrayIter_Type = {
2950 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2951 "bytearray_iterator", /* tp_name */
2952 sizeof(bytesiterobject), /* tp_basicsize */
2953 0, /* tp_itemsize */
2954 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002955 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002956 0, /* tp_print */
2957 0, /* tp_getattr */
2958 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002959 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002960 0, /* tp_repr */
2961 0, /* tp_as_number */
2962 0, /* tp_as_sequence */
2963 0, /* tp_as_mapping */
2964 0, /* tp_hash */
2965 0, /* tp_call */
2966 0, /* tp_str */
2967 PyObject_GenericGetAttr, /* tp_getattro */
2968 0, /* tp_setattro */
2969 0, /* tp_as_buffer */
2970 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2971 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002972 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002973 0, /* tp_clear */
2974 0, /* tp_richcompare */
2975 0, /* tp_weaklistoffset */
2976 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002977 (iternextfunc)bytearrayiter_next, /* tp_iternext */
2978 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002979 0,
2980};
2981
2982static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002983bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002984{
2985 bytesiterobject *it;
2986
2987 if (!PyByteArray_Check(seq)) {
2988 PyErr_BadInternalCall();
2989 return NULL;
2990 }
2991 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
2992 if (it == NULL)
2993 return NULL;
2994 it->it_index = 0;
2995 Py_INCREF(seq);
2996 it->it_seq = (PyByteArrayObject *)seq;
2997 _PyObject_GC_TRACK(it);
2998 return (PyObject *)it;
2999}