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