blob: 03e51e8a43dce0ace0df1712f85983471f4be17c [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
Benjamin Petersona786b022008-08-25 21:05:21 +00001029#define FROM_BYTEARRAY 1
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001030
1031#include "stringlib/fastsearch.h"
1032#include "stringlib/count.h"
1033#include "stringlib/find.h"
1034#include "stringlib/partition.h"
1035#include "stringlib/ctype.h"
1036#include "stringlib/transmogrify.h"
1037
1038
1039/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1040were copied from the old char* style string object. */
1041
1042Py_LOCAL_INLINE(void)
1043_adjust_indices(Py_ssize_t *start, Py_ssize_t *end, Py_ssize_t len)
1044{
1045 if (*end > len)
1046 *end = len;
1047 else if (*end < 0)
1048 *end += len;
1049 if (*end < 0)
1050 *end = 0;
1051 if (*start < 0)
1052 *start += len;
1053 if (*start < 0)
1054 *start = 0;
1055}
1056
1057
1058Py_LOCAL_INLINE(Py_ssize_t)
1059bytes_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
1060{
1061 PyObject *subobj;
1062 Py_buffer subbuf;
1063 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1064 Py_ssize_t res;
1065
1066 if (!PyArg_ParseTuple(args, "O|O&O&:find/rfind/index/rindex", &subobj,
1067 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1068 return -2;
1069 if (_getbuffer(subobj, &subbuf) < 0)
1070 return -2;
1071 if (dir > 0)
1072 res = stringlib_find_slice(
1073 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1074 subbuf.buf, subbuf.len, start, end);
1075 else
1076 res = stringlib_rfind_slice(
1077 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1078 subbuf.buf, subbuf.len, start, end);
Martin v. Löwis423be952008-08-13 15:53:07 +00001079 PyBuffer_Release(&subbuf);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001080 return res;
1081}
1082
1083PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001084"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001085\n\
1086Return the lowest index in B where subsection sub is found,\n\
1087such that sub is contained within s[start,end]. Optional\n\
1088arguments start and end are interpreted as in slice notation.\n\
1089\n\
1090Return -1 on failure.");
1091
1092static PyObject *
1093bytes_find(PyByteArrayObject *self, PyObject *args)
1094{
1095 Py_ssize_t result = bytes_find_internal(self, args, +1);
1096 if (result == -2)
1097 return NULL;
1098 return PyLong_FromSsize_t(result);
1099}
1100
1101PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001102"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001103\n\
1104Return the number of non-overlapping occurrences of subsection sub in\n\
1105bytes B[start:end]. Optional arguments start and end are interpreted\n\
1106as in slice notation.");
1107
1108static PyObject *
1109bytes_count(PyByteArrayObject *self, PyObject *args)
1110{
1111 PyObject *sub_obj;
1112 const char *str = PyByteArray_AS_STRING(self);
1113 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
1114 Py_buffer vsub;
1115 PyObject *count_obj;
1116
1117 if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj,
1118 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1119 return NULL;
1120
1121 if (_getbuffer(sub_obj, &vsub) < 0)
1122 return NULL;
1123
1124 _adjust_indices(&start, &end, PyByteArray_GET_SIZE(self));
1125
1126 count_obj = PyLong_FromSsize_t(
1127 stringlib_count(str + start, end - start, vsub.buf, vsub.len)
1128 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001129 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001130 return count_obj;
1131}
1132
1133
1134PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001135"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001136\n\
1137Like B.find() but raise ValueError when the subsection is not found.");
1138
1139static PyObject *
1140bytes_index(PyByteArrayObject *self, PyObject *args)
1141{
1142 Py_ssize_t result = bytes_find_internal(self, args, +1);
1143 if (result == -2)
1144 return NULL;
1145 if (result == -1) {
1146 PyErr_SetString(PyExc_ValueError,
1147 "subsection not found");
1148 return NULL;
1149 }
1150 return PyLong_FromSsize_t(result);
1151}
1152
1153
1154PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001155"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001156\n\
1157Return the highest index in B where subsection sub is found,\n\
1158such that sub is contained within s[start,end]. Optional\n\
1159arguments start and end are interpreted as in slice notation.\n\
1160\n\
1161Return -1 on failure.");
1162
1163static PyObject *
1164bytes_rfind(PyByteArrayObject *self, PyObject *args)
1165{
1166 Py_ssize_t result = bytes_find_internal(self, args, -1);
1167 if (result == -2)
1168 return NULL;
1169 return PyLong_FromSsize_t(result);
1170}
1171
1172
1173PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001174"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001175\n\
1176Like B.rfind() but raise ValueError when the subsection is not found.");
1177
1178static PyObject *
1179bytes_rindex(PyByteArrayObject *self, PyObject *args)
1180{
1181 Py_ssize_t result = bytes_find_internal(self, args, -1);
1182 if (result == -2)
1183 return NULL;
1184 if (result == -1) {
1185 PyErr_SetString(PyExc_ValueError,
1186 "subsection not found");
1187 return NULL;
1188 }
1189 return PyLong_FromSsize_t(result);
1190}
1191
1192
1193static int
1194bytes_contains(PyObject *self, PyObject *arg)
1195{
1196 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1197 if (ival == -1 && PyErr_Occurred()) {
1198 Py_buffer varg;
1199 int pos;
1200 PyErr_Clear();
1201 if (_getbuffer(arg, &varg) < 0)
1202 return -1;
1203 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1204 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001205 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001206 return pos >= 0;
1207 }
1208 if (ival < 0 || ival >= 256) {
1209 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1210 return -1;
1211 }
1212
1213 return memchr(PyByteArray_AS_STRING(self), ival, Py_SIZE(self)) != NULL;
1214}
1215
1216
1217/* Matches the end (direction >= 0) or start (direction < 0) of self
1218 * against substr, using the start and end arguments. Returns
1219 * -1 on error, 0 if not found and 1 if found.
1220 */
1221Py_LOCAL(int)
1222_bytes_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
1223 Py_ssize_t end, int direction)
1224{
1225 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1226 const char* str;
1227 Py_buffer vsubstr;
1228 int rv = 0;
1229
1230 str = PyByteArray_AS_STRING(self);
1231
1232 if (_getbuffer(substr, &vsubstr) < 0)
1233 return -1;
1234
1235 _adjust_indices(&start, &end, len);
1236
1237 if (direction < 0) {
1238 /* startswith */
1239 if (start+vsubstr.len > len) {
1240 goto done;
1241 }
1242 } else {
1243 /* endswith */
1244 if (end-start < vsubstr.len || start > len) {
1245 goto done;
1246 }
1247
1248 if (end-vsubstr.len > start)
1249 start = end - vsubstr.len;
1250 }
1251 if (end-start >= vsubstr.len)
1252 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1253
1254done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001255 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001256 return rv;
1257}
1258
1259
1260PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001261"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001262\n\
1263Return True if B starts with the specified prefix, False otherwise.\n\
1264With optional start, test B beginning at that position.\n\
1265With optional end, stop comparing B at that position.\n\
1266prefix can also be a tuple of strings to try.");
1267
1268static PyObject *
1269bytes_startswith(PyByteArrayObject *self, PyObject *args)
1270{
1271 Py_ssize_t start = 0;
1272 Py_ssize_t end = PY_SSIZE_T_MAX;
1273 PyObject *subobj;
1274 int result;
1275
1276 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
1277 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1278 return NULL;
1279 if (PyTuple_Check(subobj)) {
1280 Py_ssize_t i;
1281 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
1282 result = _bytes_tailmatch(self,
1283 PyTuple_GET_ITEM(subobj, i),
1284 start, end, -1);
1285 if (result == -1)
1286 return NULL;
1287 else if (result) {
1288 Py_RETURN_TRUE;
1289 }
1290 }
1291 Py_RETURN_FALSE;
1292 }
1293 result = _bytes_tailmatch(self, subobj, start, end, -1);
1294 if (result == -1)
1295 return NULL;
1296 else
1297 return PyBool_FromLong(result);
1298}
1299
1300PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001301"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001302\n\
1303Return True if B ends with the specified suffix, False otherwise.\n\
1304With optional start, test B beginning at that position.\n\
1305With optional end, stop comparing B at that position.\n\
1306suffix can also be a tuple of strings to try.");
1307
1308static PyObject *
1309bytes_endswith(PyByteArrayObject *self, PyObject *args)
1310{
1311 Py_ssize_t start = 0;
1312 Py_ssize_t end = PY_SSIZE_T_MAX;
1313 PyObject *subobj;
1314 int result;
1315
1316 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
1317 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1318 return NULL;
1319 if (PyTuple_Check(subobj)) {
1320 Py_ssize_t i;
1321 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
1322 result = _bytes_tailmatch(self,
1323 PyTuple_GET_ITEM(subobj, i),
1324 start, end, +1);
1325 if (result == -1)
1326 return NULL;
1327 else if (result) {
1328 Py_RETURN_TRUE;
1329 }
1330 }
1331 Py_RETURN_FALSE;
1332 }
1333 result = _bytes_tailmatch(self, subobj, start, end, +1);
1334 if (result == -1)
1335 return NULL;
1336 else
1337 return PyBool_FromLong(result);
1338}
1339
1340
1341PyDoc_STRVAR(translate__doc__,
1342"B.translate(table[, deletechars]) -> bytearray\n\
1343\n\
1344Return a copy of B, where all characters occurring in the\n\
1345optional argument deletechars are removed, and the remaining\n\
1346characters have been mapped through the given translation\n\
1347table, which must be a bytes object of length 256.");
1348
1349static PyObject *
1350bytes_translate(PyByteArrayObject *self, PyObject *args)
1351{
1352 register char *input, *output;
1353 register const char *table;
1354 register Py_ssize_t i, c, changed = 0;
1355 PyObject *input_obj = (PyObject*)self;
1356 const char *output_start;
1357 Py_ssize_t inlen;
1358 PyObject *result;
1359 int trans_table[256];
1360 PyObject *tableobj, *delobj = NULL;
1361 Py_buffer vtable, vdel;
1362
1363 if (!PyArg_UnpackTuple(args, "translate", 1, 2,
1364 &tableobj, &delobj))
1365 return NULL;
1366
1367 if (_getbuffer(tableobj, &vtable) < 0)
1368 return NULL;
1369
1370 if (vtable.len != 256) {
1371 PyErr_SetString(PyExc_ValueError,
1372 "translation table must be 256 characters long");
1373 result = NULL;
1374 goto done;
1375 }
1376
1377 if (delobj != NULL) {
1378 if (_getbuffer(delobj, &vdel) < 0) {
1379 result = NULL;
1380 goto done;
1381 }
1382 }
1383 else {
1384 vdel.buf = NULL;
1385 vdel.len = 0;
1386 }
1387
1388 table = (const char *)vtable.buf;
1389 inlen = PyByteArray_GET_SIZE(input_obj);
1390 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1391 if (result == NULL)
1392 goto done;
1393 output_start = output = PyByteArray_AsString(result);
1394 input = PyByteArray_AS_STRING(input_obj);
1395
1396 if (vdel.len == 0) {
1397 /* If no deletions are required, use faster code */
1398 for (i = inlen; --i >= 0; ) {
1399 c = Py_CHARMASK(*input++);
1400 if (Py_CHARMASK((*output++ = table[c])) != c)
1401 changed = 1;
1402 }
1403 if (changed || !PyByteArray_CheckExact(input_obj))
1404 goto done;
1405 Py_DECREF(result);
1406 Py_INCREF(input_obj);
1407 result = input_obj;
1408 goto done;
1409 }
1410
1411 for (i = 0; i < 256; i++)
1412 trans_table[i] = Py_CHARMASK(table[i]);
1413
1414 for (i = 0; i < vdel.len; i++)
1415 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1416
1417 for (i = inlen; --i >= 0; ) {
1418 c = Py_CHARMASK(*input++);
1419 if (trans_table[c] != -1)
1420 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1421 continue;
1422 changed = 1;
1423 }
1424 if (!changed && PyByteArray_CheckExact(input_obj)) {
1425 Py_DECREF(result);
1426 Py_INCREF(input_obj);
1427 result = input_obj;
1428 goto done;
1429 }
1430 /* Fix the size of the resulting string */
1431 if (inlen > 0)
1432 PyByteArray_Resize(result, output - output_start);
1433
1434done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001435 PyBuffer_Release(&vtable);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001436 if (delobj != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001437 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001438 return result;
1439}
1440
1441
1442#define FORWARD 1
1443#define REVERSE -1
1444
1445/* find and count characters and substrings */
1446
1447#define findchar(target, target_len, c) \
1448 ((char *)memchr((const void *)(target), c, target_len))
1449
1450/* Don't call if length < 2 */
1451#define Py_STRING_MATCH(target, offset, pattern, length) \
1452 (target[offset] == pattern[0] && \
1453 target[offset+length-1] == pattern[length-1] && \
1454 !memcmp(target+offset+1, pattern+1, length-2) )
1455
1456
1457/* Bytes ops must return a string. */
1458/* If the object is subclass of bytes, create a copy */
1459Py_LOCAL(PyByteArrayObject *)
1460return_self(PyByteArrayObject *self)
1461{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001462 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001463 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1464 PyByteArray_AS_STRING(self),
1465 PyByteArray_GET_SIZE(self));
1466}
1467
1468Py_LOCAL_INLINE(Py_ssize_t)
1469countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1470{
1471 Py_ssize_t count=0;
1472 const char *start=target;
1473 const char *end=target+target_len;
1474
1475 while ( (start=findchar(start, end-start, c)) != NULL ) {
1476 count++;
1477 if (count >= maxcount)
1478 break;
1479 start += 1;
1480 }
1481 return count;
1482}
1483
1484Py_LOCAL(Py_ssize_t)
1485findstring(const char *target, Py_ssize_t target_len,
1486 const char *pattern, Py_ssize_t pattern_len,
1487 Py_ssize_t start,
1488 Py_ssize_t end,
1489 int direction)
1490{
1491 if (start < 0) {
1492 start += target_len;
1493 if (start < 0)
1494 start = 0;
1495 }
1496 if (end > target_len) {
1497 end = target_len;
1498 } else if (end < 0) {
1499 end += target_len;
1500 if (end < 0)
1501 end = 0;
1502 }
1503
1504 /* zero-length substrings always match at the first attempt */
1505 if (pattern_len == 0)
1506 return (direction > 0) ? start : end;
1507
1508 end -= pattern_len;
1509
1510 if (direction < 0) {
1511 for (; end >= start; end--)
1512 if (Py_STRING_MATCH(target, end, pattern, pattern_len))
1513 return end;
1514 } else {
1515 for (; start <= end; start++)
1516 if (Py_STRING_MATCH(target, start, pattern, pattern_len))
1517 return start;
1518 }
1519 return -1;
1520}
1521
1522Py_LOCAL_INLINE(Py_ssize_t)
1523countstring(const char *target, Py_ssize_t target_len,
1524 const char *pattern, Py_ssize_t pattern_len,
1525 Py_ssize_t start,
1526 Py_ssize_t end,
1527 int direction, Py_ssize_t maxcount)
1528{
1529 Py_ssize_t count=0;
1530
1531 if (start < 0) {
1532 start += target_len;
1533 if (start < 0)
1534 start = 0;
1535 }
1536 if (end > target_len) {
1537 end = target_len;
1538 } else if (end < 0) {
1539 end += target_len;
1540 if (end < 0)
1541 end = 0;
1542 }
1543
1544 /* zero-length substrings match everywhere */
1545 if (pattern_len == 0 || maxcount == 0) {
1546 if (target_len+1 < maxcount)
1547 return target_len+1;
1548 return maxcount;
1549 }
1550
1551 end -= pattern_len;
1552 if (direction < 0) {
1553 for (; (end >= start); end--)
1554 if (Py_STRING_MATCH(target, end, pattern, pattern_len)) {
1555 count++;
1556 if (--maxcount <= 0) break;
1557 end -= pattern_len-1;
1558 }
1559 } else {
1560 for (; (start <= end); start++)
1561 if (Py_STRING_MATCH(target, start, pattern, pattern_len)) {
1562 count++;
1563 if (--maxcount <= 0)
1564 break;
1565 start += pattern_len-1;
1566 }
1567 }
1568 return count;
1569}
1570
1571
1572/* Algorithms for different cases of string replacement */
1573
1574/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1575Py_LOCAL(PyByteArrayObject *)
1576replace_interleave(PyByteArrayObject *self,
1577 const char *to_s, Py_ssize_t to_len,
1578 Py_ssize_t maxcount)
1579{
1580 char *self_s, *result_s;
1581 Py_ssize_t self_len, result_len;
1582 Py_ssize_t count, i, product;
1583 PyByteArrayObject *result;
1584
1585 self_len = PyByteArray_GET_SIZE(self);
1586
1587 /* 1 at the end plus 1 after every character */
1588 count = self_len+1;
1589 if (maxcount < count)
1590 count = maxcount;
1591
1592 /* Check for overflow */
1593 /* result_len = count * to_len + self_len; */
1594 product = count * to_len;
1595 if (product / to_len != count) {
1596 PyErr_SetString(PyExc_OverflowError,
1597 "replace string is too long");
1598 return NULL;
1599 }
1600 result_len = product + self_len;
1601 if (result_len < 0) {
1602 PyErr_SetString(PyExc_OverflowError,
1603 "replace string is too long");
1604 return NULL;
1605 }
1606
1607 if (! (result = (PyByteArrayObject *)
1608 PyByteArray_FromStringAndSize(NULL, result_len)) )
1609 return NULL;
1610
1611 self_s = PyByteArray_AS_STRING(self);
1612 result_s = PyByteArray_AS_STRING(result);
1613
1614 /* TODO: special case single character, which doesn't need memcpy */
1615
1616 /* Lay the first one down (guaranteed this will occur) */
1617 Py_MEMCPY(result_s, to_s, to_len);
1618 result_s += to_len;
1619 count -= 1;
1620
1621 for (i=0; i<count; i++) {
1622 *result_s++ = *self_s++;
1623 Py_MEMCPY(result_s, to_s, to_len);
1624 result_s += to_len;
1625 }
1626
1627 /* Copy the rest of the original string */
1628 Py_MEMCPY(result_s, self_s, self_len-i);
1629
1630 return result;
1631}
1632
1633/* Special case for deleting a single character */
1634/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1635Py_LOCAL(PyByteArrayObject *)
1636replace_delete_single_character(PyByteArrayObject *self,
1637 char from_c, Py_ssize_t maxcount)
1638{
1639 char *self_s, *result_s;
1640 char *start, *next, *end;
1641 Py_ssize_t self_len, result_len;
1642 Py_ssize_t count;
1643 PyByteArrayObject *result;
1644
1645 self_len = PyByteArray_GET_SIZE(self);
1646 self_s = PyByteArray_AS_STRING(self);
1647
1648 count = countchar(self_s, self_len, from_c, maxcount);
1649 if (count == 0) {
1650 return return_self(self);
1651 }
1652
1653 result_len = self_len - count; /* from_len == 1 */
1654 assert(result_len>=0);
1655
1656 if ( (result = (PyByteArrayObject *)
1657 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1658 return NULL;
1659 result_s = PyByteArray_AS_STRING(result);
1660
1661 start = self_s;
1662 end = self_s + self_len;
1663 while (count-- > 0) {
1664 next = findchar(start, end-start, from_c);
1665 if (next == NULL)
1666 break;
1667 Py_MEMCPY(result_s, start, next-start);
1668 result_s += (next-start);
1669 start = next+1;
1670 }
1671 Py_MEMCPY(result_s, start, end-start);
1672
1673 return result;
1674}
1675
1676/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1677
1678Py_LOCAL(PyByteArrayObject *)
1679replace_delete_substring(PyByteArrayObject *self,
1680 const char *from_s, Py_ssize_t from_len,
1681 Py_ssize_t maxcount)
1682{
1683 char *self_s, *result_s;
1684 char *start, *next, *end;
1685 Py_ssize_t self_len, result_len;
1686 Py_ssize_t count, offset;
1687 PyByteArrayObject *result;
1688
1689 self_len = PyByteArray_GET_SIZE(self);
1690 self_s = PyByteArray_AS_STRING(self);
1691
1692 count = countstring(self_s, self_len,
1693 from_s, from_len,
1694 0, self_len, 1,
1695 maxcount);
1696
1697 if (count == 0) {
1698 /* no matches */
1699 return return_self(self);
1700 }
1701
1702 result_len = self_len - (count * from_len);
1703 assert (result_len>=0);
1704
1705 if ( (result = (PyByteArrayObject *)
1706 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1707 return NULL;
1708
1709 result_s = PyByteArray_AS_STRING(result);
1710
1711 start = self_s;
1712 end = self_s + self_len;
1713 while (count-- > 0) {
1714 offset = findstring(start, end-start,
1715 from_s, from_len,
1716 0, end-start, FORWARD);
1717 if (offset == -1)
1718 break;
1719 next = start + offset;
1720
1721 Py_MEMCPY(result_s, start, next-start);
1722
1723 result_s += (next-start);
1724 start = next+from_len;
1725 }
1726 Py_MEMCPY(result_s, start, end-start);
1727 return result;
1728}
1729
1730/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1731Py_LOCAL(PyByteArrayObject *)
1732replace_single_character_in_place(PyByteArrayObject *self,
1733 char from_c, char to_c,
1734 Py_ssize_t maxcount)
1735{
1736 char *self_s, *result_s, *start, *end, *next;
1737 Py_ssize_t self_len;
1738 PyByteArrayObject *result;
1739
1740 /* The result string will be the same size */
1741 self_s = PyByteArray_AS_STRING(self);
1742 self_len = PyByteArray_GET_SIZE(self);
1743
1744 next = findchar(self_s, self_len, from_c);
1745
1746 if (next == NULL) {
1747 /* No matches; return the original bytes */
1748 return return_self(self);
1749 }
1750
1751 /* Need to make a new bytes */
1752 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1753 if (result == NULL)
1754 return NULL;
1755 result_s = PyByteArray_AS_STRING(result);
1756 Py_MEMCPY(result_s, self_s, self_len);
1757
1758 /* change everything in-place, starting with this one */
1759 start = result_s + (next-self_s);
1760 *start = to_c;
1761 start++;
1762 end = result_s + self_len;
1763
1764 while (--maxcount > 0) {
1765 next = findchar(start, end-start, from_c);
1766 if (next == NULL)
1767 break;
1768 *next = to_c;
1769 start = next+1;
1770 }
1771
1772 return result;
1773}
1774
1775/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1776Py_LOCAL(PyByteArrayObject *)
1777replace_substring_in_place(PyByteArrayObject *self,
1778 const char *from_s, Py_ssize_t from_len,
1779 const char *to_s, Py_ssize_t to_len,
1780 Py_ssize_t maxcount)
1781{
1782 char *result_s, *start, *end;
1783 char *self_s;
1784 Py_ssize_t self_len, offset;
1785 PyByteArrayObject *result;
1786
1787 /* The result bytes will be the same size */
1788
1789 self_s = PyByteArray_AS_STRING(self);
1790 self_len = PyByteArray_GET_SIZE(self);
1791
1792 offset = findstring(self_s, self_len,
1793 from_s, from_len,
1794 0, self_len, FORWARD);
1795 if (offset == -1) {
1796 /* No matches; return the original bytes */
1797 return return_self(self);
1798 }
1799
1800 /* Need to make a new bytes */
1801 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1802 if (result == NULL)
1803 return NULL;
1804 result_s = PyByteArray_AS_STRING(result);
1805 Py_MEMCPY(result_s, self_s, self_len);
1806
1807 /* change everything in-place, starting with this one */
1808 start = result_s + offset;
1809 Py_MEMCPY(start, to_s, from_len);
1810 start += from_len;
1811 end = result_s + self_len;
1812
1813 while ( --maxcount > 0) {
1814 offset = findstring(start, end-start,
1815 from_s, from_len,
1816 0, end-start, FORWARD);
1817 if (offset==-1)
1818 break;
1819 Py_MEMCPY(start+offset, to_s, from_len);
1820 start += offset+from_len;
1821 }
1822
1823 return result;
1824}
1825
1826/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
1827Py_LOCAL(PyByteArrayObject *)
1828replace_single_character(PyByteArrayObject *self,
1829 char from_c,
1830 const char *to_s, Py_ssize_t to_len,
1831 Py_ssize_t maxcount)
1832{
1833 char *self_s, *result_s;
1834 char *start, *next, *end;
1835 Py_ssize_t self_len, result_len;
1836 Py_ssize_t count, product;
1837 PyByteArrayObject *result;
1838
1839 self_s = PyByteArray_AS_STRING(self);
1840 self_len = PyByteArray_GET_SIZE(self);
1841
1842 count = countchar(self_s, self_len, from_c, maxcount);
1843 if (count == 0) {
1844 /* no matches, return unchanged */
1845 return return_self(self);
1846 }
1847
1848 /* use the difference between current and new, hence the "-1" */
1849 /* result_len = self_len + count * (to_len-1) */
1850 product = count * (to_len-1);
1851 if (product / (to_len-1) != count) {
1852 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1853 return NULL;
1854 }
1855 result_len = self_len + product;
1856 if (result_len < 0) {
1857 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1858 return NULL;
1859 }
1860
1861 if ( (result = (PyByteArrayObject *)
1862 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1863 return NULL;
1864 result_s = PyByteArray_AS_STRING(result);
1865
1866 start = self_s;
1867 end = self_s + self_len;
1868 while (count-- > 0) {
1869 next = findchar(start, end-start, from_c);
1870 if (next == NULL)
1871 break;
1872
1873 if (next == start) {
1874 /* replace with the 'to' */
1875 Py_MEMCPY(result_s, to_s, to_len);
1876 result_s += to_len;
1877 start += 1;
1878 } else {
1879 /* copy the unchanged old then the 'to' */
1880 Py_MEMCPY(result_s, start, next-start);
1881 result_s += (next-start);
1882 Py_MEMCPY(result_s, to_s, to_len);
1883 result_s += to_len;
1884 start = next+1;
1885 }
1886 }
1887 /* Copy the remainder of the remaining bytes */
1888 Py_MEMCPY(result_s, start, end-start);
1889
1890 return result;
1891}
1892
1893/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
1894Py_LOCAL(PyByteArrayObject *)
1895replace_substring(PyByteArrayObject *self,
1896 const char *from_s, Py_ssize_t from_len,
1897 const char *to_s, Py_ssize_t to_len,
1898 Py_ssize_t maxcount)
1899{
1900 char *self_s, *result_s;
1901 char *start, *next, *end;
1902 Py_ssize_t self_len, result_len;
1903 Py_ssize_t count, offset, product;
1904 PyByteArrayObject *result;
1905
1906 self_s = PyByteArray_AS_STRING(self);
1907 self_len = PyByteArray_GET_SIZE(self);
1908
1909 count = countstring(self_s, self_len,
1910 from_s, from_len,
1911 0, self_len, FORWARD, maxcount);
1912 if (count == 0) {
1913 /* no matches, return unchanged */
1914 return return_self(self);
1915 }
1916
1917 /* Check for overflow */
1918 /* result_len = self_len + count * (to_len-from_len) */
1919 product = count * (to_len-from_len);
1920 if (product / (to_len-from_len) != count) {
1921 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1922 return NULL;
1923 }
1924 result_len = self_len + product;
1925 if (result_len < 0) {
1926 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1927 return NULL;
1928 }
1929
1930 if ( (result = (PyByteArrayObject *)
1931 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1932 return NULL;
1933 result_s = PyByteArray_AS_STRING(result);
1934
1935 start = self_s;
1936 end = self_s + self_len;
1937 while (count-- > 0) {
1938 offset = findstring(start, end-start,
1939 from_s, from_len,
1940 0, end-start, FORWARD);
1941 if (offset == -1)
1942 break;
1943 next = start+offset;
1944 if (next == start) {
1945 /* replace with the 'to' */
1946 Py_MEMCPY(result_s, to_s, to_len);
1947 result_s += to_len;
1948 start += from_len;
1949 } else {
1950 /* copy the unchanged old then the 'to' */
1951 Py_MEMCPY(result_s, start, next-start);
1952 result_s += (next-start);
1953 Py_MEMCPY(result_s, to_s, to_len);
1954 result_s += to_len;
1955 start = next+from_len;
1956 }
1957 }
1958 /* Copy the remainder of the remaining bytes */
1959 Py_MEMCPY(result_s, start, end-start);
1960
1961 return result;
1962}
1963
1964
1965Py_LOCAL(PyByteArrayObject *)
1966replace(PyByteArrayObject *self,
1967 const char *from_s, Py_ssize_t from_len,
1968 const char *to_s, Py_ssize_t to_len,
1969 Py_ssize_t maxcount)
1970{
1971 if (maxcount < 0) {
1972 maxcount = PY_SSIZE_T_MAX;
1973 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
1974 /* nothing to do; return the original bytes */
1975 return return_self(self);
1976 }
1977
1978 if (maxcount == 0 ||
1979 (from_len == 0 && to_len == 0)) {
1980 /* nothing to do; return the original bytes */
1981 return return_self(self);
1982 }
1983
1984 /* Handle zero-length special cases */
1985
1986 if (from_len == 0) {
1987 /* insert the 'to' bytes everywhere. */
1988 /* >>> "Python".replace("", ".") */
1989 /* '.P.y.t.h.o.n.' */
1990 return replace_interleave(self, to_s, to_len, maxcount);
1991 }
1992
1993 /* Except for "".replace("", "A") == "A" there is no way beyond this */
1994 /* point for an empty self bytes to generate a non-empty bytes */
1995 /* Special case so the remaining code always gets a non-empty bytes */
1996 if (PyByteArray_GET_SIZE(self) == 0) {
1997 return return_self(self);
1998 }
1999
2000 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00002001 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002002 if (from_len == 1) {
2003 return replace_delete_single_character(
2004 self, from_s[0], maxcount);
2005 } else {
2006 return replace_delete_substring(self, from_s, from_len, maxcount);
2007 }
2008 }
2009
2010 /* Handle special case where both bytes have the same length */
2011
2012 if (from_len == to_len) {
2013 if (from_len == 1) {
2014 return replace_single_character_in_place(
2015 self,
2016 from_s[0],
2017 to_s[0],
2018 maxcount);
2019 } else {
2020 return replace_substring_in_place(
2021 self, from_s, from_len, to_s, to_len, maxcount);
2022 }
2023 }
2024
2025 /* Otherwise use the more generic algorithms */
2026 if (from_len == 1) {
2027 return replace_single_character(self, from_s[0],
2028 to_s, to_len, maxcount);
2029 } else {
2030 /* len('from')>=2, len('to')>=1 */
2031 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
2032 }
2033}
2034
2035
2036PyDoc_STRVAR(replace__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002037"B.replace(old, new[, count]) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002038\n\
2039Return a copy of B with all occurrences of subsection\n\
2040old replaced by new. If the optional argument count is\n\
2041given, only the first count occurrences are replaced.");
2042
2043static PyObject *
2044bytes_replace(PyByteArrayObject *self, PyObject *args)
2045{
2046 Py_ssize_t count = -1;
2047 PyObject *from, *to, *res;
2048 Py_buffer vfrom, vto;
2049
2050 if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
2051 return NULL;
2052
2053 if (_getbuffer(from, &vfrom) < 0)
2054 return NULL;
2055 if (_getbuffer(to, &vto) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +00002056 PyBuffer_Release(&vfrom);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002057 return NULL;
2058 }
2059
2060 res = (PyObject *)replace((PyByteArrayObject *) self,
2061 vfrom.buf, vfrom.len,
2062 vto.buf, vto.len, count);
2063
Martin v. Löwis423be952008-08-13 15:53:07 +00002064 PyBuffer_Release(&vfrom);
2065 PyBuffer_Release(&vto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002066 return res;
2067}
2068
2069
2070/* Overallocate the initial list to reduce the number of reallocs for small
2071 split sizes. Eg, "A A A A A A A A A A".split() (10 elements) has three
2072 resizes, to sizes 4, 8, then 16. Most observed string splits are for human
2073 text (roughly 11 words per line) and field delimited data (usually 1-10
2074 fields). For large strings the split algorithms are bandwidth limited
2075 so increasing the preallocation likely will not improve things.*/
2076
2077#define MAX_PREALLOC 12
2078
2079/* 5 splits gives 6 elements */
2080#define PREALLOC_SIZE(maxsplit) \
2081 (maxsplit >= MAX_PREALLOC ? MAX_PREALLOC : maxsplit+1)
2082
2083#define SPLIT_APPEND(data, left, right) \
2084 str = PyByteArray_FromStringAndSize((data) + (left), \
2085 (right) - (left)); \
2086 if (str == NULL) \
2087 goto onError; \
2088 if (PyList_Append(list, str)) { \
2089 Py_DECREF(str); \
2090 goto onError; \
2091 } \
2092 else \
2093 Py_DECREF(str);
2094
2095#define SPLIT_ADD(data, left, right) { \
2096 str = PyByteArray_FromStringAndSize((data) + (left), \
2097 (right) - (left)); \
2098 if (str == NULL) \
2099 goto onError; \
2100 if (count < MAX_PREALLOC) { \
2101 PyList_SET_ITEM(list, count, str); \
2102 } else { \
2103 if (PyList_Append(list, str)) { \
2104 Py_DECREF(str); \
2105 goto onError; \
2106 } \
2107 else \
2108 Py_DECREF(str); \
2109 } \
2110 count++; }
2111
2112/* Always force the list to the expected size. */
2113#define FIX_PREALLOC_SIZE(list) Py_SIZE(list) = count
2114
2115
2116Py_LOCAL_INLINE(PyObject *)
2117split_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount)
2118{
2119 register Py_ssize_t i, j, count = 0;
2120 PyObject *str;
2121 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2122
2123 if (list == NULL)
2124 return NULL;
2125
2126 i = j = 0;
2127 while ((j < len) && (maxcount-- > 0)) {
2128 for(; j < len; j++) {
2129 /* I found that using memchr makes no difference */
2130 if (s[j] == ch) {
2131 SPLIT_ADD(s, i, j);
2132 i = j = j + 1;
2133 break;
2134 }
2135 }
2136 }
2137 if (i <= len) {
2138 SPLIT_ADD(s, i, len);
2139 }
2140 FIX_PREALLOC_SIZE(list);
2141 return list;
2142
2143 onError:
2144 Py_DECREF(list);
2145 return NULL;
2146}
2147
2148
2149Py_LOCAL_INLINE(PyObject *)
2150split_whitespace(const char *s, Py_ssize_t len, Py_ssize_t maxcount)
2151{
2152 register Py_ssize_t i, j, count = 0;
2153 PyObject *str;
2154 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2155
2156 if (list == NULL)
2157 return NULL;
2158
2159 for (i = j = 0; i < len; ) {
2160 /* find a token */
2161 while (i < len && ISSPACE(s[i]))
2162 i++;
2163 j = i;
2164 while (i < len && !ISSPACE(s[i]))
2165 i++;
2166 if (j < i) {
2167 if (maxcount-- <= 0)
2168 break;
2169 SPLIT_ADD(s, j, i);
2170 while (i < len && ISSPACE(s[i]))
2171 i++;
2172 j = i;
2173 }
2174 }
2175 if (j < len) {
2176 SPLIT_ADD(s, j, len);
2177 }
2178 FIX_PREALLOC_SIZE(list);
2179 return list;
2180
2181 onError:
2182 Py_DECREF(list);
2183 return NULL;
2184}
2185
2186PyDoc_STRVAR(split__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002187"B.split([sep[, maxsplit]]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002188\n\
2189Return a list of the sections in B, using sep as the delimiter.\n\
2190If sep is not given, B is split on ASCII whitespace characters\n\
2191(space, tab, return, newline, formfeed, vertical tab).\n\
2192If maxsplit is given, at most maxsplit splits are done.");
2193
2194static PyObject *
2195bytes_split(PyByteArrayObject *self, PyObject *args)
2196{
2197 Py_ssize_t len = PyByteArray_GET_SIZE(self), n, i, j;
2198 Py_ssize_t maxsplit = -1, count = 0;
2199 const char *s = PyByteArray_AS_STRING(self), *sub;
2200 PyObject *list, *str, *subobj = Py_None;
2201 Py_buffer vsub;
2202#ifdef USE_FAST
2203 Py_ssize_t pos;
2204#endif
2205
2206 if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
2207 return NULL;
2208 if (maxsplit < 0)
2209 maxsplit = PY_SSIZE_T_MAX;
2210
2211 if (subobj == Py_None)
2212 return split_whitespace(s, len, maxsplit);
2213
2214 if (_getbuffer(subobj, &vsub) < 0)
2215 return NULL;
2216 sub = vsub.buf;
2217 n = vsub.len;
2218
2219 if (n == 0) {
2220 PyErr_SetString(PyExc_ValueError, "empty separator");
Martin v. Löwis423be952008-08-13 15:53:07 +00002221 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002222 return NULL;
2223 }
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +00002224 if (n == 1) {
2225 list = split_char(s, len, sub[0], maxsplit);
2226 PyBuffer_Release(&vsub);
2227 return list;
2228 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002229
2230 list = PyList_New(PREALLOC_SIZE(maxsplit));
2231 if (list == NULL) {
Martin v. Löwis423be952008-08-13 15:53:07 +00002232 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002233 return NULL;
2234 }
2235
2236#ifdef USE_FAST
2237 i = j = 0;
2238 while (maxsplit-- > 0) {
2239 pos = fastsearch(s+i, len-i, sub, n, FAST_SEARCH);
2240 if (pos < 0)
2241 break;
2242 j = i+pos;
2243 SPLIT_ADD(s, i, j);
2244 i = j + n;
2245 }
2246#else
2247 i = j = 0;
2248 while ((j+n <= len) && (maxsplit-- > 0)) {
2249 for (; j+n <= len; j++) {
2250 if (Py_STRING_MATCH(s, j, sub, n)) {
2251 SPLIT_ADD(s, i, j);
2252 i = j = j + n;
2253 break;
2254 }
2255 }
2256 }
2257#endif
2258 SPLIT_ADD(s, i, len);
2259 FIX_PREALLOC_SIZE(list);
Martin v. Löwis423be952008-08-13 15:53:07 +00002260 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002261 return list;
2262
2263 onError:
2264 Py_DECREF(list);
Martin v. Löwis423be952008-08-13 15:53:07 +00002265 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002266 return NULL;
2267}
2268
2269/* stringlib's partition shares nullbytes in some cases.
2270 undo this, we don't want the nullbytes to be shared. */
2271static PyObject *
2272make_nullbytes_unique(PyObject *result)
2273{
2274 if (result != NULL) {
2275 int i;
2276 assert(PyTuple_Check(result));
2277 assert(PyTuple_GET_SIZE(result) == 3);
2278 for (i = 0; i < 3; i++) {
2279 if (PyTuple_GET_ITEM(result, i) == (PyObject *)nullbytes) {
2280 PyObject *new = PyByteArray_FromStringAndSize(NULL, 0);
2281 if (new == NULL) {
2282 Py_DECREF(result);
2283 result = NULL;
2284 break;
2285 }
2286 Py_DECREF(nullbytes);
2287 PyTuple_SET_ITEM(result, i, new);
2288 }
2289 }
2290 }
2291 return result;
2292}
2293
2294PyDoc_STRVAR(partition__doc__,
2295"B.partition(sep) -> (head, sep, tail)\n\
2296\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002297Search for the separator sep in B, and return the part before it,\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002298the separator itself, and the part after it. If the separator is not\n\
2299found, returns B and two empty bytearray objects.");
2300
2301static PyObject *
2302bytes_partition(PyByteArrayObject *self, PyObject *sep_obj)
2303{
2304 PyObject *bytesep, *result;
2305
2306 bytesep = PyByteArray_FromObject(sep_obj);
2307 if (! bytesep)
2308 return NULL;
2309
2310 result = stringlib_partition(
2311 (PyObject*) self,
2312 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2313 bytesep,
2314 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2315 );
2316
2317 Py_DECREF(bytesep);
2318 return make_nullbytes_unique(result);
2319}
2320
2321PyDoc_STRVAR(rpartition__doc__,
2322"B.rpartition(sep) -> (tail, sep, head)\n\
2323\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002324Search for the separator sep in B, starting at the end of B,\n\
2325and return the part before it, the separator itself, and the\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002326part after it. If the separator is not found, returns two empty\n\
2327bytearray objects and B.");
2328
2329static PyObject *
2330bytes_rpartition(PyByteArrayObject *self, PyObject *sep_obj)
2331{
2332 PyObject *bytesep, *result;
2333
2334 bytesep = PyByteArray_FromObject(sep_obj);
2335 if (! bytesep)
2336 return NULL;
2337
2338 result = stringlib_rpartition(
2339 (PyObject*) self,
2340 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2341 bytesep,
2342 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2343 );
2344
2345 Py_DECREF(bytesep);
2346 return make_nullbytes_unique(result);
2347}
2348
2349Py_LOCAL_INLINE(PyObject *)
2350rsplit_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount)
2351{
2352 register Py_ssize_t i, j, count=0;
2353 PyObject *str;
2354 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2355
2356 if (list == NULL)
2357 return NULL;
2358
2359 i = j = len - 1;
2360 while ((i >= 0) && (maxcount-- > 0)) {
2361 for (; i >= 0; i--) {
2362 if (s[i] == ch) {
2363 SPLIT_ADD(s, i + 1, j + 1);
2364 j = i = i - 1;
2365 break;
2366 }
2367 }
2368 }
2369 if (j >= -1) {
2370 SPLIT_ADD(s, 0, j + 1);
2371 }
2372 FIX_PREALLOC_SIZE(list);
2373 if (PyList_Reverse(list) < 0)
2374 goto onError;
2375
2376 return list;
2377
2378 onError:
2379 Py_DECREF(list);
2380 return NULL;
2381}
2382
2383Py_LOCAL_INLINE(PyObject *)
2384rsplit_whitespace(const char *s, Py_ssize_t len, Py_ssize_t maxcount)
2385{
2386 register Py_ssize_t i, j, count = 0;
2387 PyObject *str;
2388 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2389
2390 if (list == NULL)
2391 return NULL;
2392
2393 for (i = j = len - 1; i >= 0; ) {
2394 /* find a token */
2395 while (i >= 0 && ISSPACE(s[i]))
2396 i--;
2397 j = i;
2398 while (i >= 0 && !ISSPACE(s[i]))
2399 i--;
2400 if (j > i) {
2401 if (maxcount-- <= 0)
2402 break;
2403 SPLIT_ADD(s, i + 1, j + 1);
2404 while (i >= 0 && ISSPACE(s[i]))
2405 i--;
2406 j = i;
2407 }
2408 }
2409 if (j >= 0) {
2410 SPLIT_ADD(s, 0, j + 1);
2411 }
2412 FIX_PREALLOC_SIZE(list);
2413 if (PyList_Reverse(list) < 0)
2414 goto onError;
2415
2416 return list;
2417
2418 onError:
2419 Py_DECREF(list);
2420 return NULL;
2421}
2422
2423PyDoc_STRVAR(rsplit__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002424"B.rsplit(sep[, maxsplit]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002425\n\
2426Return a list of the sections in B, using sep as the delimiter,\n\
2427starting at the end of B and working to the front.\n\
2428If sep is not given, B is split on ASCII whitespace characters\n\
2429(space, tab, return, newline, formfeed, vertical tab).\n\
2430If maxsplit is given, at most maxsplit splits are done.");
2431
2432static PyObject *
2433bytes_rsplit(PyByteArrayObject *self, PyObject *args)
2434{
2435 Py_ssize_t len = PyByteArray_GET_SIZE(self), n, i, j;
2436 Py_ssize_t maxsplit = -1, count = 0;
2437 const char *s = PyByteArray_AS_STRING(self), *sub;
2438 PyObject *list, *str, *subobj = Py_None;
2439 Py_buffer vsub;
2440
2441 if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
2442 return NULL;
2443 if (maxsplit < 0)
2444 maxsplit = PY_SSIZE_T_MAX;
2445
2446 if (subobj == Py_None)
2447 return rsplit_whitespace(s, len, maxsplit);
2448
2449 if (_getbuffer(subobj, &vsub) < 0)
2450 return NULL;
2451 sub = vsub.buf;
2452 n = vsub.len;
2453
2454 if (n == 0) {
2455 PyErr_SetString(PyExc_ValueError, "empty separator");
Martin v. Löwis423be952008-08-13 15:53:07 +00002456 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002457 return NULL;
2458 }
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +00002459 else if (n == 1) {
2460 list = rsplit_char(s, len, sub[0], maxsplit);
2461 PyBuffer_Release(&vsub);
2462 return list;
2463 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002464
2465 list = PyList_New(PREALLOC_SIZE(maxsplit));
2466 if (list == NULL) {
Martin v. Löwis423be952008-08-13 15:53:07 +00002467 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002468 return NULL;
2469 }
2470
2471 j = len;
2472 i = j - n;
2473
2474 while ( (i >= 0) && (maxsplit-- > 0) ) {
2475 for (; i>=0; i--) {
2476 if (Py_STRING_MATCH(s, i, sub, n)) {
2477 SPLIT_ADD(s, i + n, j);
2478 j = i;
2479 i -= n;
2480 break;
2481 }
2482 }
2483 }
2484 SPLIT_ADD(s, 0, j);
2485 FIX_PREALLOC_SIZE(list);
2486 if (PyList_Reverse(list) < 0)
2487 goto onError;
Martin v. Löwis423be952008-08-13 15:53:07 +00002488 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002489 return list;
2490
2491onError:
2492 Py_DECREF(list);
Martin v. Löwis423be952008-08-13 15:53:07 +00002493 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002494 return NULL;
2495}
2496
2497PyDoc_STRVAR(reverse__doc__,
2498"B.reverse() -> None\n\
2499\n\
2500Reverse the order of the values in B in place.");
2501static PyObject *
2502bytes_reverse(PyByteArrayObject *self, PyObject *unused)
2503{
2504 char swap, *head, *tail;
2505 Py_ssize_t i, j, n = Py_SIZE(self);
2506
2507 j = n / 2;
2508 head = self->ob_bytes;
2509 tail = head + n - 1;
2510 for (i = 0; i < j; i++) {
2511 swap = *head;
2512 *head++ = *tail;
2513 *tail-- = swap;
2514 }
2515
2516 Py_RETURN_NONE;
2517}
2518
2519PyDoc_STRVAR(insert__doc__,
2520"B.insert(index, int) -> None\n\
2521\n\
2522Insert a single item into the bytearray before the given index.");
2523static PyObject *
2524bytes_insert(PyByteArrayObject *self, PyObject *args)
2525{
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002526 PyObject *value;
2527 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002528 Py_ssize_t where, n = Py_SIZE(self);
2529
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002530 if (!PyArg_ParseTuple(args, "nO:insert", &where, &value))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002531 return NULL;
2532
2533 if (n == PY_SSIZE_T_MAX) {
2534 PyErr_SetString(PyExc_OverflowError,
2535 "cannot add more objects to bytes");
2536 return NULL;
2537 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002538 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002539 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002540 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2541 return NULL;
2542
2543 if (where < 0) {
2544 where += n;
2545 if (where < 0)
2546 where = 0;
2547 }
2548 if (where > n)
2549 where = n;
2550 memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where);
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002551 self->ob_bytes[where] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002552
2553 Py_RETURN_NONE;
2554}
2555
2556PyDoc_STRVAR(append__doc__,
2557"B.append(int) -> None\n\
2558\n\
2559Append a single item to the end of B.");
2560static PyObject *
2561bytes_append(PyByteArrayObject *self, PyObject *arg)
2562{
2563 int value;
2564 Py_ssize_t n = Py_SIZE(self);
2565
2566 if (! _getbytevalue(arg, &value))
2567 return NULL;
2568 if (n == PY_SSIZE_T_MAX) {
2569 PyErr_SetString(PyExc_OverflowError,
2570 "cannot add more objects to bytes");
2571 return NULL;
2572 }
2573 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2574 return NULL;
2575
2576 self->ob_bytes[n] = value;
2577
2578 Py_RETURN_NONE;
2579}
2580
2581PyDoc_STRVAR(extend__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002582"B.extend(iterable_of_ints) -> None\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002583\n\
2584Append all the elements from the iterator or sequence to the\n\
2585end of B.");
2586static PyObject *
2587bytes_extend(PyByteArrayObject *self, PyObject *arg)
2588{
2589 PyObject *it, *item, *bytes_obj;
2590 Py_ssize_t buf_size = 0, len = 0;
2591 int value;
2592 char *buf;
2593
2594 /* bytes_setslice code only accepts something supporting PEP 3118. */
2595 if (PyObject_CheckBuffer(arg)) {
2596 if (bytes_setslice(self, Py_SIZE(self), Py_SIZE(self), arg) == -1)
2597 return NULL;
2598
2599 Py_RETURN_NONE;
2600 }
2601
2602 it = PyObject_GetIter(arg);
2603 if (it == NULL)
2604 return NULL;
2605
2606 /* Try to determine the length of the argument. 32 is abitrary. */
2607 buf_size = _PyObject_LengthHint(arg, 32);
2608
2609 bytes_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
2610 if (bytes_obj == NULL)
2611 return NULL;
2612 buf = PyByteArray_AS_STRING(bytes_obj);
2613
2614 while ((item = PyIter_Next(it)) != NULL) {
2615 if (! _getbytevalue(item, &value)) {
2616 Py_DECREF(item);
2617 Py_DECREF(it);
2618 Py_DECREF(bytes_obj);
2619 return NULL;
2620 }
2621 buf[len++] = value;
2622 Py_DECREF(item);
2623
2624 if (len >= buf_size) {
2625 buf_size = len + (len >> 1) + 1;
2626 if (PyByteArray_Resize((PyObject *)bytes_obj, buf_size) < 0) {
2627 Py_DECREF(it);
2628 Py_DECREF(bytes_obj);
2629 return NULL;
2630 }
2631 /* Recompute the `buf' pointer, since the resizing operation may
2632 have invalidated it. */
2633 buf = PyByteArray_AS_STRING(bytes_obj);
2634 }
2635 }
2636 Py_DECREF(it);
2637
2638 /* Resize down to exact size. */
2639 if (PyByteArray_Resize((PyObject *)bytes_obj, len) < 0) {
2640 Py_DECREF(bytes_obj);
2641 return NULL;
2642 }
2643
2644 if (bytes_setslice(self, Py_SIZE(self), Py_SIZE(self), bytes_obj) == -1)
2645 return NULL;
2646 Py_DECREF(bytes_obj);
2647
2648 Py_RETURN_NONE;
2649}
2650
2651PyDoc_STRVAR(pop__doc__,
2652"B.pop([index]) -> int\n\
2653\n\
2654Remove and return a single item from B. If no index\n\
Benjamin Petersondcf97b92008-07-02 17:30:14 +00002655argument is given, will pop the last value.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002656static PyObject *
2657bytes_pop(PyByteArrayObject *self, PyObject *args)
2658{
2659 int value;
2660 Py_ssize_t where = -1, n = Py_SIZE(self);
2661
2662 if (!PyArg_ParseTuple(args, "|n:pop", &where))
2663 return NULL;
2664
2665 if (n == 0) {
2666 PyErr_SetString(PyExc_OverflowError,
2667 "cannot pop an empty bytes");
2668 return NULL;
2669 }
2670 if (where < 0)
2671 where += Py_SIZE(self);
2672 if (where < 0 || where >= Py_SIZE(self)) {
2673 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2674 return NULL;
2675 }
2676
2677 value = self->ob_bytes[where];
2678 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2679 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2680 return NULL;
2681
2682 return PyLong_FromLong(value);
2683}
2684
2685PyDoc_STRVAR(remove__doc__,
2686"B.remove(int) -> None\n\
2687\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002688Remove the first occurrence of a value in B.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002689static PyObject *
2690bytes_remove(PyByteArrayObject *self, PyObject *arg)
2691{
2692 int value;
2693 Py_ssize_t where, n = Py_SIZE(self);
2694
2695 if (! _getbytevalue(arg, &value))
2696 return NULL;
2697
2698 for (where = 0; where < n; where++) {
2699 if (self->ob_bytes[where] == value)
2700 break;
2701 }
2702 if (where == n) {
2703 PyErr_SetString(PyExc_ValueError, "value not found in bytes");
2704 return NULL;
2705 }
2706
2707 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2708 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2709 return NULL;
2710
2711 Py_RETURN_NONE;
2712}
2713
2714/* XXX These two helpers could be optimized if argsize == 1 */
2715
2716static Py_ssize_t
2717lstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2718 void *argptr, Py_ssize_t argsize)
2719{
2720 Py_ssize_t i = 0;
2721 while (i < mysize && memchr(argptr, myptr[i], argsize))
2722 i++;
2723 return i;
2724}
2725
2726static Py_ssize_t
2727rstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2728 void *argptr, Py_ssize_t argsize)
2729{
2730 Py_ssize_t i = mysize - 1;
2731 while (i >= 0 && memchr(argptr, myptr[i], argsize))
2732 i--;
2733 return i + 1;
2734}
2735
2736PyDoc_STRVAR(strip__doc__,
2737"B.strip([bytes]) -> bytearray\n\
2738\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002739Strip leading and trailing bytes contained in the argument\n\
2740and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002741If the argument is omitted, strip ASCII whitespace.");
2742static PyObject *
2743bytes_strip(PyByteArrayObject *self, PyObject *args)
2744{
2745 Py_ssize_t left, right, mysize, argsize;
2746 void *myptr, *argptr;
2747 PyObject *arg = Py_None;
2748 Py_buffer varg;
2749 if (!PyArg_ParseTuple(args, "|O:strip", &arg))
2750 return NULL;
2751 if (arg == Py_None) {
2752 argptr = "\t\n\r\f\v ";
2753 argsize = 6;
2754 }
2755 else {
2756 if (_getbuffer(arg, &varg) < 0)
2757 return NULL;
2758 argptr = varg.buf;
2759 argsize = varg.len;
2760 }
2761 myptr = self->ob_bytes;
2762 mysize = Py_SIZE(self);
2763 left = lstrip_helper(myptr, mysize, argptr, argsize);
2764 if (left == mysize)
2765 right = left;
2766 else
2767 right = rstrip_helper(myptr, mysize, argptr, argsize);
2768 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002769 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002770 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2771}
2772
2773PyDoc_STRVAR(lstrip__doc__,
2774"B.lstrip([bytes]) -> bytearray\n\
2775\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002776Strip leading bytes contained in the argument\n\
2777and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002778If the argument is omitted, strip leading ASCII whitespace.");
2779static PyObject *
2780bytes_lstrip(PyByteArrayObject *self, PyObject *args)
2781{
2782 Py_ssize_t left, right, mysize, argsize;
2783 void *myptr, *argptr;
2784 PyObject *arg = Py_None;
2785 Py_buffer varg;
2786 if (!PyArg_ParseTuple(args, "|O:lstrip", &arg))
2787 return NULL;
2788 if (arg == Py_None) {
2789 argptr = "\t\n\r\f\v ";
2790 argsize = 6;
2791 }
2792 else {
2793 if (_getbuffer(arg, &varg) < 0)
2794 return NULL;
2795 argptr = varg.buf;
2796 argsize = varg.len;
2797 }
2798 myptr = self->ob_bytes;
2799 mysize = Py_SIZE(self);
2800 left = lstrip_helper(myptr, mysize, argptr, argsize);
2801 right = mysize;
2802 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002803 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002804 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2805}
2806
2807PyDoc_STRVAR(rstrip__doc__,
2808"B.rstrip([bytes]) -> bytearray\n\
2809\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002810Strip trailing bytes contained in the argument\n\
2811and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002812If the argument is omitted, strip trailing ASCII whitespace.");
2813static PyObject *
2814bytes_rstrip(PyByteArrayObject *self, PyObject *args)
2815{
2816 Py_ssize_t left, right, mysize, argsize;
2817 void *myptr, *argptr;
2818 PyObject *arg = Py_None;
2819 Py_buffer varg;
2820 if (!PyArg_ParseTuple(args, "|O:rstrip", &arg))
2821 return NULL;
2822 if (arg == Py_None) {
2823 argptr = "\t\n\r\f\v ";
2824 argsize = 6;
2825 }
2826 else {
2827 if (_getbuffer(arg, &varg) < 0)
2828 return NULL;
2829 argptr = varg.buf;
2830 argsize = varg.len;
2831 }
2832 myptr = self->ob_bytes;
2833 mysize = Py_SIZE(self);
2834 left = 0;
2835 right = rstrip_helper(myptr, mysize, argptr, argsize);
2836 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002837 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002838 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2839}
2840
2841PyDoc_STRVAR(decode_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002842"B.decode([encoding[, errors]]) -> str\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002843\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002844Decode B using the codec registered for encoding. encoding defaults\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002845to the default encoding. errors may be given to set a different error\n\
2846handling scheme. Default is 'strict' meaning that encoding errors raise\n\
2847a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
2848as well as any other name registered with codecs.register_error that is\n\
2849able to handle UnicodeDecodeErrors.");
2850
2851static PyObject *
2852bytes_decode(PyObject *self, PyObject *args)
2853{
2854 const char *encoding = NULL;
2855 const char *errors = NULL;
2856
2857 if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
2858 return NULL;
2859 if (encoding == NULL)
2860 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002861 return PyUnicode_FromEncodedObject(self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002862}
2863
2864PyDoc_STRVAR(alloc_doc,
2865"B.__alloc__() -> int\n\
2866\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002867Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002868
2869static PyObject *
2870bytes_alloc(PyByteArrayObject *self)
2871{
2872 return PyLong_FromSsize_t(self->ob_alloc);
2873}
2874
2875PyDoc_STRVAR(join_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002876"B.join(iterable_of_bytes) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002877\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002878Concatenate any number of bytes/bytearray objects, with B\n\
2879in between each pair, and return the result as a new bytearray.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002880
2881static PyObject *
2882bytes_join(PyByteArrayObject *self, PyObject *it)
2883{
2884 PyObject *seq;
2885 Py_ssize_t mysize = Py_SIZE(self);
2886 Py_ssize_t i;
2887 Py_ssize_t n;
2888 PyObject **items;
2889 Py_ssize_t totalsize = 0;
2890 PyObject *result;
2891 char *dest;
2892
2893 seq = PySequence_Fast(it, "can only join an iterable");
2894 if (seq == NULL)
2895 return NULL;
2896 n = PySequence_Fast_GET_SIZE(seq);
2897 items = PySequence_Fast_ITEMS(seq);
2898
2899 /* Compute the total size, and check that they are all bytes */
2900 /* XXX Shouldn't we use _getbuffer() on these items instead? */
2901 for (i = 0; i < n; i++) {
2902 PyObject *obj = items[i];
2903 if (!PyByteArray_Check(obj) && !PyBytes_Check(obj)) {
2904 PyErr_Format(PyExc_TypeError,
2905 "can only join an iterable of bytes "
2906 "(item %ld has type '%.100s')",
2907 /* XXX %ld isn't right on Win64 */
2908 (long)i, Py_TYPE(obj)->tp_name);
2909 goto error;
2910 }
2911 if (i > 0)
2912 totalsize += mysize;
2913 totalsize += Py_SIZE(obj);
2914 if (totalsize < 0) {
2915 PyErr_NoMemory();
2916 goto error;
2917 }
2918 }
2919
2920 /* Allocate the result, and copy the bytes */
2921 result = PyByteArray_FromStringAndSize(NULL, totalsize);
2922 if (result == NULL)
2923 goto error;
2924 dest = PyByteArray_AS_STRING(result);
2925 for (i = 0; i < n; i++) {
2926 PyObject *obj = items[i];
2927 Py_ssize_t size = Py_SIZE(obj);
2928 char *buf;
2929 if (PyByteArray_Check(obj))
2930 buf = PyByteArray_AS_STRING(obj);
2931 else
2932 buf = PyBytes_AS_STRING(obj);
2933 if (i) {
2934 memcpy(dest, self->ob_bytes, mysize);
2935 dest += mysize;
2936 }
2937 memcpy(dest, buf, size);
2938 dest += size;
2939 }
2940
2941 /* Done */
2942 Py_DECREF(seq);
2943 return result;
2944
2945 /* Error handling */
2946 error:
2947 Py_DECREF(seq);
2948 return NULL;
2949}
2950
2951PyDoc_STRVAR(fromhex_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002952"bytearray.fromhex(string) -> bytearray (static method)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002953\n\
2954Create a bytearray object from a string of hexadecimal numbers.\n\
2955Spaces between two numbers are accepted.\n\
2956Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef').");
2957
2958static int
2959hex_digit_to_int(Py_UNICODE c)
2960{
2961 if (c >= 128)
2962 return -1;
2963 if (ISDIGIT(c))
2964 return c - '0';
2965 else {
2966 if (ISUPPER(c))
2967 c = TOLOWER(c);
2968 if (c >= 'a' && c <= 'f')
2969 return c - 'a' + 10;
2970 }
2971 return -1;
2972}
2973
2974static PyObject *
2975bytes_fromhex(PyObject *cls, PyObject *args)
2976{
2977 PyObject *newbytes, *hexobj;
2978 char *buf;
2979 Py_UNICODE *hex;
2980 Py_ssize_t hexlen, byteslen, i, j;
2981 int top, bot;
2982
2983 if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj))
2984 return NULL;
2985 assert(PyUnicode_Check(hexobj));
2986 hexlen = PyUnicode_GET_SIZE(hexobj);
2987 hex = PyUnicode_AS_UNICODE(hexobj);
2988 byteslen = hexlen/2; /* This overestimates if there are spaces */
2989 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
2990 if (!newbytes)
2991 return NULL;
2992 buf = PyByteArray_AS_STRING(newbytes);
2993 for (i = j = 0; i < hexlen; i += 2) {
2994 /* skip over spaces in the input */
2995 while (hex[i] == ' ')
2996 i++;
2997 if (i >= hexlen)
2998 break;
2999 top = hex_digit_to_int(hex[i]);
3000 bot = hex_digit_to_int(hex[i+1]);
3001 if (top == -1 || bot == -1) {
3002 PyErr_Format(PyExc_ValueError,
3003 "non-hexadecimal number found in "
3004 "fromhex() arg at position %zd", i);
3005 goto error;
3006 }
3007 buf[j++] = (top << 4) + bot;
3008 }
3009 if (PyByteArray_Resize(newbytes, j) < 0)
3010 goto error;
3011 return newbytes;
3012
3013 error:
3014 Py_DECREF(newbytes);
3015 return NULL;
3016}
3017
3018PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3019
3020static PyObject *
3021bytes_reduce(PyByteArrayObject *self)
3022{
3023 PyObject *latin1, *dict;
3024 if (self->ob_bytes)
3025 latin1 = PyUnicode_DecodeLatin1(self->ob_bytes,
3026 Py_SIZE(self), NULL);
3027 else
3028 latin1 = PyUnicode_FromString("");
3029
3030 dict = PyObject_GetAttrString((PyObject *)self, "__dict__");
3031 if (dict == NULL) {
3032 PyErr_Clear();
3033 dict = Py_None;
3034 Py_INCREF(dict);
3035 }
3036
3037 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
3038}
3039
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003040PyDoc_STRVAR(sizeof_doc,
3041"B.__sizeof__() -> int\n\
3042 \n\
3043Returns the size of B in memory, in bytes");
3044static PyObject *
3045bytes_sizeof(PyByteArrayObject *self)
3046{
3047 Py_ssize_t res;
3048
3049 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
3050 return PyLong_FromSsize_t(res);
3051}
3052
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003053static PySequenceMethods bytes_as_sequence = {
3054 (lenfunc)bytes_length, /* sq_length */
3055 (binaryfunc)PyByteArray_Concat, /* sq_concat */
3056 (ssizeargfunc)bytes_repeat, /* sq_repeat */
3057 (ssizeargfunc)bytes_getitem, /* sq_item */
3058 0, /* sq_slice */
3059 (ssizeobjargproc)bytes_setitem, /* sq_ass_item */
3060 0, /* sq_ass_slice */
3061 (objobjproc)bytes_contains, /* sq_contains */
3062 (binaryfunc)bytes_iconcat, /* sq_inplace_concat */
3063 (ssizeargfunc)bytes_irepeat, /* sq_inplace_repeat */
3064};
3065
3066static PyMappingMethods bytes_as_mapping = {
3067 (lenfunc)bytes_length,
3068 (binaryfunc)bytes_subscript,
3069 (objobjargproc)bytes_ass_subscript,
3070};
3071
3072static PyBufferProcs bytes_as_buffer = {
3073 (getbufferproc)bytes_getbuffer,
3074 (releasebufferproc)bytes_releasebuffer,
3075};
3076
3077static PyMethodDef
3078bytes_methods[] = {
3079 {"__alloc__", (PyCFunction)bytes_alloc, METH_NOARGS, alloc_doc},
3080 {"__reduce__", (PyCFunction)bytes_reduce, METH_NOARGS, reduce_doc},
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003081 {"__sizeof__", (PyCFunction)bytes_sizeof, METH_NOARGS, sizeof_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003082 {"append", (PyCFunction)bytes_append, METH_O, append__doc__},
3083 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
3084 _Py_capitalize__doc__},
3085 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
3086 {"count", (PyCFunction)bytes_count, METH_VARARGS, count__doc__},
3087 {"decode", (PyCFunction)bytes_decode, METH_VARARGS, decode_doc},
3088 {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS, endswith__doc__},
3089 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS,
3090 expandtabs__doc__},
3091 {"extend", (PyCFunction)bytes_extend, METH_O, extend__doc__},
3092 {"find", (PyCFunction)bytes_find, METH_VARARGS, find__doc__},
3093 {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS,
3094 fromhex_doc},
3095 {"index", (PyCFunction)bytes_index, METH_VARARGS, index__doc__},
3096 {"insert", (PyCFunction)bytes_insert, METH_VARARGS, insert__doc__},
3097 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
3098 _Py_isalnum__doc__},
3099 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
3100 _Py_isalpha__doc__},
3101 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
3102 _Py_isdigit__doc__},
3103 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
3104 _Py_islower__doc__},
3105 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
3106 _Py_isspace__doc__},
3107 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
3108 _Py_istitle__doc__},
3109 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
3110 _Py_isupper__doc__},
3111 {"join", (PyCFunction)bytes_join, METH_O, join_doc},
3112 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
3113 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
3114 {"lstrip", (PyCFunction)bytes_lstrip, METH_VARARGS, lstrip__doc__},
3115 {"partition", (PyCFunction)bytes_partition, METH_O, partition__doc__},
3116 {"pop", (PyCFunction)bytes_pop, METH_VARARGS, pop__doc__},
3117 {"remove", (PyCFunction)bytes_remove, METH_O, remove__doc__},
3118 {"replace", (PyCFunction)bytes_replace, METH_VARARGS, replace__doc__},
3119 {"reverse", (PyCFunction)bytes_reverse, METH_NOARGS, reverse__doc__},
3120 {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, rfind__doc__},
3121 {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, rindex__doc__},
3122 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
3123 {"rpartition", (PyCFunction)bytes_rpartition, METH_O, rpartition__doc__},
3124 {"rsplit", (PyCFunction)bytes_rsplit, METH_VARARGS, rsplit__doc__},
3125 {"rstrip", (PyCFunction)bytes_rstrip, METH_VARARGS, rstrip__doc__},
3126 {"split", (PyCFunction)bytes_split, METH_VARARGS, split__doc__},
3127 {"splitlines", (PyCFunction)stringlib_splitlines, METH_VARARGS,
3128 splitlines__doc__},
3129 {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS ,
3130 startswith__doc__},
3131 {"strip", (PyCFunction)bytes_strip, METH_VARARGS, strip__doc__},
3132 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
3133 _Py_swapcase__doc__},
3134 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
3135 {"translate", (PyCFunction)bytes_translate, METH_VARARGS,
3136 translate__doc__},
3137 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
3138 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
3139 {NULL}
3140};
3141
3142PyDoc_STRVAR(bytes_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00003143"bytearray(iterable_of_ints) -> bytearray\n\
3144bytearray(string, encoding[, errors]) -> bytearray\n\
3145bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray\n\
3146bytearray(memory_view) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003147\n\
3148Construct an mutable bytearray object from:\n\
3149 - an iterable yielding integers in range(256)\n\
3150 - a text string encoded using the specified encoding\n\
3151 - a bytes or a bytearray object\n\
3152 - any object implementing the buffer API.\n\
3153\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00003154bytearray(int) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003155\n\
3156Construct a zero-initialized bytearray of the given length.");
3157
3158
3159static PyObject *bytes_iter(PyObject *seq);
3160
3161PyTypeObject PyByteArray_Type = {
3162 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3163 "bytearray",
3164 sizeof(PyByteArrayObject),
3165 0,
3166 (destructor)bytes_dealloc, /* tp_dealloc */
3167 0, /* tp_print */
3168 0, /* tp_getattr */
3169 0, /* tp_setattr */
3170 0, /* tp_compare */
3171 (reprfunc)bytes_repr, /* tp_repr */
3172 0, /* tp_as_number */
3173 &bytes_as_sequence, /* tp_as_sequence */
3174 &bytes_as_mapping, /* tp_as_mapping */
3175 0, /* tp_hash */
3176 0, /* tp_call */
3177 bytes_str, /* tp_str */
3178 PyObject_GenericGetAttr, /* tp_getattro */
3179 0, /* tp_setattro */
3180 &bytes_as_buffer, /* tp_as_buffer */
3181 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3182 bytes_doc, /* tp_doc */
3183 0, /* tp_traverse */
3184 0, /* tp_clear */
3185 (richcmpfunc)bytes_richcompare, /* tp_richcompare */
3186 0, /* tp_weaklistoffset */
3187 bytes_iter, /* tp_iter */
3188 0, /* tp_iternext */
3189 bytes_methods, /* tp_methods */
3190 0, /* tp_members */
3191 0, /* tp_getset */
3192 0, /* tp_base */
3193 0, /* tp_dict */
3194 0, /* tp_descr_get */
3195 0, /* tp_descr_set */
3196 0, /* tp_dictoffset */
3197 (initproc)bytes_init, /* tp_init */
3198 PyType_GenericAlloc, /* tp_alloc */
3199 PyType_GenericNew, /* tp_new */
3200 PyObject_Del, /* tp_free */
3201};
3202
3203/*********************** Bytes Iterator ****************************/
3204
3205typedef struct {
3206 PyObject_HEAD
3207 Py_ssize_t it_index;
3208 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
3209} bytesiterobject;
3210
3211static void
3212bytesiter_dealloc(bytesiterobject *it)
3213{
3214 _PyObject_GC_UNTRACK(it);
3215 Py_XDECREF(it->it_seq);
3216 PyObject_GC_Del(it);
3217}
3218
3219static int
3220bytesiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
3221{
3222 Py_VISIT(it->it_seq);
3223 return 0;
3224}
3225
3226static PyObject *
3227bytesiter_next(bytesiterobject *it)
3228{
3229 PyByteArrayObject *seq;
3230 PyObject *item;
3231
3232 assert(it != NULL);
3233 seq = it->it_seq;
3234 if (seq == NULL)
3235 return NULL;
3236 assert(PyByteArray_Check(seq));
3237
3238 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
3239 item = PyLong_FromLong(
3240 (unsigned char)seq->ob_bytes[it->it_index]);
3241 if (item != NULL)
3242 ++it->it_index;
3243 return item;
3244 }
3245
3246 Py_DECREF(seq);
3247 it->it_seq = NULL;
3248 return NULL;
3249}
3250
3251static PyObject *
3252bytesiter_length_hint(bytesiterobject *it)
3253{
3254 Py_ssize_t len = 0;
3255 if (it->it_seq)
3256 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
3257 return PyLong_FromSsize_t(len);
3258}
3259
3260PyDoc_STRVAR(length_hint_doc,
3261 "Private method returning an estimate of len(list(it)).");
3262
3263static PyMethodDef bytesiter_methods[] = {
3264 {"__length_hint__", (PyCFunction)bytesiter_length_hint, METH_NOARGS,
3265 length_hint_doc},
3266 {NULL, NULL} /* sentinel */
3267};
3268
3269PyTypeObject PyByteArrayIter_Type = {
3270 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3271 "bytearray_iterator", /* tp_name */
3272 sizeof(bytesiterobject), /* tp_basicsize */
3273 0, /* tp_itemsize */
3274 /* methods */
3275 (destructor)bytesiter_dealloc, /* tp_dealloc */
3276 0, /* tp_print */
3277 0, /* tp_getattr */
3278 0, /* tp_setattr */
3279 0, /* tp_compare */
3280 0, /* tp_repr */
3281 0, /* tp_as_number */
3282 0, /* tp_as_sequence */
3283 0, /* tp_as_mapping */
3284 0, /* tp_hash */
3285 0, /* tp_call */
3286 0, /* tp_str */
3287 PyObject_GenericGetAttr, /* tp_getattro */
3288 0, /* tp_setattro */
3289 0, /* tp_as_buffer */
3290 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
3291 0, /* tp_doc */
3292 (traverseproc)bytesiter_traverse, /* tp_traverse */
3293 0, /* tp_clear */
3294 0, /* tp_richcompare */
3295 0, /* tp_weaklistoffset */
3296 PyObject_SelfIter, /* tp_iter */
3297 (iternextfunc)bytesiter_next, /* tp_iternext */
3298 bytesiter_methods, /* tp_methods */
3299 0,
3300};
3301
3302static PyObject *
3303bytes_iter(PyObject *seq)
3304{
3305 bytesiterobject *it;
3306
3307 if (!PyByteArray_Check(seq)) {
3308 PyErr_BadInternalCall();
3309 return NULL;
3310 }
3311 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
3312 if (it == NULL)
3313 return NULL;
3314 it->it_index = 0;
3315 Py_INCREF(seq);
3316 it->it_seq = (PyByteArrayObject *)seq;
3317 _PyObject_GC_TRACK(it);
3318 return (PyObject *)it;
3319}