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