blob: a76f8274d250f0ac92b44333b8b603729e165f69 [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
8static PyByteArrayObject *nullbytes = NULL;
9
10void
11PyByteArray_Fini(void)
12{
13 Py_CLEAR(nullbytes);
14}
15
16int
17PyByteArray_Init(void)
18{
19 nullbytes = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
20 if (nullbytes == NULL)
21 return 0;
22 nullbytes->ob_bytes = NULL;
23 Py_SIZE(nullbytes) = nullbytes->ob_alloc = 0;
24 nullbytes->ob_exports = 0;
25 return 1;
26}
27
28/* end nullbytes support */
29
30/* Helpers */
31
32static int
33_getbytevalue(PyObject* arg, int *value)
34{
35 long face_value;
36
37 if (PyLong_Check(arg)) {
38 face_value = PyLong_AsLong(arg);
Georg Brandl9a54d7c2008-07-16 23:15:30 +000039 } else {
40 PyObject *index = PyNumber_Index(arg);
41 if (index == NULL) {
42 PyErr_Format(PyExc_TypeError, "an integer is required");
Christian Heimes2c9c7a52008-05-26 13:42:13 +000043 return 0;
44 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +000045 face_value = PyLong_AsLong(index);
46 Py_DECREF(index);
47 }
48
49 if (face_value < 0 || face_value >= 256) {
50 /* this includes the OverflowError in case the long is too large */
51 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
Christian Heimes2c9c7a52008-05-26 13:42:13 +000052 return 0;
53 }
54
55 *value = face_value;
56 return 1;
57}
58
59static int
60bytes_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
61{
62 int ret;
63 void *ptr;
64 if (view == NULL) {
65 obj->ob_exports++;
66 return 0;
67 }
68 if (obj->ob_bytes == NULL)
69 ptr = "";
70 else
71 ptr = obj->ob_bytes;
72 ret = PyBuffer_FillInfo(view, ptr, Py_SIZE(obj), 0, flags);
73 if (ret >= 0) {
74 obj->ob_exports++;
75 }
76 return ret;
77}
78
79static void
80bytes_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
81{
82 obj->ob_exports--;
83}
84
85static Py_ssize_t
86_getbuffer(PyObject *obj, Py_buffer *view)
87{
88 PyBufferProcs *buffer = Py_TYPE(obj)->tp_as_buffer;
89
90 if (buffer == NULL || buffer->bf_getbuffer == NULL)
91 {
92 PyErr_Format(PyExc_TypeError,
93 "Type %.100s doesn't support the buffer API",
94 Py_TYPE(obj)->tp_name);
95 return -1;
96 }
97
98 if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0)
99 return -1;
100 return view->len;
101}
102
103/* Direct API functions */
104
105PyObject *
106PyByteArray_FromObject(PyObject *input)
107{
108 return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
109 input, NULL);
110}
111
112PyObject *
113PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
114{
115 PyByteArrayObject *new;
116 Py_ssize_t alloc;
117
118 if (size < 0) {
119 PyErr_SetString(PyExc_SystemError,
120 "Negative size passed to PyByteArray_FromStringAndSize");
121 return NULL;
122 }
123
124 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
125 if (new == NULL)
126 return NULL;
127
128 if (size == 0) {
129 new->ob_bytes = NULL;
130 alloc = 0;
131 }
132 else {
133 alloc = size + 1;
134 new->ob_bytes = PyMem_Malloc(alloc);
135 if (new->ob_bytes == NULL) {
136 Py_DECREF(new);
137 return PyErr_NoMemory();
138 }
139 if (bytes != NULL)
140 memcpy(new->ob_bytes, bytes, size);
141 new->ob_bytes[size] = '\0'; /* Trailing null byte */
142 }
143 Py_SIZE(new) = size;
144 new->ob_alloc = alloc;
145 new->ob_exports = 0;
146
147 return (PyObject *)new;
148}
149
150Py_ssize_t
151PyByteArray_Size(PyObject *self)
152{
153 assert(self != NULL);
154 assert(PyByteArray_Check(self));
155
156 return PyByteArray_GET_SIZE(self);
157}
158
159char *
160PyByteArray_AsString(PyObject *self)
161{
162 assert(self != NULL);
163 assert(PyByteArray_Check(self));
164
165 return PyByteArray_AS_STRING(self);
166}
167
168int
169PyByteArray_Resize(PyObject *self, Py_ssize_t size)
170{
171 void *sval;
172 Py_ssize_t alloc = ((PyByteArrayObject *)self)->ob_alloc;
173
174 assert(self != NULL);
175 assert(PyByteArray_Check(self));
176 assert(size >= 0);
177
178 if (size < alloc / 2) {
179 /* Major downsize; resize down to exact size */
180 alloc = size + 1;
181 }
182 else if (size < alloc) {
183 /* Within allocated size; quick exit */
184 Py_SIZE(self) = size;
185 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null */
186 return 0;
187 }
188 else if (size <= alloc * 1.125) {
189 /* Moderate upsize; overallocate similar to list_resize() */
190 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
191 }
192 else {
193 /* Major upsize; resize up to exact size */
194 alloc = size + 1;
195 }
196
197 if (((PyByteArrayObject *)self)->ob_exports > 0) {
198 /*
199 fprintf(stderr, "%d: %s", ((PyByteArrayObject *)self)->ob_exports,
200 ((PyByteArrayObject *)self)->ob_bytes);
201 */
202 PyErr_SetString(PyExc_BufferError,
203 "Existing exports of data: object cannot be re-sized");
204 return -1;
205 }
206
207 sval = PyMem_Realloc(((PyByteArrayObject *)self)->ob_bytes, alloc);
208 if (sval == NULL) {
209 PyErr_NoMemory();
210 return -1;
211 }
212
213 ((PyByteArrayObject *)self)->ob_bytes = sval;
214 Py_SIZE(self) = size;
215 ((PyByteArrayObject *)self)->ob_alloc = alloc;
216 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null byte */
217
218 return 0;
219}
220
221PyObject *
222PyByteArray_Concat(PyObject *a, PyObject *b)
223{
224 Py_ssize_t size;
225 Py_buffer va, vb;
226 PyByteArrayObject *result = NULL;
227
228 va.len = -1;
229 vb.len = -1;
230 if (_getbuffer(a, &va) < 0 ||
231 _getbuffer(b, &vb) < 0) {
232 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
233 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
234 goto done;
235 }
236
237 size = va.len + vb.len;
238 if (size < 0) {
239 return PyErr_NoMemory();
240 goto done;
241 }
242
243 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
244 if (result != NULL) {
245 memcpy(result->ob_bytes, va.buf, va.len);
246 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
247 }
248
249 done:
250 if (va.len != -1)
251 PyObject_ReleaseBuffer(a, &va);
252 if (vb.len != -1)
253 PyObject_ReleaseBuffer(b, &vb);
254 return (PyObject *)result;
255}
256
257/* Functions stuffed into the type object */
258
259static Py_ssize_t
260bytes_length(PyByteArrayObject *self)
261{
262 return Py_SIZE(self);
263}
264
265static PyObject *
266bytes_iconcat(PyByteArrayObject *self, PyObject *other)
267{
268 Py_ssize_t mysize;
269 Py_ssize_t size;
270 Py_buffer vo;
271
272 if (_getbuffer(other, &vo) < 0) {
273 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
274 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
275 return NULL;
276 }
277
278 mysize = Py_SIZE(self);
279 size = mysize + vo.len;
280 if (size < 0) {
281 PyObject_ReleaseBuffer(other, &vo);
282 return PyErr_NoMemory();
283 }
284 if (size < self->ob_alloc) {
285 Py_SIZE(self) = size;
286 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
287 }
288 else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
289 PyObject_ReleaseBuffer(other, &vo);
290 return NULL;
291 }
292 memcpy(self->ob_bytes + mysize, vo.buf, vo.len);
293 PyObject_ReleaseBuffer(other, &vo);
294 Py_INCREF(self);
295 return (PyObject *)self;
296}
297
298static PyObject *
299bytes_repeat(PyByteArrayObject *self, Py_ssize_t count)
300{
301 PyByteArrayObject *result;
302 Py_ssize_t mysize;
303 Py_ssize_t size;
304
305 if (count < 0)
306 count = 0;
307 mysize = Py_SIZE(self);
308 size = mysize * count;
309 if (count != 0 && size / count != mysize)
310 return PyErr_NoMemory();
311 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
312 if (result != NULL && size != 0) {
313 if (mysize == 1)
314 memset(result->ob_bytes, self->ob_bytes[0], size);
315 else {
316 Py_ssize_t i;
317 for (i = 0; i < count; i++)
318 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
319 }
320 }
321 return (PyObject *)result;
322}
323
324static PyObject *
325bytes_irepeat(PyByteArrayObject *self, Py_ssize_t count)
326{
327 Py_ssize_t mysize;
328 Py_ssize_t size;
329
330 if (count < 0)
331 count = 0;
332 mysize = Py_SIZE(self);
333 size = mysize * count;
334 if (count != 0 && size / count != mysize)
335 return PyErr_NoMemory();
336 if (size < self->ob_alloc) {
337 Py_SIZE(self) = size;
338 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
339 }
340 else if (PyByteArray_Resize((PyObject *)self, size) < 0)
341 return NULL;
342
343 if (mysize == 1)
344 memset(self->ob_bytes, self->ob_bytes[0], size);
345 else {
346 Py_ssize_t i;
347 for (i = 1; i < count; i++)
348 memcpy(self->ob_bytes + i*mysize, self->ob_bytes, mysize);
349 }
350
351 Py_INCREF(self);
352 return (PyObject *)self;
353}
354
355static PyObject *
356bytes_getitem(PyByteArrayObject *self, Py_ssize_t i)
357{
358 if (i < 0)
359 i += Py_SIZE(self);
360 if (i < 0 || i >= Py_SIZE(self)) {
361 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
362 return NULL;
363 }
364 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
365}
366
367static PyObject *
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000368bytes_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000369{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000370 if (PyIndex_Check(index)) {
371 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000372
373 if (i == -1 && PyErr_Occurred())
374 return NULL;
375
376 if (i < 0)
377 i += PyByteArray_GET_SIZE(self);
378
379 if (i < 0 || i >= Py_SIZE(self)) {
380 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
381 return NULL;
382 }
383 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
384 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000385 else if (PySlice_Check(index)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000386 Py_ssize_t start, stop, step, slicelength, cur, i;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000387 if (PySlice_GetIndicesEx((PySliceObject *)index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000388 PyByteArray_GET_SIZE(self),
389 &start, &stop, &step, &slicelength) < 0) {
390 return NULL;
391 }
392
393 if (slicelength <= 0)
394 return PyByteArray_FromStringAndSize("", 0);
395 else if (step == 1) {
396 return PyByteArray_FromStringAndSize(self->ob_bytes + start,
397 slicelength);
398 }
399 else {
400 char *source_buf = PyByteArray_AS_STRING(self);
401 char *result_buf = (char *)PyMem_Malloc(slicelength);
402 PyObject *result;
403
404 if (result_buf == NULL)
405 return PyErr_NoMemory();
406
407 for (cur = start, i = 0; i < slicelength;
408 cur += step, i++) {
409 result_buf[i] = source_buf[cur];
410 }
411 result = PyByteArray_FromStringAndSize(result_buf, slicelength);
412 PyMem_Free(result_buf);
413 return result;
414 }
415 }
416 else {
417 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integers");
418 return NULL;
419 }
420}
421
422static int
423bytes_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
424 PyObject *values)
425{
426 Py_ssize_t avail, needed;
427 void *bytes;
428 Py_buffer vbytes;
429 int res = 0;
430
431 vbytes.len = -1;
432 if (values == (PyObject *)self) {
433 /* Make a copy and call this function recursively */
434 int err;
435 values = PyByteArray_FromObject(values);
436 if (values == NULL)
437 return -1;
438 err = bytes_setslice(self, lo, hi, values);
439 Py_DECREF(values);
440 return err;
441 }
442 if (values == NULL) {
443 /* del b[lo:hi] */
444 bytes = NULL;
445 needed = 0;
446 }
447 else {
448 if (_getbuffer(values, &vbytes) < 0) {
449 PyErr_Format(PyExc_TypeError,
Georg Brandl3dbca812008-07-23 16:10:53 +0000450 "can't set bytearray slice from %.100s",
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000451 Py_TYPE(values)->tp_name);
452 return -1;
453 }
454 needed = vbytes.len;
455 bytes = vbytes.buf;
456 }
457
458 if (lo < 0)
459 lo = 0;
460 if (hi < lo)
461 hi = lo;
462 if (hi > Py_SIZE(self))
463 hi = Py_SIZE(self);
464
465 avail = hi - lo;
466 if (avail < 0)
467 lo = hi = avail = 0;
468
469 if (avail != needed) {
470 if (avail > needed) {
471 /*
472 0 lo hi old_size
473 | |<----avail----->|<-----tomove------>|
474 | |<-needed->|<-----tomove------>|
475 0 lo new_hi new_size
476 */
477 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
478 Py_SIZE(self) - hi);
479 }
480 /* XXX(nnorwitz): need to verify this can't overflow! */
481 if (PyByteArray_Resize((PyObject *)self,
482 Py_SIZE(self) + needed - avail) < 0) {
483 res = -1;
484 goto finish;
485 }
486 if (avail < needed) {
487 /*
488 0 lo hi old_size
489 | |<-avail->|<-----tomove------>|
490 | |<----needed---->|<-----tomove------>|
491 0 lo new_hi new_size
492 */
493 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
494 Py_SIZE(self) - lo - needed);
495 }
496 }
497
498 if (needed > 0)
499 memcpy(self->ob_bytes + lo, bytes, needed);
500
501
502 finish:
503 if (vbytes.len != -1)
504 PyObject_ReleaseBuffer(values, &vbytes);
505 return res;
506}
507
508static int
509bytes_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
510{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000511 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000512
513 if (i < 0)
514 i += Py_SIZE(self);
515
516 if (i < 0 || i >= Py_SIZE(self)) {
517 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
518 return -1;
519 }
520
521 if (value == NULL)
522 return bytes_setslice(self, i, i+1, NULL);
523
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000524 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000525 return -1;
526
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000527 self->ob_bytes[i] = ival;
528 return 0;
529}
530
531static int
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000532bytes_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000533{
534 Py_ssize_t start, stop, step, slicelen, needed;
535 char *bytes;
536
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000537 if (PyIndex_Check(index)) {
538 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000539
540 if (i == -1 && PyErr_Occurred())
541 return -1;
542
543 if (i < 0)
544 i += PyByteArray_GET_SIZE(self);
545
546 if (i < 0 || i >= Py_SIZE(self)) {
547 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
548 return -1;
549 }
550
551 if (values == NULL) {
552 /* Fall through to slice assignment */
553 start = i;
554 stop = i + 1;
555 step = 1;
556 slicelen = 1;
557 }
558 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000559 int ival;
560 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000561 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000562 self->ob_bytes[i] = (char)ival;
563 return 0;
564 }
565 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000566 else if (PySlice_Check(index)) {
567 if (PySlice_GetIndicesEx((PySliceObject *)index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000568 PyByteArray_GET_SIZE(self),
569 &start, &stop, &step, &slicelen) < 0) {
570 return -1;
571 }
572 }
573 else {
574 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integer");
575 return -1;
576 }
577
578 if (values == NULL) {
579 bytes = NULL;
580 needed = 0;
581 }
582 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
583 /* Make a copy an call this function recursively */
584 int err;
585 values = PyByteArray_FromObject(values);
586 if (values == NULL)
587 return -1;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000588 err = bytes_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000589 Py_DECREF(values);
590 return err;
591 }
592 else {
593 assert(PyByteArray_Check(values));
594 bytes = ((PyByteArrayObject *)values)->ob_bytes;
595 needed = Py_SIZE(values);
596 }
597 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
598 if ((step < 0 && start < stop) ||
599 (step > 0 && start > stop))
600 stop = start;
601 if (step == 1) {
602 if (slicelen != needed) {
603 if (slicelen > needed) {
604 /*
605 0 start stop old_size
606 | |<---slicelen--->|<-----tomove------>|
607 | |<-needed->|<-----tomove------>|
608 0 lo new_hi new_size
609 */
610 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
611 Py_SIZE(self) - stop);
612 }
613 if (PyByteArray_Resize((PyObject *)self,
614 Py_SIZE(self) + needed - slicelen) < 0)
615 return -1;
616 if (slicelen < needed) {
617 /*
618 0 lo hi old_size
619 | |<-avail->|<-----tomove------>|
620 | |<----needed---->|<-----tomove------>|
621 0 lo new_hi new_size
622 */
623 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
624 Py_SIZE(self) - start - needed);
625 }
626 }
627
628 if (needed > 0)
629 memcpy(self->ob_bytes + start, bytes, needed);
630
631 return 0;
632 }
633 else {
634 if (needed == 0) {
635 /* Delete slice */
636 Py_ssize_t cur, i;
637
638 if (step < 0) {
639 stop = start + 1;
640 start = stop + step * (slicelen - 1) - 1;
641 step = -step;
642 }
643 for (cur = start, i = 0;
644 i < slicelen; cur += step, i++) {
645 Py_ssize_t lim = step - 1;
646
647 if (cur + step >= PyByteArray_GET_SIZE(self))
648 lim = PyByteArray_GET_SIZE(self) - cur - 1;
649
650 memmove(self->ob_bytes + cur - i,
651 self->ob_bytes + cur + 1, lim);
652 }
653 /* Move the tail of the bytes, in one chunk */
654 cur = start + slicelen*step;
655 if (cur < PyByteArray_GET_SIZE(self)) {
656 memmove(self->ob_bytes + cur - slicelen,
657 self->ob_bytes + cur,
658 PyByteArray_GET_SIZE(self) - cur);
659 }
660 if (PyByteArray_Resize((PyObject *)self,
661 PyByteArray_GET_SIZE(self) - slicelen) < 0)
662 return -1;
663
664 return 0;
665 }
666 else {
667 /* Assign slice */
668 Py_ssize_t cur, i;
669
670 if (needed != slicelen) {
671 PyErr_Format(PyExc_ValueError,
672 "attempt to assign bytes of size %zd "
673 "to extended slice of size %zd",
674 needed, slicelen);
675 return -1;
676 }
677 for (cur = start, i = 0; i < slicelen; cur += step, i++)
678 self->ob_bytes[cur] = bytes[i];
679 return 0;
680 }
681 }
682}
683
684static int
685bytes_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
686{
687 static char *kwlist[] = {"source", "encoding", "errors", 0};
688 PyObject *arg = NULL;
689 const char *encoding = NULL;
690 const char *errors = NULL;
691 Py_ssize_t count;
692 PyObject *it;
693 PyObject *(*iternext)(PyObject *);
694
695 if (Py_SIZE(self) != 0) {
696 /* Empty previous contents (yes, do this first of all!) */
697 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
698 return -1;
699 }
700
701 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000702 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000703 &arg, &encoding, &errors))
704 return -1;
705
706 /* Make a quick exit if no first argument */
707 if (arg == NULL) {
708 if (encoding != NULL || errors != NULL) {
709 PyErr_SetString(PyExc_TypeError,
710 "encoding or errors without sequence argument");
711 return -1;
712 }
713 return 0;
714 }
715
716 if (PyUnicode_Check(arg)) {
717 /* Encode via the codec registry */
718 PyObject *encoded, *new;
719 if (encoding == NULL) {
720 PyErr_SetString(PyExc_TypeError,
721 "string argument without an encoding");
722 return -1;
723 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000724 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000725 if (encoded == NULL)
726 return -1;
727 assert(PyBytes_Check(encoded));
728 new = bytes_iconcat(self, encoded);
729 Py_DECREF(encoded);
730 if (new == NULL)
731 return -1;
732 Py_DECREF(new);
733 return 0;
734 }
735
736 /* If it's not unicode, there can't be encoding or errors */
737 if (encoding != NULL || errors != NULL) {
738 PyErr_SetString(PyExc_TypeError,
739 "encoding or errors without a string argument");
740 return -1;
741 }
742
743 /* Is it an int? */
744 count = PyNumber_AsSsize_t(arg, PyExc_ValueError);
745 if (count == -1 && PyErr_Occurred())
746 PyErr_Clear();
747 else {
748 if (count < 0) {
749 PyErr_SetString(PyExc_ValueError, "negative count");
750 return -1;
751 }
752 if (count > 0) {
753 if (PyByteArray_Resize((PyObject *)self, count))
754 return -1;
755 memset(self->ob_bytes, 0, count);
756 }
757 return 0;
758 }
759
760 /* Use the buffer API */
761 if (PyObject_CheckBuffer(arg)) {
762 Py_ssize_t size;
763 Py_buffer view;
764 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
765 return -1;
766 size = view.len;
767 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
768 if (PyBuffer_ToContiguous(self->ob_bytes, &view, size, 'C') < 0)
769 goto fail;
770 PyObject_ReleaseBuffer(arg, &view);
771 return 0;
772 fail:
773 PyObject_ReleaseBuffer(arg, &view);
774 return -1;
775 }
776
777 /* XXX Optimize this if the arguments is a list, tuple */
778
779 /* Get the iterator */
780 it = PyObject_GetIter(arg);
781 if (it == NULL)
782 return -1;
783 iternext = *Py_TYPE(it)->tp_iternext;
784
785 /* Run the iterator to exhaustion */
786 for (;;) {
787 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000788 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000789
790 /* Get the next item */
791 item = iternext(it);
792 if (item == NULL) {
793 if (PyErr_Occurred()) {
794 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
795 goto error;
796 PyErr_Clear();
797 }
798 break;
799 }
800
801 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000802 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000803 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000804 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000805 goto error;
806
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000807 /* Append the byte */
808 if (Py_SIZE(self) < self->ob_alloc)
809 Py_SIZE(self)++;
810 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
811 goto error;
812 self->ob_bytes[Py_SIZE(self)-1] = value;
813 }
814
815 /* Clean up and return success */
816 Py_DECREF(it);
817 return 0;
818
819 error:
820 /* Error handling when it != NULL */
821 Py_DECREF(it);
822 return -1;
823}
824
825/* Mostly copied from string_repr, but without the
826 "smart quote" functionality. */
827static PyObject *
828bytes_repr(PyByteArrayObject *self)
829{
830 static const char *hexdigits = "0123456789abcdef";
831 const char *quote_prefix = "bytearray(b";
832 const char *quote_postfix = ")";
833 Py_ssize_t length = Py_SIZE(self);
834 /* 14 == strlen(quote_prefix) + 2 + strlen(quote_postfix) */
835 size_t newsize = 14 + 4 * length;
836 PyObject *v;
837 if (newsize > PY_SSIZE_T_MAX || newsize / 4 - 3 != length) {
838 PyErr_SetString(PyExc_OverflowError,
839 "bytearray object is too large to make repr");
840 return NULL;
841 }
842 v = PyUnicode_FromUnicode(NULL, newsize);
843 if (v == NULL) {
844 return NULL;
845 }
846 else {
847 register Py_ssize_t i;
848 register Py_UNICODE c;
849 register Py_UNICODE *p;
850 int quote;
851
852 /* Figure out which quote to use; single is preferred */
853 quote = '\'';
854 {
855 char *test, *start;
856 start = PyByteArray_AS_STRING(self);
857 for (test = start; test < start+length; ++test) {
858 if (*test == '"') {
859 quote = '\''; /* back to single */
860 goto decided;
861 }
862 else if (*test == '\'')
863 quote = '"';
864 }
865 decided:
866 ;
867 }
868
869 p = PyUnicode_AS_UNICODE(v);
870 while (*quote_prefix)
871 *p++ = *quote_prefix++;
872 *p++ = quote;
873
874 for (i = 0; i < length; i++) {
875 /* There's at least enough room for a hex escape
876 and a closing quote. */
877 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5);
878 c = self->ob_bytes[i];
879 if (c == '\'' || c == '\\')
880 *p++ = '\\', *p++ = c;
881 else if (c == '\t')
882 *p++ = '\\', *p++ = 't';
883 else if (c == '\n')
884 *p++ = '\\', *p++ = 'n';
885 else if (c == '\r')
886 *p++ = '\\', *p++ = 'r';
887 else if (c == 0)
888 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
889 else if (c < ' ' || c >= 0x7f) {
890 *p++ = '\\';
891 *p++ = 'x';
892 *p++ = hexdigits[(c & 0xf0) >> 4];
893 *p++ = hexdigits[c & 0xf];
894 }
895 else
896 *p++ = c;
897 }
898 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1);
899 *p++ = quote;
900 while (*quote_postfix) {
901 *p++ = *quote_postfix++;
902 }
903 *p = '\0';
904 if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) {
905 Py_DECREF(v);
906 return NULL;
907 }
908 return v;
909 }
910}
911
912static PyObject *
913bytes_str(PyObject *op)
914{
915 if (Py_BytesWarningFlag) {
916 if (PyErr_WarnEx(PyExc_BytesWarning,
917 "str() on a bytearray instance", 1))
918 return NULL;
919 }
920 return bytes_repr((PyByteArrayObject*)op);
921}
922
923static PyObject *
924bytes_richcompare(PyObject *self, PyObject *other, int op)
925{
926 Py_ssize_t self_size, other_size;
927 Py_buffer self_bytes, other_bytes;
928 PyObject *res;
929 Py_ssize_t minsize;
930 int cmp;
931
932 /* Bytes can be compared to anything that supports the (binary)
933 buffer API. Except that a comparison with Unicode is always an
934 error, even if the comparison is for equality. */
935 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
936 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
937 if (Py_BytesWarningFlag && op == Py_EQ) {
938 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +0000939 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000940 return NULL;
941 }
942
943 Py_INCREF(Py_NotImplemented);
944 return Py_NotImplemented;
945 }
946
947 self_size = _getbuffer(self, &self_bytes);
948 if (self_size < 0) {
949 PyErr_Clear();
950 Py_INCREF(Py_NotImplemented);
951 return Py_NotImplemented;
952 }
953
954 other_size = _getbuffer(other, &other_bytes);
955 if (other_size < 0) {
956 PyErr_Clear();
957 PyObject_ReleaseBuffer(self, &self_bytes);
958 Py_INCREF(Py_NotImplemented);
959 return Py_NotImplemented;
960 }
961
962 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
963 /* Shortcut: if the lengths differ, the objects differ */
964 cmp = (op == Py_NE);
965 }
966 else {
967 minsize = self_size;
968 if (other_size < minsize)
969 minsize = other_size;
970
971 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
972 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
973
974 if (cmp == 0) {
975 if (self_size < other_size)
976 cmp = -1;
977 else if (self_size > other_size)
978 cmp = 1;
979 }
980
981 switch (op) {
982 case Py_LT: cmp = cmp < 0; break;
983 case Py_LE: cmp = cmp <= 0; break;
984 case Py_EQ: cmp = cmp == 0; break;
985 case Py_NE: cmp = cmp != 0; break;
986 case Py_GT: cmp = cmp > 0; break;
987 case Py_GE: cmp = cmp >= 0; break;
988 }
989 }
990
991 res = cmp ? Py_True : Py_False;
992 PyObject_ReleaseBuffer(self, &self_bytes);
993 PyObject_ReleaseBuffer(other, &other_bytes);
994 Py_INCREF(res);
995 return res;
996}
997
998static void
999bytes_dealloc(PyByteArrayObject *self)
1000{
1001 if (self->ob_bytes != 0) {
1002 PyMem_Free(self->ob_bytes);
1003 }
1004 Py_TYPE(self)->tp_free((PyObject *)self);
1005}
1006
1007
1008/* -------------------------------------------------------------------- */
1009/* Methods */
1010
1011#define STRINGLIB_CHAR char
1012#define STRINGLIB_CMP memcmp
1013#define STRINGLIB_LEN PyByteArray_GET_SIZE
1014#define STRINGLIB_STR PyByteArray_AS_STRING
1015#define STRINGLIB_NEW PyByteArray_FromStringAndSize
1016#define STRINGLIB_EMPTY nullbytes
1017#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1018#define STRINGLIB_MUTABLE 1
1019
1020#include "stringlib/fastsearch.h"
1021#include "stringlib/count.h"
1022#include "stringlib/find.h"
1023#include "stringlib/partition.h"
1024#include "stringlib/ctype.h"
1025#include "stringlib/transmogrify.h"
1026
1027
1028/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1029were copied from the old char* style string object. */
1030
1031Py_LOCAL_INLINE(void)
1032_adjust_indices(Py_ssize_t *start, Py_ssize_t *end, Py_ssize_t len)
1033{
1034 if (*end > len)
1035 *end = len;
1036 else if (*end < 0)
1037 *end += len;
1038 if (*end < 0)
1039 *end = 0;
1040 if (*start < 0)
1041 *start += len;
1042 if (*start < 0)
1043 *start = 0;
1044}
1045
1046
1047Py_LOCAL_INLINE(Py_ssize_t)
1048bytes_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
1049{
1050 PyObject *subobj;
1051 Py_buffer subbuf;
1052 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1053 Py_ssize_t res;
1054
1055 if (!PyArg_ParseTuple(args, "O|O&O&:find/rfind/index/rindex", &subobj,
1056 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1057 return -2;
1058 if (_getbuffer(subobj, &subbuf) < 0)
1059 return -2;
1060 if (dir > 0)
1061 res = stringlib_find_slice(
1062 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1063 subbuf.buf, subbuf.len, start, end);
1064 else
1065 res = stringlib_rfind_slice(
1066 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1067 subbuf.buf, subbuf.len, start, end);
1068 PyObject_ReleaseBuffer(subobj, &subbuf);
1069 return res;
1070}
1071
1072PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001073"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001074\n\
1075Return the lowest index in B where subsection sub is found,\n\
1076such that sub is contained within s[start,end]. Optional\n\
1077arguments start and end are interpreted as in slice notation.\n\
1078\n\
1079Return -1 on failure.");
1080
1081static PyObject *
1082bytes_find(PyByteArrayObject *self, PyObject *args)
1083{
1084 Py_ssize_t result = bytes_find_internal(self, args, +1);
1085 if (result == -2)
1086 return NULL;
1087 return PyLong_FromSsize_t(result);
1088}
1089
1090PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001091"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001092\n\
1093Return the number of non-overlapping occurrences of subsection sub in\n\
1094bytes B[start:end]. Optional arguments start and end are interpreted\n\
1095as in slice notation.");
1096
1097static PyObject *
1098bytes_count(PyByteArrayObject *self, PyObject *args)
1099{
1100 PyObject *sub_obj;
1101 const char *str = PyByteArray_AS_STRING(self);
1102 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
1103 Py_buffer vsub;
1104 PyObject *count_obj;
1105
1106 if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj,
1107 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1108 return NULL;
1109
1110 if (_getbuffer(sub_obj, &vsub) < 0)
1111 return NULL;
1112
1113 _adjust_indices(&start, &end, PyByteArray_GET_SIZE(self));
1114
1115 count_obj = PyLong_FromSsize_t(
1116 stringlib_count(str + start, end - start, vsub.buf, vsub.len)
1117 );
1118 PyObject_ReleaseBuffer(sub_obj, &vsub);
1119 return count_obj;
1120}
1121
1122
1123PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001124"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001125\n\
1126Like B.find() but raise ValueError when the subsection is not found.");
1127
1128static PyObject *
1129bytes_index(PyByteArrayObject *self, PyObject *args)
1130{
1131 Py_ssize_t result = bytes_find_internal(self, args, +1);
1132 if (result == -2)
1133 return NULL;
1134 if (result == -1) {
1135 PyErr_SetString(PyExc_ValueError,
1136 "subsection not found");
1137 return NULL;
1138 }
1139 return PyLong_FromSsize_t(result);
1140}
1141
1142
1143PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001144"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001145\n\
1146Return the highest index in B where subsection sub is found,\n\
1147such that sub is contained within s[start,end]. Optional\n\
1148arguments start and end are interpreted as in slice notation.\n\
1149\n\
1150Return -1 on failure.");
1151
1152static PyObject *
1153bytes_rfind(PyByteArrayObject *self, PyObject *args)
1154{
1155 Py_ssize_t result = bytes_find_internal(self, args, -1);
1156 if (result == -2)
1157 return NULL;
1158 return PyLong_FromSsize_t(result);
1159}
1160
1161
1162PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001163"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001164\n\
1165Like B.rfind() but raise ValueError when the subsection is not found.");
1166
1167static PyObject *
1168bytes_rindex(PyByteArrayObject *self, PyObject *args)
1169{
1170 Py_ssize_t result = bytes_find_internal(self, args, -1);
1171 if (result == -2)
1172 return NULL;
1173 if (result == -1) {
1174 PyErr_SetString(PyExc_ValueError,
1175 "subsection not found");
1176 return NULL;
1177 }
1178 return PyLong_FromSsize_t(result);
1179}
1180
1181
1182static int
1183bytes_contains(PyObject *self, PyObject *arg)
1184{
1185 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1186 if (ival == -1 && PyErr_Occurred()) {
1187 Py_buffer varg;
1188 int pos;
1189 PyErr_Clear();
1190 if (_getbuffer(arg, &varg) < 0)
1191 return -1;
1192 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1193 varg.buf, varg.len, 0);
1194 PyObject_ReleaseBuffer(arg, &varg);
1195 return pos >= 0;
1196 }
1197 if (ival < 0 || ival >= 256) {
1198 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1199 return -1;
1200 }
1201
1202 return memchr(PyByteArray_AS_STRING(self), ival, Py_SIZE(self)) != NULL;
1203}
1204
1205
1206/* Matches the end (direction >= 0) or start (direction < 0) of self
1207 * against substr, using the start and end arguments. Returns
1208 * -1 on error, 0 if not found and 1 if found.
1209 */
1210Py_LOCAL(int)
1211_bytes_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
1212 Py_ssize_t end, int direction)
1213{
1214 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1215 const char* str;
1216 Py_buffer vsubstr;
1217 int rv = 0;
1218
1219 str = PyByteArray_AS_STRING(self);
1220
1221 if (_getbuffer(substr, &vsubstr) < 0)
1222 return -1;
1223
1224 _adjust_indices(&start, &end, len);
1225
1226 if (direction < 0) {
1227 /* startswith */
1228 if (start+vsubstr.len > len) {
1229 goto done;
1230 }
1231 } else {
1232 /* endswith */
1233 if (end-start < vsubstr.len || start > len) {
1234 goto done;
1235 }
1236
1237 if (end-vsubstr.len > start)
1238 start = end - vsubstr.len;
1239 }
1240 if (end-start >= vsubstr.len)
1241 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1242
1243done:
1244 PyObject_ReleaseBuffer(substr, &vsubstr);
1245 return rv;
1246}
1247
1248
1249PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001250"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001251\n\
1252Return True if B starts with the specified prefix, False otherwise.\n\
1253With optional start, test B beginning at that position.\n\
1254With optional end, stop comparing B at that position.\n\
1255prefix can also be a tuple of strings to try.");
1256
1257static PyObject *
1258bytes_startswith(PyByteArrayObject *self, PyObject *args)
1259{
1260 Py_ssize_t start = 0;
1261 Py_ssize_t end = PY_SSIZE_T_MAX;
1262 PyObject *subobj;
1263 int result;
1264
1265 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
1266 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1267 return NULL;
1268 if (PyTuple_Check(subobj)) {
1269 Py_ssize_t i;
1270 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
1271 result = _bytes_tailmatch(self,
1272 PyTuple_GET_ITEM(subobj, i),
1273 start, end, -1);
1274 if (result == -1)
1275 return NULL;
1276 else if (result) {
1277 Py_RETURN_TRUE;
1278 }
1279 }
1280 Py_RETURN_FALSE;
1281 }
1282 result = _bytes_tailmatch(self, subobj, start, end, -1);
1283 if (result == -1)
1284 return NULL;
1285 else
1286 return PyBool_FromLong(result);
1287}
1288
1289PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001290"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001291\n\
1292Return True if B ends with the specified suffix, False otherwise.\n\
1293With optional start, test B beginning at that position.\n\
1294With optional end, stop comparing B at that position.\n\
1295suffix can also be a tuple of strings to try.");
1296
1297static PyObject *
1298bytes_endswith(PyByteArrayObject *self, PyObject *args)
1299{
1300 Py_ssize_t start = 0;
1301 Py_ssize_t end = PY_SSIZE_T_MAX;
1302 PyObject *subobj;
1303 int result;
1304
1305 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
1306 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1307 return NULL;
1308 if (PyTuple_Check(subobj)) {
1309 Py_ssize_t i;
1310 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
1311 result = _bytes_tailmatch(self,
1312 PyTuple_GET_ITEM(subobj, i),
1313 start, end, +1);
1314 if (result == -1)
1315 return NULL;
1316 else if (result) {
1317 Py_RETURN_TRUE;
1318 }
1319 }
1320 Py_RETURN_FALSE;
1321 }
1322 result = _bytes_tailmatch(self, subobj, start, end, +1);
1323 if (result == -1)
1324 return NULL;
1325 else
1326 return PyBool_FromLong(result);
1327}
1328
1329
1330PyDoc_STRVAR(translate__doc__,
1331"B.translate(table[, deletechars]) -> bytearray\n\
1332\n\
1333Return a copy of B, where all characters occurring in the\n\
1334optional argument deletechars are removed, and the remaining\n\
1335characters have been mapped through the given translation\n\
1336table, which must be a bytes object of length 256.");
1337
1338static PyObject *
1339bytes_translate(PyByteArrayObject *self, PyObject *args)
1340{
1341 register char *input, *output;
1342 register const char *table;
1343 register Py_ssize_t i, c, changed = 0;
1344 PyObject *input_obj = (PyObject*)self;
1345 const char *output_start;
1346 Py_ssize_t inlen;
1347 PyObject *result;
1348 int trans_table[256];
1349 PyObject *tableobj, *delobj = NULL;
1350 Py_buffer vtable, vdel;
1351
1352 if (!PyArg_UnpackTuple(args, "translate", 1, 2,
1353 &tableobj, &delobj))
1354 return NULL;
1355
1356 if (_getbuffer(tableobj, &vtable) < 0)
1357 return NULL;
1358
1359 if (vtable.len != 256) {
1360 PyErr_SetString(PyExc_ValueError,
1361 "translation table must be 256 characters long");
1362 result = NULL;
1363 goto done;
1364 }
1365
1366 if (delobj != NULL) {
1367 if (_getbuffer(delobj, &vdel) < 0) {
1368 result = NULL;
1369 goto done;
1370 }
1371 }
1372 else {
1373 vdel.buf = NULL;
1374 vdel.len = 0;
1375 }
1376
1377 table = (const char *)vtable.buf;
1378 inlen = PyByteArray_GET_SIZE(input_obj);
1379 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1380 if (result == NULL)
1381 goto done;
1382 output_start = output = PyByteArray_AsString(result);
1383 input = PyByteArray_AS_STRING(input_obj);
1384
1385 if (vdel.len == 0) {
1386 /* If no deletions are required, use faster code */
1387 for (i = inlen; --i >= 0; ) {
1388 c = Py_CHARMASK(*input++);
1389 if (Py_CHARMASK((*output++ = table[c])) != c)
1390 changed = 1;
1391 }
1392 if (changed || !PyByteArray_CheckExact(input_obj))
1393 goto done;
1394 Py_DECREF(result);
1395 Py_INCREF(input_obj);
1396 result = input_obj;
1397 goto done;
1398 }
1399
1400 for (i = 0; i < 256; i++)
1401 trans_table[i] = Py_CHARMASK(table[i]);
1402
1403 for (i = 0; i < vdel.len; i++)
1404 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1405
1406 for (i = inlen; --i >= 0; ) {
1407 c = Py_CHARMASK(*input++);
1408 if (trans_table[c] != -1)
1409 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1410 continue;
1411 changed = 1;
1412 }
1413 if (!changed && PyByteArray_CheckExact(input_obj)) {
1414 Py_DECREF(result);
1415 Py_INCREF(input_obj);
1416 result = input_obj;
1417 goto done;
1418 }
1419 /* Fix the size of the resulting string */
1420 if (inlen > 0)
1421 PyByteArray_Resize(result, output - output_start);
1422
1423done:
1424 PyObject_ReleaseBuffer(tableobj, &vtable);
1425 if (delobj != NULL)
1426 PyObject_ReleaseBuffer(delobj, &vdel);
1427 return result;
1428}
1429
1430
1431#define FORWARD 1
1432#define REVERSE -1
1433
1434/* find and count characters and substrings */
1435
1436#define findchar(target, target_len, c) \
1437 ((char *)memchr((const void *)(target), c, target_len))
1438
1439/* Don't call if length < 2 */
1440#define Py_STRING_MATCH(target, offset, pattern, length) \
1441 (target[offset] == pattern[0] && \
1442 target[offset+length-1] == pattern[length-1] && \
1443 !memcmp(target+offset+1, pattern+1, length-2) )
1444
1445
1446/* Bytes ops must return a string. */
1447/* If the object is subclass of bytes, create a copy */
1448Py_LOCAL(PyByteArrayObject *)
1449return_self(PyByteArrayObject *self)
1450{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001451 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001452 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1453 PyByteArray_AS_STRING(self),
1454 PyByteArray_GET_SIZE(self));
1455}
1456
1457Py_LOCAL_INLINE(Py_ssize_t)
1458countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1459{
1460 Py_ssize_t count=0;
1461 const char *start=target;
1462 const char *end=target+target_len;
1463
1464 while ( (start=findchar(start, end-start, c)) != NULL ) {
1465 count++;
1466 if (count >= maxcount)
1467 break;
1468 start += 1;
1469 }
1470 return count;
1471}
1472
1473Py_LOCAL(Py_ssize_t)
1474findstring(const char *target, Py_ssize_t target_len,
1475 const char *pattern, Py_ssize_t pattern_len,
1476 Py_ssize_t start,
1477 Py_ssize_t end,
1478 int direction)
1479{
1480 if (start < 0) {
1481 start += target_len;
1482 if (start < 0)
1483 start = 0;
1484 }
1485 if (end > target_len) {
1486 end = target_len;
1487 } else if (end < 0) {
1488 end += target_len;
1489 if (end < 0)
1490 end = 0;
1491 }
1492
1493 /* zero-length substrings always match at the first attempt */
1494 if (pattern_len == 0)
1495 return (direction > 0) ? start : end;
1496
1497 end -= pattern_len;
1498
1499 if (direction < 0) {
1500 for (; end >= start; end--)
1501 if (Py_STRING_MATCH(target, end, pattern, pattern_len))
1502 return end;
1503 } else {
1504 for (; start <= end; start++)
1505 if (Py_STRING_MATCH(target, start, pattern, pattern_len))
1506 return start;
1507 }
1508 return -1;
1509}
1510
1511Py_LOCAL_INLINE(Py_ssize_t)
1512countstring(const char *target, Py_ssize_t target_len,
1513 const char *pattern, Py_ssize_t pattern_len,
1514 Py_ssize_t start,
1515 Py_ssize_t end,
1516 int direction, Py_ssize_t maxcount)
1517{
1518 Py_ssize_t count=0;
1519
1520 if (start < 0) {
1521 start += target_len;
1522 if (start < 0)
1523 start = 0;
1524 }
1525 if (end > target_len) {
1526 end = target_len;
1527 } else if (end < 0) {
1528 end += target_len;
1529 if (end < 0)
1530 end = 0;
1531 }
1532
1533 /* zero-length substrings match everywhere */
1534 if (pattern_len == 0 || maxcount == 0) {
1535 if (target_len+1 < maxcount)
1536 return target_len+1;
1537 return maxcount;
1538 }
1539
1540 end -= pattern_len;
1541 if (direction < 0) {
1542 for (; (end >= start); end--)
1543 if (Py_STRING_MATCH(target, end, pattern, pattern_len)) {
1544 count++;
1545 if (--maxcount <= 0) break;
1546 end -= pattern_len-1;
1547 }
1548 } else {
1549 for (; (start <= end); start++)
1550 if (Py_STRING_MATCH(target, start, pattern, pattern_len)) {
1551 count++;
1552 if (--maxcount <= 0)
1553 break;
1554 start += pattern_len-1;
1555 }
1556 }
1557 return count;
1558}
1559
1560
1561/* Algorithms for different cases of string replacement */
1562
1563/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1564Py_LOCAL(PyByteArrayObject *)
1565replace_interleave(PyByteArrayObject *self,
1566 const char *to_s, Py_ssize_t to_len,
1567 Py_ssize_t maxcount)
1568{
1569 char *self_s, *result_s;
1570 Py_ssize_t self_len, result_len;
1571 Py_ssize_t count, i, product;
1572 PyByteArrayObject *result;
1573
1574 self_len = PyByteArray_GET_SIZE(self);
1575
1576 /* 1 at the end plus 1 after every character */
1577 count = self_len+1;
1578 if (maxcount < count)
1579 count = maxcount;
1580
1581 /* Check for overflow */
1582 /* result_len = count * to_len + self_len; */
1583 product = count * to_len;
1584 if (product / to_len != count) {
1585 PyErr_SetString(PyExc_OverflowError,
1586 "replace string is too long");
1587 return NULL;
1588 }
1589 result_len = product + self_len;
1590 if (result_len < 0) {
1591 PyErr_SetString(PyExc_OverflowError,
1592 "replace string is too long");
1593 return NULL;
1594 }
1595
1596 if (! (result = (PyByteArrayObject *)
1597 PyByteArray_FromStringAndSize(NULL, result_len)) )
1598 return NULL;
1599
1600 self_s = PyByteArray_AS_STRING(self);
1601 result_s = PyByteArray_AS_STRING(result);
1602
1603 /* TODO: special case single character, which doesn't need memcpy */
1604
1605 /* Lay the first one down (guaranteed this will occur) */
1606 Py_MEMCPY(result_s, to_s, to_len);
1607 result_s += to_len;
1608 count -= 1;
1609
1610 for (i=0; i<count; i++) {
1611 *result_s++ = *self_s++;
1612 Py_MEMCPY(result_s, to_s, to_len);
1613 result_s += to_len;
1614 }
1615
1616 /* Copy the rest of the original string */
1617 Py_MEMCPY(result_s, self_s, self_len-i);
1618
1619 return result;
1620}
1621
1622/* Special case for deleting a single character */
1623/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1624Py_LOCAL(PyByteArrayObject *)
1625replace_delete_single_character(PyByteArrayObject *self,
1626 char from_c, Py_ssize_t maxcount)
1627{
1628 char *self_s, *result_s;
1629 char *start, *next, *end;
1630 Py_ssize_t self_len, result_len;
1631 Py_ssize_t count;
1632 PyByteArrayObject *result;
1633
1634 self_len = PyByteArray_GET_SIZE(self);
1635 self_s = PyByteArray_AS_STRING(self);
1636
1637 count = countchar(self_s, self_len, from_c, maxcount);
1638 if (count == 0) {
1639 return return_self(self);
1640 }
1641
1642 result_len = self_len - count; /* from_len == 1 */
1643 assert(result_len>=0);
1644
1645 if ( (result = (PyByteArrayObject *)
1646 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1647 return NULL;
1648 result_s = PyByteArray_AS_STRING(result);
1649
1650 start = self_s;
1651 end = self_s + self_len;
1652 while (count-- > 0) {
1653 next = findchar(start, end-start, from_c);
1654 if (next == NULL)
1655 break;
1656 Py_MEMCPY(result_s, start, next-start);
1657 result_s += (next-start);
1658 start = next+1;
1659 }
1660 Py_MEMCPY(result_s, start, end-start);
1661
1662 return result;
1663}
1664
1665/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1666
1667Py_LOCAL(PyByteArrayObject *)
1668replace_delete_substring(PyByteArrayObject *self,
1669 const char *from_s, Py_ssize_t from_len,
1670 Py_ssize_t maxcount)
1671{
1672 char *self_s, *result_s;
1673 char *start, *next, *end;
1674 Py_ssize_t self_len, result_len;
1675 Py_ssize_t count, offset;
1676 PyByteArrayObject *result;
1677
1678 self_len = PyByteArray_GET_SIZE(self);
1679 self_s = PyByteArray_AS_STRING(self);
1680
1681 count = countstring(self_s, self_len,
1682 from_s, from_len,
1683 0, self_len, 1,
1684 maxcount);
1685
1686 if (count == 0) {
1687 /* no matches */
1688 return return_self(self);
1689 }
1690
1691 result_len = self_len - (count * from_len);
1692 assert (result_len>=0);
1693
1694 if ( (result = (PyByteArrayObject *)
1695 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1696 return NULL;
1697
1698 result_s = PyByteArray_AS_STRING(result);
1699
1700 start = self_s;
1701 end = self_s + self_len;
1702 while (count-- > 0) {
1703 offset = findstring(start, end-start,
1704 from_s, from_len,
1705 0, end-start, FORWARD);
1706 if (offset == -1)
1707 break;
1708 next = start + offset;
1709
1710 Py_MEMCPY(result_s, start, next-start);
1711
1712 result_s += (next-start);
1713 start = next+from_len;
1714 }
1715 Py_MEMCPY(result_s, start, end-start);
1716 return result;
1717}
1718
1719/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1720Py_LOCAL(PyByteArrayObject *)
1721replace_single_character_in_place(PyByteArrayObject *self,
1722 char from_c, char to_c,
1723 Py_ssize_t maxcount)
1724{
1725 char *self_s, *result_s, *start, *end, *next;
1726 Py_ssize_t self_len;
1727 PyByteArrayObject *result;
1728
1729 /* The result string will be the same size */
1730 self_s = PyByteArray_AS_STRING(self);
1731 self_len = PyByteArray_GET_SIZE(self);
1732
1733 next = findchar(self_s, self_len, from_c);
1734
1735 if (next == NULL) {
1736 /* No matches; return the original bytes */
1737 return return_self(self);
1738 }
1739
1740 /* Need to make a new bytes */
1741 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1742 if (result == NULL)
1743 return NULL;
1744 result_s = PyByteArray_AS_STRING(result);
1745 Py_MEMCPY(result_s, self_s, self_len);
1746
1747 /* change everything in-place, starting with this one */
1748 start = result_s + (next-self_s);
1749 *start = to_c;
1750 start++;
1751 end = result_s + self_len;
1752
1753 while (--maxcount > 0) {
1754 next = findchar(start, end-start, from_c);
1755 if (next == NULL)
1756 break;
1757 *next = to_c;
1758 start = next+1;
1759 }
1760
1761 return result;
1762}
1763
1764/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1765Py_LOCAL(PyByteArrayObject *)
1766replace_substring_in_place(PyByteArrayObject *self,
1767 const char *from_s, Py_ssize_t from_len,
1768 const char *to_s, Py_ssize_t to_len,
1769 Py_ssize_t maxcount)
1770{
1771 char *result_s, *start, *end;
1772 char *self_s;
1773 Py_ssize_t self_len, offset;
1774 PyByteArrayObject *result;
1775
1776 /* The result bytes will be the same size */
1777
1778 self_s = PyByteArray_AS_STRING(self);
1779 self_len = PyByteArray_GET_SIZE(self);
1780
1781 offset = findstring(self_s, self_len,
1782 from_s, from_len,
1783 0, self_len, FORWARD);
1784 if (offset == -1) {
1785 /* No matches; return the original bytes */
1786 return return_self(self);
1787 }
1788
1789 /* Need to make a new bytes */
1790 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1791 if (result == NULL)
1792 return NULL;
1793 result_s = PyByteArray_AS_STRING(result);
1794 Py_MEMCPY(result_s, self_s, self_len);
1795
1796 /* change everything in-place, starting with this one */
1797 start = result_s + offset;
1798 Py_MEMCPY(start, to_s, from_len);
1799 start += from_len;
1800 end = result_s + self_len;
1801
1802 while ( --maxcount > 0) {
1803 offset = findstring(start, end-start,
1804 from_s, from_len,
1805 0, end-start, FORWARD);
1806 if (offset==-1)
1807 break;
1808 Py_MEMCPY(start+offset, to_s, from_len);
1809 start += offset+from_len;
1810 }
1811
1812 return result;
1813}
1814
1815/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
1816Py_LOCAL(PyByteArrayObject *)
1817replace_single_character(PyByteArrayObject *self,
1818 char from_c,
1819 const char *to_s, Py_ssize_t to_len,
1820 Py_ssize_t maxcount)
1821{
1822 char *self_s, *result_s;
1823 char *start, *next, *end;
1824 Py_ssize_t self_len, result_len;
1825 Py_ssize_t count, product;
1826 PyByteArrayObject *result;
1827
1828 self_s = PyByteArray_AS_STRING(self);
1829 self_len = PyByteArray_GET_SIZE(self);
1830
1831 count = countchar(self_s, self_len, from_c, maxcount);
1832 if (count == 0) {
1833 /* no matches, return unchanged */
1834 return return_self(self);
1835 }
1836
1837 /* use the difference between current and new, hence the "-1" */
1838 /* result_len = self_len + count * (to_len-1) */
1839 product = count * (to_len-1);
1840 if (product / (to_len-1) != count) {
1841 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1842 return NULL;
1843 }
1844 result_len = self_len + product;
1845 if (result_len < 0) {
1846 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1847 return NULL;
1848 }
1849
1850 if ( (result = (PyByteArrayObject *)
1851 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1852 return NULL;
1853 result_s = PyByteArray_AS_STRING(result);
1854
1855 start = self_s;
1856 end = self_s + self_len;
1857 while (count-- > 0) {
1858 next = findchar(start, end-start, from_c);
1859 if (next == NULL)
1860 break;
1861
1862 if (next == start) {
1863 /* replace with the 'to' */
1864 Py_MEMCPY(result_s, to_s, to_len);
1865 result_s += to_len;
1866 start += 1;
1867 } else {
1868 /* copy the unchanged old then the 'to' */
1869 Py_MEMCPY(result_s, start, next-start);
1870 result_s += (next-start);
1871 Py_MEMCPY(result_s, to_s, to_len);
1872 result_s += to_len;
1873 start = next+1;
1874 }
1875 }
1876 /* Copy the remainder of the remaining bytes */
1877 Py_MEMCPY(result_s, start, end-start);
1878
1879 return result;
1880}
1881
1882/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
1883Py_LOCAL(PyByteArrayObject *)
1884replace_substring(PyByteArrayObject *self,
1885 const char *from_s, Py_ssize_t from_len,
1886 const char *to_s, Py_ssize_t to_len,
1887 Py_ssize_t maxcount)
1888{
1889 char *self_s, *result_s;
1890 char *start, *next, *end;
1891 Py_ssize_t self_len, result_len;
1892 Py_ssize_t count, offset, product;
1893 PyByteArrayObject *result;
1894
1895 self_s = PyByteArray_AS_STRING(self);
1896 self_len = PyByteArray_GET_SIZE(self);
1897
1898 count = countstring(self_s, self_len,
1899 from_s, from_len,
1900 0, self_len, FORWARD, maxcount);
1901 if (count == 0) {
1902 /* no matches, return unchanged */
1903 return return_self(self);
1904 }
1905
1906 /* Check for overflow */
1907 /* result_len = self_len + count * (to_len-from_len) */
1908 product = count * (to_len-from_len);
1909 if (product / (to_len-from_len) != count) {
1910 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1911 return NULL;
1912 }
1913 result_len = self_len + product;
1914 if (result_len < 0) {
1915 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1916 return NULL;
1917 }
1918
1919 if ( (result = (PyByteArrayObject *)
1920 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1921 return NULL;
1922 result_s = PyByteArray_AS_STRING(result);
1923
1924 start = self_s;
1925 end = self_s + self_len;
1926 while (count-- > 0) {
1927 offset = findstring(start, end-start,
1928 from_s, from_len,
1929 0, end-start, FORWARD);
1930 if (offset == -1)
1931 break;
1932 next = start+offset;
1933 if (next == start) {
1934 /* replace with the 'to' */
1935 Py_MEMCPY(result_s, to_s, to_len);
1936 result_s += to_len;
1937 start += from_len;
1938 } else {
1939 /* copy the unchanged old then the 'to' */
1940 Py_MEMCPY(result_s, start, next-start);
1941 result_s += (next-start);
1942 Py_MEMCPY(result_s, to_s, to_len);
1943 result_s += to_len;
1944 start = next+from_len;
1945 }
1946 }
1947 /* Copy the remainder of the remaining bytes */
1948 Py_MEMCPY(result_s, start, end-start);
1949
1950 return result;
1951}
1952
1953
1954Py_LOCAL(PyByteArrayObject *)
1955replace(PyByteArrayObject *self,
1956 const char *from_s, Py_ssize_t from_len,
1957 const char *to_s, Py_ssize_t to_len,
1958 Py_ssize_t maxcount)
1959{
1960 if (maxcount < 0) {
1961 maxcount = PY_SSIZE_T_MAX;
1962 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
1963 /* nothing to do; return the original bytes */
1964 return return_self(self);
1965 }
1966
1967 if (maxcount == 0 ||
1968 (from_len == 0 && to_len == 0)) {
1969 /* nothing to do; return the original bytes */
1970 return return_self(self);
1971 }
1972
1973 /* Handle zero-length special cases */
1974
1975 if (from_len == 0) {
1976 /* insert the 'to' bytes everywhere. */
1977 /* >>> "Python".replace("", ".") */
1978 /* '.P.y.t.h.o.n.' */
1979 return replace_interleave(self, to_s, to_len, maxcount);
1980 }
1981
1982 /* Except for "".replace("", "A") == "A" there is no way beyond this */
1983 /* point for an empty self bytes to generate a non-empty bytes */
1984 /* Special case so the remaining code always gets a non-empty bytes */
1985 if (PyByteArray_GET_SIZE(self) == 0) {
1986 return return_self(self);
1987 }
1988
1989 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00001990 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001991 if (from_len == 1) {
1992 return replace_delete_single_character(
1993 self, from_s[0], maxcount);
1994 } else {
1995 return replace_delete_substring(self, from_s, from_len, maxcount);
1996 }
1997 }
1998
1999 /* Handle special case where both bytes have the same length */
2000
2001 if (from_len == to_len) {
2002 if (from_len == 1) {
2003 return replace_single_character_in_place(
2004 self,
2005 from_s[0],
2006 to_s[0],
2007 maxcount);
2008 } else {
2009 return replace_substring_in_place(
2010 self, from_s, from_len, to_s, to_len, maxcount);
2011 }
2012 }
2013
2014 /* Otherwise use the more generic algorithms */
2015 if (from_len == 1) {
2016 return replace_single_character(self, from_s[0],
2017 to_s, to_len, maxcount);
2018 } else {
2019 /* len('from')>=2, len('to')>=1 */
2020 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
2021 }
2022}
2023
2024
2025PyDoc_STRVAR(replace__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002026"B.replace(old, new[, count]) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002027\n\
2028Return a copy of B with all occurrences of subsection\n\
2029old replaced by new. If the optional argument count is\n\
2030given, only the first count occurrences are replaced.");
2031
2032static PyObject *
2033bytes_replace(PyByteArrayObject *self, PyObject *args)
2034{
2035 Py_ssize_t count = -1;
2036 PyObject *from, *to, *res;
2037 Py_buffer vfrom, vto;
2038
2039 if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
2040 return NULL;
2041
2042 if (_getbuffer(from, &vfrom) < 0)
2043 return NULL;
2044 if (_getbuffer(to, &vto) < 0) {
2045 PyObject_ReleaseBuffer(from, &vfrom);
2046 return NULL;
2047 }
2048
2049 res = (PyObject *)replace((PyByteArrayObject *) self,
2050 vfrom.buf, vfrom.len,
2051 vto.buf, vto.len, count);
2052
2053 PyObject_ReleaseBuffer(from, &vfrom);
2054 PyObject_ReleaseBuffer(to, &vto);
2055 return res;
2056}
2057
2058
2059/* Overallocate the initial list to reduce the number of reallocs for small
2060 split sizes. Eg, "A A A A A A A A A A".split() (10 elements) has three
2061 resizes, to sizes 4, 8, then 16. Most observed string splits are for human
2062 text (roughly 11 words per line) and field delimited data (usually 1-10
2063 fields). For large strings the split algorithms are bandwidth limited
2064 so increasing the preallocation likely will not improve things.*/
2065
2066#define MAX_PREALLOC 12
2067
2068/* 5 splits gives 6 elements */
2069#define PREALLOC_SIZE(maxsplit) \
2070 (maxsplit >= MAX_PREALLOC ? MAX_PREALLOC : maxsplit+1)
2071
2072#define SPLIT_APPEND(data, left, right) \
2073 str = PyByteArray_FromStringAndSize((data) + (left), \
2074 (right) - (left)); \
2075 if (str == NULL) \
2076 goto onError; \
2077 if (PyList_Append(list, str)) { \
2078 Py_DECREF(str); \
2079 goto onError; \
2080 } \
2081 else \
2082 Py_DECREF(str);
2083
2084#define SPLIT_ADD(data, left, right) { \
2085 str = PyByteArray_FromStringAndSize((data) + (left), \
2086 (right) - (left)); \
2087 if (str == NULL) \
2088 goto onError; \
2089 if (count < MAX_PREALLOC) { \
2090 PyList_SET_ITEM(list, count, str); \
2091 } else { \
2092 if (PyList_Append(list, str)) { \
2093 Py_DECREF(str); \
2094 goto onError; \
2095 } \
2096 else \
2097 Py_DECREF(str); \
2098 } \
2099 count++; }
2100
2101/* Always force the list to the expected size. */
2102#define FIX_PREALLOC_SIZE(list) Py_SIZE(list) = count
2103
2104
2105Py_LOCAL_INLINE(PyObject *)
2106split_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount)
2107{
2108 register Py_ssize_t i, j, count = 0;
2109 PyObject *str;
2110 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2111
2112 if (list == NULL)
2113 return NULL;
2114
2115 i = j = 0;
2116 while ((j < len) && (maxcount-- > 0)) {
2117 for(; j < len; j++) {
2118 /* I found that using memchr makes no difference */
2119 if (s[j] == ch) {
2120 SPLIT_ADD(s, i, j);
2121 i = j = j + 1;
2122 break;
2123 }
2124 }
2125 }
2126 if (i <= len) {
2127 SPLIT_ADD(s, i, len);
2128 }
2129 FIX_PREALLOC_SIZE(list);
2130 return list;
2131
2132 onError:
2133 Py_DECREF(list);
2134 return NULL;
2135}
2136
2137
2138Py_LOCAL_INLINE(PyObject *)
2139split_whitespace(const char *s, Py_ssize_t len, Py_ssize_t maxcount)
2140{
2141 register Py_ssize_t i, j, count = 0;
2142 PyObject *str;
2143 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2144
2145 if (list == NULL)
2146 return NULL;
2147
2148 for (i = j = 0; i < len; ) {
2149 /* find a token */
2150 while (i < len && ISSPACE(s[i]))
2151 i++;
2152 j = i;
2153 while (i < len && !ISSPACE(s[i]))
2154 i++;
2155 if (j < i) {
2156 if (maxcount-- <= 0)
2157 break;
2158 SPLIT_ADD(s, j, i);
2159 while (i < len && ISSPACE(s[i]))
2160 i++;
2161 j = i;
2162 }
2163 }
2164 if (j < len) {
2165 SPLIT_ADD(s, j, len);
2166 }
2167 FIX_PREALLOC_SIZE(list);
2168 return list;
2169
2170 onError:
2171 Py_DECREF(list);
2172 return NULL;
2173}
2174
2175PyDoc_STRVAR(split__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002176"B.split([sep[, maxsplit]]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002177\n\
2178Return a list of the sections in B, using sep as the delimiter.\n\
2179If sep is not given, B is split on ASCII whitespace characters\n\
2180(space, tab, return, newline, formfeed, vertical tab).\n\
2181If maxsplit is given, at most maxsplit splits are done.");
2182
2183static PyObject *
2184bytes_split(PyByteArrayObject *self, PyObject *args)
2185{
2186 Py_ssize_t len = PyByteArray_GET_SIZE(self), n, i, j;
2187 Py_ssize_t maxsplit = -1, count = 0;
2188 const char *s = PyByteArray_AS_STRING(self), *sub;
2189 PyObject *list, *str, *subobj = Py_None;
2190 Py_buffer vsub;
2191#ifdef USE_FAST
2192 Py_ssize_t pos;
2193#endif
2194
2195 if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
2196 return NULL;
2197 if (maxsplit < 0)
2198 maxsplit = PY_SSIZE_T_MAX;
2199
2200 if (subobj == Py_None)
2201 return split_whitespace(s, len, maxsplit);
2202
2203 if (_getbuffer(subobj, &vsub) < 0)
2204 return NULL;
2205 sub = vsub.buf;
2206 n = vsub.len;
2207
2208 if (n == 0) {
2209 PyErr_SetString(PyExc_ValueError, "empty separator");
2210 PyObject_ReleaseBuffer(subobj, &vsub);
2211 return NULL;
2212 }
2213 if (n == 1)
2214 return split_char(s, len, sub[0], maxsplit);
2215
2216 list = PyList_New(PREALLOC_SIZE(maxsplit));
2217 if (list == NULL) {
2218 PyObject_ReleaseBuffer(subobj, &vsub);
2219 return NULL;
2220 }
2221
2222#ifdef USE_FAST
2223 i = j = 0;
2224 while (maxsplit-- > 0) {
2225 pos = fastsearch(s+i, len-i, sub, n, FAST_SEARCH);
2226 if (pos < 0)
2227 break;
2228 j = i+pos;
2229 SPLIT_ADD(s, i, j);
2230 i = j + n;
2231 }
2232#else
2233 i = j = 0;
2234 while ((j+n <= len) && (maxsplit-- > 0)) {
2235 for (; j+n <= len; j++) {
2236 if (Py_STRING_MATCH(s, j, sub, n)) {
2237 SPLIT_ADD(s, i, j);
2238 i = j = j + n;
2239 break;
2240 }
2241 }
2242 }
2243#endif
2244 SPLIT_ADD(s, i, len);
2245 FIX_PREALLOC_SIZE(list);
2246 PyObject_ReleaseBuffer(subobj, &vsub);
2247 return list;
2248
2249 onError:
2250 Py_DECREF(list);
2251 PyObject_ReleaseBuffer(subobj, &vsub);
2252 return NULL;
2253}
2254
2255/* stringlib's partition shares nullbytes in some cases.
2256 undo this, we don't want the nullbytes to be shared. */
2257static PyObject *
2258make_nullbytes_unique(PyObject *result)
2259{
2260 if (result != NULL) {
2261 int i;
2262 assert(PyTuple_Check(result));
2263 assert(PyTuple_GET_SIZE(result) == 3);
2264 for (i = 0; i < 3; i++) {
2265 if (PyTuple_GET_ITEM(result, i) == (PyObject *)nullbytes) {
2266 PyObject *new = PyByteArray_FromStringAndSize(NULL, 0);
2267 if (new == NULL) {
2268 Py_DECREF(result);
2269 result = NULL;
2270 break;
2271 }
2272 Py_DECREF(nullbytes);
2273 PyTuple_SET_ITEM(result, i, new);
2274 }
2275 }
2276 }
2277 return result;
2278}
2279
2280PyDoc_STRVAR(partition__doc__,
2281"B.partition(sep) -> (head, sep, tail)\n\
2282\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002283Search for the separator sep in B, and return the part before it,\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002284the separator itself, and the part after it. If the separator is not\n\
2285found, returns B and two empty bytearray objects.");
2286
2287static PyObject *
2288bytes_partition(PyByteArrayObject *self, PyObject *sep_obj)
2289{
2290 PyObject *bytesep, *result;
2291
2292 bytesep = PyByteArray_FromObject(sep_obj);
2293 if (! bytesep)
2294 return NULL;
2295
2296 result = stringlib_partition(
2297 (PyObject*) self,
2298 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2299 bytesep,
2300 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2301 );
2302
2303 Py_DECREF(bytesep);
2304 return make_nullbytes_unique(result);
2305}
2306
2307PyDoc_STRVAR(rpartition__doc__,
2308"B.rpartition(sep) -> (tail, sep, head)\n\
2309\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002310Search for the separator sep in B, starting at the end of B,\n\
2311and return the part before it, the separator itself, and the\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002312part after it. If the separator is not found, returns two empty\n\
2313bytearray objects and B.");
2314
2315static PyObject *
2316bytes_rpartition(PyByteArrayObject *self, PyObject *sep_obj)
2317{
2318 PyObject *bytesep, *result;
2319
2320 bytesep = PyByteArray_FromObject(sep_obj);
2321 if (! bytesep)
2322 return NULL;
2323
2324 result = stringlib_rpartition(
2325 (PyObject*) self,
2326 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2327 bytesep,
2328 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2329 );
2330
2331 Py_DECREF(bytesep);
2332 return make_nullbytes_unique(result);
2333}
2334
2335Py_LOCAL_INLINE(PyObject *)
2336rsplit_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount)
2337{
2338 register Py_ssize_t i, j, count=0;
2339 PyObject *str;
2340 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2341
2342 if (list == NULL)
2343 return NULL;
2344
2345 i = j = len - 1;
2346 while ((i >= 0) && (maxcount-- > 0)) {
2347 for (; i >= 0; i--) {
2348 if (s[i] == ch) {
2349 SPLIT_ADD(s, i + 1, j + 1);
2350 j = i = i - 1;
2351 break;
2352 }
2353 }
2354 }
2355 if (j >= -1) {
2356 SPLIT_ADD(s, 0, j + 1);
2357 }
2358 FIX_PREALLOC_SIZE(list);
2359 if (PyList_Reverse(list) < 0)
2360 goto onError;
2361
2362 return list;
2363
2364 onError:
2365 Py_DECREF(list);
2366 return NULL;
2367}
2368
2369Py_LOCAL_INLINE(PyObject *)
2370rsplit_whitespace(const char *s, Py_ssize_t len, Py_ssize_t maxcount)
2371{
2372 register Py_ssize_t i, j, count = 0;
2373 PyObject *str;
2374 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2375
2376 if (list == NULL)
2377 return NULL;
2378
2379 for (i = j = len - 1; i >= 0; ) {
2380 /* find a token */
2381 while (i >= 0 && ISSPACE(s[i]))
2382 i--;
2383 j = i;
2384 while (i >= 0 && !ISSPACE(s[i]))
2385 i--;
2386 if (j > i) {
2387 if (maxcount-- <= 0)
2388 break;
2389 SPLIT_ADD(s, i + 1, j + 1);
2390 while (i >= 0 && ISSPACE(s[i]))
2391 i--;
2392 j = i;
2393 }
2394 }
2395 if (j >= 0) {
2396 SPLIT_ADD(s, 0, j + 1);
2397 }
2398 FIX_PREALLOC_SIZE(list);
2399 if (PyList_Reverse(list) < 0)
2400 goto onError;
2401
2402 return list;
2403
2404 onError:
2405 Py_DECREF(list);
2406 return NULL;
2407}
2408
2409PyDoc_STRVAR(rsplit__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002410"B.rsplit(sep[, maxsplit]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002411\n\
2412Return a list of the sections in B, using sep as the delimiter,\n\
2413starting at the end of B and working to the front.\n\
2414If sep is not given, B is split on ASCII whitespace characters\n\
2415(space, tab, return, newline, formfeed, vertical tab).\n\
2416If maxsplit is given, at most maxsplit splits are done.");
2417
2418static PyObject *
2419bytes_rsplit(PyByteArrayObject *self, PyObject *args)
2420{
2421 Py_ssize_t len = PyByteArray_GET_SIZE(self), n, i, j;
2422 Py_ssize_t maxsplit = -1, count = 0;
2423 const char *s = PyByteArray_AS_STRING(self), *sub;
2424 PyObject *list, *str, *subobj = Py_None;
2425 Py_buffer vsub;
2426
2427 if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
2428 return NULL;
2429 if (maxsplit < 0)
2430 maxsplit = PY_SSIZE_T_MAX;
2431
2432 if (subobj == Py_None)
2433 return rsplit_whitespace(s, len, maxsplit);
2434
2435 if (_getbuffer(subobj, &vsub) < 0)
2436 return NULL;
2437 sub = vsub.buf;
2438 n = vsub.len;
2439
2440 if (n == 0) {
2441 PyErr_SetString(PyExc_ValueError, "empty separator");
2442 PyObject_ReleaseBuffer(subobj, &vsub);
2443 return NULL;
2444 }
2445 else if (n == 1)
2446 return rsplit_char(s, len, sub[0], maxsplit);
2447
2448 list = PyList_New(PREALLOC_SIZE(maxsplit));
2449 if (list == NULL) {
2450 PyObject_ReleaseBuffer(subobj, &vsub);
2451 return NULL;
2452 }
2453
2454 j = len;
2455 i = j - n;
2456
2457 while ( (i >= 0) && (maxsplit-- > 0) ) {
2458 for (; i>=0; i--) {
2459 if (Py_STRING_MATCH(s, i, sub, n)) {
2460 SPLIT_ADD(s, i + n, j);
2461 j = i;
2462 i -= n;
2463 break;
2464 }
2465 }
2466 }
2467 SPLIT_ADD(s, 0, j);
2468 FIX_PREALLOC_SIZE(list);
2469 if (PyList_Reverse(list) < 0)
2470 goto onError;
2471 PyObject_ReleaseBuffer(subobj, &vsub);
2472 return list;
2473
2474onError:
2475 Py_DECREF(list);
2476 PyObject_ReleaseBuffer(subobj, &vsub);
2477 return NULL;
2478}
2479
2480PyDoc_STRVAR(reverse__doc__,
2481"B.reverse() -> None\n\
2482\n\
2483Reverse the order of the values in B in place.");
2484static PyObject *
2485bytes_reverse(PyByteArrayObject *self, PyObject *unused)
2486{
2487 char swap, *head, *tail;
2488 Py_ssize_t i, j, n = Py_SIZE(self);
2489
2490 j = n / 2;
2491 head = self->ob_bytes;
2492 tail = head + n - 1;
2493 for (i = 0; i < j; i++) {
2494 swap = *head;
2495 *head++ = *tail;
2496 *tail-- = swap;
2497 }
2498
2499 Py_RETURN_NONE;
2500}
2501
2502PyDoc_STRVAR(insert__doc__,
2503"B.insert(index, int) -> None\n\
2504\n\
2505Insert a single item into the bytearray before the given index.");
2506static PyObject *
2507bytes_insert(PyByteArrayObject *self, PyObject *args)
2508{
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002509 PyObject *value;
2510 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002511 Py_ssize_t where, n = Py_SIZE(self);
2512
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002513 if (!PyArg_ParseTuple(args, "nO:insert", &where, &value))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002514 return NULL;
2515
2516 if (n == PY_SSIZE_T_MAX) {
2517 PyErr_SetString(PyExc_OverflowError,
2518 "cannot add more objects to bytes");
2519 return NULL;
2520 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002521 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002522 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002523 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2524 return NULL;
2525
2526 if (where < 0) {
2527 where += n;
2528 if (where < 0)
2529 where = 0;
2530 }
2531 if (where > n)
2532 where = n;
2533 memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where);
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002534 self->ob_bytes[where] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002535
2536 Py_RETURN_NONE;
2537}
2538
2539PyDoc_STRVAR(append__doc__,
2540"B.append(int) -> None\n\
2541\n\
2542Append a single item to the end of B.");
2543static PyObject *
2544bytes_append(PyByteArrayObject *self, PyObject *arg)
2545{
2546 int value;
2547 Py_ssize_t n = Py_SIZE(self);
2548
2549 if (! _getbytevalue(arg, &value))
2550 return NULL;
2551 if (n == PY_SSIZE_T_MAX) {
2552 PyErr_SetString(PyExc_OverflowError,
2553 "cannot add more objects to bytes");
2554 return NULL;
2555 }
2556 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2557 return NULL;
2558
2559 self->ob_bytes[n] = value;
2560
2561 Py_RETURN_NONE;
2562}
2563
2564PyDoc_STRVAR(extend__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002565"B.extend(iterable_of_ints) -> None\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002566\n\
2567Append all the elements from the iterator or sequence to the\n\
2568end of B.");
2569static PyObject *
2570bytes_extend(PyByteArrayObject *self, PyObject *arg)
2571{
2572 PyObject *it, *item, *bytes_obj;
2573 Py_ssize_t buf_size = 0, len = 0;
2574 int value;
2575 char *buf;
2576
2577 /* bytes_setslice code only accepts something supporting PEP 3118. */
2578 if (PyObject_CheckBuffer(arg)) {
2579 if (bytes_setslice(self, Py_SIZE(self), Py_SIZE(self), arg) == -1)
2580 return NULL;
2581
2582 Py_RETURN_NONE;
2583 }
2584
2585 it = PyObject_GetIter(arg);
2586 if (it == NULL)
2587 return NULL;
2588
2589 /* Try to determine the length of the argument. 32 is abitrary. */
2590 buf_size = _PyObject_LengthHint(arg, 32);
2591
2592 bytes_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
2593 if (bytes_obj == NULL)
2594 return NULL;
2595 buf = PyByteArray_AS_STRING(bytes_obj);
2596
2597 while ((item = PyIter_Next(it)) != NULL) {
2598 if (! _getbytevalue(item, &value)) {
2599 Py_DECREF(item);
2600 Py_DECREF(it);
2601 Py_DECREF(bytes_obj);
2602 return NULL;
2603 }
2604 buf[len++] = value;
2605 Py_DECREF(item);
2606
2607 if (len >= buf_size) {
2608 buf_size = len + (len >> 1) + 1;
2609 if (PyByteArray_Resize((PyObject *)bytes_obj, buf_size) < 0) {
2610 Py_DECREF(it);
2611 Py_DECREF(bytes_obj);
2612 return NULL;
2613 }
2614 /* Recompute the `buf' pointer, since the resizing operation may
2615 have invalidated it. */
2616 buf = PyByteArray_AS_STRING(bytes_obj);
2617 }
2618 }
2619 Py_DECREF(it);
2620
2621 /* Resize down to exact size. */
2622 if (PyByteArray_Resize((PyObject *)bytes_obj, len) < 0) {
2623 Py_DECREF(bytes_obj);
2624 return NULL;
2625 }
2626
2627 if (bytes_setslice(self, Py_SIZE(self), Py_SIZE(self), bytes_obj) == -1)
2628 return NULL;
2629 Py_DECREF(bytes_obj);
2630
2631 Py_RETURN_NONE;
2632}
2633
2634PyDoc_STRVAR(pop__doc__,
2635"B.pop([index]) -> int\n\
2636\n\
2637Remove and return a single item from B. If no index\n\
Benjamin Petersondcf97b92008-07-02 17:30:14 +00002638argument is given, will pop the last value.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002639static PyObject *
2640bytes_pop(PyByteArrayObject *self, PyObject *args)
2641{
2642 int value;
2643 Py_ssize_t where = -1, n = Py_SIZE(self);
2644
2645 if (!PyArg_ParseTuple(args, "|n:pop", &where))
2646 return NULL;
2647
2648 if (n == 0) {
2649 PyErr_SetString(PyExc_OverflowError,
2650 "cannot pop an empty bytes");
2651 return NULL;
2652 }
2653 if (where < 0)
2654 where += Py_SIZE(self);
2655 if (where < 0 || where >= Py_SIZE(self)) {
2656 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2657 return NULL;
2658 }
2659
2660 value = self->ob_bytes[where];
2661 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2662 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2663 return NULL;
2664
2665 return PyLong_FromLong(value);
2666}
2667
2668PyDoc_STRVAR(remove__doc__,
2669"B.remove(int) -> None\n\
2670\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002671Remove the first occurrence of a value in B.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002672static PyObject *
2673bytes_remove(PyByteArrayObject *self, PyObject *arg)
2674{
2675 int value;
2676 Py_ssize_t where, n = Py_SIZE(self);
2677
2678 if (! _getbytevalue(arg, &value))
2679 return NULL;
2680
2681 for (where = 0; where < n; where++) {
2682 if (self->ob_bytes[where] == value)
2683 break;
2684 }
2685 if (where == n) {
2686 PyErr_SetString(PyExc_ValueError, "value not found in bytes");
2687 return NULL;
2688 }
2689
2690 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2691 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2692 return NULL;
2693
2694 Py_RETURN_NONE;
2695}
2696
2697/* XXX These two helpers could be optimized if argsize == 1 */
2698
2699static Py_ssize_t
2700lstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2701 void *argptr, Py_ssize_t argsize)
2702{
2703 Py_ssize_t i = 0;
2704 while (i < mysize && memchr(argptr, myptr[i], argsize))
2705 i++;
2706 return i;
2707}
2708
2709static Py_ssize_t
2710rstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2711 void *argptr, Py_ssize_t argsize)
2712{
2713 Py_ssize_t i = mysize - 1;
2714 while (i >= 0 && memchr(argptr, myptr[i], argsize))
2715 i--;
2716 return i + 1;
2717}
2718
2719PyDoc_STRVAR(strip__doc__,
2720"B.strip([bytes]) -> bytearray\n\
2721\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002722Strip leading and trailing bytes contained in the argument\n\
2723and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002724If the argument is omitted, strip ASCII whitespace.");
2725static PyObject *
2726bytes_strip(PyByteArrayObject *self, PyObject *args)
2727{
2728 Py_ssize_t left, right, mysize, argsize;
2729 void *myptr, *argptr;
2730 PyObject *arg = Py_None;
2731 Py_buffer varg;
2732 if (!PyArg_ParseTuple(args, "|O:strip", &arg))
2733 return NULL;
2734 if (arg == Py_None) {
2735 argptr = "\t\n\r\f\v ";
2736 argsize = 6;
2737 }
2738 else {
2739 if (_getbuffer(arg, &varg) < 0)
2740 return NULL;
2741 argptr = varg.buf;
2742 argsize = varg.len;
2743 }
2744 myptr = self->ob_bytes;
2745 mysize = Py_SIZE(self);
2746 left = lstrip_helper(myptr, mysize, argptr, argsize);
2747 if (left == mysize)
2748 right = left;
2749 else
2750 right = rstrip_helper(myptr, mysize, argptr, argsize);
2751 if (arg != Py_None)
2752 PyObject_ReleaseBuffer(arg, &varg);
2753 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2754}
2755
2756PyDoc_STRVAR(lstrip__doc__,
2757"B.lstrip([bytes]) -> bytearray\n\
2758\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002759Strip leading bytes contained in the argument\n\
2760and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002761If the argument is omitted, strip leading ASCII whitespace.");
2762static PyObject *
2763bytes_lstrip(PyByteArrayObject *self, PyObject *args)
2764{
2765 Py_ssize_t left, right, mysize, argsize;
2766 void *myptr, *argptr;
2767 PyObject *arg = Py_None;
2768 Py_buffer varg;
2769 if (!PyArg_ParseTuple(args, "|O:lstrip", &arg))
2770 return NULL;
2771 if (arg == Py_None) {
2772 argptr = "\t\n\r\f\v ";
2773 argsize = 6;
2774 }
2775 else {
2776 if (_getbuffer(arg, &varg) < 0)
2777 return NULL;
2778 argptr = varg.buf;
2779 argsize = varg.len;
2780 }
2781 myptr = self->ob_bytes;
2782 mysize = Py_SIZE(self);
2783 left = lstrip_helper(myptr, mysize, argptr, argsize);
2784 right = mysize;
2785 if (arg != Py_None)
2786 PyObject_ReleaseBuffer(arg, &varg);
2787 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2788}
2789
2790PyDoc_STRVAR(rstrip__doc__,
2791"B.rstrip([bytes]) -> bytearray\n\
2792\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002793Strip trailing bytes contained in the argument\n\
2794and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002795If the argument is omitted, strip trailing ASCII whitespace.");
2796static PyObject *
2797bytes_rstrip(PyByteArrayObject *self, PyObject *args)
2798{
2799 Py_ssize_t left, right, mysize, argsize;
2800 void *myptr, *argptr;
2801 PyObject *arg = Py_None;
2802 Py_buffer varg;
2803 if (!PyArg_ParseTuple(args, "|O:rstrip", &arg))
2804 return NULL;
2805 if (arg == Py_None) {
2806 argptr = "\t\n\r\f\v ";
2807 argsize = 6;
2808 }
2809 else {
2810 if (_getbuffer(arg, &varg) < 0)
2811 return NULL;
2812 argptr = varg.buf;
2813 argsize = varg.len;
2814 }
2815 myptr = self->ob_bytes;
2816 mysize = Py_SIZE(self);
2817 left = 0;
2818 right = rstrip_helper(myptr, mysize, argptr, argsize);
2819 if (arg != Py_None)
2820 PyObject_ReleaseBuffer(arg, &varg);
2821 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2822}
2823
2824PyDoc_STRVAR(decode_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002825"B.decode([encoding[, errors]]) -> str\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002826\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002827Decode B using the codec registered for encoding. encoding defaults\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002828to the default encoding. errors may be given to set a different error\n\
2829handling scheme. Default is 'strict' meaning that encoding errors raise\n\
2830a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
2831as well as any other name registered with codecs.register_error that is\n\
2832able to handle UnicodeDecodeErrors.");
2833
2834static PyObject *
2835bytes_decode(PyObject *self, PyObject *args)
2836{
2837 const char *encoding = NULL;
2838 const char *errors = NULL;
2839
2840 if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
2841 return NULL;
2842 if (encoding == NULL)
2843 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002844 return PyUnicode_FromEncodedObject(self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002845}
2846
2847PyDoc_STRVAR(alloc_doc,
2848"B.__alloc__() -> int\n\
2849\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002850Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002851
2852static PyObject *
2853bytes_alloc(PyByteArrayObject *self)
2854{
2855 return PyLong_FromSsize_t(self->ob_alloc);
2856}
2857
2858PyDoc_STRVAR(join_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002859"B.join(iterable_of_bytes) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002860\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002861Concatenate any number of bytes/bytearray objects, with B\n\
2862in between each pair, and return the result as a new bytearray.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002863
2864static PyObject *
2865bytes_join(PyByteArrayObject *self, PyObject *it)
2866{
2867 PyObject *seq;
2868 Py_ssize_t mysize = Py_SIZE(self);
2869 Py_ssize_t i;
2870 Py_ssize_t n;
2871 PyObject **items;
2872 Py_ssize_t totalsize = 0;
2873 PyObject *result;
2874 char *dest;
2875
2876 seq = PySequence_Fast(it, "can only join an iterable");
2877 if (seq == NULL)
2878 return NULL;
2879 n = PySequence_Fast_GET_SIZE(seq);
2880 items = PySequence_Fast_ITEMS(seq);
2881
2882 /* Compute the total size, and check that they are all bytes */
2883 /* XXX Shouldn't we use _getbuffer() on these items instead? */
2884 for (i = 0; i < n; i++) {
2885 PyObject *obj = items[i];
2886 if (!PyByteArray_Check(obj) && !PyBytes_Check(obj)) {
2887 PyErr_Format(PyExc_TypeError,
2888 "can only join an iterable of bytes "
2889 "(item %ld has type '%.100s')",
2890 /* XXX %ld isn't right on Win64 */
2891 (long)i, Py_TYPE(obj)->tp_name);
2892 goto error;
2893 }
2894 if (i > 0)
2895 totalsize += mysize;
2896 totalsize += Py_SIZE(obj);
2897 if (totalsize < 0) {
2898 PyErr_NoMemory();
2899 goto error;
2900 }
2901 }
2902
2903 /* Allocate the result, and copy the bytes */
2904 result = PyByteArray_FromStringAndSize(NULL, totalsize);
2905 if (result == NULL)
2906 goto error;
2907 dest = PyByteArray_AS_STRING(result);
2908 for (i = 0; i < n; i++) {
2909 PyObject *obj = items[i];
2910 Py_ssize_t size = Py_SIZE(obj);
2911 char *buf;
2912 if (PyByteArray_Check(obj))
2913 buf = PyByteArray_AS_STRING(obj);
2914 else
2915 buf = PyBytes_AS_STRING(obj);
2916 if (i) {
2917 memcpy(dest, self->ob_bytes, mysize);
2918 dest += mysize;
2919 }
2920 memcpy(dest, buf, size);
2921 dest += size;
2922 }
2923
2924 /* Done */
2925 Py_DECREF(seq);
2926 return result;
2927
2928 /* Error handling */
2929 error:
2930 Py_DECREF(seq);
2931 return NULL;
2932}
2933
2934PyDoc_STRVAR(fromhex_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002935"bytearray.fromhex(string) -> bytearray (static method)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002936\n\
2937Create a bytearray object from a string of hexadecimal numbers.\n\
2938Spaces between two numbers are accepted.\n\
2939Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef').");
2940
2941static int
2942hex_digit_to_int(Py_UNICODE c)
2943{
2944 if (c >= 128)
2945 return -1;
2946 if (ISDIGIT(c))
2947 return c - '0';
2948 else {
2949 if (ISUPPER(c))
2950 c = TOLOWER(c);
2951 if (c >= 'a' && c <= 'f')
2952 return c - 'a' + 10;
2953 }
2954 return -1;
2955}
2956
2957static PyObject *
2958bytes_fromhex(PyObject *cls, PyObject *args)
2959{
2960 PyObject *newbytes, *hexobj;
2961 char *buf;
2962 Py_UNICODE *hex;
2963 Py_ssize_t hexlen, byteslen, i, j;
2964 int top, bot;
2965
2966 if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj))
2967 return NULL;
2968 assert(PyUnicode_Check(hexobj));
2969 hexlen = PyUnicode_GET_SIZE(hexobj);
2970 hex = PyUnicode_AS_UNICODE(hexobj);
2971 byteslen = hexlen/2; /* This overestimates if there are spaces */
2972 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
2973 if (!newbytes)
2974 return NULL;
2975 buf = PyByteArray_AS_STRING(newbytes);
2976 for (i = j = 0; i < hexlen; i += 2) {
2977 /* skip over spaces in the input */
2978 while (hex[i] == ' ')
2979 i++;
2980 if (i >= hexlen)
2981 break;
2982 top = hex_digit_to_int(hex[i]);
2983 bot = hex_digit_to_int(hex[i+1]);
2984 if (top == -1 || bot == -1) {
2985 PyErr_Format(PyExc_ValueError,
2986 "non-hexadecimal number found in "
2987 "fromhex() arg at position %zd", i);
2988 goto error;
2989 }
2990 buf[j++] = (top << 4) + bot;
2991 }
2992 if (PyByteArray_Resize(newbytes, j) < 0)
2993 goto error;
2994 return newbytes;
2995
2996 error:
2997 Py_DECREF(newbytes);
2998 return NULL;
2999}
3000
3001PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3002
3003static PyObject *
3004bytes_reduce(PyByteArrayObject *self)
3005{
3006 PyObject *latin1, *dict;
3007 if (self->ob_bytes)
3008 latin1 = PyUnicode_DecodeLatin1(self->ob_bytes,
3009 Py_SIZE(self), NULL);
3010 else
3011 latin1 = PyUnicode_FromString("");
3012
3013 dict = PyObject_GetAttrString((PyObject *)self, "__dict__");
3014 if (dict == NULL) {
3015 PyErr_Clear();
3016 dict = Py_None;
3017 Py_INCREF(dict);
3018 }
3019
3020 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
3021}
3022
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003023PyDoc_STRVAR(sizeof_doc,
3024"B.__sizeof__() -> int\n\
3025 \n\
3026Returns the size of B in memory, in bytes");
3027static PyObject *
3028bytes_sizeof(PyByteArrayObject *self)
3029{
3030 Py_ssize_t res;
3031
3032 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
3033 return PyLong_FromSsize_t(res);
3034}
3035
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003036static PySequenceMethods bytes_as_sequence = {
3037 (lenfunc)bytes_length, /* sq_length */
3038 (binaryfunc)PyByteArray_Concat, /* sq_concat */
3039 (ssizeargfunc)bytes_repeat, /* sq_repeat */
3040 (ssizeargfunc)bytes_getitem, /* sq_item */
3041 0, /* sq_slice */
3042 (ssizeobjargproc)bytes_setitem, /* sq_ass_item */
3043 0, /* sq_ass_slice */
3044 (objobjproc)bytes_contains, /* sq_contains */
3045 (binaryfunc)bytes_iconcat, /* sq_inplace_concat */
3046 (ssizeargfunc)bytes_irepeat, /* sq_inplace_repeat */
3047};
3048
3049static PyMappingMethods bytes_as_mapping = {
3050 (lenfunc)bytes_length,
3051 (binaryfunc)bytes_subscript,
3052 (objobjargproc)bytes_ass_subscript,
3053};
3054
3055static PyBufferProcs bytes_as_buffer = {
3056 (getbufferproc)bytes_getbuffer,
3057 (releasebufferproc)bytes_releasebuffer,
3058};
3059
3060static PyMethodDef
3061bytes_methods[] = {
3062 {"__alloc__", (PyCFunction)bytes_alloc, METH_NOARGS, alloc_doc},
3063 {"__reduce__", (PyCFunction)bytes_reduce, METH_NOARGS, reduce_doc},
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003064 {"__sizeof__", (PyCFunction)bytes_sizeof, METH_NOARGS, sizeof_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003065 {"append", (PyCFunction)bytes_append, METH_O, append__doc__},
3066 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
3067 _Py_capitalize__doc__},
3068 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
3069 {"count", (PyCFunction)bytes_count, METH_VARARGS, count__doc__},
3070 {"decode", (PyCFunction)bytes_decode, METH_VARARGS, decode_doc},
3071 {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS, endswith__doc__},
3072 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS,
3073 expandtabs__doc__},
3074 {"extend", (PyCFunction)bytes_extend, METH_O, extend__doc__},
3075 {"find", (PyCFunction)bytes_find, METH_VARARGS, find__doc__},
3076 {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS,
3077 fromhex_doc},
3078 {"index", (PyCFunction)bytes_index, METH_VARARGS, index__doc__},
3079 {"insert", (PyCFunction)bytes_insert, METH_VARARGS, insert__doc__},
3080 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
3081 _Py_isalnum__doc__},
3082 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
3083 _Py_isalpha__doc__},
3084 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
3085 _Py_isdigit__doc__},
3086 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
3087 _Py_islower__doc__},
3088 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
3089 _Py_isspace__doc__},
3090 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
3091 _Py_istitle__doc__},
3092 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
3093 _Py_isupper__doc__},
3094 {"join", (PyCFunction)bytes_join, METH_O, join_doc},
3095 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
3096 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
3097 {"lstrip", (PyCFunction)bytes_lstrip, METH_VARARGS, lstrip__doc__},
3098 {"partition", (PyCFunction)bytes_partition, METH_O, partition__doc__},
3099 {"pop", (PyCFunction)bytes_pop, METH_VARARGS, pop__doc__},
3100 {"remove", (PyCFunction)bytes_remove, METH_O, remove__doc__},
3101 {"replace", (PyCFunction)bytes_replace, METH_VARARGS, replace__doc__},
3102 {"reverse", (PyCFunction)bytes_reverse, METH_NOARGS, reverse__doc__},
3103 {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, rfind__doc__},
3104 {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, rindex__doc__},
3105 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
3106 {"rpartition", (PyCFunction)bytes_rpartition, METH_O, rpartition__doc__},
3107 {"rsplit", (PyCFunction)bytes_rsplit, METH_VARARGS, rsplit__doc__},
3108 {"rstrip", (PyCFunction)bytes_rstrip, METH_VARARGS, rstrip__doc__},
3109 {"split", (PyCFunction)bytes_split, METH_VARARGS, split__doc__},
3110 {"splitlines", (PyCFunction)stringlib_splitlines, METH_VARARGS,
3111 splitlines__doc__},
3112 {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS ,
3113 startswith__doc__},
3114 {"strip", (PyCFunction)bytes_strip, METH_VARARGS, strip__doc__},
3115 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
3116 _Py_swapcase__doc__},
3117 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
3118 {"translate", (PyCFunction)bytes_translate, METH_VARARGS,
3119 translate__doc__},
3120 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
3121 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
3122 {NULL}
3123};
3124
3125PyDoc_STRVAR(bytes_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00003126"bytearray(iterable_of_ints) -> bytearray\n\
3127bytearray(string, encoding[, errors]) -> bytearray\n\
3128bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray\n\
3129bytearray(memory_view) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003130\n\
3131Construct an mutable bytearray object from:\n\
3132 - an iterable yielding integers in range(256)\n\
3133 - a text string encoded using the specified encoding\n\
3134 - a bytes or a bytearray object\n\
3135 - any object implementing the buffer API.\n\
3136\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00003137bytearray(int) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003138\n\
3139Construct a zero-initialized bytearray of the given length.");
3140
3141
3142static PyObject *bytes_iter(PyObject *seq);
3143
3144PyTypeObject PyByteArray_Type = {
3145 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3146 "bytearray",
3147 sizeof(PyByteArrayObject),
3148 0,
3149 (destructor)bytes_dealloc, /* tp_dealloc */
3150 0, /* tp_print */
3151 0, /* tp_getattr */
3152 0, /* tp_setattr */
3153 0, /* tp_compare */
3154 (reprfunc)bytes_repr, /* tp_repr */
3155 0, /* tp_as_number */
3156 &bytes_as_sequence, /* tp_as_sequence */
3157 &bytes_as_mapping, /* tp_as_mapping */
3158 0, /* tp_hash */
3159 0, /* tp_call */
3160 bytes_str, /* tp_str */
3161 PyObject_GenericGetAttr, /* tp_getattro */
3162 0, /* tp_setattro */
3163 &bytes_as_buffer, /* tp_as_buffer */
3164 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3165 bytes_doc, /* tp_doc */
3166 0, /* tp_traverse */
3167 0, /* tp_clear */
3168 (richcmpfunc)bytes_richcompare, /* tp_richcompare */
3169 0, /* tp_weaklistoffset */
3170 bytes_iter, /* tp_iter */
3171 0, /* tp_iternext */
3172 bytes_methods, /* tp_methods */
3173 0, /* tp_members */
3174 0, /* tp_getset */
3175 0, /* tp_base */
3176 0, /* tp_dict */
3177 0, /* tp_descr_get */
3178 0, /* tp_descr_set */
3179 0, /* tp_dictoffset */
3180 (initproc)bytes_init, /* tp_init */
3181 PyType_GenericAlloc, /* tp_alloc */
3182 PyType_GenericNew, /* tp_new */
3183 PyObject_Del, /* tp_free */
3184};
3185
3186/*********************** Bytes Iterator ****************************/
3187
3188typedef struct {
3189 PyObject_HEAD
3190 Py_ssize_t it_index;
3191 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
3192} bytesiterobject;
3193
3194static void
3195bytesiter_dealloc(bytesiterobject *it)
3196{
3197 _PyObject_GC_UNTRACK(it);
3198 Py_XDECREF(it->it_seq);
3199 PyObject_GC_Del(it);
3200}
3201
3202static int
3203bytesiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
3204{
3205 Py_VISIT(it->it_seq);
3206 return 0;
3207}
3208
3209static PyObject *
3210bytesiter_next(bytesiterobject *it)
3211{
3212 PyByteArrayObject *seq;
3213 PyObject *item;
3214
3215 assert(it != NULL);
3216 seq = it->it_seq;
3217 if (seq == NULL)
3218 return NULL;
3219 assert(PyByteArray_Check(seq));
3220
3221 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
3222 item = PyLong_FromLong(
3223 (unsigned char)seq->ob_bytes[it->it_index]);
3224 if (item != NULL)
3225 ++it->it_index;
3226 return item;
3227 }
3228
3229 Py_DECREF(seq);
3230 it->it_seq = NULL;
3231 return NULL;
3232}
3233
3234static PyObject *
3235bytesiter_length_hint(bytesiterobject *it)
3236{
3237 Py_ssize_t len = 0;
3238 if (it->it_seq)
3239 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
3240 return PyLong_FromSsize_t(len);
3241}
3242
3243PyDoc_STRVAR(length_hint_doc,
3244 "Private method returning an estimate of len(list(it)).");
3245
3246static PyMethodDef bytesiter_methods[] = {
3247 {"__length_hint__", (PyCFunction)bytesiter_length_hint, METH_NOARGS,
3248 length_hint_doc},
3249 {NULL, NULL} /* sentinel */
3250};
3251
3252PyTypeObject PyByteArrayIter_Type = {
3253 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3254 "bytearray_iterator", /* tp_name */
3255 sizeof(bytesiterobject), /* tp_basicsize */
3256 0, /* tp_itemsize */
3257 /* methods */
3258 (destructor)bytesiter_dealloc, /* tp_dealloc */
3259 0, /* tp_print */
3260 0, /* tp_getattr */
3261 0, /* tp_setattr */
3262 0, /* tp_compare */
3263 0, /* tp_repr */
3264 0, /* tp_as_number */
3265 0, /* tp_as_sequence */
3266 0, /* tp_as_mapping */
3267 0, /* tp_hash */
3268 0, /* tp_call */
3269 0, /* tp_str */
3270 PyObject_GenericGetAttr, /* tp_getattro */
3271 0, /* tp_setattro */
3272 0, /* tp_as_buffer */
3273 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
3274 0, /* tp_doc */
3275 (traverseproc)bytesiter_traverse, /* tp_traverse */
3276 0, /* tp_clear */
3277 0, /* tp_richcompare */
3278 0, /* tp_weaklistoffset */
3279 PyObject_SelfIter, /* tp_iter */
3280 (iternextfunc)bytesiter_next, /* tp_iternext */
3281 bytesiter_methods, /* tp_methods */
3282 0,
3283};
3284
3285static PyObject *
3286bytes_iter(PyObject *seq)
3287{
3288 bytesiterobject *it;
3289
3290 if (!PyByteArray_Check(seq)) {
3291 PyErr_BadInternalCall();
3292 return NULL;
3293 }
3294 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
3295 if (it == NULL)
3296 return NULL;
3297 it->it_index = 0;
3298 Py_INCREF(seq);
3299 it->it_seq = (PyByteArrayObject *)seq;
3300 _PyObject_GC_TRACK(it);
3301 return (PyObject *)it;
3302}