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