blob: 3d7b0b2aa56c7a2e535769fce2d4fcc752bc01d2 [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;
Antoine Pitrou20d6c152010-01-17 12:43:00 +00009char _PyByteArray_empty_string[] = "";
Christian Heimes2c9c7a52008-05-26 13:42:13 +000010
11void
12PyByteArray_Fini(void)
13{
14 Py_CLEAR(nullbytes);
15}
16
17int
18PyByteArray_Init(void)
19{
20 nullbytes = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
21 if (nullbytes == NULL)
22 return 0;
23 nullbytes->ob_bytes = NULL;
24 Py_SIZE(nullbytes) = nullbytes->ob_alloc = 0;
25 nullbytes->ob_exports = 0;
26 return 1;
27}
28
29/* end nullbytes support */
30
31/* Helpers */
32
33static int
34_getbytevalue(PyObject* arg, int *value)
35{
36 long face_value;
37
38 if (PyLong_Check(arg)) {
39 face_value = PyLong_AsLong(arg);
Georg Brandl9a54d7c2008-07-16 23:15:30 +000040 } else {
41 PyObject *index = PyNumber_Index(arg);
42 if (index == NULL) {
43 PyErr_Format(PyExc_TypeError, "an integer is required");
Christian Heimes2c9c7a52008-05-26 13:42:13 +000044 return 0;
45 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +000046 face_value = PyLong_AsLong(index);
47 Py_DECREF(index);
48 }
49
50 if (face_value < 0 || face_value >= 256) {
51 /* this includes the OverflowError in case the long is too large */
52 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
Christian Heimes2c9c7a52008-05-26 13:42:13 +000053 return 0;
54 }
55
56 *value = face_value;
57 return 1;
58}
59
60static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +000061bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000062{
63 int ret;
64 void *ptr;
65 if (view == NULL) {
66 obj->ob_exports++;
67 return 0;
68 }
Antoine Pitrou20d6c152010-01-17 12:43:00 +000069 ptr = (void *) PyByteArray_AS_STRING(obj);
Martin v. Löwis423be952008-08-13 15:53:07 +000070 ret = PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
Christian Heimes2c9c7a52008-05-26 13:42:13 +000071 if (ret >= 0) {
72 obj->ob_exports++;
73 }
74 return ret;
75}
76
77static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +000078bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000079{
80 obj->ob_exports--;
81}
82
83static Py_ssize_t
84_getbuffer(PyObject *obj, Py_buffer *view)
85{
86 PyBufferProcs *buffer = Py_TYPE(obj)->tp_as_buffer;
87
88 if (buffer == NULL || buffer->bf_getbuffer == NULL)
89 {
90 PyErr_Format(PyExc_TypeError,
91 "Type %.100s doesn't support the buffer API",
92 Py_TYPE(obj)->tp_name);
93 return -1;
94 }
95
96 if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0)
97 return -1;
98 return view->len;
99}
100
Antoine Pitrou5504e892008-12-06 21:27:53 +0000101static int
102_canresize(PyByteArrayObject *self)
103{
104 if (self->ob_exports > 0) {
105 PyErr_SetString(PyExc_BufferError,
106 "Existing exports of data: object cannot be re-sized");
107 return 0;
108 }
109 return 1;
110}
111
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000112/* Direct API functions */
113
114PyObject *
115PyByteArray_FromObject(PyObject *input)
116{
117 return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
118 input, NULL);
119}
120
121PyObject *
122PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
123{
124 PyByteArrayObject *new;
125 Py_ssize_t alloc;
126
127 if (size < 0) {
128 PyErr_SetString(PyExc_SystemError,
129 "Negative size passed to PyByteArray_FromStringAndSize");
130 return NULL;
131 }
132
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000133 /* Prevent buffer overflow when setting alloc to size+1. */
134 if (size == PY_SSIZE_T_MAX) {
135 return PyErr_NoMemory();
136 }
137
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000138 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
139 if (new == NULL)
140 return NULL;
141
142 if (size == 0) {
143 new->ob_bytes = NULL;
144 alloc = 0;
145 }
146 else {
147 alloc = size + 1;
148 new->ob_bytes = PyMem_Malloc(alloc);
149 if (new->ob_bytes == NULL) {
150 Py_DECREF(new);
151 return PyErr_NoMemory();
152 }
Antoine Pitrou20d6c152010-01-17 12:43:00 +0000153 if (bytes != NULL && size > 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000154 memcpy(new->ob_bytes, bytes, size);
155 new->ob_bytes[size] = '\0'; /* Trailing null byte */
156 }
157 Py_SIZE(new) = size;
158 new->ob_alloc = alloc;
159 new->ob_exports = 0;
160
161 return (PyObject *)new;
162}
163
164Py_ssize_t
165PyByteArray_Size(PyObject *self)
166{
167 assert(self != NULL);
168 assert(PyByteArray_Check(self));
169
170 return PyByteArray_GET_SIZE(self);
171}
172
173char *
174PyByteArray_AsString(PyObject *self)
175{
176 assert(self != NULL);
177 assert(PyByteArray_Check(self));
178
179 return PyByteArray_AS_STRING(self);
180}
181
182int
183PyByteArray_Resize(PyObject *self, Py_ssize_t size)
184{
185 void *sval;
186 Py_ssize_t alloc = ((PyByteArrayObject *)self)->ob_alloc;
187
188 assert(self != NULL);
189 assert(PyByteArray_Check(self));
190 assert(size >= 0);
191
Antoine Pitrou5504e892008-12-06 21:27:53 +0000192 if (size == Py_SIZE(self)) {
193 return 0;
194 }
195 if (!_canresize((PyByteArrayObject *)self)) {
196 return -1;
197 }
198
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000199 if (size < alloc / 2) {
200 /* Major downsize; resize down to exact size */
201 alloc = size + 1;
202 }
203 else if (size < alloc) {
204 /* Within allocated size; quick exit */
205 Py_SIZE(self) = size;
206 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null */
207 return 0;
208 }
209 else if (size <= alloc * 1.125) {
210 /* Moderate upsize; overallocate similar to list_resize() */
211 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
212 }
213 else {
214 /* Major upsize; resize up to exact size */
215 alloc = size + 1;
216 }
217
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000218 sval = PyMem_Realloc(((PyByteArrayObject *)self)->ob_bytes, alloc);
219 if (sval == NULL) {
220 PyErr_NoMemory();
221 return -1;
222 }
223
224 ((PyByteArrayObject *)self)->ob_bytes = sval;
225 Py_SIZE(self) = size;
226 ((PyByteArrayObject *)self)->ob_alloc = alloc;
227 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null byte */
228
229 return 0;
230}
231
232PyObject *
233PyByteArray_Concat(PyObject *a, PyObject *b)
234{
235 Py_ssize_t size;
236 Py_buffer va, vb;
237 PyByteArrayObject *result = NULL;
238
239 va.len = -1;
240 vb.len = -1;
241 if (_getbuffer(a, &va) < 0 ||
242 _getbuffer(b, &vb) < 0) {
243 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
244 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
245 goto done;
246 }
247
248 size = va.len + vb.len;
249 if (size < 0) {
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000250 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000251 goto done;
252 }
253
254 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
255 if (result != NULL) {
256 memcpy(result->ob_bytes, va.buf, va.len);
257 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
258 }
259
260 done:
261 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000262 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000263 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000264 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000265 return (PyObject *)result;
266}
267
268/* Functions stuffed into the type object */
269
270static Py_ssize_t
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000271bytearray_length(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000272{
273 return Py_SIZE(self);
274}
275
276static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000277bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000278{
279 Py_ssize_t mysize;
280 Py_ssize_t size;
281 Py_buffer vo;
282
283 if (_getbuffer(other, &vo) < 0) {
284 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
285 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
286 return NULL;
287 }
288
289 mysize = Py_SIZE(self);
290 size = mysize + vo.len;
291 if (size < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000292 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000293 return PyErr_NoMemory();
294 }
295 if (size < self->ob_alloc) {
296 Py_SIZE(self) = size;
297 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
298 }
299 else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000300 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000301 return NULL;
302 }
303 memcpy(self->ob_bytes + mysize, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000304 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000305 Py_INCREF(self);
306 return (PyObject *)self;
307}
308
309static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000310bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000311{
312 PyByteArrayObject *result;
313 Py_ssize_t mysize;
314 Py_ssize_t size;
315
316 if (count < 0)
317 count = 0;
318 mysize = Py_SIZE(self);
319 size = mysize * count;
320 if (count != 0 && size / count != mysize)
321 return PyErr_NoMemory();
322 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
323 if (result != NULL && size != 0) {
324 if (mysize == 1)
325 memset(result->ob_bytes, self->ob_bytes[0], size);
326 else {
327 Py_ssize_t i;
328 for (i = 0; i < count; i++)
329 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
330 }
331 }
332 return (PyObject *)result;
333}
334
335static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000336bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000337{
338 Py_ssize_t mysize;
339 Py_ssize_t size;
340
341 if (count < 0)
342 count = 0;
343 mysize = Py_SIZE(self);
344 size = mysize * count;
345 if (count != 0 && size / count != mysize)
346 return PyErr_NoMemory();
347 if (size < self->ob_alloc) {
348 Py_SIZE(self) = size;
349 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
350 }
351 else if (PyByteArray_Resize((PyObject *)self, size) < 0)
352 return NULL;
353
354 if (mysize == 1)
355 memset(self->ob_bytes, self->ob_bytes[0], size);
356 else {
357 Py_ssize_t i;
358 for (i = 1; i < count; i++)
359 memcpy(self->ob_bytes + i*mysize, self->ob_bytes, mysize);
360 }
361
362 Py_INCREF(self);
363 return (PyObject *)self;
364}
365
366static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000367bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000368{
369 if (i < 0)
370 i += Py_SIZE(self);
371 if (i < 0 || i >= Py_SIZE(self)) {
372 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
373 return NULL;
374 }
375 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
376}
377
378static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000379bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000380{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000381 if (PyIndex_Check(index)) {
382 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000383
384 if (i == -1 && PyErr_Occurred())
385 return NULL;
386
387 if (i < 0)
388 i += PyByteArray_GET_SIZE(self);
389
390 if (i < 0 || i >= Py_SIZE(self)) {
391 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
392 return NULL;
393 }
394 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
395 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000396 else if (PySlice_Check(index)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000397 Py_ssize_t start, stop, step, slicelength, cur, i;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000398 if (PySlice_GetIndicesEx((PySliceObject *)index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000399 PyByteArray_GET_SIZE(self),
400 &start, &stop, &step, &slicelength) < 0) {
401 return NULL;
402 }
403
404 if (slicelength <= 0)
405 return PyByteArray_FromStringAndSize("", 0);
406 else if (step == 1) {
407 return PyByteArray_FromStringAndSize(self->ob_bytes + start,
408 slicelength);
409 }
410 else {
411 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000412 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000413 PyObject *result;
414
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000415 result = PyByteArray_FromStringAndSize(NULL, slicelength);
416 if (result == NULL)
417 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000418
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000419 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000420 for (cur = start, i = 0; i < slicelength;
421 cur += step, i++) {
422 result_buf[i] = source_buf[cur];
423 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000424 return result;
425 }
426 }
427 else {
428 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integers");
429 return NULL;
430 }
431}
432
433static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000434bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000435 PyObject *values)
436{
437 Py_ssize_t avail, needed;
438 void *bytes;
439 Py_buffer vbytes;
440 int res = 0;
441
442 vbytes.len = -1;
443 if (values == (PyObject *)self) {
444 /* Make a copy and call this function recursively */
445 int err;
446 values = PyByteArray_FromObject(values);
447 if (values == NULL)
448 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000449 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000450 Py_DECREF(values);
451 return err;
452 }
453 if (values == NULL) {
454 /* del b[lo:hi] */
455 bytes = NULL;
456 needed = 0;
457 }
458 else {
459 if (_getbuffer(values, &vbytes) < 0) {
460 PyErr_Format(PyExc_TypeError,
Georg Brandl3dbca812008-07-23 16:10:53 +0000461 "can't set bytearray slice from %.100s",
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000462 Py_TYPE(values)->tp_name);
463 return -1;
464 }
465 needed = vbytes.len;
466 bytes = vbytes.buf;
467 }
468
469 if (lo < 0)
470 lo = 0;
471 if (hi < lo)
472 hi = lo;
473 if (hi > Py_SIZE(self))
474 hi = Py_SIZE(self);
475
476 avail = hi - lo;
477 if (avail < 0)
478 lo = hi = avail = 0;
479
480 if (avail != needed) {
481 if (avail > needed) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000482 if (!_canresize(self)) {
483 res = -1;
484 goto finish;
485 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000486 /*
487 0 lo hi old_size
488 | |<----avail----->|<-----tomove------>|
489 | |<-needed->|<-----tomove------>|
490 0 lo new_hi new_size
491 */
492 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
493 Py_SIZE(self) - hi);
494 }
495 /* XXX(nnorwitz): need to verify this can't overflow! */
496 if (PyByteArray_Resize((PyObject *)self,
497 Py_SIZE(self) + needed - avail) < 0) {
498 res = -1;
499 goto finish;
500 }
501 if (avail < needed) {
502 /*
503 0 lo hi old_size
504 | |<-avail->|<-----tomove------>|
505 | |<----needed---->|<-----tomove------>|
506 0 lo new_hi new_size
507 */
508 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
509 Py_SIZE(self) - lo - needed);
510 }
511 }
512
513 if (needed > 0)
514 memcpy(self->ob_bytes + lo, bytes, needed);
515
516
517 finish:
518 if (vbytes.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000519 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000520 return res;
521}
522
523static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000524bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000525{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000526 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000527
528 if (i < 0)
529 i += Py_SIZE(self);
530
531 if (i < 0 || i >= Py_SIZE(self)) {
532 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
533 return -1;
534 }
535
536 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000537 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000538
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000539 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000540 return -1;
541
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000542 self->ob_bytes[i] = ival;
543 return 0;
544}
545
546static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000547bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000548{
549 Py_ssize_t start, stop, step, slicelen, needed;
550 char *bytes;
551
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000552 if (PyIndex_Check(index)) {
553 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000554
555 if (i == -1 && PyErr_Occurred())
556 return -1;
557
558 if (i < 0)
559 i += PyByteArray_GET_SIZE(self);
560
561 if (i < 0 || i >= Py_SIZE(self)) {
562 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
563 return -1;
564 }
565
566 if (values == NULL) {
567 /* Fall through to slice assignment */
568 start = i;
569 stop = i + 1;
570 step = 1;
571 slicelen = 1;
572 }
573 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000574 int ival;
575 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000576 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000577 self->ob_bytes[i] = (char)ival;
578 return 0;
579 }
580 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000581 else if (PySlice_Check(index)) {
582 if (PySlice_GetIndicesEx((PySliceObject *)index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000583 PyByteArray_GET_SIZE(self),
584 &start, &stop, &step, &slicelen) < 0) {
585 return -1;
586 }
587 }
588 else {
589 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integer");
590 return -1;
591 }
592
593 if (values == NULL) {
594 bytes = NULL;
595 needed = 0;
596 }
597 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
598 /* Make a copy an call this function recursively */
599 int err;
600 values = PyByteArray_FromObject(values);
601 if (values == NULL)
602 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000603 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000604 Py_DECREF(values);
605 return err;
606 }
607 else {
608 assert(PyByteArray_Check(values));
609 bytes = ((PyByteArrayObject *)values)->ob_bytes;
610 needed = Py_SIZE(values);
611 }
612 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
613 if ((step < 0 && start < stop) ||
614 (step > 0 && start > stop))
615 stop = start;
616 if (step == 1) {
617 if (slicelen != needed) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000618 if (!_canresize(self))
619 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000620 if (slicelen > needed) {
621 /*
622 0 start stop old_size
623 | |<---slicelen--->|<-----tomove------>|
624 | |<-needed->|<-----tomove------>|
625 0 lo new_hi new_size
626 */
627 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
628 Py_SIZE(self) - stop);
629 }
630 if (PyByteArray_Resize((PyObject *)self,
631 Py_SIZE(self) + needed - slicelen) < 0)
632 return -1;
633 if (slicelen < needed) {
634 /*
635 0 lo hi old_size
636 | |<-avail->|<-----tomove------>|
637 | |<----needed---->|<-----tomove------>|
638 0 lo new_hi new_size
639 */
640 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
641 Py_SIZE(self) - start - needed);
642 }
643 }
644
645 if (needed > 0)
646 memcpy(self->ob_bytes + start, bytes, needed);
647
648 return 0;
649 }
650 else {
651 if (needed == 0) {
652 /* Delete slice */
653 Py_ssize_t cur, i;
654
Antoine Pitrou5504e892008-12-06 21:27:53 +0000655 if (!_canresize(self))
656 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000657 if (step < 0) {
658 stop = start + 1;
659 start = stop + step * (slicelen - 1) - 1;
660 step = -step;
661 }
662 for (cur = start, i = 0;
663 i < slicelen; cur += step, i++) {
664 Py_ssize_t lim = step - 1;
665
666 if (cur + step >= PyByteArray_GET_SIZE(self))
667 lim = PyByteArray_GET_SIZE(self) - cur - 1;
668
669 memmove(self->ob_bytes + cur - i,
670 self->ob_bytes + cur + 1, lim);
671 }
672 /* Move the tail of the bytes, in one chunk */
673 cur = start + slicelen*step;
674 if (cur < PyByteArray_GET_SIZE(self)) {
675 memmove(self->ob_bytes + cur - slicelen,
676 self->ob_bytes + cur,
677 PyByteArray_GET_SIZE(self) - cur);
678 }
679 if (PyByteArray_Resize((PyObject *)self,
680 PyByteArray_GET_SIZE(self) - slicelen) < 0)
681 return -1;
682
683 return 0;
684 }
685 else {
686 /* Assign slice */
687 Py_ssize_t cur, i;
688
689 if (needed != slicelen) {
690 PyErr_Format(PyExc_ValueError,
691 "attempt to assign bytes of size %zd "
692 "to extended slice of size %zd",
693 needed, slicelen);
694 return -1;
695 }
696 for (cur = start, i = 0; i < slicelen; cur += step, i++)
697 self->ob_bytes[cur] = bytes[i];
698 return 0;
699 }
700 }
701}
702
703static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000704bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000705{
706 static char *kwlist[] = {"source", "encoding", "errors", 0};
707 PyObject *arg = NULL;
708 const char *encoding = NULL;
709 const char *errors = NULL;
710 Py_ssize_t count;
711 PyObject *it;
712 PyObject *(*iternext)(PyObject *);
713
714 if (Py_SIZE(self) != 0) {
715 /* Empty previous contents (yes, do this first of all!) */
716 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
717 return -1;
718 }
719
720 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000721 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000722 &arg, &encoding, &errors))
723 return -1;
724
725 /* Make a quick exit if no first argument */
726 if (arg == NULL) {
727 if (encoding != NULL || errors != NULL) {
728 PyErr_SetString(PyExc_TypeError,
729 "encoding or errors without sequence argument");
730 return -1;
731 }
732 return 0;
733 }
734
735 if (PyUnicode_Check(arg)) {
736 /* Encode via the codec registry */
737 PyObject *encoded, *new;
738 if (encoding == NULL) {
739 PyErr_SetString(PyExc_TypeError,
740 "string argument without an encoding");
741 return -1;
742 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000743 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000744 if (encoded == NULL)
745 return -1;
746 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000747 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000748 Py_DECREF(encoded);
749 if (new == NULL)
750 return -1;
751 Py_DECREF(new);
752 return 0;
753 }
754
755 /* If it's not unicode, there can't be encoding or errors */
756 if (encoding != NULL || errors != NULL) {
757 PyErr_SetString(PyExc_TypeError,
758 "encoding or errors without a string argument");
759 return -1;
760 }
761
762 /* Is it an int? */
763 count = PyNumber_AsSsize_t(arg, PyExc_ValueError);
764 if (count == -1 && PyErr_Occurred())
765 PyErr_Clear();
766 else {
767 if (count < 0) {
768 PyErr_SetString(PyExc_ValueError, "negative count");
769 return -1;
770 }
771 if (count > 0) {
772 if (PyByteArray_Resize((PyObject *)self, count))
773 return -1;
774 memset(self->ob_bytes, 0, count);
775 }
776 return 0;
777 }
778
779 /* Use the buffer API */
780 if (PyObject_CheckBuffer(arg)) {
781 Py_ssize_t size;
782 Py_buffer view;
783 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
784 return -1;
785 size = view.len;
786 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
787 if (PyBuffer_ToContiguous(self->ob_bytes, &view, size, 'C') < 0)
788 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000789 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000790 return 0;
791 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000792 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000793 return -1;
794 }
795
796 /* XXX Optimize this if the arguments is a list, tuple */
797
798 /* Get the iterator */
799 it = PyObject_GetIter(arg);
800 if (it == NULL)
801 return -1;
802 iternext = *Py_TYPE(it)->tp_iternext;
803
804 /* Run the iterator to exhaustion */
805 for (;;) {
806 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000807 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000808
809 /* Get the next item */
810 item = iternext(it);
811 if (item == NULL) {
812 if (PyErr_Occurred()) {
813 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
814 goto error;
815 PyErr_Clear();
816 }
817 break;
818 }
819
820 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000821 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000822 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000823 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000824 goto error;
825
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000826 /* Append the byte */
827 if (Py_SIZE(self) < self->ob_alloc)
828 Py_SIZE(self)++;
829 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
830 goto error;
831 self->ob_bytes[Py_SIZE(self)-1] = value;
832 }
833
834 /* Clean up and return success */
835 Py_DECREF(it);
836 return 0;
837
838 error:
839 /* Error handling when it != NULL */
840 Py_DECREF(it);
841 return -1;
842}
843
844/* Mostly copied from string_repr, but without the
845 "smart quote" functionality. */
846static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000847bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000848{
849 static const char *hexdigits = "0123456789abcdef";
850 const char *quote_prefix = "bytearray(b";
851 const char *quote_postfix = ")";
852 Py_ssize_t length = Py_SIZE(self);
853 /* 14 == strlen(quote_prefix) + 2 + strlen(quote_postfix) */
854 size_t newsize = 14 + 4 * length;
855 PyObject *v;
856 if (newsize > PY_SSIZE_T_MAX || newsize / 4 - 3 != length) {
857 PyErr_SetString(PyExc_OverflowError,
858 "bytearray object is too large to make repr");
859 return NULL;
860 }
861 v = PyUnicode_FromUnicode(NULL, newsize);
862 if (v == NULL) {
863 return NULL;
864 }
865 else {
866 register Py_ssize_t i;
867 register Py_UNICODE c;
868 register Py_UNICODE *p;
869 int quote;
870
871 /* Figure out which quote to use; single is preferred */
872 quote = '\'';
873 {
874 char *test, *start;
875 start = PyByteArray_AS_STRING(self);
876 for (test = start; test < start+length; ++test) {
877 if (*test == '"') {
878 quote = '\''; /* back to single */
879 goto decided;
880 }
881 else if (*test == '\'')
882 quote = '"';
883 }
884 decided:
885 ;
886 }
887
888 p = PyUnicode_AS_UNICODE(v);
889 while (*quote_prefix)
890 *p++ = *quote_prefix++;
891 *p++ = quote;
892
893 for (i = 0; i < length; i++) {
894 /* There's at least enough room for a hex escape
895 and a closing quote. */
896 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5);
897 c = self->ob_bytes[i];
898 if (c == '\'' || c == '\\')
899 *p++ = '\\', *p++ = c;
900 else if (c == '\t')
901 *p++ = '\\', *p++ = 't';
902 else if (c == '\n')
903 *p++ = '\\', *p++ = 'n';
904 else if (c == '\r')
905 *p++ = '\\', *p++ = 'r';
906 else if (c == 0)
907 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
908 else if (c < ' ' || c >= 0x7f) {
909 *p++ = '\\';
910 *p++ = 'x';
911 *p++ = hexdigits[(c & 0xf0) >> 4];
912 *p++ = hexdigits[c & 0xf];
913 }
914 else
915 *p++ = c;
916 }
917 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1);
918 *p++ = quote;
919 while (*quote_postfix) {
920 *p++ = *quote_postfix++;
921 }
922 *p = '\0';
923 if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) {
924 Py_DECREF(v);
925 return NULL;
926 }
927 return v;
928 }
929}
930
931static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000932bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000933{
934 if (Py_BytesWarningFlag) {
935 if (PyErr_WarnEx(PyExc_BytesWarning,
936 "str() on a bytearray instance", 1))
937 return NULL;
938 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000939 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000940}
941
942static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000943bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000944{
945 Py_ssize_t self_size, other_size;
946 Py_buffer self_bytes, other_bytes;
947 PyObject *res;
948 Py_ssize_t minsize;
949 int cmp;
950
951 /* Bytes can be compared to anything that supports the (binary)
952 buffer API. Except that a comparison with Unicode is always an
953 error, even if the comparison is for equality. */
954 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
955 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
Barry Warsaw9e9dcd62008-10-17 01:50:37 +0000956 if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000957 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +0000958 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000959 return NULL;
960 }
961
962 Py_INCREF(Py_NotImplemented);
963 return Py_NotImplemented;
964 }
965
966 self_size = _getbuffer(self, &self_bytes);
967 if (self_size < 0) {
968 PyErr_Clear();
969 Py_INCREF(Py_NotImplemented);
970 return Py_NotImplemented;
971 }
972
973 other_size = _getbuffer(other, &other_bytes);
974 if (other_size < 0) {
975 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +0000976 PyBuffer_Release(&self_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000977 Py_INCREF(Py_NotImplemented);
978 return Py_NotImplemented;
979 }
980
981 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
982 /* Shortcut: if the lengths differ, the objects differ */
983 cmp = (op == Py_NE);
984 }
985 else {
986 minsize = self_size;
987 if (other_size < minsize)
988 minsize = other_size;
989
990 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
991 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
992
993 if (cmp == 0) {
994 if (self_size < other_size)
995 cmp = -1;
996 else if (self_size > other_size)
997 cmp = 1;
998 }
999
1000 switch (op) {
1001 case Py_LT: cmp = cmp < 0; break;
1002 case Py_LE: cmp = cmp <= 0; break;
1003 case Py_EQ: cmp = cmp == 0; break;
1004 case Py_NE: cmp = cmp != 0; break;
1005 case Py_GT: cmp = cmp > 0; break;
1006 case Py_GE: cmp = cmp >= 0; break;
1007 }
1008 }
1009
1010 res = cmp ? Py_True : Py_False;
Martin v. Löwis423be952008-08-13 15:53:07 +00001011 PyBuffer_Release(&self_bytes);
1012 PyBuffer_Release(&other_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001013 Py_INCREF(res);
1014 return res;
1015}
1016
1017static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001018bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001019{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001020 if (self->ob_exports > 0) {
1021 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001022 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001023 PyErr_Print();
1024 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001025 if (self->ob_bytes != 0) {
1026 PyMem_Free(self->ob_bytes);
1027 }
1028 Py_TYPE(self)->tp_free((PyObject *)self);
1029}
1030
1031
1032/* -------------------------------------------------------------------- */
1033/* Methods */
1034
1035#define STRINGLIB_CHAR char
1036#define STRINGLIB_CMP memcmp
1037#define STRINGLIB_LEN PyByteArray_GET_SIZE
1038#define STRINGLIB_STR PyByteArray_AS_STRING
1039#define STRINGLIB_NEW PyByteArray_FromStringAndSize
1040#define STRINGLIB_EMPTY nullbytes
1041#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1042#define STRINGLIB_MUTABLE 1
Benjamin Petersona786b022008-08-25 21:05:21 +00001043#define FROM_BYTEARRAY 1
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001044
1045#include "stringlib/fastsearch.h"
1046#include "stringlib/count.h"
1047#include "stringlib/find.h"
1048#include "stringlib/partition.h"
1049#include "stringlib/ctype.h"
1050#include "stringlib/transmogrify.h"
1051
1052
1053/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1054were copied from the old char* style string object. */
1055
1056Py_LOCAL_INLINE(void)
1057_adjust_indices(Py_ssize_t *start, Py_ssize_t *end, Py_ssize_t len)
1058{
1059 if (*end > len)
1060 *end = len;
1061 else if (*end < 0)
1062 *end += len;
1063 if (*end < 0)
1064 *end = 0;
1065 if (*start < 0)
1066 *start += len;
1067 if (*start < 0)
1068 *start = 0;
1069}
1070
1071
1072Py_LOCAL_INLINE(Py_ssize_t)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001073bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001074{
1075 PyObject *subobj;
1076 Py_buffer subbuf;
1077 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1078 Py_ssize_t res;
1079
1080 if (!PyArg_ParseTuple(args, "O|O&O&:find/rfind/index/rindex", &subobj,
1081 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1082 return -2;
1083 if (_getbuffer(subobj, &subbuf) < 0)
1084 return -2;
1085 if (dir > 0)
1086 res = stringlib_find_slice(
1087 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1088 subbuf.buf, subbuf.len, start, end);
1089 else
1090 res = stringlib_rfind_slice(
1091 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1092 subbuf.buf, subbuf.len, start, end);
Martin v. Löwis423be952008-08-13 15:53:07 +00001093 PyBuffer_Release(&subbuf);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001094 return res;
1095}
1096
1097PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001098"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001099\n\
1100Return the lowest index in B where subsection sub is found,\n\
1101such that sub is contained within s[start,end]. Optional\n\
1102arguments start and end are interpreted as in slice notation.\n\
1103\n\
1104Return -1 on failure.");
1105
1106static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001107bytearray_find(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001108{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001109 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001110 if (result == -2)
1111 return NULL;
1112 return PyLong_FromSsize_t(result);
1113}
1114
1115PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001116"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001117\n\
1118Return the number of non-overlapping occurrences of subsection sub in\n\
1119bytes B[start:end]. Optional arguments start and end are interpreted\n\
1120as in slice notation.");
1121
1122static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001123bytearray_count(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001124{
1125 PyObject *sub_obj;
1126 const char *str = PyByteArray_AS_STRING(self);
1127 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
1128 Py_buffer vsub;
1129 PyObject *count_obj;
1130
1131 if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj,
1132 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1133 return NULL;
1134
1135 if (_getbuffer(sub_obj, &vsub) < 0)
1136 return NULL;
1137
1138 _adjust_indices(&start, &end, PyByteArray_GET_SIZE(self));
1139
1140 count_obj = PyLong_FromSsize_t(
1141 stringlib_count(str + start, end - start, vsub.buf, vsub.len)
1142 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001143 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001144 return count_obj;
1145}
1146
1147
1148PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001149"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001150\n\
1151Like B.find() but raise ValueError when the subsection is not found.");
1152
1153static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001154bytearray_index(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001155{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001156 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001157 if (result == -2)
1158 return NULL;
1159 if (result == -1) {
1160 PyErr_SetString(PyExc_ValueError,
1161 "subsection not found");
1162 return NULL;
1163 }
1164 return PyLong_FromSsize_t(result);
1165}
1166
1167
1168PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001169"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001170\n\
1171Return the highest index in B where subsection sub is found,\n\
1172such that sub is contained within s[start,end]. Optional\n\
1173arguments start and end are interpreted as in slice notation.\n\
1174\n\
1175Return -1 on failure.");
1176
1177static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001178bytearray_rfind(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001179{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001180 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001181 if (result == -2)
1182 return NULL;
1183 return PyLong_FromSsize_t(result);
1184}
1185
1186
1187PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001188"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001189\n\
1190Like B.rfind() but raise ValueError when the subsection is not found.");
1191
1192static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001193bytearray_rindex(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001194{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001195 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001196 if (result == -2)
1197 return NULL;
1198 if (result == -1) {
1199 PyErr_SetString(PyExc_ValueError,
1200 "subsection not found");
1201 return NULL;
1202 }
1203 return PyLong_FromSsize_t(result);
1204}
1205
1206
1207static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001208bytearray_contains(PyObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001209{
1210 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1211 if (ival == -1 && PyErr_Occurred()) {
1212 Py_buffer varg;
1213 int pos;
1214 PyErr_Clear();
1215 if (_getbuffer(arg, &varg) < 0)
1216 return -1;
1217 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1218 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001219 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001220 return pos >= 0;
1221 }
1222 if (ival < 0 || ival >= 256) {
1223 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1224 return -1;
1225 }
1226
1227 return memchr(PyByteArray_AS_STRING(self), ival, Py_SIZE(self)) != NULL;
1228}
1229
1230
1231/* Matches the end (direction >= 0) or start (direction < 0) of self
1232 * against substr, using the start and end arguments. Returns
1233 * -1 on error, 0 if not found and 1 if found.
1234 */
1235Py_LOCAL(int)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001236_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001237 Py_ssize_t end, int direction)
1238{
1239 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1240 const char* str;
1241 Py_buffer vsubstr;
1242 int rv = 0;
1243
1244 str = PyByteArray_AS_STRING(self);
1245
1246 if (_getbuffer(substr, &vsubstr) < 0)
1247 return -1;
1248
1249 _adjust_indices(&start, &end, len);
1250
1251 if (direction < 0) {
1252 /* startswith */
1253 if (start+vsubstr.len > len) {
1254 goto done;
1255 }
1256 } else {
1257 /* endswith */
1258 if (end-start < vsubstr.len || start > len) {
1259 goto done;
1260 }
1261
1262 if (end-vsubstr.len > start)
1263 start = end - vsubstr.len;
1264 }
1265 if (end-start >= vsubstr.len)
1266 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1267
1268done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001269 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001270 return rv;
1271}
1272
1273
1274PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001275"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001276\n\
1277Return True if B starts with the specified prefix, False otherwise.\n\
1278With optional start, test B beginning at that position.\n\
1279With optional end, stop comparing B at that position.\n\
1280prefix can also be a tuple of strings to try.");
1281
1282static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001283bytearray_startswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001284{
1285 Py_ssize_t start = 0;
1286 Py_ssize_t end = PY_SSIZE_T_MAX;
1287 PyObject *subobj;
1288 int result;
1289
1290 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
1291 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1292 return NULL;
1293 if (PyTuple_Check(subobj)) {
1294 Py_ssize_t i;
1295 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001296 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001297 PyTuple_GET_ITEM(subobj, i),
1298 start, end, -1);
1299 if (result == -1)
1300 return NULL;
1301 else if (result) {
1302 Py_RETURN_TRUE;
1303 }
1304 }
1305 Py_RETURN_FALSE;
1306 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001307 result = _bytearray_tailmatch(self, subobj, start, end, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001308 if (result == -1)
1309 return NULL;
1310 else
1311 return PyBool_FromLong(result);
1312}
1313
1314PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001315"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001316\n\
1317Return True if B ends with the specified suffix, False otherwise.\n\
1318With optional start, test B beginning at that position.\n\
1319With optional end, stop comparing B at that position.\n\
1320suffix can also be a tuple of strings to try.");
1321
1322static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001323bytearray_endswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001324{
1325 Py_ssize_t start = 0;
1326 Py_ssize_t end = PY_SSIZE_T_MAX;
1327 PyObject *subobj;
1328 int result;
1329
1330 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
1331 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1332 return NULL;
1333 if (PyTuple_Check(subobj)) {
1334 Py_ssize_t i;
1335 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001336 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001337 PyTuple_GET_ITEM(subobj, i),
1338 start, end, +1);
1339 if (result == -1)
1340 return NULL;
1341 else if (result) {
1342 Py_RETURN_TRUE;
1343 }
1344 }
1345 Py_RETURN_FALSE;
1346 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001347 result = _bytearray_tailmatch(self, subobj, start, end, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001348 if (result == -1)
1349 return NULL;
1350 else
1351 return PyBool_FromLong(result);
1352}
1353
1354
1355PyDoc_STRVAR(translate__doc__,
1356"B.translate(table[, deletechars]) -> bytearray\n\
1357\n\
1358Return a copy of B, where all characters occurring in the\n\
1359optional argument deletechars are removed, and the remaining\n\
1360characters have been mapped through the given translation\n\
1361table, which must be a bytes object of length 256.");
1362
1363static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001364bytearray_translate(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001365{
1366 register char *input, *output;
1367 register const char *table;
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001368 register Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001369 PyObject *input_obj = (PyObject*)self;
1370 const char *output_start;
1371 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001372 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001373 int trans_table[256];
Georg Brandlccc47b62008-12-28 11:44:14 +00001374 PyObject *tableobj = NULL, *delobj = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001375 Py_buffer vtable, vdel;
1376
1377 if (!PyArg_UnpackTuple(args, "translate", 1, 2,
1378 &tableobj, &delobj))
1379 return NULL;
1380
Georg Brandlccc47b62008-12-28 11:44:14 +00001381 if (tableobj == Py_None) {
1382 table = NULL;
1383 tableobj = NULL;
1384 } else if (_getbuffer(tableobj, &vtable) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001385 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001386 } else {
1387 if (vtable.len != 256) {
1388 PyErr_SetString(PyExc_ValueError,
1389 "translation table must be 256 characters long");
Georg Brandl069bcc32009-07-22 12:06:11 +00001390 PyBuffer_Release(&vtable);
1391 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001392 }
1393 table = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001394 }
1395
1396 if (delobj != NULL) {
1397 if (_getbuffer(delobj, &vdel) < 0) {
Georg Brandl069bcc32009-07-22 12:06:11 +00001398 if (tableobj != NULL)
1399 PyBuffer_Release(&vtable);
1400 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001401 }
1402 }
1403 else {
1404 vdel.buf = NULL;
1405 vdel.len = 0;
1406 }
1407
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001408 inlen = PyByteArray_GET_SIZE(input_obj);
1409 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1410 if (result == NULL)
1411 goto done;
1412 output_start = output = PyByteArray_AsString(result);
1413 input = PyByteArray_AS_STRING(input_obj);
1414
Georg Brandlccc47b62008-12-28 11:44:14 +00001415 if (vdel.len == 0 && table != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001416 /* If no deletions are required, use faster code */
1417 for (i = inlen; --i >= 0; ) {
1418 c = Py_CHARMASK(*input++);
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001419 *output++ = table[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001420 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001421 goto done;
1422 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001423
1424 if (table == NULL) {
1425 for (i = 0; i < 256; i++)
1426 trans_table[i] = Py_CHARMASK(i);
1427 } else {
1428 for (i = 0; i < 256; i++)
1429 trans_table[i] = Py_CHARMASK(table[i]);
1430 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001431
1432 for (i = 0; i < vdel.len; i++)
1433 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1434
1435 for (i = inlen; --i >= 0; ) {
1436 c = Py_CHARMASK(*input++);
1437 if (trans_table[c] != -1)
1438 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1439 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001440 }
1441 /* Fix the size of the resulting string */
1442 if (inlen > 0)
1443 PyByteArray_Resize(result, output - output_start);
1444
1445done:
Georg Brandlccc47b62008-12-28 11:44:14 +00001446 if (tableobj != NULL)
1447 PyBuffer_Release(&vtable);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001448 if (delobj != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001449 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001450 return result;
1451}
1452
1453
Georg Brandlabc38772009-04-12 15:51:51 +00001454static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001455bytearray_maketrans(PyObject *null, PyObject *args)
Georg Brandlabc38772009-04-12 15:51:51 +00001456{
1457 return _Py_bytes_maketrans(args);
1458}
1459
1460
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001461#define FORWARD 1
1462#define REVERSE -1
1463
1464/* find and count characters and substrings */
1465
1466#define findchar(target, target_len, c) \
1467 ((char *)memchr((const void *)(target), c, target_len))
1468
1469/* Don't call if length < 2 */
1470#define Py_STRING_MATCH(target, offset, pattern, length) \
1471 (target[offset] == pattern[0] && \
1472 target[offset+length-1] == pattern[length-1] && \
1473 !memcmp(target+offset+1, pattern+1, length-2) )
1474
1475
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001476/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001477Py_LOCAL(PyByteArrayObject *)
1478return_self(PyByteArrayObject *self)
1479{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001480 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001481 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1482 PyByteArray_AS_STRING(self),
1483 PyByteArray_GET_SIZE(self));
1484}
1485
1486Py_LOCAL_INLINE(Py_ssize_t)
1487countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1488{
1489 Py_ssize_t count=0;
1490 const char *start=target;
1491 const char *end=target+target_len;
1492
1493 while ( (start=findchar(start, end-start, c)) != NULL ) {
1494 count++;
1495 if (count >= maxcount)
1496 break;
1497 start += 1;
1498 }
1499 return count;
1500}
1501
1502Py_LOCAL(Py_ssize_t)
1503findstring(const char *target, Py_ssize_t target_len,
1504 const char *pattern, Py_ssize_t pattern_len,
1505 Py_ssize_t start,
1506 Py_ssize_t end,
1507 int direction)
1508{
1509 if (start < 0) {
1510 start += target_len;
1511 if (start < 0)
1512 start = 0;
1513 }
1514 if (end > target_len) {
1515 end = target_len;
1516 } else if (end < 0) {
1517 end += target_len;
1518 if (end < 0)
1519 end = 0;
1520 }
1521
1522 /* zero-length substrings always match at the first attempt */
1523 if (pattern_len == 0)
1524 return (direction > 0) ? start : end;
1525
1526 end -= pattern_len;
1527
1528 if (direction < 0) {
1529 for (; end >= start; end--)
1530 if (Py_STRING_MATCH(target, end, pattern, pattern_len))
1531 return end;
1532 } else {
1533 for (; start <= end; start++)
1534 if (Py_STRING_MATCH(target, start, pattern, pattern_len))
1535 return start;
1536 }
1537 return -1;
1538}
1539
1540Py_LOCAL_INLINE(Py_ssize_t)
1541countstring(const char *target, Py_ssize_t target_len,
1542 const char *pattern, Py_ssize_t pattern_len,
1543 Py_ssize_t start,
1544 Py_ssize_t end,
1545 int direction, Py_ssize_t maxcount)
1546{
1547 Py_ssize_t count=0;
1548
1549 if (start < 0) {
1550 start += target_len;
1551 if (start < 0)
1552 start = 0;
1553 }
1554 if (end > target_len) {
1555 end = target_len;
1556 } else if (end < 0) {
1557 end += target_len;
1558 if (end < 0)
1559 end = 0;
1560 }
1561
1562 /* zero-length substrings match everywhere */
1563 if (pattern_len == 0 || maxcount == 0) {
1564 if (target_len+1 < maxcount)
1565 return target_len+1;
1566 return maxcount;
1567 }
1568
1569 end -= pattern_len;
1570 if (direction < 0) {
1571 for (; (end >= start); end--)
1572 if (Py_STRING_MATCH(target, end, pattern, pattern_len)) {
1573 count++;
1574 if (--maxcount <= 0) break;
1575 end -= pattern_len-1;
1576 }
1577 } else {
1578 for (; (start <= end); start++)
1579 if (Py_STRING_MATCH(target, start, pattern, pattern_len)) {
1580 count++;
1581 if (--maxcount <= 0)
1582 break;
1583 start += pattern_len-1;
1584 }
1585 }
1586 return count;
1587}
1588
1589
1590/* Algorithms for different cases of string replacement */
1591
1592/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1593Py_LOCAL(PyByteArrayObject *)
1594replace_interleave(PyByteArrayObject *self,
1595 const char *to_s, Py_ssize_t to_len,
1596 Py_ssize_t maxcount)
1597{
1598 char *self_s, *result_s;
1599 Py_ssize_t self_len, result_len;
1600 Py_ssize_t count, i, product;
1601 PyByteArrayObject *result;
1602
1603 self_len = PyByteArray_GET_SIZE(self);
1604
1605 /* 1 at the end plus 1 after every character */
1606 count = self_len+1;
1607 if (maxcount < count)
1608 count = maxcount;
1609
1610 /* Check for overflow */
1611 /* result_len = count * to_len + self_len; */
1612 product = count * to_len;
1613 if (product / to_len != count) {
1614 PyErr_SetString(PyExc_OverflowError,
1615 "replace string is too long");
1616 return NULL;
1617 }
1618 result_len = product + self_len;
1619 if (result_len < 0) {
1620 PyErr_SetString(PyExc_OverflowError,
1621 "replace string is too long");
1622 return NULL;
1623 }
1624
1625 if (! (result = (PyByteArrayObject *)
1626 PyByteArray_FromStringAndSize(NULL, result_len)) )
1627 return NULL;
1628
1629 self_s = PyByteArray_AS_STRING(self);
1630 result_s = PyByteArray_AS_STRING(result);
1631
1632 /* TODO: special case single character, which doesn't need memcpy */
1633
1634 /* Lay the first one down (guaranteed this will occur) */
1635 Py_MEMCPY(result_s, to_s, to_len);
1636 result_s += to_len;
1637 count -= 1;
1638
1639 for (i=0; i<count; i++) {
1640 *result_s++ = *self_s++;
1641 Py_MEMCPY(result_s, to_s, to_len);
1642 result_s += to_len;
1643 }
1644
1645 /* Copy the rest of the original string */
1646 Py_MEMCPY(result_s, self_s, self_len-i);
1647
1648 return result;
1649}
1650
1651/* Special case for deleting a single character */
1652/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1653Py_LOCAL(PyByteArrayObject *)
1654replace_delete_single_character(PyByteArrayObject *self,
1655 char from_c, Py_ssize_t maxcount)
1656{
1657 char *self_s, *result_s;
1658 char *start, *next, *end;
1659 Py_ssize_t self_len, result_len;
1660 Py_ssize_t count;
1661 PyByteArrayObject *result;
1662
1663 self_len = PyByteArray_GET_SIZE(self);
1664 self_s = PyByteArray_AS_STRING(self);
1665
1666 count = countchar(self_s, self_len, from_c, maxcount);
1667 if (count == 0) {
1668 return return_self(self);
1669 }
1670
1671 result_len = self_len - count; /* from_len == 1 */
1672 assert(result_len>=0);
1673
1674 if ( (result = (PyByteArrayObject *)
1675 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1676 return NULL;
1677 result_s = PyByteArray_AS_STRING(result);
1678
1679 start = self_s;
1680 end = self_s + self_len;
1681 while (count-- > 0) {
1682 next = findchar(start, end-start, from_c);
1683 if (next == NULL)
1684 break;
1685 Py_MEMCPY(result_s, start, next-start);
1686 result_s += (next-start);
1687 start = next+1;
1688 }
1689 Py_MEMCPY(result_s, start, end-start);
1690
1691 return result;
1692}
1693
1694/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1695
1696Py_LOCAL(PyByteArrayObject *)
1697replace_delete_substring(PyByteArrayObject *self,
1698 const char *from_s, Py_ssize_t from_len,
1699 Py_ssize_t maxcount)
1700{
1701 char *self_s, *result_s;
1702 char *start, *next, *end;
1703 Py_ssize_t self_len, result_len;
1704 Py_ssize_t count, offset;
1705 PyByteArrayObject *result;
1706
1707 self_len = PyByteArray_GET_SIZE(self);
1708 self_s = PyByteArray_AS_STRING(self);
1709
1710 count = countstring(self_s, self_len,
1711 from_s, from_len,
1712 0, self_len, 1,
1713 maxcount);
1714
1715 if (count == 0) {
1716 /* no matches */
1717 return return_self(self);
1718 }
1719
1720 result_len = self_len - (count * from_len);
1721 assert (result_len>=0);
1722
1723 if ( (result = (PyByteArrayObject *)
1724 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1725 return NULL;
1726
1727 result_s = PyByteArray_AS_STRING(result);
1728
1729 start = self_s;
1730 end = self_s + self_len;
1731 while (count-- > 0) {
1732 offset = findstring(start, end-start,
1733 from_s, from_len,
1734 0, end-start, FORWARD);
1735 if (offset == -1)
1736 break;
1737 next = start + offset;
1738
1739 Py_MEMCPY(result_s, start, next-start);
1740
1741 result_s += (next-start);
1742 start = next+from_len;
1743 }
1744 Py_MEMCPY(result_s, start, end-start);
1745 return result;
1746}
1747
1748/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1749Py_LOCAL(PyByteArrayObject *)
1750replace_single_character_in_place(PyByteArrayObject *self,
1751 char from_c, char to_c,
1752 Py_ssize_t maxcount)
1753{
1754 char *self_s, *result_s, *start, *end, *next;
1755 Py_ssize_t self_len;
1756 PyByteArrayObject *result;
1757
1758 /* The result string will be the same size */
1759 self_s = PyByteArray_AS_STRING(self);
1760 self_len = PyByteArray_GET_SIZE(self);
1761
1762 next = findchar(self_s, self_len, from_c);
1763
1764 if (next == NULL) {
1765 /* No matches; return the original bytes */
1766 return return_self(self);
1767 }
1768
1769 /* Need to make a new bytes */
1770 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1771 if (result == NULL)
1772 return NULL;
1773 result_s = PyByteArray_AS_STRING(result);
1774 Py_MEMCPY(result_s, self_s, self_len);
1775
1776 /* change everything in-place, starting with this one */
1777 start = result_s + (next-self_s);
1778 *start = to_c;
1779 start++;
1780 end = result_s + self_len;
1781
1782 while (--maxcount > 0) {
1783 next = findchar(start, end-start, from_c);
1784 if (next == NULL)
1785 break;
1786 *next = to_c;
1787 start = next+1;
1788 }
1789
1790 return result;
1791}
1792
1793/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1794Py_LOCAL(PyByteArrayObject *)
1795replace_substring_in_place(PyByteArrayObject *self,
1796 const char *from_s, Py_ssize_t from_len,
1797 const char *to_s, Py_ssize_t to_len,
1798 Py_ssize_t maxcount)
1799{
1800 char *result_s, *start, *end;
1801 char *self_s;
1802 Py_ssize_t self_len, offset;
1803 PyByteArrayObject *result;
1804
1805 /* The result bytes will be the same size */
1806
1807 self_s = PyByteArray_AS_STRING(self);
1808 self_len = PyByteArray_GET_SIZE(self);
1809
1810 offset = findstring(self_s, self_len,
1811 from_s, from_len,
1812 0, self_len, FORWARD);
1813 if (offset == -1) {
1814 /* No matches; return the original bytes */
1815 return return_self(self);
1816 }
1817
1818 /* Need to make a new bytes */
1819 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1820 if (result == NULL)
1821 return NULL;
1822 result_s = PyByteArray_AS_STRING(result);
1823 Py_MEMCPY(result_s, self_s, self_len);
1824
1825 /* change everything in-place, starting with this one */
1826 start = result_s + offset;
1827 Py_MEMCPY(start, to_s, from_len);
1828 start += from_len;
1829 end = result_s + self_len;
1830
1831 while ( --maxcount > 0) {
1832 offset = findstring(start, end-start,
1833 from_s, from_len,
1834 0, end-start, FORWARD);
1835 if (offset==-1)
1836 break;
1837 Py_MEMCPY(start+offset, to_s, from_len);
1838 start += offset+from_len;
1839 }
1840
1841 return result;
1842}
1843
1844/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
1845Py_LOCAL(PyByteArrayObject *)
1846replace_single_character(PyByteArrayObject *self,
1847 char from_c,
1848 const char *to_s, Py_ssize_t to_len,
1849 Py_ssize_t maxcount)
1850{
1851 char *self_s, *result_s;
1852 char *start, *next, *end;
1853 Py_ssize_t self_len, result_len;
1854 Py_ssize_t count, product;
1855 PyByteArrayObject *result;
1856
1857 self_s = PyByteArray_AS_STRING(self);
1858 self_len = PyByteArray_GET_SIZE(self);
1859
1860 count = countchar(self_s, self_len, from_c, maxcount);
1861 if (count == 0) {
1862 /* no matches, return unchanged */
1863 return return_self(self);
1864 }
1865
1866 /* use the difference between current and new, hence the "-1" */
1867 /* result_len = self_len + count * (to_len-1) */
1868 product = count * (to_len-1);
1869 if (product / (to_len-1) != count) {
1870 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1871 return NULL;
1872 }
1873 result_len = self_len + product;
1874 if (result_len < 0) {
1875 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1876 return NULL;
1877 }
1878
1879 if ( (result = (PyByteArrayObject *)
1880 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1881 return NULL;
1882 result_s = PyByteArray_AS_STRING(result);
1883
1884 start = self_s;
1885 end = self_s + self_len;
1886 while (count-- > 0) {
1887 next = findchar(start, end-start, from_c);
1888 if (next == NULL)
1889 break;
1890
1891 if (next == start) {
1892 /* replace with the 'to' */
1893 Py_MEMCPY(result_s, to_s, to_len);
1894 result_s += to_len;
1895 start += 1;
1896 } else {
1897 /* copy the unchanged old then the 'to' */
1898 Py_MEMCPY(result_s, start, next-start);
1899 result_s += (next-start);
1900 Py_MEMCPY(result_s, to_s, to_len);
1901 result_s += to_len;
1902 start = next+1;
1903 }
1904 }
1905 /* Copy the remainder of the remaining bytes */
1906 Py_MEMCPY(result_s, start, end-start);
1907
1908 return result;
1909}
1910
1911/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
1912Py_LOCAL(PyByteArrayObject *)
1913replace_substring(PyByteArrayObject *self,
1914 const char *from_s, Py_ssize_t from_len,
1915 const char *to_s, Py_ssize_t to_len,
1916 Py_ssize_t maxcount)
1917{
1918 char *self_s, *result_s;
1919 char *start, *next, *end;
1920 Py_ssize_t self_len, result_len;
1921 Py_ssize_t count, offset, product;
1922 PyByteArrayObject *result;
1923
1924 self_s = PyByteArray_AS_STRING(self);
1925 self_len = PyByteArray_GET_SIZE(self);
1926
1927 count = countstring(self_s, self_len,
1928 from_s, from_len,
1929 0, self_len, FORWARD, maxcount);
1930 if (count == 0) {
1931 /* no matches, return unchanged */
1932 return return_self(self);
1933 }
1934
1935 /* Check for overflow */
1936 /* result_len = self_len + count * (to_len-from_len) */
1937 product = count * (to_len-from_len);
1938 if (product / (to_len-from_len) != count) {
1939 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1940 return NULL;
1941 }
1942 result_len = self_len + product;
1943 if (result_len < 0) {
1944 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1945 return NULL;
1946 }
1947
1948 if ( (result = (PyByteArrayObject *)
1949 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1950 return NULL;
1951 result_s = PyByteArray_AS_STRING(result);
1952
1953 start = self_s;
1954 end = self_s + self_len;
1955 while (count-- > 0) {
1956 offset = findstring(start, end-start,
1957 from_s, from_len,
1958 0, end-start, FORWARD);
1959 if (offset == -1)
1960 break;
1961 next = start+offset;
1962 if (next == start) {
1963 /* replace with the 'to' */
1964 Py_MEMCPY(result_s, to_s, to_len);
1965 result_s += to_len;
1966 start += from_len;
1967 } else {
1968 /* copy the unchanged old then the 'to' */
1969 Py_MEMCPY(result_s, start, next-start);
1970 result_s += (next-start);
1971 Py_MEMCPY(result_s, to_s, to_len);
1972 result_s += to_len;
1973 start = next+from_len;
1974 }
1975 }
1976 /* Copy the remainder of the remaining bytes */
1977 Py_MEMCPY(result_s, start, end-start);
1978
1979 return result;
1980}
1981
1982
1983Py_LOCAL(PyByteArrayObject *)
1984replace(PyByteArrayObject *self,
1985 const char *from_s, Py_ssize_t from_len,
1986 const char *to_s, Py_ssize_t to_len,
1987 Py_ssize_t maxcount)
1988{
1989 if (maxcount < 0) {
1990 maxcount = PY_SSIZE_T_MAX;
1991 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
1992 /* nothing to do; return the original bytes */
1993 return return_self(self);
1994 }
1995
1996 if (maxcount == 0 ||
1997 (from_len == 0 && to_len == 0)) {
1998 /* nothing to do; return the original bytes */
1999 return return_self(self);
2000 }
2001
2002 /* Handle zero-length special cases */
2003
2004 if (from_len == 0) {
2005 /* insert the 'to' bytes everywhere. */
2006 /* >>> "Python".replace("", ".") */
2007 /* '.P.y.t.h.o.n.' */
2008 return replace_interleave(self, to_s, to_len, maxcount);
2009 }
2010
2011 /* Except for "".replace("", "A") == "A" there is no way beyond this */
2012 /* point for an empty self bytes to generate a non-empty bytes */
2013 /* Special case so the remaining code always gets a non-empty bytes */
2014 if (PyByteArray_GET_SIZE(self) == 0) {
2015 return return_self(self);
2016 }
2017
2018 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00002019 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002020 if (from_len == 1) {
2021 return replace_delete_single_character(
2022 self, from_s[0], maxcount);
2023 } else {
2024 return replace_delete_substring(self, from_s, from_len, maxcount);
2025 }
2026 }
2027
2028 /* Handle special case where both bytes have the same length */
2029
2030 if (from_len == to_len) {
2031 if (from_len == 1) {
2032 return replace_single_character_in_place(
2033 self,
2034 from_s[0],
2035 to_s[0],
2036 maxcount);
2037 } else {
2038 return replace_substring_in_place(
2039 self, from_s, from_len, to_s, to_len, maxcount);
2040 }
2041 }
2042
2043 /* Otherwise use the more generic algorithms */
2044 if (from_len == 1) {
2045 return replace_single_character(self, from_s[0],
2046 to_s, to_len, maxcount);
2047 } else {
2048 /* len('from')>=2, len('to')>=1 */
2049 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
2050 }
2051}
2052
2053
2054PyDoc_STRVAR(replace__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002055"B.replace(old, new[, count]) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002056\n\
2057Return a copy of B with all occurrences of subsection\n\
2058old replaced by new. If the optional argument count is\n\
2059given, only the first count occurrences are replaced.");
2060
2061static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002062bytearray_replace(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002063{
2064 Py_ssize_t count = -1;
2065 PyObject *from, *to, *res;
2066 Py_buffer vfrom, vto;
2067
2068 if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
2069 return NULL;
2070
2071 if (_getbuffer(from, &vfrom) < 0)
2072 return NULL;
2073 if (_getbuffer(to, &vto) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +00002074 PyBuffer_Release(&vfrom);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002075 return NULL;
2076 }
2077
2078 res = (PyObject *)replace((PyByteArrayObject *) self,
2079 vfrom.buf, vfrom.len,
2080 vto.buf, vto.len, count);
2081
Martin v. Löwis423be952008-08-13 15:53:07 +00002082 PyBuffer_Release(&vfrom);
2083 PyBuffer_Release(&vto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002084 return res;
2085}
2086
2087
2088/* Overallocate the initial list to reduce the number of reallocs for small
2089 split sizes. Eg, "A A A A A A A A A A".split() (10 elements) has three
2090 resizes, to sizes 4, 8, then 16. Most observed string splits are for human
2091 text (roughly 11 words per line) and field delimited data (usually 1-10
2092 fields). For large strings the split algorithms are bandwidth limited
2093 so increasing the preallocation likely will not improve things.*/
2094
2095#define MAX_PREALLOC 12
2096
2097/* 5 splits gives 6 elements */
2098#define PREALLOC_SIZE(maxsplit) \
2099 (maxsplit >= MAX_PREALLOC ? MAX_PREALLOC : maxsplit+1)
2100
2101#define SPLIT_APPEND(data, left, right) \
2102 str = PyByteArray_FromStringAndSize((data) + (left), \
2103 (right) - (left)); \
2104 if (str == NULL) \
2105 goto onError; \
2106 if (PyList_Append(list, str)) { \
2107 Py_DECREF(str); \
2108 goto onError; \
2109 } \
2110 else \
2111 Py_DECREF(str);
2112
2113#define SPLIT_ADD(data, left, right) { \
2114 str = PyByteArray_FromStringAndSize((data) + (left), \
2115 (right) - (left)); \
2116 if (str == NULL) \
2117 goto onError; \
2118 if (count < MAX_PREALLOC) { \
2119 PyList_SET_ITEM(list, count, str); \
2120 } else { \
2121 if (PyList_Append(list, str)) { \
2122 Py_DECREF(str); \
2123 goto onError; \
2124 } \
2125 else \
2126 Py_DECREF(str); \
2127 } \
2128 count++; }
2129
2130/* Always force the list to the expected size. */
2131#define FIX_PREALLOC_SIZE(list) Py_SIZE(list) = count
2132
2133
2134Py_LOCAL_INLINE(PyObject *)
2135split_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount)
2136{
2137 register Py_ssize_t i, j, count = 0;
2138 PyObject *str;
2139 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2140
2141 if (list == NULL)
2142 return NULL;
2143
2144 i = j = 0;
2145 while ((j < len) && (maxcount-- > 0)) {
2146 for(; j < len; j++) {
2147 /* I found that using memchr makes no difference */
2148 if (s[j] == ch) {
2149 SPLIT_ADD(s, i, j);
2150 i = j = j + 1;
2151 break;
2152 }
2153 }
2154 }
2155 if (i <= len) {
2156 SPLIT_ADD(s, i, len);
2157 }
2158 FIX_PREALLOC_SIZE(list);
2159 return list;
2160
2161 onError:
2162 Py_DECREF(list);
2163 return NULL;
2164}
2165
2166
2167Py_LOCAL_INLINE(PyObject *)
2168split_whitespace(const char *s, Py_ssize_t len, Py_ssize_t maxcount)
2169{
2170 register Py_ssize_t i, j, count = 0;
2171 PyObject *str;
2172 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2173
2174 if (list == NULL)
2175 return NULL;
2176
2177 for (i = j = 0; i < len; ) {
2178 /* find a token */
Eric Smith6dc46f52009-04-27 20:39:49 +00002179 while (i < len && Py_ISSPACE(s[i]))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002180 i++;
2181 j = i;
Eric Smith6dc46f52009-04-27 20:39:49 +00002182 while (i < len && !Py_ISSPACE(s[i]))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002183 i++;
2184 if (j < i) {
2185 if (maxcount-- <= 0)
2186 break;
2187 SPLIT_ADD(s, j, i);
Eric Smith6dc46f52009-04-27 20:39:49 +00002188 while (i < len && Py_ISSPACE(s[i]))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002189 i++;
2190 j = i;
2191 }
2192 }
2193 if (j < len) {
2194 SPLIT_ADD(s, j, len);
2195 }
2196 FIX_PREALLOC_SIZE(list);
2197 return list;
2198
2199 onError:
2200 Py_DECREF(list);
2201 return NULL;
2202}
2203
2204PyDoc_STRVAR(split__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002205"B.split([sep[, maxsplit]]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002206\n\
2207Return a list of the sections in B, using sep as the delimiter.\n\
2208If sep is not given, B is split on ASCII whitespace characters\n\
2209(space, tab, return, newline, formfeed, vertical tab).\n\
2210If maxsplit is given, at most maxsplit splits are done.");
2211
2212static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002213bytearray_split(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002214{
2215 Py_ssize_t len = PyByteArray_GET_SIZE(self), n, i, j;
2216 Py_ssize_t maxsplit = -1, count = 0;
2217 const char *s = PyByteArray_AS_STRING(self), *sub;
2218 PyObject *list, *str, *subobj = Py_None;
2219 Py_buffer vsub;
2220#ifdef USE_FAST
2221 Py_ssize_t pos;
2222#endif
2223
2224 if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
2225 return NULL;
2226 if (maxsplit < 0)
2227 maxsplit = PY_SSIZE_T_MAX;
2228
2229 if (subobj == Py_None)
2230 return split_whitespace(s, len, maxsplit);
2231
2232 if (_getbuffer(subobj, &vsub) < 0)
2233 return NULL;
2234 sub = vsub.buf;
2235 n = vsub.len;
2236
2237 if (n == 0) {
2238 PyErr_SetString(PyExc_ValueError, "empty separator");
Martin v. Löwis423be952008-08-13 15:53:07 +00002239 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002240 return NULL;
2241 }
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +00002242 if (n == 1) {
2243 list = split_char(s, len, sub[0], maxsplit);
2244 PyBuffer_Release(&vsub);
2245 return list;
2246 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002247
2248 list = PyList_New(PREALLOC_SIZE(maxsplit));
2249 if (list == NULL) {
Martin v. Löwis423be952008-08-13 15:53:07 +00002250 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002251 return NULL;
2252 }
2253
2254#ifdef USE_FAST
2255 i = j = 0;
2256 while (maxsplit-- > 0) {
2257 pos = fastsearch(s+i, len-i, sub, n, FAST_SEARCH);
2258 if (pos < 0)
2259 break;
2260 j = i+pos;
2261 SPLIT_ADD(s, i, j);
2262 i = j + n;
2263 }
2264#else
2265 i = j = 0;
2266 while ((j+n <= len) && (maxsplit-- > 0)) {
2267 for (; j+n <= len; j++) {
2268 if (Py_STRING_MATCH(s, j, sub, n)) {
2269 SPLIT_ADD(s, i, j);
2270 i = j = j + n;
2271 break;
2272 }
2273 }
2274 }
2275#endif
2276 SPLIT_ADD(s, i, len);
2277 FIX_PREALLOC_SIZE(list);
Martin v. Löwis423be952008-08-13 15:53:07 +00002278 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002279 return list;
2280
2281 onError:
2282 Py_DECREF(list);
Martin v. Löwis423be952008-08-13 15:53:07 +00002283 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002284 return NULL;
2285}
2286
2287/* stringlib's partition shares nullbytes in some cases.
2288 undo this, we don't want the nullbytes to be shared. */
2289static PyObject *
2290make_nullbytes_unique(PyObject *result)
2291{
2292 if (result != NULL) {
2293 int i;
2294 assert(PyTuple_Check(result));
2295 assert(PyTuple_GET_SIZE(result) == 3);
2296 for (i = 0; i < 3; i++) {
2297 if (PyTuple_GET_ITEM(result, i) == (PyObject *)nullbytes) {
2298 PyObject *new = PyByteArray_FromStringAndSize(NULL, 0);
2299 if (new == NULL) {
2300 Py_DECREF(result);
2301 result = NULL;
2302 break;
2303 }
2304 Py_DECREF(nullbytes);
2305 PyTuple_SET_ITEM(result, i, new);
2306 }
2307 }
2308 }
2309 return result;
2310}
2311
2312PyDoc_STRVAR(partition__doc__,
2313"B.partition(sep) -> (head, sep, tail)\n\
2314\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002315Search for the separator sep in B, and return the part before it,\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002316the separator itself, and the part after it. If the separator is not\n\
2317found, returns B and two empty bytearray objects.");
2318
2319static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002320bytearray_partition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002321{
2322 PyObject *bytesep, *result;
2323
2324 bytesep = PyByteArray_FromObject(sep_obj);
2325 if (! bytesep)
2326 return NULL;
2327
2328 result = stringlib_partition(
2329 (PyObject*) self,
2330 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2331 bytesep,
2332 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2333 );
2334
2335 Py_DECREF(bytesep);
2336 return make_nullbytes_unique(result);
2337}
2338
2339PyDoc_STRVAR(rpartition__doc__,
2340"B.rpartition(sep) -> (tail, sep, head)\n\
2341\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002342Search for the separator sep in B, starting at the end of B,\n\
2343and return the part before it, the separator itself, and the\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002344part after it. If the separator is not found, returns two empty\n\
2345bytearray objects and B.");
2346
2347static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002348bytearray_rpartition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002349{
2350 PyObject *bytesep, *result;
2351
2352 bytesep = PyByteArray_FromObject(sep_obj);
2353 if (! bytesep)
2354 return NULL;
2355
2356 result = stringlib_rpartition(
2357 (PyObject*) self,
2358 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2359 bytesep,
2360 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2361 );
2362
2363 Py_DECREF(bytesep);
2364 return make_nullbytes_unique(result);
2365}
2366
2367Py_LOCAL_INLINE(PyObject *)
2368rsplit_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount)
2369{
2370 register Py_ssize_t i, j, count=0;
2371 PyObject *str;
2372 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2373
2374 if (list == NULL)
2375 return NULL;
2376
2377 i = j = len - 1;
2378 while ((i >= 0) && (maxcount-- > 0)) {
2379 for (; i >= 0; i--) {
2380 if (s[i] == ch) {
2381 SPLIT_ADD(s, i + 1, j + 1);
2382 j = i = i - 1;
2383 break;
2384 }
2385 }
2386 }
2387 if (j >= -1) {
2388 SPLIT_ADD(s, 0, j + 1);
2389 }
2390 FIX_PREALLOC_SIZE(list);
2391 if (PyList_Reverse(list) < 0)
2392 goto onError;
2393
2394 return list;
2395
2396 onError:
2397 Py_DECREF(list);
2398 return NULL;
2399}
2400
2401Py_LOCAL_INLINE(PyObject *)
2402rsplit_whitespace(const char *s, Py_ssize_t len, Py_ssize_t maxcount)
2403{
2404 register Py_ssize_t i, j, count = 0;
2405 PyObject *str;
2406 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2407
2408 if (list == NULL)
2409 return NULL;
2410
2411 for (i = j = len - 1; i >= 0; ) {
2412 /* find a token */
Eric Smith6dc46f52009-04-27 20:39:49 +00002413 while (i >= 0 && Py_ISSPACE(s[i]))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002414 i--;
2415 j = i;
Eric Smith6dc46f52009-04-27 20:39:49 +00002416 while (i >= 0 && !Py_ISSPACE(s[i]))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002417 i--;
2418 if (j > i) {
2419 if (maxcount-- <= 0)
2420 break;
2421 SPLIT_ADD(s, i + 1, j + 1);
Eric Smith6dc46f52009-04-27 20:39:49 +00002422 while (i >= 0 && Py_ISSPACE(s[i]))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002423 i--;
2424 j = i;
2425 }
2426 }
2427 if (j >= 0) {
2428 SPLIT_ADD(s, 0, j + 1);
2429 }
2430 FIX_PREALLOC_SIZE(list);
2431 if (PyList_Reverse(list) < 0)
2432 goto onError;
2433
2434 return list;
2435
2436 onError:
2437 Py_DECREF(list);
2438 return NULL;
2439}
2440
2441PyDoc_STRVAR(rsplit__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002442"B.rsplit(sep[, maxsplit]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002443\n\
2444Return a list of the sections in B, using sep as the delimiter,\n\
2445starting at the end of B and working to the front.\n\
2446If sep is not given, B is split on ASCII whitespace characters\n\
2447(space, tab, return, newline, formfeed, vertical tab).\n\
2448If maxsplit is given, at most maxsplit splits are done.");
2449
2450static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002451bytearray_rsplit(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002452{
2453 Py_ssize_t len = PyByteArray_GET_SIZE(self), n, i, j;
2454 Py_ssize_t maxsplit = -1, count = 0;
2455 const char *s = PyByteArray_AS_STRING(self), *sub;
2456 PyObject *list, *str, *subobj = Py_None;
2457 Py_buffer vsub;
2458
2459 if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
2460 return NULL;
2461 if (maxsplit < 0)
2462 maxsplit = PY_SSIZE_T_MAX;
2463
2464 if (subobj == Py_None)
2465 return rsplit_whitespace(s, len, maxsplit);
2466
2467 if (_getbuffer(subobj, &vsub) < 0)
2468 return NULL;
2469 sub = vsub.buf;
2470 n = vsub.len;
2471
2472 if (n == 0) {
2473 PyErr_SetString(PyExc_ValueError, "empty separator");
Martin v. Löwis423be952008-08-13 15:53:07 +00002474 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002475 return NULL;
2476 }
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +00002477 else if (n == 1) {
2478 list = rsplit_char(s, len, sub[0], maxsplit);
2479 PyBuffer_Release(&vsub);
2480 return list;
2481 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002482
2483 list = PyList_New(PREALLOC_SIZE(maxsplit));
2484 if (list == NULL) {
Martin v. Löwis423be952008-08-13 15:53:07 +00002485 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002486 return NULL;
2487 }
2488
2489 j = len;
2490 i = j - n;
2491
2492 while ( (i >= 0) && (maxsplit-- > 0) ) {
2493 for (; i>=0; i--) {
2494 if (Py_STRING_MATCH(s, i, sub, n)) {
2495 SPLIT_ADD(s, i + n, j);
2496 j = i;
2497 i -= n;
2498 break;
2499 }
2500 }
2501 }
2502 SPLIT_ADD(s, 0, j);
2503 FIX_PREALLOC_SIZE(list);
2504 if (PyList_Reverse(list) < 0)
2505 goto onError;
Martin v. Löwis423be952008-08-13 15:53:07 +00002506 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002507 return list;
2508
2509onError:
2510 Py_DECREF(list);
Martin v. Löwis423be952008-08-13 15:53:07 +00002511 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002512 return NULL;
2513}
2514
2515PyDoc_STRVAR(reverse__doc__,
2516"B.reverse() -> None\n\
2517\n\
2518Reverse the order of the values in B in place.");
2519static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002520bytearray_reverse(PyByteArrayObject *self, PyObject *unused)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002521{
2522 char swap, *head, *tail;
2523 Py_ssize_t i, j, n = Py_SIZE(self);
2524
2525 j = n / 2;
2526 head = self->ob_bytes;
2527 tail = head + n - 1;
2528 for (i = 0; i < j; i++) {
2529 swap = *head;
2530 *head++ = *tail;
2531 *tail-- = swap;
2532 }
2533
2534 Py_RETURN_NONE;
2535}
2536
2537PyDoc_STRVAR(insert__doc__,
2538"B.insert(index, int) -> None\n\
2539\n\
2540Insert a single item into the bytearray before the given index.");
2541static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002542bytearray_insert(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002543{
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002544 PyObject *value;
2545 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002546 Py_ssize_t where, n = Py_SIZE(self);
2547
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002548 if (!PyArg_ParseTuple(args, "nO:insert", &where, &value))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002549 return NULL;
2550
2551 if (n == PY_SSIZE_T_MAX) {
2552 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson099d7a02009-09-06 10:35:38 +00002553 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002554 return NULL;
2555 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002556 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002557 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002558 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2559 return NULL;
2560
2561 if (where < 0) {
2562 where += n;
2563 if (where < 0)
2564 where = 0;
2565 }
2566 if (where > n)
2567 where = n;
2568 memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where);
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002569 self->ob_bytes[where] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002570
2571 Py_RETURN_NONE;
2572}
2573
2574PyDoc_STRVAR(append__doc__,
2575"B.append(int) -> None\n\
2576\n\
2577Append a single item to the end of B.");
2578static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002579bytearray_append(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002580{
2581 int value;
2582 Py_ssize_t n = Py_SIZE(self);
2583
2584 if (! _getbytevalue(arg, &value))
2585 return NULL;
2586 if (n == PY_SSIZE_T_MAX) {
2587 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson099d7a02009-09-06 10:35:38 +00002588 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002589 return NULL;
2590 }
2591 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2592 return NULL;
2593
2594 self->ob_bytes[n] = value;
2595
2596 Py_RETURN_NONE;
2597}
2598
2599PyDoc_STRVAR(extend__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002600"B.extend(iterable_of_ints) -> None\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002601\n\
2602Append all the elements from the iterator or sequence to the\n\
2603end of B.");
2604static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002605bytearray_extend(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002606{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002607 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002608 Py_ssize_t buf_size = 0, len = 0;
2609 int value;
2610 char *buf;
2611
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002612 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002613 if (PyObject_CheckBuffer(arg)) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002614 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), arg) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002615 return NULL;
2616
2617 Py_RETURN_NONE;
2618 }
2619
2620 it = PyObject_GetIter(arg);
2621 if (it == NULL)
2622 return NULL;
2623
2624 /* Try to determine the length of the argument. 32 is abitrary. */
2625 buf_size = _PyObject_LengthHint(arg, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002626 if (buf_size == -1) {
2627 Py_DECREF(it);
2628 return NULL;
2629 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002630
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002631 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
2632 if (bytearray_obj == NULL)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002633 return NULL;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002634 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002635
2636 while ((item = PyIter_Next(it)) != NULL) {
2637 if (! _getbytevalue(item, &value)) {
2638 Py_DECREF(item);
2639 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002640 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002641 return NULL;
2642 }
2643 buf[len++] = value;
2644 Py_DECREF(item);
2645
2646 if (len >= buf_size) {
2647 buf_size = len + (len >> 1) + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002648 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002649 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002650 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002651 return NULL;
2652 }
2653 /* Recompute the `buf' pointer, since the resizing operation may
2654 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002655 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002656 }
2657 }
2658 Py_DECREF(it);
2659
2660 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002661 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
2662 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002663 return NULL;
2664 }
2665
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002666 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002667 return NULL;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002668 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002669
2670 Py_RETURN_NONE;
2671}
2672
2673PyDoc_STRVAR(pop__doc__,
2674"B.pop([index]) -> int\n\
2675\n\
2676Remove and return a single item from B. If no index\n\
Benjamin Petersondcf97b92008-07-02 17:30:14 +00002677argument is given, will pop the last value.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002678static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002679bytearray_pop(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002680{
2681 int value;
2682 Py_ssize_t where = -1, n = Py_SIZE(self);
2683
2684 if (!PyArg_ParseTuple(args, "|n:pop", &where))
2685 return NULL;
2686
2687 if (n == 0) {
2688 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson099d7a02009-09-06 10:35:38 +00002689 "cannot pop an empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002690 return NULL;
2691 }
2692 if (where < 0)
2693 where += Py_SIZE(self);
2694 if (where < 0 || where >= Py_SIZE(self)) {
2695 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2696 return NULL;
2697 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002698 if (!_canresize(self))
2699 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002700
2701 value = self->ob_bytes[where];
2702 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2703 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2704 return NULL;
2705
Mark Dickinson424d75a2009-09-06 10:20:23 +00002706 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002707}
2708
2709PyDoc_STRVAR(remove__doc__,
2710"B.remove(int) -> None\n\
2711\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002712Remove the first occurrence of a value in B.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002713static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002714bytearray_remove(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002715{
2716 int value;
2717 Py_ssize_t where, n = Py_SIZE(self);
2718
2719 if (! _getbytevalue(arg, &value))
2720 return NULL;
2721
2722 for (where = 0; where < n; where++) {
2723 if (self->ob_bytes[where] == value)
2724 break;
2725 }
2726 if (where == n) {
Mark Dickinson099d7a02009-09-06 10:35:38 +00002727 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002728 return NULL;
2729 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002730 if (!_canresize(self))
2731 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002732
2733 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2734 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2735 return NULL;
2736
2737 Py_RETURN_NONE;
2738}
2739
2740/* XXX These two helpers could be optimized if argsize == 1 */
2741
2742static Py_ssize_t
2743lstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2744 void *argptr, Py_ssize_t argsize)
2745{
2746 Py_ssize_t i = 0;
2747 while (i < mysize && memchr(argptr, myptr[i], argsize))
2748 i++;
2749 return i;
2750}
2751
2752static Py_ssize_t
2753rstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2754 void *argptr, Py_ssize_t argsize)
2755{
2756 Py_ssize_t i = mysize - 1;
2757 while (i >= 0 && memchr(argptr, myptr[i], argsize))
2758 i--;
2759 return i + 1;
2760}
2761
2762PyDoc_STRVAR(strip__doc__,
2763"B.strip([bytes]) -> bytearray\n\
2764\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002765Strip leading and trailing bytes contained in the argument\n\
2766and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002767If the argument is omitted, strip ASCII whitespace.");
2768static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002769bytearray_strip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002770{
2771 Py_ssize_t left, right, mysize, argsize;
2772 void *myptr, *argptr;
2773 PyObject *arg = Py_None;
2774 Py_buffer varg;
2775 if (!PyArg_ParseTuple(args, "|O:strip", &arg))
2776 return NULL;
2777 if (arg == Py_None) {
2778 argptr = "\t\n\r\f\v ";
2779 argsize = 6;
2780 }
2781 else {
2782 if (_getbuffer(arg, &varg) < 0)
2783 return NULL;
2784 argptr = varg.buf;
2785 argsize = varg.len;
2786 }
2787 myptr = self->ob_bytes;
2788 mysize = Py_SIZE(self);
2789 left = lstrip_helper(myptr, mysize, argptr, argsize);
2790 if (left == mysize)
2791 right = left;
2792 else
2793 right = rstrip_helper(myptr, mysize, argptr, argsize);
2794 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002795 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002796 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2797}
2798
2799PyDoc_STRVAR(lstrip__doc__,
2800"B.lstrip([bytes]) -> bytearray\n\
2801\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002802Strip leading bytes contained in the argument\n\
2803and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002804If the argument is omitted, strip leading ASCII whitespace.");
2805static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002806bytearray_lstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002807{
2808 Py_ssize_t left, right, mysize, argsize;
2809 void *myptr, *argptr;
2810 PyObject *arg = Py_None;
2811 Py_buffer varg;
2812 if (!PyArg_ParseTuple(args, "|O:lstrip", &arg))
2813 return NULL;
2814 if (arg == Py_None) {
2815 argptr = "\t\n\r\f\v ";
2816 argsize = 6;
2817 }
2818 else {
2819 if (_getbuffer(arg, &varg) < 0)
2820 return NULL;
2821 argptr = varg.buf;
2822 argsize = varg.len;
2823 }
2824 myptr = self->ob_bytes;
2825 mysize = Py_SIZE(self);
2826 left = lstrip_helper(myptr, mysize, argptr, argsize);
2827 right = mysize;
2828 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002829 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002830 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2831}
2832
2833PyDoc_STRVAR(rstrip__doc__,
2834"B.rstrip([bytes]) -> bytearray\n\
2835\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002836Strip trailing bytes contained in the argument\n\
2837and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002838If the argument is omitted, strip trailing ASCII whitespace.");
2839static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002840bytearray_rstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002841{
2842 Py_ssize_t left, right, mysize, argsize;
2843 void *myptr, *argptr;
2844 PyObject *arg = Py_None;
2845 Py_buffer varg;
2846 if (!PyArg_ParseTuple(args, "|O:rstrip", &arg))
2847 return NULL;
2848 if (arg == Py_None) {
2849 argptr = "\t\n\r\f\v ";
2850 argsize = 6;
2851 }
2852 else {
2853 if (_getbuffer(arg, &varg) < 0)
2854 return NULL;
2855 argptr = varg.buf;
2856 argsize = varg.len;
2857 }
2858 myptr = self->ob_bytes;
2859 mysize = Py_SIZE(self);
2860 left = 0;
2861 right = rstrip_helper(myptr, mysize, argptr, argsize);
2862 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002863 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002864 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2865}
2866
2867PyDoc_STRVAR(decode_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002868"B.decode([encoding[, errors]]) -> str\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002869\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002870Decode B using the codec registered for encoding. encoding defaults\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002871to the default encoding. errors may be given to set a different error\n\
2872handling scheme. Default is 'strict' meaning that encoding errors raise\n\
2873a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
2874as well as any other name registered with codecs.register_error that is\n\
2875able to handle UnicodeDecodeErrors.");
2876
2877static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002878bytearray_decode(PyObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002879{
2880 const char *encoding = NULL;
2881 const char *errors = NULL;
2882
2883 if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
2884 return NULL;
2885 if (encoding == NULL)
2886 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002887 return PyUnicode_FromEncodedObject(self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002888}
2889
2890PyDoc_STRVAR(alloc_doc,
2891"B.__alloc__() -> int\n\
2892\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002893Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002894
2895static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002896bytearray_alloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002897{
2898 return PyLong_FromSsize_t(self->ob_alloc);
2899}
2900
2901PyDoc_STRVAR(join_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002902"B.join(iterable_of_bytes) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002903\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002904Concatenate any number of bytes/bytearray objects, with B\n\
2905in between each pair, and return the result as a new bytearray.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002906
2907static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002908bytearray_join(PyByteArrayObject *self, PyObject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002909{
2910 PyObject *seq;
2911 Py_ssize_t mysize = Py_SIZE(self);
2912 Py_ssize_t i;
2913 Py_ssize_t n;
2914 PyObject **items;
2915 Py_ssize_t totalsize = 0;
2916 PyObject *result;
2917 char *dest;
2918
2919 seq = PySequence_Fast(it, "can only join an iterable");
2920 if (seq == NULL)
2921 return NULL;
2922 n = PySequence_Fast_GET_SIZE(seq);
2923 items = PySequence_Fast_ITEMS(seq);
2924
2925 /* Compute the total size, and check that they are all bytes */
2926 /* XXX Shouldn't we use _getbuffer() on these items instead? */
2927 for (i = 0; i < n; i++) {
2928 PyObject *obj = items[i];
2929 if (!PyByteArray_Check(obj) && !PyBytes_Check(obj)) {
2930 PyErr_Format(PyExc_TypeError,
2931 "can only join an iterable of bytes "
2932 "(item %ld has type '%.100s')",
2933 /* XXX %ld isn't right on Win64 */
2934 (long)i, Py_TYPE(obj)->tp_name);
2935 goto error;
2936 }
2937 if (i > 0)
2938 totalsize += mysize;
2939 totalsize += Py_SIZE(obj);
2940 if (totalsize < 0) {
2941 PyErr_NoMemory();
2942 goto error;
2943 }
2944 }
2945
2946 /* Allocate the result, and copy the bytes */
2947 result = PyByteArray_FromStringAndSize(NULL, totalsize);
2948 if (result == NULL)
2949 goto error;
2950 dest = PyByteArray_AS_STRING(result);
2951 for (i = 0; i < n; i++) {
2952 PyObject *obj = items[i];
2953 Py_ssize_t size = Py_SIZE(obj);
2954 char *buf;
2955 if (PyByteArray_Check(obj))
2956 buf = PyByteArray_AS_STRING(obj);
2957 else
2958 buf = PyBytes_AS_STRING(obj);
2959 if (i) {
2960 memcpy(dest, self->ob_bytes, mysize);
2961 dest += mysize;
2962 }
2963 memcpy(dest, buf, size);
2964 dest += size;
2965 }
2966
2967 /* Done */
2968 Py_DECREF(seq);
2969 return result;
2970
2971 /* Error handling */
2972 error:
2973 Py_DECREF(seq);
2974 return NULL;
2975}
2976
2977PyDoc_STRVAR(fromhex_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002978"bytearray.fromhex(string) -> bytearray (static method)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002979\n\
2980Create a bytearray object from a string of hexadecimal numbers.\n\
2981Spaces between two numbers are accepted.\n\
2982Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef').");
2983
2984static int
2985hex_digit_to_int(Py_UNICODE c)
2986{
2987 if (c >= 128)
2988 return -1;
Eric Smith6dc46f52009-04-27 20:39:49 +00002989 if (Py_ISDIGIT(c))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002990 return c - '0';
2991 else {
Eric Smith6dc46f52009-04-27 20:39:49 +00002992 if (Py_ISUPPER(c))
2993 c = Py_TOLOWER(c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002994 if (c >= 'a' && c <= 'f')
2995 return c - 'a' + 10;
2996 }
2997 return -1;
2998}
2999
3000static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003001bytearray_fromhex(PyObject *cls, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003002{
3003 PyObject *newbytes, *hexobj;
3004 char *buf;
3005 Py_UNICODE *hex;
3006 Py_ssize_t hexlen, byteslen, i, j;
3007 int top, bot;
3008
3009 if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj))
3010 return NULL;
3011 assert(PyUnicode_Check(hexobj));
3012 hexlen = PyUnicode_GET_SIZE(hexobj);
3013 hex = PyUnicode_AS_UNICODE(hexobj);
3014 byteslen = hexlen/2; /* This overestimates if there are spaces */
3015 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
3016 if (!newbytes)
3017 return NULL;
3018 buf = PyByteArray_AS_STRING(newbytes);
3019 for (i = j = 0; i < hexlen; i += 2) {
3020 /* skip over spaces in the input */
3021 while (hex[i] == ' ')
3022 i++;
3023 if (i >= hexlen)
3024 break;
3025 top = hex_digit_to_int(hex[i]);
3026 bot = hex_digit_to_int(hex[i+1]);
3027 if (top == -1 || bot == -1) {
3028 PyErr_Format(PyExc_ValueError,
3029 "non-hexadecimal number found in "
3030 "fromhex() arg at position %zd", i);
3031 goto error;
3032 }
3033 buf[j++] = (top << 4) + bot;
3034 }
3035 if (PyByteArray_Resize(newbytes, j) < 0)
3036 goto error;
3037 return newbytes;
3038
3039 error:
3040 Py_DECREF(newbytes);
3041 return NULL;
3042}
3043
3044PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3045
3046static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003047bytearray_reduce(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003048{
3049 PyObject *latin1, *dict;
3050 if (self->ob_bytes)
3051 latin1 = PyUnicode_DecodeLatin1(self->ob_bytes,
3052 Py_SIZE(self), NULL);
3053 else
3054 latin1 = PyUnicode_FromString("");
3055
3056 dict = PyObject_GetAttrString((PyObject *)self, "__dict__");
3057 if (dict == NULL) {
3058 PyErr_Clear();
3059 dict = Py_None;
3060 Py_INCREF(dict);
3061 }
3062
3063 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
3064}
3065
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003066PyDoc_STRVAR(sizeof_doc,
3067"B.__sizeof__() -> int\n\
3068 \n\
3069Returns the size of B in memory, in bytes");
3070static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003071bytearray_sizeof(PyByteArrayObject *self)
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003072{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00003073 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003074
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00003075 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
3076 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003077}
3078
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003079static PySequenceMethods bytearray_as_sequence = {
3080 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003081 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003082 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
3083 (ssizeargfunc)bytearray_getitem, /* sq_item */
3084 0, /* sq_slice */
3085 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
3086 0, /* sq_ass_slice */
3087 (objobjproc)bytearray_contains, /* sq_contains */
3088 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
3089 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003090};
3091
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003092static PyMappingMethods bytearray_as_mapping = {
3093 (lenfunc)bytearray_length,
3094 (binaryfunc)bytearray_subscript,
3095 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003096};
3097
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003098static PyBufferProcs bytearray_as_buffer = {
3099 (getbufferproc)bytearray_getbuffer,
3100 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003101};
3102
3103static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003104bytearray_methods[] = {
3105 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
3106 {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, reduce_doc},
3107 {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, sizeof_doc},
3108 {"append", (PyCFunction)bytearray_append, METH_O, append__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003109 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
3110 _Py_capitalize__doc__},
3111 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003112 {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
3113 {"decode", (PyCFunction)bytearray_decode, METH_VARARGS, decode_doc},
3114 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003115 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS,
3116 expandtabs__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003117 {"extend", (PyCFunction)bytearray_extend, METH_O, extend__doc__},
3118 {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
3119 {"fromhex", (PyCFunction)bytearray_fromhex, METH_VARARGS|METH_CLASS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003120 fromhex_doc},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003121 {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
3122 {"insert", (PyCFunction)bytearray_insert, METH_VARARGS, insert__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003123 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
3124 _Py_isalnum__doc__},
3125 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
3126 _Py_isalpha__doc__},
3127 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
3128 _Py_isdigit__doc__},
3129 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
3130 _Py_islower__doc__},
3131 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
3132 _Py_isspace__doc__},
3133 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
3134 _Py_istitle__doc__},
3135 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
3136 _Py_isupper__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003137 {"join", (PyCFunction)bytearray_join, METH_O, join_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003138 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
3139 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003140 {"lstrip", (PyCFunction)bytearray_lstrip, METH_VARARGS, lstrip__doc__},
3141 {"maketrans", (PyCFunction)bytearray_maketrans, METH_VARARGS|METH_STATIC,
Georg Brandlabc38772009-04-12 15:51:51 +00003142 _Py_maketrans__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003143 {"partition", (PyCFunction)bytearray_partition, METH_O, partition__doc__},
3144 {"pop", (PyCFunction)bytearray_pop, METH_VARARGS, pop__doc__},
3145 {"remove", (PyCFunction)bytearray_remove, METH_O, remove__doc__},
3146 {"replace", (PyCFunction)bytearray_replace, METH_VARARGS, replace__doc__},
3147 {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, reverse__doc__},
3148 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
3149 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003150 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003151 {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, rpartition__doc__},
3152 {"rsplit", (PyCFunction)bytearray_rsplit, METH_VARARGS, rsplit__doc__},
3153 {"rstrip", (PyCFunction)bytearray_rstrip, METH_VARARGS, rstrip__doc__},
3154 {"split", (PyCFunction)bytearray_split, METH_VARARGS, split__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003155 {"splitlines", (PyCFunction)stringlib_splitlines, METH_VARARGS,
3156 splitlines__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003157 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003158 startswith__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003159 {"strip", (PyCFunction)bytearray_strip, METH_VARARGS, strip__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003160 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
3161 _Py_swapcase__doc__},
3162 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003163 {"translate", (PyCFunction)bytearray_translate, METH_VARARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003164 translate__doc__},
3165 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
3166 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
3167 {NULL}
3168};
3169
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003170PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00003171"bytearray(iterable_of_ints) -> bytearray\n\
3172bytearray(string, encoding[, errors]) -> bytearray\n\
3173bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray\n\
3174bytearray(memory_view) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003175\n\
3176Construct an mutable bytearray object from:\n\
3177 - an iterable yielding integers in range(256)\n\
3178 - a text string encoded using the specified encoding\n\
3179 - a bytes or a bytearray object\n\
3180 - any object implementing the buffer API.\n\
3181\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00003182bytearray(int) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003183\n\
3184Construct a zero-initialized bytearray of the given length.");
3185
3186
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003187static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003188
3189PyTypeObject PyByteArray_Type = {
3190 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3191 "bytearray",
3192 sizeof(PyByteArrayObject),
3193 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003194 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003195 0, /* tp_print */
3196 0, /* tp_getattr */
3197 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003198 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003199 (reprfunc)bytearray_repr, /* tp_repr */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003200 0, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003201 &bytearray_as_sequence, /* tp_as_sequence */
3202 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003203 0, /* tp_hash */
3204 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003205 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003206 PyObject_GenericGetAttr, /* tp_getattro */
3207 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003208 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003209 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003210 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003211 0, /* tp_traverse */
3212 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003213 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003214 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003215 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003216 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003217 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003218 0, /* tp_members */
3219 0, /* tp_getset */
3220 0, /* tp_base */
3221 0, /* tp_dict */
3222 0, /* tp_descr_get */
3223 0, /* tp_descr_set */
3224 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003225 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003226 PyType_GenericAlloc, /* tp_alloc */
3227 PyType_GenericNew, /* tp_new */
3228 PyObject_Del, /* tp_free */
3229};
3230
3231/*********************** Bytes Iterator ****************************/
3232
3233typedef struct {
3234 PyObject_HEAD
3235 Py_ssize_t it_index;
3236 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
3237} bytesiterobject;
3238
3239static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003240bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003241{
3242 _PyObject_GC_UNTRACK(it);
3243 Py_XDECREF(it->it_seq);
3244 PyObject_GC_Del(it);
3245}
3246
3247static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003248bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003249{
3250 Py_VISIT(it->it_seq);
3251 return 0;
3252}
3253
3254static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003255bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003256{
3257 PyByteArrayObject *seq;
3258 PyObject *item;
3259
3260 assert(it != NULL);
3261 seq = it->it_seq;
3262 if (seq == NULL)
3263 return NULL;
3264 assert(PyByteArray_Check(seq));
3265
3266 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
3267 item = PyLong_FromLong(
3268 (unsigned char)seq->ob_bytes[it->it_index]);
3269 if (item != NULL)
3270 ++it->it_index;
3271 return item;
3272 }
3273
3274 Py_DECREF(seq);
3275 it->it_seq = NULL;
3276 return NULL;
3277}
3278
3279static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003280bytesarrayiter_length_hint(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003281{
3282 Py_ssize_t len = 0;
3283 if (it->it_seq)
3284 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
3285 return PyLong_FromSsize_t(len);
3286}
3287
3288PyDoc_STRVAR(length_hint_doc,
3289 "Private method returning an estimate of len(list(it)).");
3290
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003291static PyMethodDef bytearrayiter_methods[] = {
3292 {"__length_hint__", (PyCFunction)bytesarrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003293 length_hint_doc},
3294 {NULL, NULL} /* sentinel */
3295};
3296
3297PyTypeObject PyByteArrayIter_Type = {
3298 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3299 "bytearray_iterator", /* tp_name */
3300 sizeof(bytesiterobject), /* tp_basicsize */
3301 0, /* tp_itemsize */
3302 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003303 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003304 0, /* tp_print */
3305 0, /* tp_getattr */
3306 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003307 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003308 0, /* tp_repr */
3309 0, /* tp_as_number */
3310 0, /* tp_as_sequence */
3311 0, /* tp_as_mapping */
3312 0, /* tp_hash */
3313 0, /* tp_call */
3314 0, /* tp_str */
3315 PyObject_GenericGetAttr, /* tp_getattro */
3316 0, /* tp_setattro */
3317 0, /* tp_as_buffer */
3318 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
3319 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003320 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003321 0, /* tp_clear */
3322 0, /* tp_richcompare */
3323 0, /* tp_weaklistoffset */
3324 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003325 (iternextfunc)bytearrayiter_next, /* tp_iternext */
3326 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003327 0,
3328};
3329
3330static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00003331bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003332{
3333 bytesiterobject *it;
3334
3335 if (!PyByteArray_Check(seq)) {
3336 PyErr_BadInternalCall();
3337 return NULL;
3338 }
3339 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
3340 if (it == NULL)
3341 return NULL;
3342 it->it_index = 0;
3343 Py_INCREF(seq);
3344 it->it_seq = (PyByteArrayObject *)seq;
3345 _PyObject_GC_TRACK(it);
3346 return (PyObject *)it;
3347}