blob: 72e581552a5d0156b116c629a93f57633ae6894b [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
Antoine Pitroufc8d6f42010-01-17 12:38:54 +00008char _PyByteArray_empty_string[] = "";
Christian Heimes2c9c7a52008-05-26 13:42:13 +00009
10void
11PyByteArray_Fini(void)
12{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000013}
14
15int
16PyByteArray_Init(void)
17{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000018 return 1;
19}
20
21/* end nullbytes support */
22
23/* Helpers */
24
25static int
26_getbytevalue(PyObject* arg, int *value)
27{
28 long face_value;
29
30 if (PyLong_Check(arg)) {
31 face_value = PyLong_AsLong(arg);
Georg Brandl9a54d7c2008-07-16 23:15:30 +000032 } else {
33 PyObject *index = PyNumber_Index(arg);
34 if (index == NULL) {
35 PyErr_Format(PyExc_TypeError, "an integer is required");
Mark Dickinson10de93a2010-07-09 19:25:48 +000036 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000037 return 0;
38 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +000039 face_value = PyLong_AsLong(index);
40 Py_DECREF(index);
41 }
42
43 if (face_value < 0 || face_value >= 256) {
44 /* this includes the OverflowError in case the long is too large */
45 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
Mark Dickinson10de93a2010-07-09 19:25:48 +000046 *value = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +000047 return 0;
48 }
49
50 *value = face_value;
51 return 1;
52}
53
54static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +000055bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000056{
57 int ret;
58 void *ptr;
59 if (view == NULL) {
60 obj->ob_exports++;
61 return 0;
62 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000063 ptr = (void *) PyByteArray_AS_STRING(obj);
Martin v. Löwis423be952008-08-13 15:53:07 +000064 ret = PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
Christian Heimes2c9c7a52008-05-26 13:42:13 +000065 if (ret >= 0) {
66 obj->ob_exports++;
67 }
68 return ret;
69}
70
71static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +000072bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000073{
74 obj->ob_exports--;
75}
76
77static Py_ssize_t
78_getbuffer(PyObject *obj, Py_buffer *view)
79{
80 PyBufferProcs *buffer = Py_TYPE(obj)->tp_as_buffer;
81
82 if (buffer == NULL || buffer->bf_getbuffer == NULL)
83 {
84 PyErr_Format(PyExc_TypeError,
85 "Type %.100s doesn't support the buffer API",
86 Py_TYPE(obj)->tp_name);
87 return -1;
88 }
89
90 if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0)
91 return -1;
92 return view->len;
93}
94
Antoine Pitrou5504e892008-12-06 21:27:53 +000095static int
96_canresize(PyByteArrayObject *self)
97{
98 if (self->ob_exports > 0) {
99 PyErr_SetString(PyExc_BufferError,
100 "Existing exports of data: object cannot be re-sized");
101 return 0;
102 }
103 return 1;
104}
105
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000106/* Direct API functions */
107
108PyObject *
109PyByteArray_FromObject(PyObject *input)
110{
111 return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
112 input, NULL);
113}
114
115PyObject *
116PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
117{
118 PyByteArrayObject *new;
119 Py_ssize_t alloc;
120
121 if (size < 0) {
122 PyErr_SetString(PyExc_SystemError,
123 "Negative size passed to PyByteArray_FromStringAndSize");
124 return NULL;
125 }
126
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000127 /* Prevent buffer overflow when setting alloc to size+1. */
128 if (size == PY_SSIZE_T_MAX) {
129 return PyErr_NoMemory();
130 }
131
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000132 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
133 if (new == NULL)
134 return NULL;
135
136 if (size == 0) {
137 new->ob_bytes = NULL;
138 alloc = 0;
139 }
140 else {
141 alloc = size + 1;
142 new->ob_bytes = PyMem_Malloc(alloc);
143 if (new->ob_bytes == NULL) {
144 Py_DECREF(new);
145 return PyErr_NoMemory();
146 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +0000147 if (bytes != NULL && size > 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000148 memcpy(new->ob_bytes, bytes, size);
149 new->ob_bytes[size] = '\0'; /* Trailing null byte */
150 }
151 Py_SIZE(new) = size;
152 new->ob_alloc = alloc;
153 new->ob_exports = 0;
154
155 return (PyObject *)new;
156}
157
158Py_ssize_t
159PyByteArray_Size(PyObject *self)
160{
161 assert(self != NULL);
162 assert(PyByteArray_Check(self));
163
164 return PyByteArray_GET_SIZE(self);
165}
166
167char *
168PyByteArray_AsString(PyObject *self)
169{
170 assert(self != NULL);
171 assert(PyByteArray_Check(self));
172
173 return PyByteArray_AS_STRING(self);
174}
175
176int
177PyByteArray_Resize(PyObject *self, Py_ssize_t size)
178{
179 void *sval;
180 Py_ssize_t alloc = ((PyByteArrayObject *)self)->ob_alloc;
181
182 assert(self != NULL);
183 assert(PyByteArray_Check(self));
184 assert(size >= 0);
185
Antoine Pitrou5504e892008-12-06 21:27:53 +0000186 if (size == Py_SIZE(self)) {
187 return 0;
188 }
189 if (!_canresize((PyByteArrayObject *)self)) {
190 return -1;
191 }
192
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000193 if (size < alloc / 2) {
194 /* Major downsize; resize down to exact size */
195 alloc = size + 1;
196 }
197 else if (size < alloc) {
198 /* Within allocated size; quick exit */
199 Py_SIZE(self) = size;
200 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null */
201 return 0;
202 }
203 else if (size <= alloc * 1.125) {
204 /* Moderate upsize; overallocate similar to list_resize() */
205 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
206 }
207 else {
208 /* Major upsize; resize up to exact size */
209 alloc = size + 1;
210 }
211
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000212 sval = PyMem_Realloc(((PyByteArrayObject *)self)->ob_bytes, alloc);
213 if (sval == NULL) {
214 PyErr_NoMemory();
215 return -1;
216 }
217
218 ((PyByteArrayObject *)self)->ob_bytes = sval;
219 Py_SIZE(self) = size;
220 ((PyByteArrayObject *)self)->ob_alloc = alloc;
221 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null byte */
222
223 return 0;
224}
225
226PyObject *
227PyByteArray_Concat(PyObject *a, PyObject *b)
228{
229 Py_ssize_t size;
230 Py_buffer va, vb;
231 PyByteArrayObject *result = NULL;
232
233 va.len = -1;
234 vb.len = -1;
235 if (_getbuffer(a, &va) < 0 ||
236 _getbuffer(b, &vb) < 0) {
237 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
238 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
239 goto done;
240 }
241
242 size = va.len + vb.len;
243 if (size < 0) {
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000244 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000245 goto done;
246 }
247
248 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
249 if (result != NULL) {
250 memcpy(result->ob_bytes, va.buf, va.len);
251 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
252 }
253
254 done:
255 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000256 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000257 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000258 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000259 return (PyObject *)result;
260}
261
262/* Functions stuffed into the type object */
263
264static Py_ssize_t
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000265bytearray_length(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000266{
267 return Py_SIZE(self);
268}
269
270static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000271bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000272{
273 Py_ssize_t mysize;
274 Py_ssize_t size;
275 Py_buffer vo;
276
277 if (_getbuffer(other, &vo) < 0) {
278 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
279 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
280 return NULL;
281 }
282
283 mysize = Py_SIZE(self);
284 size = mysize + vo.len;
285 if (size < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000286 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000287 return PyErr_NoMemory();
288 }
289 if (size < self->ob_alloc) {
290 Py_SIZE(self) = size;
291 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
292 }
293 else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000294 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000295 return NULL;
296 }
297 memcpy(self->ob_bytes + mysize, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000298 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000299 Py_INCREF(self);
300 return (PyObject *)self;
301}
302
303static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000304bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000305{
306 PyByteArrayObject *result;
307 Py_ssize_t mysize;
308 Py_ssize_t size;
309
310 if (count < 0)
311 count = 0;
312 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000313 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000314 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000315 size = mysize * count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000316 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
317 if (result != NULL && size != 0) {
318 if (mysize == 1)
319 memset(result->ob_bytes, self->ob_bytes[0], size);
320 else {
321 Py_ssize_t i;
322 for (i = 0; i < count; i++)
323 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
324 }
325 }
326 return (PyObject *)result;
327}
328
329static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000330bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000331{
332 Py_ssize_t mysize;
333 Py_ssize_t size;
334
335 if (count < 0)
336 count = 0;
337 mysize = Py_SIZE(self);
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000338 if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000339 return PyErr_NoMemory();
Mark Dickinsoncf940c72010-08-10 18:35:01 +0000340 size = mysize * count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000341 if (size < self->ob_alloc) {
342 Py_SIZE(self) = size;
343 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
344 }
345 else if (PyByteArray_Resize((PyObject *)self, size) < 0)
346 return NULL;
347
348 if (mysize == 1)
349 memset(self->ob_bytes, self->ob_bytes[0], size);
350 else {
351 Py_ssize_t i;
352 for (i = 1; i < count; i++)
353 memcpy(self->ob_bytes + i*mysize, self->ob_bytes, mysize);
354 }
355
356 Py_INCREF(self);
357 return (PyObject *)self;
358}
359
360static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000361bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000362{
363 if (i < 0)
364 i += Py_SIZE(self);
365 if (i < 0 || i >= Py_SIZE(self)) {
366 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
367 return NULL;
368 }
369 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
370}
371
372static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000373bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000374{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000375 if (PyIndex_Check(index)) {
376 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000377
378 if (i == -1 && PyErr_Occurred())
379 return NULL;
380
381 if (i < 0)
382 i += PyByteArray_GET_SIZE(self);
383
384 if (i < 0 || i >= Py_SIZE(self)) {
385 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
386 return NULL;
387 }
388 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
389 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000390 else if (PySlice_Check(index)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000391 Py_ssize_t start, stop, step, slicelength, cur, i;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000392 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000393 PyByteArray_GET_SIZE(self),
394 &start, &stop, &step, &slicelength) < 0) {
395 return NULL;
396 }
397
398 if (slicelength <= 0)
399 return PyByteArray_FromStringAndSize("", 0);
400 else if (step == 1) {
401 return PyByteArray_FromStringAndSize(self->ob_bytes + start,
402 slicelength);
403 }
404 else {
405 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000406 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000407 PyObject *result;
408
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000409 result = PyByteArray_FromStringAndSize(NULL, slicelength);
410 if (result == NULL)
411 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000412
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000413 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000414 for (cur = start, i = 0; i < slicelength;
415 cur += step, i++) {
416 result_buf[i] = source_buf[cur];
417 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000418 return result;
419 }
420 }
421 else {
422 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integers");
423 return NULL;
424 }
425}
426
427static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000428bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000429 PyObject *values)
430{
431 Py_ssize_t avail, needed;
432 void *bytes;
433 Py_buffer vbytes;
434 int res = 0;
435
436 vbytes.len = -1;
437 if (values == (PyObject *)self) {
438 /* Make a copy and call this function recursively */
439 int err;
440 values = PyByteArray_FromObject(values);
441 if (values == NULL)
442 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000443 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000444 Py_DECREF(values);
445 return err;
446 }
447 if (values == NULL) {
448 /* del b[lo:hi] */
449 bytes = NULL;
450 needed = 0;
451 }
452 else {
453 if (_getbuffer(values, &vbytes) < 0) {
454 PyErr_Format(PyExc_TypeError,
Georg Brandl3dbca812008-07-23 16:10:53 +0000455 "can't set bytearray slice from %.100s",
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000456 Py_TYPE(values)->tp_name);
457 return -1;
458 }
459 needed = vbytes.len;
460 bytes = vbytes.buf;
461 }
462
463 if (lo < 0)
464 lo = 0;
465 if (hi < lo)
466 hi = lo;
467 if (hi > Py_SIZE(self))
468 hi = Py_SIZE(self);
469
470 avail = hi - lo;
471 if (avail < 0)
472 lo = hi = avail = 0;
473
474 if (avail != needed) {
475 if (avail > needed) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000476 if (!_canresize(self)) {
477 res = -1;
478 goto finish;
479 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000480 /*
481 0 lo hi old_size
482 | |<----avail----->|<-----tomove------>|
483 | |<-needed->|<-----tomove------>|
484 0 lo new_hi new_size
485 */
486 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
487 Py_SIZE(self) - hi);
488 }
489 /* XXX(nnorwitz): need to verify this can't overflow! */
490 if (PyByteArray_Resize((PyObject *)self,
491 Py_SIZE(self) + needed - avail) < 0) {
492 res = -1;
493 goto finish;
494 }
495 if (avail < needed) {
496 /*
497 0 lo hi old_size
498 | |<-avail->|<-----tomove------>|
499 | |<----needed---->|<-----tomove------>|
500 0 lo new_hi new_size
501 */
502 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
503 Py_SIZE(self) - lo - needed);
504 }
505 }
506
507 if (needed > 0)
508 memcpy(self->ob_bytes + lo, bytes, needed);
509
510
511 finish:
512 if (vbytes.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000513 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000514 return res;
515}
516
517static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000518bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000519{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000520 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000521
522 if (i < 0)
523 i += Py_SIZE(self);
524
525 if (i < 0 || i >= Py_SIZE(self)) {
526 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
527 return -1;
528 }
529
530 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000531 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000532
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000533 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000534 return -1;
535
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000536 self->ob_bytes[i] = ival;
537 return 0;
538}
539
540static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000541bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000542{
543 Py_ssize_t start, stop, step, slicelen, needed;
544 char *bytes;
545
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000546 if (PyIndex_Check(index)) {
547 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000548
549 if (i == -1 && PyErr_Occurred())
550 return -1;
551
552 if (i < 0)
553 i += PyByteArray_GET_SIZE(self);
554
555 if (i < 0 || i >= Py_SIZE(self)) {
556 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
557 return -1;
558 }
559
560 if (values == NULL) {
561 /* Fall through to slice assignment */
562 start = i;
563 stop = i + 1;
564 step = 1;
565 slicelen = 1;
566 }
567 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000568 int ival;
569 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000570 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000571 self->ob_bytes[i] = (char)ival;
572 return 0;
573 }
574 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000575 else if (PySlice_Check(index)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000576 if (PySlice_GetIndicesEx(index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000577 PyByteArray_GET_SIZE(self),
578 &start, &stop, &step, &slicelen) < 0) {
579 return -1;
580 }
581 }
582 else {
583 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integer");
584 return -1;
585 }
586
587 if (values == NULL) {
588 bytes = NULL;
589 needed = 0;
590 }
591 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
Georg Brandlf3fa5682010-12-04 17:09:30 +0000592 /* Make a copy and call this function recursively */
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000593 int err;
594 values = PyByteArray_FromObject(values);
595 if (values == NULL)
596 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000597 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000598 Py_DECREF(values);
599 return err;
600 }
601 else {
602 assert(PyByteArray_Check(values));
603 bytes = ((PyByteArrayObject *)values)->ob_bytes;
604 needed = Py_SIZE(values);
605 }
606 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
607 if ((step < 0 && start < stop) ||
608 (step > 0 && start > stop))
609 stop = start;
610 if (step == 1) {
611 if (slicelen != needed) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000612 if (!_canresize(self))
613 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000614 if (slicelen > needed) {
615 /*
616 0 start stop old_size
617 | |<---slicelen--->|<-----tomove------>|
618 | |<-needed->|<-----tomove------>|
619 0 lo new_hi new_size
620 */
621 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
622 Py_SIZE(self) - stop);
623 }
624 if (PyByteArray_Resize((PyObject *)self,
625 Py_SIZE(self) + needed - slicelen) < 0)
626 return -1;
627 if (slicelen < needed) {
628 /*
629 0 lo hi old_size
630 | |<-avail->|<-----tomove------>|
631 | |<----needed---->|<-----tomove------>|
632 0 lo new_hi new_size
633 */
634 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
635 Py_SIZE(self) - start - needed);
636 }
637 }
638
639 if (needed > 0)
640 memcpy(self->ob_bytes + start, bytes, needed);
641
642 return 0;
643 }
644 else {
645 if (needed == 0) {
646 /* Delete slice */
Mark Dickinsonbc099642010-01-29 17:27:24 +0000647 size_t cur;
648 Py_ssize_t i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000649
Antoine Pitrou5504e892008-12-06 21:27:53 +0000650 if (!_canresize(self))
651 return -1;
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000652
653 if (slicelen == 0)
654 /* Nothing to do here. */
655 return 0;
656
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
Mark Dickinson66f575b2010-02-14 12:53:32 +0000666 if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000667 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 */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000673 cur = start + (size_t)slicelen*step;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000674 if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000675 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 */
Mark Dickinson7e3b9482010-08-06 21:33:18 +0000687 Py_ssize_t i;
688 size_t cur;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000689
690 if (needed != slicelen) {
691 PyErr_Format(PyExc_ValueError,
692 "attempt to assign bytes of size %zd "
693 "to extended slice of size %zd",
694 needed, slicelen);
695 return -1;
696 }
697 for (cur = start, i = 0; i < slicelen; cur += step, i++)
698 self->ob_bytes[cur] = bytes[i];
699 return 0;
700 }
701 }
702}
703
704static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000705bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000706{
707 static char *kwlist[] = {"source", "encoding", "errors", 0};
708 PyObject *arg = NULL;
709 const char *encoding = NULL;
710 const char *errors = NULL;
711 Py_ssize_t count;
712 PyObject *it;
713 PyObject *(*iternext)(PyObject *);
714
715 if (Py_SIZE(self) != 0) {
716 /* Empty previous contents (yes, do this first of all!) */
717 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
718 return -1;
719 }
720
721 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000722 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000723 &arg, &encoding, &errors))
724 return -1;
725
726 /* Make a quick exit if no first argument */
727 if (arg == NULL) {
728 if (encoding != NULL || errors != NULL) {
729 PyErr_SetString(PyExc_TypeError,
730 "encoding or errors without sequence argument");
731 return -1;
732 }
733 return 0;
734 }
735
736 if (PyUnicode_Check(arg)) {
737 /* Encode via the codec registry */
738 PyObject *encoded, *new;
739 if (encoding == NULL) {
740 PyErr_SetString(PyExc_TypeError,
741 "string argument without an encoding");
742 return -1;
743 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000744 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000745 if (encoded == NULL)
746 return -1;
747 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000748 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000749 Py_DECREF(encoded);
750 if (new == NULL)
751 return -1;
752 Py_DECREF(new);
753 return 0;
754 }
755
756 /* If it's not unicode, there can't be encoding or errors */
757 if (encoding != NULL || errors != NULL) {
758 PyErr_SetString(PyExc_TypeError,
759 "encoding or errors without a string argument");
760 return -1;
761 }
762
763 /* Is it an int? */
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000764 count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
765 if (count == -1 && PyErr_Occurred()) {
766 if (PyErr_ExceptionMatches(PyExc_OverflowError))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000767 return -1;
Benjamin Peterson9c0e94f2010-04-16 23:00:53 +0000768 PyErr_Clear();
Benjamin Peterson8380dd52010-04-16 22:51:37 +0000769 }
770 else if (count < 0) {
771 PyErr_SetString(PyExc_ValueError, "negative count");
772 return -1;
773 }
774 else {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000775 if (count > 0) {
776 if (PyByteArray_Resize((PyObject *)self, count))
777 return -1;
778 memset(self->ob_bytes, 0, count);
779 }
780 return 0;
781 }
782
783 /* Use the buffer API */
784 if (PyObject_CheckBuffer(arg)) {
785 Py_ssize_t size;
786 Py_buffer view;
787 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
788 return -1;
789 size = view.len;
790 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
791 if (PyBuffer_ToContiguous(self->ob_bytes, &view, size, 'C') < 0)
792 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000793 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000794 return 0;
795 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000796 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000797 return -1;
798 }
799
800 /* XXX Optimize this if the arguments is a list, tuple */
801
802 /* Get the iterator */
803 it = PyObject_GetIter(arg);
804 if (it == NULL)
805 return -1;
806 iternext = *Py_TYPE(it)->tp_iternext;
807
808 /* Run the iterator to exhaustion */
809 for (;;) {
810 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000811 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000812
813 /* Get the next item */
814 item = iternext(it);
815 if (item == NULL) {
816 if (PyErr_Occurred()) {
817 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
818 goto error;
819 PyErr_Clear();
820 }
821 break;
822 }
823
824 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000825 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000826 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000827 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000828 goto error;
829
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000830 /* Append the byte */
831 if (Py_SIZE(self) < self->ob_alloc)
832 Py_SIZE(self)++;
833 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
834 goto error;
835 self->ob_bytes[Py_SIZE(self)-1] = value;
836 }
837
838 /* Clean up and return success */
839 Py_DECREF(it);
840 return 0;
841
842 error:
843 /* Error handling when it != NULL */
844 Py_DECREF(it);
845 return -1;
846}
847
848/* Mostly copied from string_repr, but without the
849 "smart quote" functionality. */
850static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000851bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000852{
853 static const char *hexdigits = "0123456789abcdef";
854 const char *quote_prefix = "bytearray(b";
855 const char *quote_postfix = ")";
856 Py_ssize_t length = Py_SIZE(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200857 /* 15 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */
Mark Dickinson66f575b2010-02-14 12:53:32 +0000858 size_t newsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000859 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200860 register Py_ssize_t i;
861 register char c;
862 register char *p;
863 int quote;
864 char *test, *start;
865 char *buffer;
866
867 if (length > (PY_SSIZE_T_MAX - 15) / 4) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000868 PyErr_SetString(PyExc_OverflowError,
869 "bytearray object is too large to make repr");
870 return NULL;
871 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200872
873 newsize = 15 + length * 4;
874 buffer = PyMem_Malloc(newsize);
875 if (buffer == NULL) {
876 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000877 return NULL;
878 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000879
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200880 /* Figure out which quote to use; single is preferred */
881 quote = '\'';
882 start = PyByteArray_AS_STRING(self);
883 for (test = start; test < start+length; ++test) {
884 if (*test == '"') {
885 quote = '\''; /* back to single */
886 break;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000887 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200888 else if (*test == '\'')
889 quote = '"';
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000890 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200891
892 p = buffer;
893 while (*quote_prefix)
894 *p++ = *quote_prefix++;
895 *p++ = quote;
896
897 for (i = 0; i < length; i++) {
898 /* There's at least enough room for a hex escape
899 and a closing quote. */
900 assert(newsize - (p - buffer) >= 5);
901 c = self->ob_bytes[i];
902 if (c == '\'' || c == '\\')
903 *p++ = '\\', *p++ = c;
904 else if (c == '\t')
905 *p++ = '\\', *p++ = 't';
906 else if (c == '\n')
907 *p++ = '\\', *p++ = 'n';
908 else if (c == '\r')
909 *p++ = '\\', *p++ = 'r';
910 else if (c == 0)
911 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
912 else if (c < ' ' || c >= 0x7f) {
913 *p++ = '\\';
914 *p++ = 'x';
915 *p++ = hexdigits[(c & 0xf0) >> 4];
916 *p++ = hexdigits[c & 0xf];
917 }
918 else
919 *p++ = c;
920 }
921 assert(newsize - (p - buffer) >= 1);
922 *p++ = quote;
923 while (*quote_postfix) {
924 *p++ = *quote_postfix++;
925 }
926
927 v = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
928 PyMem_Free(buffer);
929 return v;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000930}
931
932static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000933bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000934{
Alexander Belopolskyf0f45142010-08-11 17:31:17 +0000935 if (Py_BytesWarningFlag) {
936 if (PyErr_WarnEx(PyExc_BytesWarning,
937 "str() on a bytearray instance", 1))
938 return NULL;
939 }
940 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000941}
942
943static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000944bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000945{
946 Py_ssize_t self_size, other_size;
947 Py_buffer self_bytes, other_bytes;
948 PyObject *res;
949 Py_ssize_t minsize;
950 int cmp;
951
952 /* Bytes can be compared to anything that supports the (binary)
953 buffer API. Except that a comparison with Unicode is always an
954 error, even if the comparison is for equality. */
955 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
956 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
Barry Warsaw9e9dcd62008-10-17 01:50:37 +0000957 if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000958 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +0000959 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000960 return NULL;
961 }
962
Brian Curtindfc80e32011-08-10 20:28:54 -0500963 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000964 }
965
966 self_size = _getbuffer(self, &self_bytes);
967 if (self_size < 0) {
968 PyErr_Clear();
Brian Curtindfc80e32011-08-10 20:28:54 -0500969 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000970 }
971
972 other_size = _getbuffer(other, &other_bytes);
973 if (other_size < 0) {
974 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +0000975 PyBuffer_Release(&self_bytes);
Brian Curtindfc80e32011-08-10 20:28:54 -0500976 Py_RETURN_NOTIMPLEMENTED;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000977 }
978
979 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
980 /* Shortcut: if the lengths differ, the objects differ */
981 cmp = (op == Py_NE);
982 }
983 else {
984 minsize = self_size;
985 if (other_size < minsize)
986 minsize = other_size;
987
988 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
989 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
990
991 if (cmp == 0) {
992 if (self_size < other_size)
993 cmp = -1;
994 else if (self_size > other_size)
995 cmp = 1;
996 }
997
998 switch (op) {
999 case Py_LT: cmp = cmp < 0; break;
1000 case Py_LE: cmp = cmp <= 0; break;
1001 case Py_EQ: cmp = cmp == 0; break;
1002 case Py_NE: cmp = cmp != 0; break;
1003 case Py_GT: cmp = cmp > 0; break;
1004 case Py_GE: cmp = cmp >= 0; break;
1005 }
1006 }
1007
1008 res = cmp ? Py_True : Py_False;
Martin v. Löwis423be952008-08-13 15:53:07 +00001009 PyBuffer_Release(&self_bytes);
1010 PyBuffer_Release(&other_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001011 Py_INCREF(res);
1012 return res;
1013}
1014
1015static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001016bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001017{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001018 if (self->ob_exports > 0) {
1019 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001020 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001021 PyErr_Print();
1022 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001023 if (self->ob_bytes != 0) {
1024 PyMem_Free(self->ob_bytes);
1025 }
1026 Py_TYPE(self)->tp_free((PyObject *)self);
1027}
1028
1029
1030/* -------------------------------------------------------------------- */
1031/* Methods */
1032
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001033#define FASTSEARCH fastsearch
1034#define STRINGLIB(F) stringlib_##F
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001035#define STRINGLIB_CHAR char
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001036#define STRINGLIB_LEN PyByteArray_GET_SIZE
1037#define STRINGLIB_STR PyByteArray_AS_STRING
1038#define STRINGLIB_NEW PyByteArray_FromStringAndSize
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001039#define STRINGLIB_ISSPACE Py_ISSPACE
1040#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001041#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1042#define STRINGLIB_MUTABLE 1
1043
1044#include "stringlib/fastsearch.h"
1045#include "stringlib/count.h"
1046#include "stringlib/find.h"
1047#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001048#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001049#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
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001056/* helper macro to fixup start/end slice values */
1057#define ADJUST_INDICES(start, end, len) \
1058 if (end > len) \
1059 end = len; \
1060 else if (end < 0) { \
1061 end += len; \
1062 if (end < 0) \
1063 end = 0; \
1064 } \
1065 if (start < 0) { \
1066 start += len; \
1067 if (start < 0) \
1068 start = 0; \
1069 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001070
1071Py_LOCAL_INLINE(Py_ssize_t)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001072bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001073{
1074 PyObject *subobj;
1075 Py_buffer subbuf;
1076 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1077 Py_ssize_t res;
1078
Jesus Ceaac451502011-04-20 17:09:23 +02001079 if (!stringlib_parse_args_finds("find/rfind/index/rindex",
1080 args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001081 return -2;
1082 if (_getbuffer(subobj, &subbuf) < 0)
1083 return -2;
1084 if (dir > 0)
1085 res = stringlib_find_slice(
1086 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1087 subbuf.buf, subbuf.len, start, end);
1088 else
1089 res = stringlib_rfind_slice(
1090 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1091 subbuf.buf, subbuf.len, start, end);
Martin v. Löwis423be952008-08-13 15:53:07 +00001092 PyBuffer_Release(&subbuf);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001093 return res;
1094}
1095
1096PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001097"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001098\n\
1099Return the lowest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001100such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001101arguments start and end are interpreted as in slice notation.\n\
1102\n\
1103Return -1 on failure.");
1104
1105static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001106bytearray_find(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001107{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001108 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001109 if (result == -2)
1110 return NULL;
1111 return PyLong_FromSsize_t(result);
1112}
1113
1114PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001115"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001116\n\
1117Return the number of non-overlapping occurrences of subsection sub in\n\
1118bytes B[start:end]. Optional arguments start and end are interpreted\n\
1119as in slice notation.");
1120
1121static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001122bytearray_count(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001123{
1124 PyObject *sub_obj;
1125 const char *str = PyByteArray_AS_STRING(self);
1126 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
1127 Py_buffer vsub;
1128 PyObject *count_obj;
1129
Jesus Ceaac451502011-04-20 17:09:23 +02001130 if (!stringlib_parse_args_finds("count", args, &sub_obj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001131 return NULL;
1132
1133 if (_getbuffer(sub_obj, &vsub) < 0)
1134 return NULL;
1135
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001136 ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001137
1138 count_obj = PyLong_FromSsize_t(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001139 stringlib_count(str + start, end - start, vsub.buf, vsub.len, PY_SSIZE_T_MAX)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001140 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001141 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001142 return count_obj;
1143}
1144
Eli Bendersky4db28d32011-03-03 18:21:02 +00001145PyDoc_STRVAR(clear__doc__,
1146"B.clear() -> None\n\
1147\n\
1148Remove all items from B.");
1149
Victor Stinner6430fd52011-09-29 04:02:13 +02001150static PyObject *
Eli Bendersky4db28d32011-03-03 18:21:02 +00001151bytearray_clear(PyByteArrayObject *self)
1152{
1153 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
1154 return NULL;
1155 Py_RETURN_NONE;
1156}
1157
1158PyDoc_STRVAR(copy__doc__,
1159"B.copy() -> bytearray\n\
1160\n\
1161Return a copy of B.");
1162
1163static PyObject *
1164bytearray_copy(PyByteArrayObject *self)
1165{
1166 return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
1167 PyByteArray_GET_SIZE(self));
1168}
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001169
1170PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001171"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001172\n\
1173Like B.find() but raise ValueError when the subsection is not found.");
1174
1175static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001176bytearray_index(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001177{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001178 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001179 if (result == -2)
1180 return NULL;
1181 if (result == -1) {
1182 PyErr_SetString(PyExc_ValueError,
1183 "subsection not found");
1184 return NULL;
1185 }
1186 return PyLong_FromSsize_t(result);
1187}
1188
1189
1190PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001191"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001192\n\
1193Return the highest index in B where subsection sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08001194such that sub is contained within B[start,end]. Optional\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001195arguments start and end are interpreted as in slice notation.\n\
1196\n\
1197Return -1 on failure.");
1198
1199static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001200bytearray_rfind(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001201{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001202 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001203 if (result == -2)
1204 return NULL;
1205 return PyLong_FromSsize_t(result);
1206}
1207
1208
1209PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001210"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001211\n\
1212Like B.rfind() but raise ValueError when the subsection is not found.");
1213
1214static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001215bytearray_rindex(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001216{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001217 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001218 if (result == -2)
1219 return NULL;
1220 if (result == -1) {
1221 PyErr_SetString(PyExc_ValueError,
1222 "subsection not found");
1223 return NULL;
1224 }
1225 return PyLong_FromSsize_t(result);
1226}
1227
1228
1229static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001230bytearray_contains(PyObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001231{
1232 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1233 if (ival == -1 && PyErr_Occurred()) {
1234 Py_buffer varg;
Antoine Pitrou0010d372010-08-15 17:12:55 +00001235 Py_ssize_t pos;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001236 PyErr_Clear();
1237 if (_getbuffer(arg, &varg) < 0)
1238 return -1;
1239 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1240 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001241 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001242 return pos >= 0;
1243 }
1244 if (ival < 0 || ival >= 256) {
1245 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1246 return -1;
1247 }
1248
Antoine Pitrou0010d372010-08-15 17:12:55 +00001249 return memchr(PyByteArray_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001250}
1251
1252
1253/* Matches the end (direction >= 0) or start (direction < 0) of self
1254 * against substr, using the start and end arguments. Returns
1255 * -1 on error, 0 if not found and 1 if found.
1256 */
1257Py_LOCAL(int)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001258_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001259 Py_ssize_t end, int direction)
1260{
1261 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1262 const char* str;
1263 Py_buffer vsubstr;
1264 int rv = 0;
1265
1266 str = PyByteArray_AS_STRING(self);
1267
1268 if (_getbuffer(substr, &vsubstr) < 0)
1269 return -1;
1270
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001271 ADJUST_INDICES(start, end, len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001272
1273 if (direction < 0) {
1274 /* startswith */
1275 if (start+vsubstr.len > len) {
1276 goto done;
1277 }
1278 } else {
1279 /* endswith */
1280 if (end-start < vsubstr.len || start > len) {
1281 goto done;
1282 }
1283
1284 if (end-vsubstr.len > start)
1285 start = end - vsubstr.len;
1286 }
1287 if (end-start >= vsubstr.len)
1288 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1289
1290done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001291 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001292 return rv;
1293}
1294
1295
1296PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001297"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001298\n\
1299Return True if B starts with the specified prefix, False otherwise.\n\
1300With optional start, test B beginning at that position.\n\
1301With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001302prefix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001303
1304static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001305bytearray_startswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001306{
1307 Py_ssize_t start = 0;
1308 Py_ssize_t end = PY_SSIZE_T_MAX;
1309 PyObject *subobj;
1310 int result;
1311
Jesus Ceaac451502011-04-20 17:09:23 +02001312 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001313 return NULL;
1314 if (PyTuple_Check(subobj)) {
1315 Py_ssize_t i;
1316 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001317 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001318 PyTuple_GET_ITEM(subobj, i),
1319 start, end, -1);
1320 if (result == -1)
1321 return NULL;
1322 else if (result) {
1323 Py_RETURN_TRUE;
1324 }
1325 }
1326 Py_RETURN_FALSE;
1327 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001328 result = _bytearray_tailmatch(self, subobj, start, end, -1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001329 if (result == -1) {
1330 if (PyErr_ExceptionMatches(PyExc_TypeError))
1331 PyErr_Format(PyExc_TypeError, "startswith first arg must be bytes "
1332 "or a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001333 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001334 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001335 else
1336 return PyBool_FromLong(result);
1337}
1338
1339PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001340"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001341\n\
1342Return True if B ends with the specified suffix, False otherwise.\n\
1343With optional start, test B beginning at that position.\n\
1344With optional end, stop comparing B at that position.\n\
Ezio Melottiba42fd52011-04-26 06:09:45 +03001345suffix can also be a tuple of bytes to try.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001346
1347static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001348bytearray_endswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001349{
1350 Py_ssize_t start = 0;
1351 Py_ssize_t end = PY_SSIZE_T_MAX;
1352 PyObject *subobj;
1353 int result;
1354
Jesus Ceaac451502011-04-20 17:09:23 +02001355 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001356 return NULL;
1357 if (PyTuple_Check(subobj)) {
1358 Py_ssize_t i;
1359 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001360 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001361 PyTuple_GET_ITEM(subobj, i),
1362 start, end, +1);
1363 if (result == -1)
1364 return NULL;
1365 else if (result) {
1366 Py_RETURN_TRUE;
1367 }
1368 }
1369 Py_RETURN_FALSE;
1370 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001371 result = _bytearray_tailmatch(self, subobj, start, end, +1);
Ezio Melottiba42fd52011-04-26 06:09:45 +03001372 if (result == -1) {
1373 if (PyErr_ExceptionMatches(PyExc_TypeError))
1374 PyErr_Format(PyExc_TypeError, "endswith first arg must be bytes or "
1375 "a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001376 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +03001377 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001378 else
1379 return PyBool_FromLong(result);
1380}
1381
1382
1383PyDoc_STRVAR(translate__doc__,
1384"B.translate(table[, deletechars]) -> bytearray\n\
1385\n\
1386Return a copy of B, where all characters occurring in the\n\
1387optional argument deletechars are removed, and the remaining\n\
1388characters have been mapped through the given translation\n\
1389table, which must be a bytes object of length 256.");
1390
1391static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001392bytearray_translate(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001393{
1394 register char *input, *output;
1395 register const char *table;
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001396 register Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001397 PyObject *input_obj = (PyObject*)self;
1398 const char *output_start;
1399 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001400 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001401 int trans_table[256];
Georg Brandlccc47b62008-12-28 11:44:14 +00001402 PyObject *tableobj = NULL, *delobj = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001403 Py_buffer vtable, vdel;
1404
1405 if (!PyArg_UnpackTuple(args, "translate", 1, 2,
1406 &tableobj, &delobj))
1407 return NULL;
1408
Georg Brandlccc47b62008-12-28 11:44:14 +00001409 if (tableobj == Py_None) {
1410 table = NULL;
1411 tableobj = NULL;
1412 } else if (_getbuffer(tableobj, &vtable) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001413 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001414 } else {
1415 if (vtable.len != 256) {
1416 PyErr_SetString(PyExc_ValueError,
1417 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001418 PyBuffer_Release(&vtable);
1419 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001420 }
1421 table = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001422 }
1423
1424 if (delobj != NULL) {
1425 if (_getbuffer(delobj, &vdel) < 0) {
Georg Brandl953152f2009-07-22 12:03:59 +00001426 if (tableobj != NULL)
1427 PyBuffer_Release(&vtable);
1428 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001429 }
1430 }
1431 else {
1432 vdel.buf = NULL;
1433 vdel.len = 0;
1434 }
1435
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001436 inlen = PyByteArray_GET_SIZE(input_obj);
1437 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1438 if (result == NULL)
1439 goto done;
1440 output_start = output = PyByteArray_AsString(result);
1441 input = PyByteArray_AS_STRING(input_obj);
1442
Georg Brandlccc47b62008-12-28 11:44:14 +00001443 if (vdel.len == 0 && table != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001444 /* If no deletions are required, use faster code */
1445 for (i = inlen; --i >= 0; ) {
1446 c = Py_CHARMASK(*input++);
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001447 *output++ = table[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001448 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001449 goto done;
1450 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001451
1452 if (table == NULL) {
1453 for (i = 0; i < 256; i++)
1454 trans_table[i] = Py_CHARMASK(i);
1455 } else {
1456 for (i = 0; i < 256; i++)
1457 trans_table[i] = Py_CHARMASK(table[i]);
1458 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001459
1460 for (i = 0; i < vdel.len; i++)
1461 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1462
1463 for (i = inlen; --i >= 0; ) {
1464 c = Py_CHARMASK(*input++);
1465 if (trans_table[c] != -1)
1466 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1467 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001468 }
1469 /* Fix the size of the resulting string */
1470 if (inlen > 0)
1471 PyByteArray_Resize(result, output - output_start);
1472
1473done:
Georg Brandlccc47b62008-12-28 11:44:14 +00001474 if (tableobj != NULL)
1475 PyBuffer_Release(&vtable);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001476 if (delobj != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001477 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001478 return result;
1479}
1480
1481
Georg Brandlabc38772009-04-12 15:51:51 +00001482static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001483bytearray_maketrans(PyObject *null, PyObject *args)
Georg Brandlabc38772009-04-12 15:51:51 +00001484{
Alexander Belopolskyf0f45142010-08-11 17:31:17 +00001485 return _Py_bytes_maketrans(args);
Georg Brandlabc38772009-04-12 15:51:51 +00001486}
1487
1488
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001489/* find and count characters and substrings */
1490
1491#define findchar(target, target_len, c) \
1492 ((char *)memchr((const void *)(target), c, target_len))
1493
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001494
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001495/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001496Py_LOCAL(PyByteArrayObject *)
1497return_self(PyByteArrayObject *self)
1498{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001499 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001500 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1501 PyByteArray_AS_STRING(self),
1502 PyByteArray_GET_SIZE(self));
1503}
1504
1505Py_LOCAL_INLINE(Py_ssize_t)
1506countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1507{
1508 Py_ssize_t count=0;
1509 const char *start=target;
1510 const char *end=target+target_len;
1511
1512 while ( (start=findchar(start, end-start, c)) != NULL ) {
1513 count++;
1514 if (count >= maxcount)
1515 break;
1516 start += 1;
1517 }
1518 return count;
1519}
1520
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001521
1522/* Algorithms for different cases of string replacement */
1523
1524/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1525Py_LOCAL(PyByteArrayObject *)
1526replace_interleave(PyByteArrayObject *self,
1527 const char *to_s, Py_ssize_t to_len,
1528 Py_ssize_t maxcount)
1529{
1530 char *self_s, *result_s;
1531 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001532 Py_ssize_t count, i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001533 PyByteArrayObject *result;
1534
1535 self_len = PyByteArray_GET_SIZE(self);
1536
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001537 /* 1 at the end plus 1 after every character;
1538 count = min(maxcount, self_len + 1) */
1539 if (maxcount <= self_len)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001540 count = maxcount;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001541 else
1542 /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
1543 count = self_len + 1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001544
1545 /* Check for overflow */
1546 /* result_len = count * to_len + self_len; */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001547 assert(count > 0);
1548 if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001549 PyErr_SetString(PyExc_OverflowError,
1550 "replace string is too long");
1551 return NULL;
1552 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001553 result_len = count * to_len + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001554
1555 if (! (result = (PyByteArrayObject *)
1556 PyByteArray_FromStringAndSize(NULL, result_len)) )
1557 return NULL;
1558
1559 self_s = PyByteArray_AS_STRING(self);
1560 result_s = PyByteArray_AS_STRING(result);
1561
1562 /* TODO: special case single character, which doesn't need memcpy */
1563
1564 /* Lay the first one down (guaranteed this will occur) */
1565 Py_MEMCPY(result_s, to_s, to_len);
1566 result_s += to_len;
1567 count -= 1;
1568
1569 for (i=0; i<count; i++) {
1570 *result_s++ = *self_s++;
1571 Py_MEMCPY(result_s, to_s, to_len);
1572 result_s += to_len;
1573 }
1574
1575 /* Copy the rest of the original string */
1576 Py_MEMCPY(result_s, self_s, self_len-i);
1577
1578 return result;
1579}
1580
1581/* Special case for deleting a single character */
1582/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1583Py_LOCAL(PyByteArrayObject *)
1584replace_delete_single_character(PyByteArrayObject *self,
1585 char from_c, Py_ssize_t maxcount)
1586{
1587 char *self_s, *result_s;
1588 char *start, *next, *end;
1589 Py_ssize_t self_len, result_len;
1590 Py_ssize_t count;
1591 PyByteArrayObject *result;
1592
1593 self_len = PyByteArray_GET_SIZE(self);
1594 self_s = PyByteArray_AS_STRING(self);
1595
1596 count = countchar(self_s, self_len, from_c, maxcount);
1597 if (count == 0) {
1598 return return_self(self);
1599 }
1600
1601 result_len = self_len - count; /* from_len == 1 */
1602 assert(result_len>=0);
1603
1604 if ( (result = (PyByteArrayObject *)
1605 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1606 return NULL;
1607 result_s = PyByteArray_AS_STRING(result);
1608
1609 start = self_s;
1610 end = self_s + self_len;
1611 while (count-- > 0) {
1612 next = findchar(start, end-start, from_c);
1613 if (next == NULL)
1614 break;
1615 Py_MEMCPY(result_s, start, next-start);
1616 result_s += (next-start);
1617 start = next+1;
1618 }
1619 Py_MEMCPY(result_s, start, end-start);
1620
1621 return result;
1622}
1623
1624/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1625
1626Py_LOCAL(PyByteArrayObject *)
1627replace_delete_substring(PyByteArrayObject *self,
1628 const char *from_s, Py_ssize_t from_len,
1629 Py_ssize_t maxcount)
1630{
1631 char *self_s, *result_s;
1632 char *start, *next, *end;
1633 Py_ssize_t self_len, result_len;
1634 Py_ssize_t count, offset;
1635 PyByteArrayObject *result;
1636
1637 self_len = PyByteArray_GET_SIZE(self);
1638 self_s = PyByteArray_AS_STRING(self);
1639
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001640 count = stringlib_count(self_s, self_len,
1641 from_s, from_len,
1642 maxcount);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001643
1644 if (count == 0) {
1645 /* no matches */
1646 return return_self(self);
1647 }
1648
1649 result_len = self_len - (count * from_len);
1650 assert (result_len>=0);
1651
1652 if ( (result = (PyByteArrayObject *)
1653 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1654 return NULL;
1655
1656 result_s = PyByteArray_AS_STRING(result);
1657
1658 start = self_s;
1659 end = self_s + self_len;
1660 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001661 offset = stringlib_find(start, end-start,
1662 from_s, from_len,
1663 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001664 if (offset == -1)
1665 break;
1666 next = start + offset;
1667
1668 Py_MEMCPY(result_s, start, next-start);
1669
1670 result_s += (next-start);
1671 start = next+from_len;
1672 }
1673 Py_MEMCPY(result_s, start, end-start);
1674 return result;
1675}
1676
1677/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1678Py_LOCAL(PyByteArrayObject *)
1679replace_single_character_in_place(PyByteArrayObject *self,
1680 char from_c, char to_c,
1681 Py_ssize_t maxcount)
1682{
Antoine Pitroud1188562010-06-09 16:38:55 +00001683 char *self_s, *result_s, *start, *end, *next;
1684 Py_ssize_t self_len;
1685 PyByteArrayObject *result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001686
Antoine Pitroud1188562010-06-09 16:38:55 +00001687 /* The result string will be the same size */
1688 self_s = PyByteArray_AS_STRING(self);
1689 self_len = PyByteArray_GET_SIZE(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001690
Antoine Pitroud1188562010-06-09 16:38:55 +00001691 next = findchar(self_s, self_len, from_c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001692
Antoine Pitroud1188562010-06-09 16:38:55 +00001693 if (next == NULL) {
1694 /* No matches; return the original bytes */
1695 return return_self(self);
1696 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001697
Antoine Pitroud1188562010-06-09 16:38:55 +00001698 /* Need to make a new bytes */
1699 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1700 if (result == NULL)
1701 return NULL;
1702 result_s = PyByteArray_AS_STRING(result);
1703 Py_MEMCPY(result_s, self_s, self_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001704
Antoine Pitroud1188562010-06-09 16:38:55 +00001705 /* change everything in-place, starting with this one */
1706 start = result_s + (next-self_s);
1707 *start = to_c;
1708 start++;
1709 end = result_s + self_len;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001710
Antoine Pitroud1188562010-06-09 16:38:55 +00001711 while (--maxcount > 0) {
1712 next = findchar(start, end-start, from_c);
1713 if (next == NULL)
1714 break;
1715 *next = to_c;
1716 start = next+1;
1717 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001718
Antoine Pitroud1188562010-06-09 16:38:55 +00001719 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001720}
1721
1722/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1723Py_LOCAL(PyByteArrayObject *)
1724replace_substring_in_place(PyByteArrayObject *self,
1725 const char *from_s, Py_ssize_t from_len,
1726 const char *to_s, Py_ssize_t to_len,
1727 Py_ssize_t maxcount)
1728{
1729 char *result_s, *start, *end;
1730 char *self_s;
1731 Py_ssize_t self_len, offset;
1732 PyByteArrayObject *result;
1733
1734 /* The result bytes will be the same size */
1735
1736 self_s = PyByteArray_AS_STRING(self);
1737 self_len = PyByteArray_GET_SIZE(self);
1738
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001739 offset = stringlib_find(self_s, self_len,
1740 from_s, from_len,
1741 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001742 if (offset == -1) {
1743 /* No matches; return the original bytes */
1744 return return_self(self);
1745 }
1746
1747 /* Need to make a new bytes */
1748 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1749 if (result == NULL)
1750 return NULL;
1751 result_s = PyByteArray_AS_STRING(result);
1752 Py_MEMCPY(result_s, self_s, self_len);
1753
1754 /* change everything in-place, starting with this one */
1755 start = result_s + offset;
1756 Py_MEMCPY(start, to_s, from_len);
1757 start += from_len;
1758 end = result_s + self_len;
1759
1760 while ( --maxcount > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001761 offset = stringlib_find(start, end-start,
1762 from_s, from_len,
1763 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001764 if (offset==-1)
1765 break;
1766 Py_MEMCPY(start+offset, to_s, from_len);
1767 start += offset+from_len;
1768 }
1769
1770 return result;
1771}
1772
1773/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
1774Py_LOCAL(PyByteArrayObject *)
1775replace_single_character(PyByteArrayObject *self,
1776 char from_c,
1777 const char *to_s, Py_ssize_t to_len,
1778 Py_ssize_t maxcount)
1779{
1780 char *self_s, *result_s;
1781 char *start, *next, *end;
1782 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001783 Py_ssize_t count;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001784 PyByteArrayObject *result;
1785
1786 self_s = PyByteArray_AS_STRING(self);
1787 self_len = PyByteArray_GET_SIZE(self);
1788
1789 count = countchar(self_s, self_len, from_c, maxcount);
1790 if (count == 0) {
1791 /* no matches, return unchanged */
1792 return return_self(self);
1793 }
1794
1795 /* use the difference between current and new, hence the "-1" */
1796 /* result_len = self_len + count * (to_len-1) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001797 assert(count > 0);
1798 if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001799 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1800 return NULL;
1801 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001802 result_len = self_len + count * (to_len - 1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001803
1804 if ( (result = (PyByteArrayObject *)
1805 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1806 return NULL;
1807 result_s = PyByteArray_AS_STRING(result);
1808
1809 start = self_s;
1810 end = self_s + self_len;
1811 while (count-- > 0) {
1812 next = findchar(start, end-start, from_c);
1813 if (next == NULL)
1814 break;
1815
1816 if (next == start) {
1817 /* replace with the 'to' */
1818 Py_MEMCPY(result_s, to_s, to_len);
1819 result_s += to_len;
1820 start += 1;
1821 } else {
1822 /* copy the unchanged old then the 'to' */
1823 Py_MEMCPY(result_s, start, next-start);
1824 result_s += (next-start);
1825 Py_MEMCPY(result_s, to_s, to_len);
1826 result_s += to_len;
1827 start = next+1;
1828 }
1829 }
1830 /* Copy the remainder of the remaining bytes */
1831 Py_MEMCPY(result_s, start, end-start);
1832
1833 return result;
1834}
1835
1836/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
1837Py_LOCAL(PyByteArrayObject *)
1838replace_substring(PyByteArrayObject *self,
1839 const char *from_s, Py_ssize_t from_len,
1840 const char *to_s, Py_ssize_t to_len,
1841 Py_ssize_t maxcount)
1842{
1843 char *self_s, *result_s;
1844 char *start, *next, *end;
1845 Py_ssize_t self_len, result_len;
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001846 Py_ssize_t count, offset;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001847 PyByteArrayObject *result;
1848
1849 self_s = PyByteArray_AS_STRING(self);
1850 self_len = PyByteArray_GET_SIZE(self);
1851
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001852 count = stringlib_count(self_s, self_len,
1853 from_s, from_len,
1854 maxcount);
1855
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001856 if (count == 0) {
1857 /* no matches, return unchanged */
1858 return return_self(self);
1859 }
1860
1861 /* Check for overflow */
1862 /* result_len = self_len + count * (to_len-from_len) */
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001863 assert(count > 0);
1864 if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001865 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1866 return NULL;
1867 }
Mark Dickinsoncf940c72010-08-10 18:35:01 +00001868 result_len = self_len + count * (to_len - from_len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001869
1870 if ( (result = (PyByteArrayObject *)
1871 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1872 return NULL;
1873 result_s = PyByteArray_AS_STRING(result);
1874
1875 start = self_s;
1876 end = self_s + self_len;
1877 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001878 offset = stringlib_find(start, end-start,
1879 from_s, from_len,
1880 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001881 if (offset == -1)
1882 break;
1883 next = start+offset;
1884 if (next == start) {
1885 /* replace with the 'to' */
1886 Py_MEMCPY(result_s, to_s, to_len);
1887 result_s += to_len;
1888 start += from_len;
1889 } else {
1890 /* copy the unchanged old then the 'to' */
1891 Py_MEMCPY(result_s, start, next-start);
1892 result_s += (next-start);
1893 Py_MEMCPY(result_s, to_s, to_len);
1894 result_s += to_len;
1895 start = next+from_len;
1896 }
1897 }
1898 /* Copy the remainder of the remaining bytes */
1899 Py_MEMCPY(result_s, start, end-start);
1900
1901 return result;
1902}
1903
1904
1905Py_LOCAL(PyByteArrayObject *)
1906replace(PyByteArrayObject *self,
1907 const char *from_s, Py_ssize_t from_len,
1908 const char *to_s, Py_ssize_t to_len,
1909 Py_ssize_t maxcount)
1910{
1911 if (maxcount < 0) {
1912 maxcount = PY_SSIZE_T_MAX;
1913 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
1914 /* nothing to do; return the original bytes */
1915 return return_self(self);
1916 }
1917
1918 if (maxcount == 0 ||
1919 (from_len == 0 && to_len == 0)) {
1920 /* nothing to do; return the original bytes */
1921 return return_self(self);
1922 }
1923
1924 /* Handle zero-length special cases */
1925
1926 if (from_len == 0) {
1927 /* insert the 'to' bytes everywhere. */
1928 /* >>> "Python".replace("", ".") */
1929 /* '.P.y.t.h.o.n.' */
1930 return replace_interleave(self, to_s, to_len, maxcount);
1931 }
1932
1933 /* Except for "".replace("", "A") == "A" there is no way beyond this */
1934 /* point for an empty self bytes to generate a non-empty bytes */
1935 /* Special case so the remaining code always gets a non-empty bytes */
1936 if (PyByteArray_GET_SIZE(self) == 0) {
1937 return return_self(self);
1938 }
1939
1940 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00001941 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001942 if (from_len == 1) {
1943 return replace_delete_single_character(
1944 self, from_s[0], maxcount);
1945 } else {
1946 return replace_delete_substring(self, from_s, from_len, maxcount);
1947 }
1948 }
1949
1950 /* Handle special case where both bytes have the same length */
1951
1952 if (from_len == to_len) {
1953 if (from_len == 1) {
1954 return replace_single_character_in_place(
1955 self,
1956 from_s[0],
1957 to_s[0],
1958 maxcount);
1959 } else {
1960 return replace_substring_in_place(
1961 self, from_s, from_len, to_s, to_len, maxcount);
1962 }
1963 }
1964
1965 /* Otherwise use the more generic algorithms */
1966 if (from_len == 1) {
1967 return replace_single_character(self, from_s[0],
1968 to_s, to_len, maxcount);
1969 } else {
1970 /* len('from')>=2, len('to')>=1 */
1971 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
1972 }
1973}
1974
1975
1976PyDoc_STRVAR(replace__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001977"B.replace(old, new[, count]) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001978\n\
1979Return a copy of B with all occurrences of subsection\n\
1980old replaced by new. If the optional argument count is\n\
1981given, only the first count occurrences are replaced.");
1982
1983static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001984bytearray_replace(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001985{
1986 Py_ssize_t count = -1;
1987 PyObject *from, *to, *res;
1988 Py_buffer vfrom, vto;
1989
1990 if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
1991 return NULL;
1992
1993 if (_getbuffer(from, &vfrom) < 0)
1994 return NULL;
1995 if (_getbuffer(to, &vto) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +00001996 PyBuffer_Release(&vfrom);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001997 return NULL;
1998 }
1999
2000 res = (PyObject *)replace((PyByteArrayObject *) self,
2001 vfrom.buf, vfrom.len,
2002 vto.buf, vto.len, count);
2003
Martin v. Löwis423be952008-08-13 15:53:07 +00002004 PyBuffer_Release(&vfrom);
2005 PyBuffer_Release(&vto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002006 return res;
2007}
2008
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002009PyDoc_STRVAR(split__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002010"B.split([sep[, maxsplit]]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002011\n\
2012Return a list of the sections in B, using sep as the delimiter.\n\
2013If sep is not given, B is split on ASCII whitespace characters\n\
2014(space, tab, return, newline, formfeed, vertical tab).\n\
2015If maxsplit is given, at most maxsplit splits are done.");
2016
2017static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002018bytearray_split(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002019{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002020 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
2021 Py_ssize_t maxsplit = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002022 const char *s = PyByteArray_AS_STRING(self), *sub;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002023 PyObject *list, *subobj = Py_None;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002024 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002025
2026 if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
2027 return NULL;
2028 if (maxsplit < 0)
2029 maxsplit = PY_SSIZE_T_MAX;
2030
2031 if (subobj == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002032 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002033
2034 if (_getbuffer(subobj, &vsub) < 0)
2035 return NULL;
2036 sub = vsub.buf;
2037 n = vsub.len;
2038
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002039 list = stringlib_split(
2040 (PyObject*) self, s, len, sub, n, maxsplit
2041 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002042 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002043 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002044}
2045
2046PyDoc_STRVAR(partition__doc__,
2047"B.partition(sep) -> (head, sep, tail)\n\
2048\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002049Search for the separator sep in B, and return the part before it,\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002050the separator itself, and the part after it. If the separator is not\n\
2051found, returns B and two empty bytearray objects.");
2052
2053static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002054bytearray_partition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002055{
2056 PyObject *bytesep, *result;
2057
2058 bytesep = PyByteArray_FromObject(sep_obj);
2059 if (! bytesep)
2060 return NULL;
2061
2062 result = stringlib_partition(
2063 (PyObject*) self,
2064 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2065 bytesep,
2066 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2067 );
2068
2069 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002070 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002071}
2072
2073PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +00002074"B.rpartition(sep) -> (head, sep, tail)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002075\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002076Search for the separator sep in B, starting at the end of B,\n\
2077and return the part before it, the separator itself, and the\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002078part after it. If the separator is not found, returns two empty\n\
2079bytearray objects and B.");
2080
2081static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002082bytearray_rpartition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002083{
2084 PyObject *bytesep, *result;
2085
2086 bytesep = PyByteArray_FromObject(sep_obj);
2087 if (! bytesep)
2088 return NULL;
2089
2090 result = stringlib_rpartition(
2091 (PyObject*) self,
2092 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2093 bytesep,
2094 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2095 );
2096
2097 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002098 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002099}
2100
2101PyDoc_STRVAR(rsplit__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002102"B.rsplit(sep[, maxsplit]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002103\n\
2104Return a list of the sections in B, using sep as the delimiter,\n\
2105starting at the end of B and working to the front.\n\
2106If sep is not given, B is split on ASCII whitespace characters\n\
2107(space, tab, return, newline, formfeed, vertical tab).\n\
2108If maxsplit is given, at most maxsplit splits are done.");
2109
2110static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002111bytearray_rsplit(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002112{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002113 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
2114 Py_ssize_t maxsplit = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002115 const char *s = PyByteArray_AS_STRING(self), *sub;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002116 PyObject *list, *subobj = Py_None;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002117 Py_buffer vsub;
2118
2119 if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
2120 return NULL;
2121 if (maxsplit < 0)
2122 maxsplit = PY_SSIZE_T_MAX;
2123
2124 if (subobj == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002125 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002126
2127 if (_getbuffer(subobj, &vsub) < 0)
2128 return NULL;
2129 sub = vsub.buf;
2130 n = vsub.len;
2131
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002132 list = stringlib_rsplit(
2133 (PyObject*) self, s, len, sub, n, maxsplit
2134 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002135 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002136 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002137}
2138
2139PyDoc_STRVAR(reverse__doc__,
2140"B.reverse() -> None\n\
2141\n\
2142Reverse the order of the values in B in place.");
2143static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002144bytearray_reverse(PyByteArrayObject *self, PyObject *unused)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002145{
2146 char swap, *head, *tail;
2147 Py_ssize_t i, j, n = Py_SIZE(self);
2148
2149 j = n / 2;
2150 head = self->ob_bytes;
2151 tail = head + n - 1;
2152 for (i = 0; i < j; i++) {
2153 swap = *head;
2154 *head++ = *tail;
2155 *tail-- = swap;
2156 }
2157
2158 Py_RETURN_NONE;
2159}
2160
2161PyDoc_STRVAR(insert__doc__,
2162"B.insert(index, int) -> None\n\
2163\n\
2164Insert a single item into the bytearray before the given index.");
2165static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002166bytearray_insert(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002167{
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002168 PyObject *value;
2169 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002170 Py_ssize_t where, n = Py_SIZE(self);
2171
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002172 if (!PyArg_ParseTuple(args, "nO:insert", &where, &value))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002173 return NULL;
2174
2175 if (n == PY_SSIZE_T_MAX) {
2176 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002177 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002178 return NULL;
2179 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002180 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002181 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002182 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2183 return NULL;
2184
2185 if (where < 0) {
2186 where += n;
2187 if (where < 0)
2188 where = 0;
2189 }
2190 if (where > n)
2191 where = n;
2192 memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where);
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002193 self->ob_bytes[where] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002194
2195 Py_RETURN_NONE;
2196}
2197
2198PyDoc_STRVAR(append__doc__,
2199"B.append(int) -> None\n\
2200\n\
2201Append a single item to the end of B.");
2202static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002203bytearray_append(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002204{
2205 int value;
2206 Py_ssize_t n = Py_SIZE(self);
2207
2208 if (! _getbytevalue(arg, &value))
2209 return NULL;
2210 if (n == PY_SSIZE_T_MAX) {
2211 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002212 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002213 return NULL;
2214 }
2215 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2216 return NULL;
2217
2218 self->ob_bytes[n] = value;
2219
2220 Py_RETURN_NONE;
2221}
2222
2223PyDoc_STRVAR(extend__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002224"B.extend(iterable_of_ints) -> None\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002225\n\
2226Append all the elements from the iterator or sequence to the\n\
2227end of B.");
2228static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002229bytearray_extend(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002230{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002231 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002232 Py_ssize_t buf_size = 0, len = 0;
2233 int value;
2234 char *buf;
2235
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002236 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002237 if (PyObject_CheckBuffer(arg)) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002238 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), arg) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002239 return NULL;
2240
2241 Py_RETURN_NONE;
2242 }
2243
2244 it = PyObject_GetIter(arg);
2245 if (it == NULL)
2246 return NULL;
2247
Ezio Melotti42da6632011-03-15 05:18:48 +02002248 /* Try to determine the length of the argument. 32 is arbitrary. */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002249 buf_size = _PyObject_LengthHint(arg, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002250 if (buf_size == -1) {
2251 Py_DECREF(it);
2252 return NULL;
2253 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002254
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002255 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
2256 if (bytearray_obj == NULL)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002257 return NULL;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002258 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002259
2260 while ((item = PyIter_Next(it)) != NULL) {
2261 if (! _getbytevalue(item, &value)) {
2262 Py_DECREF(item);
2263 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002264 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002265 return NULL;
2266 }
2267 buf[len++] = value;
2268 Py_DECREF(item);
2269
2270 if (len >= buf_size) {
2271 buf_size = len + (len >> 1) + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002272 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002273 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002274 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002275 return NULL;
2276 }
2277 /* Recompute the `buf' pointer, since the resizing operation may
2278 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002279 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002280 }
2281 }
2282 Py_DECREF(it);
2283
2284 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002285 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
2286 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002287 return NULL;
2288 }
2289
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002290 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002291 return NULL;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002292 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002293
2294 Py_RETURN_NONE;
2295}
2296
2297PyDoc_STRVAR(pop__doc__,
2298"B.pop([index]) -> int\n\
2299\n\
2300Remove and return a single item from B. If no index\n\
Benjamin Petersondcf97b92008-07-02 17:30:14 +00002301argument is given, will pop the last value.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002302static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002303bytearray_pop(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002304{
2305 int value;
2306 Py_ssize_t where = -1, n = Py_SIZE(self);
2307
2308 if (!PyArg_ParseTuple(args, "|n:pop", &where))
2309 return NULL;
2310
2311 if (n == 0) {
Eli Bendersky1bc4f192011-03-04 04:55:25 +00002312 PyErr_SetString(PyExc_IndexError,
2313 "pop from empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002314 return NULL;
2315 }
2316 if (where < 0)
2317 where += Py_SIZE(self);
2318 if (where < 0 || where >= Py_SIZE(self)) {
2319 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2320 return NULL;
2321 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002322 if (!_canresize(self))
2323 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002324
2325 value = self->ob_bytes[where];
2326 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2327 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2328 return NULL;
2329
Mark Dickinson54a3db92009-09-06 10:19:23 +00002330 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002331}
2332
2333PyDoc_STRVAR(remove__doc__,
2334"B.remove(int) -> None\n\
2335\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002336Remove the first occurrence of a value in B.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002337static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002338bytearray_remove(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002339{
2340 int value;
2341 Py_ssize_t where, n = Py_SIZE(self);
2342
2343 if (! _getbytevalue(arg, &value))
2344 return NULL;
2345
2346 for (where = 0; where < n; where++) {
2347 if (self->ob_bytes[where] == value)
2348 break;
2349 }
2350 if (where == n) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002351 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002352 return NULL;
2353 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002354 if (!_canresize(self))
2355 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002356
2357 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2358 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2359 return NULL;
2360
2361 Py_RETURN_NONE;
2362}
2363
2364/* XXX These two helpers could be optimized if argsize == 1 */
2365
2366static Py_ssize_t
2367lstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2368 void *argptr, Py_ssize_t argsize)
2369{
2370 Py_ssize_t i = 0;
2371 while (i < mysize && memchr(argptr, myptr[i], argsize))
2372 i++;
2373 return i;
2374}
2375
2376static Py_ssize_t
2377rstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2378 void *argptr, Py_ssize_t argsize)
2379{
2380 Py_ssize_t i = mysize - 1;
2381 while (i >= 0 && memchr(argptr, myptr[i], argsize))
2382 i--;
2383 return i + 1;
2384}
2385
2386PyDoc_STRVAR(strip__doc__,
2387"B.strip([bytes]) -> bytearray\n\
2388\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002389Strip leading and trailing bytes contained in the argument\n\
2390and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002391If the argument is omitted, strip ASCII whitespace.");
2392static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002393bytearray_strip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002394{
2395 Py_ssize_t left, right, mysize, argsize;
2396 void *myptr, *argptr;
2397 PyObject *arg = Py_None;
2398 Py_buffer varg;
2399 if (!PyArg_ParseTuple(args, "|O:strip", &arg))
2400 return NULL;
2401 if (arg == Py_None) {
2402 argptr = "\t\n\r\f\v ";
2403 argsize = 6;
2404 }
2405 else {
2406 if (_getbuffer(arg, &varg) < 0)
2407 return NULL;
2408 argptr = varg.buf;
2409 argsize = varg.len;
2410 }
2411 myptr = self->ob_bytes;
2412 mysize = Py_SIZE(self);
2413 left = lstrip_helper(myptr, mysize, argptr, argsize);
2414 if (left == mysize)
2415 right = left;
2416 else
2417 right = rstrip_helper(myptr, mysize, argptr, argsize);
2418 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002419 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002420 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2421}
2422
2423PyDoc_STRVAR(lstrip__doc__,
2424"B.lstrip([bytes]) -> bytearray\n\
2425\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002426Strip leading bytes contained in the argument\n\
2427and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002428If the argument is omitted, strip leading ASCII whitespace.");
2429static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002430bytearray_lstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002431{
2432 Py_ssize_t left, right, mysize, argsize;
2433 void *myptr, *argptr;
2434 PyObject *arg = Py_None;
2435 Py_buffer varg;
2436 if (!PyArg_ParseTuple(args, "|O:lstrip", &arg))
2437 return NULL;
2438 if (arg == Py_None) {
2439 argptr = "\t\n\r\f\v ";
2440 argsize = 6;
2441 }
2442 else {
2443 if (_getbuffer(arg, &varg) < 0)
2444 return NULL;
2445 argptr = varg.buf;
2446 argsize = varg.len;
2447 }
2448 myptr = self->ob_bytes;
2449 mysize = Py_SIZE(self);
2450 left = lstrip_helper(myptr, mysize, argptr, argsize);
2451 right = mysize;
2452 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002453 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002454 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2455}
2456
2457PyDoc_STRVAR(rstrip__doc__,
2458"B.rstrip([bytes]) -> bytearray\n\
2459\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002460Strip trailing bytes contained in the argument\n\
2461and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002462If the argument is omitted, strip trailing ASCII whitespace.");
2463static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002464bytearray_rstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002465{
Brett Cannonb94767f2011-02-22 20:15:44 +00002466 Py_ssize_t right, mysize, argsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002467 void *myptr, *argptr;
2468 PyObject *arg = Py_None;
2469 Py_buffer varg;
2470 if (!PyArg_ParseTuple(args, "|O:rstrip", &arg))
2471 return NULL;
2472 if (arg == Py_None) {
2473 argptr = "\t\n\r\f\v ";
2474 argsize = 6;
2475 }
2476 else {
2477 if (_getbuffer(arg, &varg) < 0)
2478 return NULL;
2479 argptr = varg.buf;
2480 argsize = varg.len;
2481 }
2482 myptr = self->ob_bytes;
2483 mysize = Py_SIZE(self);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002484 right = rstrip_helper(myptr, mysize, argptr, argsize);
2485 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002486 PyBuffer_Release(&varg);
Brett Cannonb94767f2011-02-22 20:15:44 +00002487 return PyByteArray_FromStringAndSize(self->ob_bytes, right);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002488}
2489
2490PyDoc_STRVAR(decode_doc,
Victor Stinnerc911bbf2010-11-07 19:04:46 +00002491"B.decode(encoding='utf-8', errors='strict') -> str\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002492\n\
Victor Stinnere14e2122010-11-07 18:41:46 +00002493Decode B using the codec registered for encoding. Default encoding\n\
2494is 'utf-8'. errors may be given to set a different error\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002495handling scheme. Default is 'strict' meaning that encoding errors raise\n\
2496a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
2497as well as any other name registered with codecs.register_error that is\n\
2498able to handle UnicodeDecodeErrors.");
2499
2500static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00002501bytearray_decode(PyObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002502{
2503 const char *encoding = NULL;
2504 const char *errors = NULL;
Benjamin Peterson308d6372009-09-18 21:42:35 +00002505 static char *kwlist[] = {"encoding", "errors", 0};
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002506
Benjamin Peterson308d6372009-09-18 21:42:35 +00002507 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode", kwlist, &encoding, &errors))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002508 return NULL;
2509 if (encoding == NULL)
2510 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002511 return PyUnicode_FromEncodedObject(self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002512}
2513
2514PyDoc_STRVAR(alloc_doc,
2515"B.__alloc__() -> int\n\
2516\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002517Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002518
2519static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002520bytearray_alloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002521{
2522 return PyLong_FromSsize_t(self->ob_alloc);
2523}
2524
2525PyDoc_STRVAR(join_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002526"B.join(iterable_of_bytes) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002527\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002528Concatenate any number of bytes/bytearray objects, with B\n\
2529in between each pair, and return the result as a new bytearray.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002530
2531static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002532bytearray_join(PyByteArrayObject *self, PyObject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002533{
2534 PyObject *seq;
2535 Py_ssize_t mysize = Py_SIZE(self);
2536 Py_ssize_t i;
2537 Py_ssize_t n;
2538 PyObject **items;
2539 Py_ssize_t totalsize = 0;
2540 PyObject *result;
2541 char *dest;
2542
2543 seq = PySequence_Fast(it, "can only join an iterable");
2544 if (seq == NULL)
2545 return NULL;
2546 n = PySequence_Fast_GET_SIZE(seq);
2547 items = PySequence_Fast_ITEMS(seq);
2548
2549 /* Compute the total size, and check that they are all bytes */
2550 /* XXX Shouldn't we use _getbuffer() on these items instead? */
2551 for (i = 0; i < n; i++) {
2552 PyObject *obj = items[i];
2553 if (!PyByteArray_Check(obj) && !PyBytes_Check(obj)) {
2554 PyErr_Format(PyExc_TypeError,
2555 "can only join an iterable of bytes "
2556 "(item %ld has type '%.100s')",
2557 /* XXX %ld isn't right on Win64 */
2558 (long)i, Py_TYPE(obj)->tp_name);
2559 goto error;
2560 }
2561 if (i > 0)
2562 totalsize += mysize;
2563 totalsize += Py_SIZE(obj);
2564 if (totalsize < 0) {
2565 PyErr_NoMemory();
2566 goto error;
2567 }
2568 }
2569
2570 /* Allocate the result, and copy the bytes */
2571 result = PyByteArray_FromStringAndSize(NULL, totalsize);
2572 if (result == NULL)
2573 goto error;
2574 dest = PyByteArray_AS_STRING(result);
2575 for (i = 0; i < n; i++) {
2576 PyObject *obj = items[i];
2577 Py_ssize_t size = Py_SIZE(obj);
2578 char *buf;
2579 if (PyByteArray_Check(obj))
2580 buf = PyByteArray_AS_STRING(obj);
2581 else
2582 buf = PyBytes_AS_STRING(obj);
2583 if (i) {
2584 memcpy(dest, self->ob_bytes, mysize);
2585 dest += mysize;
2586 }
2587 memcpy(dest, buf, size);
2588 dest += size;
2589 }
2590
2591 /* Done */
2592 Py_DECREF(seq);
2593 return result;
2594
2595 /* Error handling */
2596 error:
2597 Py_DECREF(seq);
2598 return NULL;
2599}
2600
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002601PyDoc_STRVAR(splitlines__doc__,
2602"B.splitlines([keepends]) -> list of lines\n\
2603\n\
2604Return a list of the lines in B, breaking at line boundaries.\n\
2605Line breaks are not included in the resulting list unless keepends\n\
2606is given and true.");
2607
2608static PyObject*
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +01002609bytearray_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002610{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +01002611 static char *kwlist[] = {"keepends", 0};
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002612 int keepends = 0;
2613
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +01002614 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
2615 kwlist, &keepends))
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002616 return NULL;
2617
2618 return stringlib_splitlines(
2619 (PyObject*) self, PyByteArray_AS_STRING(self),
2620 PyByteArray_GET_SIZE(self), keepends
2621 );
2622}
2623
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002624PyDoc_STRVAR(fromhex_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002625"bytearray.fromhex(string) -> bytearray (static method)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002626\n\
2627Create a bytearray object from a string of hexadecimal numbers.\n\
2628Spaces between two numbers are accepted.\n\
2629Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef').");
2630
2631static int
Victor Stinner6430fd52011-09-29 04:02:13 +02002632hex_digit_to_int(Py_UCS4 c)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002633{
2634 if (c >= 128)
2635 return -1;
Eric Smith6dc46f52009-04-27 20:39:49 +00002636 if (Py_ISDIGIT(c))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002637 return c - '0';
2638 else {
Eric Smith6dc46f52009-04-27 20:39:49 +00002639 if (Py_ISUPPER(c))
2640 c = Py_TOLOWER(c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002641 if (c >= 'a' && c <= 'f')
2642 return c - 'a' + 10;
2643 }
2644 return -1;
2645}
2646
2647static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002648bytearray_fromhex(PyObject *cls, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002649{
2650 PyObject *newbytes, *hexobj;
2651 char *buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002652 Py_ssize_t hexlen, byteslen, i, j;
2653 int top, bot;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002654 void *data;
2655 unsigned int kind;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002656
2657 if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj))
2658 return NULL;
2659 assert(PyUnicode_Check(hexobj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002660 if (PyUnicode_READY(hexobj))
2661 return NULL;
2662 kind = PyUnicode_KIND(hexobj);
2663 data = PyUnicode_DATA(hexobj);
2664 hexlen = PyUnicode_GET_LENGTH(hexobj);
2665
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002666 byteslen = hexlen/2; /* This overestimates if there are spaces */
2667 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
2668 if (!newbytes)
2669 return NULL;
2670 buf = PyByteArray_AS_STRING(newbytes);
2671 for (i = j = 0; i < hexlen; i += 2) {
2672 /* skip over spaces in the input */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002673 while (PyUnicode_READ(kind, data, i) == ' ')
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002674 i++;
2675 if (i >= hexlen)
2676 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002677 top = hex_digit_to_int(PyUnicode_READ(kind, data, i));
2678 bot = hex_digit_to_int(PyUnicode_READ(kind, data, i+1));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002679 if (top == -1 || bot == -1) {
2680 PyErr_Format(PyExc_ValueError,
2681 "non-hexadecimal number found in "
2682 "fromhex() arg at position %zd", i);
2683 goto error;
2684 }
2685 buf[j++] = (top << 4) + bot;
2686 }
2687 if (PyByteArray_Resize(newbytes, j) < 0)
2688 goto error;
2689 return newbytes;
2690
2691 error:
2692 Py_DECREF(newbytes);
2693 return NULL;
2694}
2695
2696PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2697
2698static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002699bytearray_reduce(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002700{
2701 PyObject *latin1, *dict;
2702 if (self->ob_bytes)
2703 latin1 = PyUnicode_DecodeLatin1(self->ob_bytes,
2704 Py_SIZE(self), NULL);
2705 else
2706 latin1 = PyUnicode_FromString("");
2707
2708 dict = PyObject_GetAttrString((PyObject *)self, "__dict__");
2709 if (dict == NULL) {
2710 PyErr_Clear();
2711 dict = Py_None;
2712 Py_INCREF(dict);
2713 }
2714
2715 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
2716}
2717
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002718PyDoc_STRVAR(sizeof_doc,
2719"B.__sizeof__() -> int\n\
2720 \n\
2721Returns the size of B in memory, in bytes");
2722static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002723bytearray_sizeof(PyByteArrayObject *self)
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002724{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002725 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002726
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002727 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
2728 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002729}
2730
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002731static PySequenceMethods bytearray_as_sequence = {
2732 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002733 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002734 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
2735 (ssizeargfunc)bytearray_getitem, /* sq_item */
2736 0, /* sq_slice */
2737 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
2738 0, /* sq_ass_slice */
2739 (objobjproc)bytearray_contains, /* sq_contains */
2740 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
2741 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002742};
2743
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002744static PyMappingMethods bytearray_as_mapping = {
2745 (lenfunc)bytearray_length,
2746 (binaryfunc)bytearray_subscript,
2747 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002748};
2749
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002750static PyBufferProcs bytearray_as_buffer = {
2751 (getbufferproc)bytearray_getbuffer,
2752 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002753};
2754
2755static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002756bytearray_methods[] = {
2757 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
2758 {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, reduce_doc},
2759 {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, sizeof_doc},
2760 {"append", (PyCFunction)bytearray_append, METH_O, append__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002761 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
2762 _Py_capitalize__doc__},
2763 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
Eli Bendersky4db28d32011-03-03 18:21:02 +00002764 {"clear", (PyCFunction)bytearray_clear, METH_NOARGS, clear__doc__},
2765 {"copy", (PyCFunction)bytearray_copy, METH_NOARGS, copy__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002766 {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
Benjamin Peterson308d6372009-09-18 21:42:35 +00002767 {"decode", (PyCFunction)bytearray_decode, METH_VARARGS | METH_KEYWORDS, decode_doc},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002768 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002769 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS,
2770 expandtabs__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002771 {"extend", (PyCFunction)bytearray_extend, METH_O, extend__doc__},
2772 {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
2773 {"fromhex", (PyCFunction)bytearray_fromhex, METH_VARARGS|METH_CLASS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002774 fromhex_doc},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002775 {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
2776 {"insert", (PyCFunction)bytearray_insert, METH_VARARGS, insert__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002777 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
2778 _Py_isalnum__doc__},
2779 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
2780 _Py_isalpha__doc__},
2781 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
2782 _Py_isdigit__doc__},
2783 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
2784 _Py_islower__doc__},
2785 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
2786 _Py_isspace__doc__},
2787 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
2788 _Py_istitle__doc__},
2789 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
2790 _Py_isupper__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002791 {"join", (PyCFunction)bytearray_join, METH_O, join_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002792 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
2793 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002794 {"lstrip", (PyCFunction)bytearray_lstrip, METH_VARARGS, lstrip__doc__},
2795 {"maketrans", (PyCFunction)bytearray_maketrans, METH_VARARGS|METH_STATIC,
Georg Brandlabc38772009-04-12 15:51:51 +00002796 _Py_maketrans__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002797 {"partition", (PyCFunction)bytearray_partition, METH_O, partition__doc__},
2798 {"pop", (PyCFunction)bytearray_pop, METH_VARARGS, pop__doc__},
2799 {"remove", (PyCFunction)bytearray_remove, METH_O, remove__doc__},
2800 {"replace", (PyCFunction)bytearray_replace, METH_VARARGS, replace__doc__},
2801 {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, reverse__doc__},
2802 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
2803 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002804 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002805 {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, rpartition__doc__},
2806 {"rsplit", (PyCFunction)bytearray_rsplit, METH_VARARGS, rsplit__doc__},
2807 {"rstrip", (PyCFunction)bytearray_rstrip, METH_VARARGS, rstrip__doc__},
2808 {"split", (PyCFunction)bytearray_split, METH_VARARGS, split__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +01002809 {"splitlines", (PyCFunction)bytearray_splitlines,
2810 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002811 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002812 startswith__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002813 {"strip", (PyCFunction)bytearray_strip, METH_VARARGS, strip__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002814 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
2815 _Py_swapcase__doc__},
2816 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002817 {"translate", (PyCFunction)bytearray_translate, METH_VARARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002818 translate__doc__},
2819 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
2820 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
2821 {NULL}
2822};
2823
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002824PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002825"bytearray(iterable_of_ints) -> bytearray\n\
2826bytearray(string, encoding[, errors]) -> bytearray\n\
2827bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray\n\
2828bytearray(memory_view) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002829\n\
2830Construct an mutable bytearray object from:\n\
2831 - an iterable yielding integers in range(256)\n\
2832 - a text string encoded using the specified encoding\n\
2833 - a bytes or a bytearray object\n\
2834 - any object implementing the buffer API.\n\
2835\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002836bytearray(int) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002837\n\
2838Construct a zero-initialized bytearray of the given length.");
2839
2840
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002841static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002842
2843PyTypeObject PyByteArray_Type = {
2844 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2845 "bytearray",
2846 sizeof(PyByteArrayObject),
2847 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002848 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002849 0, /* tp_print */
2850 0, /* tp_getattr */
2851 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002852 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002853 (reprfunc)bytearray_repr, /* tp_repr */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002854 0, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002855 &bytearray_as_sequence, /* tp_as_sequence */
2856 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002857 0, /* tp_hash */
2858 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002859 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002860 PyObject_GenericGetAttr, /* tp_getattro */
2861 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002862 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002863 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002864 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002865 0, /* tp_traverse */
2866 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002867 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002868 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002869 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002870 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002871 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002872 0, /* tp_members */
2873 0, /* tp_getset */
2874 0, /* tp_base */
2875 0, /* tp_dict */
2876 0, /* tp_descr_get */
2877 0, /* tp_descr_set */
2878 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002879 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002880 PyType_GenericAlloc, /* tp_alloc */
2881 PyType_GenericNew, /* tp_new */
2882 PyObject_Del, /* tp_free */
2883};
2884
2885/*********************** Bytes Iterator ****************************/
2886
2887typedef struct {
2888 PyObject_HEAD
2889 Py_ssize_t it_index;
2890 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
2891} bytesiterobject;
2892
2893static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002894bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002895{
2896 _PyObject_GC_UNTRACK(it);
2897 Py_XDECREF(it->it_seq);
2898 PyObject_GC_Del(it);
2899}
2900
2901static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002902bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002903{
2904 Py_VISIT(it->it_seq);
2905 return 0;
2906}
2907
2908static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002909bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002910{
2911 PyByteArrayObject *seq;
2912 PyObject *item;
2913
2914 assert(it != NULL);
2915 seq = it->it_seq;
2916 if (seq == NULL)
2917 return NULL;
2918 assert(PyByteArray_Check(seq));
2919
2920 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
2921 item = PyLong_FromLong(
2922 (unsigned char)seq->ob_bytes[it->it_index]);
2923 if (item != NULL)
2924 ++it->it_index;
2925 return item;
2926 }
2927
2928 Py_DECREF(seq);
2929 it->it_seq = NULL;
2930 return NULL;
2931}
2932
2933static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002934bytesarrayiter_length_hint(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002935{
2936 Py_ssize_t len = 0;
2937 if (it->it_seq)
2938 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
2939 return PyLong_FromSsize_t(len);
2940}
2941
2942PyDoc_STRVAR(length_hint_doc,
2943 "Private method returning an estimate of len(list(it)).");
2944
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002945static PyMethodDef bytearrayiter_methods[] = {
2946 {"__length_hint__", (PyCFunction)bytesarrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002947 length_hint_doc},
2948 {NULL, NULL} /* sentinel */
2949};
2950
2951PyTypeObject PyByteArrayIter_Type = {
2952 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2953 "bytearray_iterator", /* tp_name */
2954 sizeof(bytesiterobject), /* tp_basicsize */
2955 0, /* tp_itemsize */
2956 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002957 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002958 0, /* tp_print */
2959 0, /* tp_getattr */
2960 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002961 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002962 0, /* tp_repr */
2963 0, /* tp_as_number */
2964 0, /* tp_as_sequence */
2965 0, /* tp_as_mapping */
2966 0, /* tp_hash */
2967 0, /* tp_call */
2968 0, /* tp_str */
2969 PyObject_GenericGetAttr, /* tp_getattro */
2970 0, /* tp_setattro */
2971 0, /* tp_as_buffer */
2972 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2973 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002974 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002975 0, /* tp_clear */
2976 0, /* tp_richcompare */
2977 0, /* tp_weaklistoffset */
2978 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002979 (iternextfunc)bytearrayiter_next, /* tp_iternext */
2980 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002981 0,
2982};
2983
2984static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002985bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002986{
2987 bytesiterobject *it;
2988
2989 if (!PyByteArray_Check(seq)) {
2990 PyErr_BadInternalCall();
2991 return NULL;
2992 }
2993 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
2994 if (it == NULL)
2995 return NULL;
2996 it->it_index = 0;
2997 Py_INCREF(seq);
2998 it->it_seq = (PyByteArrayObject *)seq;
2999 _PyObject_GC_TRACK(it);
3000 return (PyObject *)it;
3001}