blob: 823c800a50a0fba9dbd137bcfef8051bbc08ea2d [file] [log] [blame]
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001/* PyByteArray (bytearray) implementation */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
5#include "structmember.h"
6#include "bytes_methods.h"
7
8static PyByteArrayObject *nullbytes = NULL;
9
10void
11PyByteArray_Fini(void)
12{
13 Py_CLEAR(nullbytes);
14}
15
16int
17PyByteArray_Init(void)
18{
19 nullbytes = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
20 if (nullbytes == NULL)
21 return 0;
22 nullbytes->ob_bytes = NULL;
23 Py_SIZE(nullbytes) = nullbytes->ob_alloc = 0;
24 nullbytes->ob_exports = 0;
25 return 1;
26}
27
28/* end nullbytes support */
29
30/* Helpers */
31
32static int
33_getbytevalue(PyObject* arg, int *value)
34{
35 long face_value;
36
37 if (PyLong_Check(arg)) {
38 face_value = PyLong_AsLong(arg);
Georg Brandl9a54d7c2008-07-16 23:15:30 +000039 } else {
40 PyObject *index = PyNumber_Index(arg);
41 if (index == NULL) {
42 PyErr_Format(PyExc_TypeError, "an integer is required");
Christian Heimes2c9c7a52008-05-26 13:42:13 +000043 return 0;
44 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +000045 face_value = PyLong_AsLong(index);
46 Py_DECREF(index);
47 }
48
49 if (face_value < 0 || face_value >= 256) {
50 /* this includes the OverflowError in case the long is too large */
51 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
Christian Heimes2c9c7a52008-05-26 13:42:13 +000052 return 0;
53 }
54
55 *value = face_value;
56 return 1;
57}
58
59static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +000060bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000061{
62 int ret;
63 void *ptr;
64 if (view == NULL) {
65 obj->ob_exports++;
66 return 0;
67 }
68 if (obj->ob_bytes == NULL)
69 ptr = "";
70 else
71 ptr = obj->ob_bytes;
Martin v. Löwis423be952008-08-13 15:53:07 +000072 ret = PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
Christian Heimes2c9c7a52008-05-26 13:42:13 +000073 if (ret >= 0) {
74 obj->ob_exports++;
75 }
76 return ret;
77}
78
79static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +000080bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000081{
82 obj->ob_exports--;
83}
84
85static Py_ssize_t
86_getbuffer(PyObject *obj, Py_buffer *view)
87{
88 PyBufferProcs *buffer = Py_TYPE(obj)->tp_as_buffer;
89
90 if (buffer == NULL || buffer->bf_getbuffer == NULL)
91 {
92 PyErr_Format(PyExc_TypeError,
93 "Type %.100s doesn't support the buffer API",
94 Py_TYPE(obj)->tp_name);
95 return -1;
96 }
97
98 if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0)
99 return -1;
100 return view->len;
101}
102
Antoine Pitrou5504e892008-12-06 21:27:53 +0000103static int
104_canresize(PyByteArrayObject *self)
105{
106 if (self->ob_exports > 0) {
107 PyErr_SetString(PyExc_BufferError,
108 "Existing exports of data: object cannot be re-sized");
109 return 0;
110 }
111 return 1;
112}
113
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000114/* Direct API functions */
115
116PyObject *
117PyByteArray_FromObject(PyObject *input)
118{
119 return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
120 input, NULL);
121}
122
123PyObject *
124PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
125{
126 PyByteArrayObject *new;
127 Py_ssize_t alloc;
128
129 if (size < 0) {
130 PyErr_SetString(PyExc_SystemError,
131 "Negative size passed to PyByteArray_FromStringAndSize");
132 return NULL;
133 }
134
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000135 /* Prevent buffer overflow when setting alloc to size+1. */
136 if (size == PY_SSIZE_T_MAX) {
137 return PyErr_NoMemory();
138 }
139
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000140 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
141 if (new == NULL)
142 return NULL;
143
144 if (size == 0) {
145 new->ob_bytes = NULL;
146 alloc = 0;
147 }
148 else {
149 alloc = size + 1;
150 new->ob_bytes = PyMem_Malloc(alloc);
151 if (new->ob_bytes == NULL) {
152 Py_DECREF(new);
153 return PyErr_NoMemory();
154 }
155 if (bytes != NULL)
156 memcpy(new->ob_bytes, bytes, size);
157 new->ob_bytes[size] = '\0'; /* Trailing null byte */
158 }
159 Py_SIZE(new) = size;
160 new->ob_alloc = alloc;
161 new->ob_exports = 0;
162
163 return (PyObject *)new;
164}
165
166Py_ssize_t
167PyByteArray_Size(PyObject *self)
168{
169 assert(self != NULL);
170 assert(PyByteArray_Check(self));
171
172 return PyByteArray_GET_SIZE(self);
173}
174
175char *
176PyByteArray_AsString(PyObject *self)
177{
178 assert(self != NULL);
179 assert(PyByteArray_Check(self));
180
181 return PyByteArray_AS_STRING(self);
182}
183
184int
185PyByteArray_Resize(PyObject *self, Py_ssize_t size)
186{
187 void *sval;
188 Py_ssize_t alloc = ((PyByteArrayObject *)self)->ob_alloc;
189
190 assert(self != NULL);
191 assert(PyByteArray_Check(self));
192 assert(size >= 0);
193
Antoine Pitrou5504e892008-12-06 21:27:53 +0000194 if (size == Py_SIZE(self)) {
195 return 0;
196 }
197 if (!_canresize((PyByteArrayObject *)self)) {
198 return -1;
199 }
200
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000201 if (size < alloc / 2) {
202 /* Major downsize; resize down to exact size */
203 alloc = size + 1;
204 }
205 else if (size < alloc) {
206 /* Within allocated size; quick exit */
207 Py_SIZE(self) = size;
208 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null */
209 return 0;
210 }
211 else if (size <= alloc * 1.125) {
212 /* Moderate upsize; overallocate similar to list_resize() */
213 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
214 }
215 else {
216 /* Major upsize; resize up to exact size */
217 alloc = size + 1;
218 }
219
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000220 sval = PyMem_Realloc(((PyByteArrayObject *)self)->ob_bytes, alloc);
221 if (sval == NULL) {
222 PyErr_NoMemory();
223 return -1;
224 }
225
226 ((PyByteArrayObject *)self)->ob_bytes = sval;
227 Py_SIZE(self) = size;
228 ((PyByteArrayObject *)self)->ob_alloc = alloc;
229 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null byte */
230
231 return 0;
232}
233
234PyObject *
235PyByteArray_Concat(PyObject *a, PyObject *b)
236{
237 Py_ssize_t size;
238 Py_buffer va, vb;
239 PyByteArrayObject *result = NULL;
240
241 va.len = -1;
242 vb.len = -1;
243 if (_getbuffer(a, &va) < 0 ||
244 _getbuffer(b, &vb) < 0) {
245 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
246 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
247 goto done;
248 }
249
250 size = va.len + vb.len;
251 if (size < 0) {
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000252 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000253 goto done;
254 }
255
256 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
257 if (result != NULL) {
258 memcpy(result->ob_bytes, va.buf, va.len);
259 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
260 }
261
262 done:
263 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000264 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000265 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000266 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000267 return (PyObject *)result;
268}
269
270/* Functions stuffed into the type object */
271
272static Py_ssize_t
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000273bytearray_length(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000274{
275 return Py_SIZE(self);
276}
277
278static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000279bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000280{
281 Py_ssize_t mysize;
282 Py_ssize_t size;
283 Py_buffer vo;
284
285 if (_getbuffer(other, &vo) < 0) {
286 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
287 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
288 return NULL;
289 }
290
291 mysize = Py_SIZE(self);
292 size = mysize + vo.len;
293 if (size < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000294 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000295 return PyErr_NoMemory();
296 }
297 if (size < self->ob_alloc) {
298 Py_SIZE(self) = size;
299 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
300 }
301 else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000302 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000303 return NULL;
304 }
305 memcpy(self->ob_bytes + mysize, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000306 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000307 Py_INCREF(self);
308 return (PyObject *)self;
309}
310
311static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000312bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000313{
314 PyByteArrayObject *result;
315 Py_ssize_t mysize;
316 Py_ssize_t size;
317
318 if (count < 0)
319 count = 0;
320 mysize = Py_SIZE(self);
321 size = mysize * count;
322 if (count != 0 && size / count != mysize)
323 return PyErr_NoMemory();
324 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
325 if (result != NULL && size != 0) {
326 if (mysize == 1)
327 memset(result->ob_bytes, self->ob_bytes[0], size);
328 else {
329 Py_ssize_t i;
330 for (i = 0; i < count; i++)
331 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
332 }
333 }
334 return (PyObject *)result;
335}
336
337static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000338bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000339{
340 Py_ssize_t mysize;
341 Py_ssize_t size;
342
343 if (count < 0)
344 count = 0;
345 mysize = Py_SIZE(self);
346 size = mysize * count;
347 if (count != 0 && size / count != mysize)
348 return PyErr_NoMemory();
349 if (size < self->ob_alloc) {
350 Py_SIZE(self) = size;
351 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
352 }
353 else if (PyByteArray_Resize((PyObject *)self, size) < 0)
354 return NULL;
355
356 if (mysize == 1)
357 memset(self->ob_bytes, self->ob_bytes[0], size);
358 else {
359 Py_ssize_t i;
360 for (i = 1; i < count; i++)
361 memcpy(self->ob_bytes + i*mysize, self->ob_bytes, mysize);
362 }
363
364 Py_INCREF(self);
365 return (PyObject *)self;
366}
367
368static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000369bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000370{
371 if (i < 0)
372 i += Py_SIZE(self);
373 if (i < 0 || i >= Py_SIZE(self)) {
374 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
375 return NULL;
376 }
377 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
378}
379
380static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000381bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000382{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000383 if (PyIndex_Check(index)) {
384 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000385
386 if (i == -1 && PyErr_Occurred())
387 return NULL;
388
389 if (i < 0)
390 i += PyByteArray_GET_SIZE(self);
391
392 if (i < 0 || i >= Py_SIZE(self)) {
393 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
394 return NULL;
395 }
396 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
397 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000398 else if (PySlice_Check(index)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000399 Py_ssize_t start, stop, step, slicelength, cur, i;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000400 if (PySlice_GetIndicesEx((PySliceObject *)index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000401 PyByteArray_GET_SIZE(self),
402 &start, &stop, &step, &slicelength) < 0) {
403 return NULL;
404 }
405
406 if (slicelength <= 0)
407 return PyByteArray_FromStringAndSize("", 0);
408 else if (step == 1) {
409 return PyByteArray_FromStringAndSize(self->ob_bytes + start,
410 slicelength);
411 }
412 else {
413 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000414 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000415 PyObject *result;
416
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000417 result = PyByteArray_FromStringAndSize(NULL, slicelength);
418 if (result == NULL)
419 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000420
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000421 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000422 for (cur = start, i = 0; i < slicelength;
423 cur += step, i++) {
424 result_buf[i] = source_buf[cur];
425 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000426 return result;
427 }
428 }
429 else {
430 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integers");
431 return NULL;
432 }
433}
434
435static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000436bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000437 PyObject *values)
438{
439 Py_ssize_t avail, needed;
440 void *bytes;
441 Py_buffer vbytes;
442 int res = 0;
443
444 vbytes.len = -1;
445 if (values == (PyObject *)self) {
446 /* Make a copy and call this function recursively */
447 int err;
448 values = PyByteArray_FromObject(values);
449 if (values == NULL)
450 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000451 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000452 Py_DECREF(values);
453 return err;
454 }
455 if (values == NULL) {
456 /* del b[lo:hi] */
457 bytes = NULL;
458 needed = 0;
459 }
460 else {
461 if (_getbuffer(values, &vbytes) < 0) {
462 PyErr_Format(PyExc_TypeError,
Georg Brandl3dbca812008-07-23 16:10:53 +0000463 "can't set bytearray slice from %.100s",
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000464 Py_TYPE(values)->tp_name);
465 return -1;
466 }
467 needed = vbytes.len;
468 bytes = vbytes.buf;
469 }
470
471 if (lo < 0)
472 lo = 0;
473 if (hi < lo)
474 hi = lo;
475 if (hi > Py_SIZE(self))
476 hi = Py_SIZE(self);
477
478 avail = hi - lo;
479 if (avail < 0)
480 lo = hi = avail = 0;
481
482 if (avail != needed) {
483 if (avail > needed) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000484 if (!_canresize(self)) {
485 res = -1;
486 goto finish;
487 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000488 /*
489 0 lo hi old_size
490 | |<----avail----->|<-----tomove------>|
491 | |<-needed->|<-----tomove------>|
492 0 lo new_hi new_size
493 */
494 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
495 Py_SIZE(self) - hi);
496 }
497 /* XXX(nnorwitz): need to verify this can't overflow! */
498 if (PyByteArray_Resize((PyObject *)self,
499 Py_SIZE(self) + needed - avail) < 0) {
500 res = -1;
501 goto finish;
502 }
503 if (avail < needed) {
504 /*
505 0 lo hi old_size
506 | |<-avail->|<-----tomove------>|
507 | |<----needed---->|<-----tomove------>|
508 0 lo new_hi new_size
509 */
510 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
511 Py_SIZE(self) - lo - needed);
512 }
513 }
514
515 if (needed > 0)
516 memcpy(self->ob_bytes + lo, bytes, needed);
517
518
519 finish:
520 if (vbytes.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000521 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000522 return res;
523}
524
525static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000526bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000527{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000528 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000529
530 if (i < 0)
531 i += Py_SIZE(self);
532
533 if (i < 0 || i >= Py_SIZE(self)) {
534 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
535 return -1;
536 }
537
538 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000539 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000540
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000541 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000542 return -1;
543
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000544 self->ob_bytes[i] = ival;
545 return 0;
546}
547
548static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000549bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000550{
551 Py_ssize_t start, stop, step, slicelen, needed;
552 char *bytes;
553
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000554 if (PyIndex_Check(index)) {
555 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000556
557 if (i == -1 && PyErr_Occurred())
558 return -1;
559
560 if (i < 0)
561 i += PyByteArray_GET_SIZE(self);
562
563 if (i < 0 || i >= Py_SIZE(self)) {
564 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
565 return -1;
566 }
567
568 if (values == NULL) {
569 /* Fall through to slice assignment */
570 start = i;
571 stop = i + 1;
572 step = 1;
573 slicelen = 1;
574 }
575 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000576 int ival;
577 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000578 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000579 self->ob_bytes[i] = (char)ival;
580 return 0;
581 }
582 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000583 else if (PySlice_Check(index)) {
584 if (PySlice_GetIndicesEx((PySliceObject *)index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000585 PyByteArray_GET_SIZE(self),
586 &start, &stop, &step, &slicelen) < 0) {
587 return -1;
588 }
589 }
590 else {
591 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integer");
592 return -1;
593 }
594
595 if (values == NULL) {
596 bytes = NULL;
597 needed = 0;
598 }
599 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
600 /* Make a copy an call this function recursively */
601 int err;
602 values = PyByteArray_FromObject(values);
603 if (values == NULL)
604 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000605 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000606 Py_DECREF(values);
607 return err;
608 }
609 else {
610 assert(PyByteArray_Check(values));
611 bytes = ((PyByteArrayObject *)values)->ob_bytes;
612 needed = Py_SIZE(values);
613 }
614 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
615 if ((step < 0 && start < stop) ||
616 (step > 0 && start > stop))
617 stop = start;
618 if (step == 1) {
619 if (slicelen != needed) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000620 if (!_canresize(self))
621 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000622 if (slicelen > needed) {
623 /*
624 0 start stop old_size
625 | |<---slicelen--->|<-----tomove------>|
626 | |<-needed->|<-----tomove------>|
627 0 lo new_hi new_size
628 */
629 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
630 Py_SIZE(self) - stop);
631 }
632 if (PyByteArray_Resize((PyObject *)self,
633 Py_SIZE(self) + needed - slicelen) < 0)
634 return -1;
635 if (slicelen < needed) {
636 /*
637 0 lo hi old_size
638 | |<-avail->|<-----tomove------>|
639 | |<----needed---->|<-----tomove------>|
640 0 lo new_hi new_size
641 */
642 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
643 Py_SIZE(self) - start - needed);
644 }
645 }
646
647 if (needed > 0)
648 memcpy(self->ob_bytes + start, bytes, needed);
649
650 return 0;
651 }
652 else {
653 if (needed == 0) {
654 /* Delete slice */
655 Py_ssize_t cur, i;
656
Antoine Pitrou5504e892008-12-06 21:27:53 +0000657 if (!_canresize(self))
658 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000659 if (step < 0) {
660 stop = start + 1;
661 start = stop + step * (slicelen - 1) - 1;
662 step = -step;
663 }
664 for (cur = start, i = 0;
665 i < slicelen; cur += step, i++) {
666 Py_ssize_t lim = step - 1;
667
668 if (cur + step >= PyByteArray_GET_SIZE(self))
669 lim = PyByteArray_GET_SIZE(self) - cur - 1;
670
671 memmove(self->ob_bytes + cur - i,
672 self->ob_bytes + cur + 1, lim);
673 }
674 /* Move the tail of the bytes, in one chunk */
675 cur = start + slicelen*step;
676 if (cur < PyByteArray_GET_SIZE(self)) {
677 memmove(self->ob_bytes + cur - slicelen,
678 self->ob_bytes + cur,
679 PyByteArray_GET_SIZE(self) - cur);
680 }
681 if (PyByteArray_Resize((PyObject *)self,
682 PyByteArray_GET_SIZE(self) - slicelen) < 0)
683 return -1;
684
685 return 0;
686 }
687 else {
688 /* Assign slice */
689 Py_ssize_t cur, i;
690
691 if (needed != slicelen) {
692 PyErr_Format(PyExc_ValueError,
693 "attempt to assign bytes of size %zd "
694 "to extended slice of size %zd",
695 needed, slicelen);
696 return -1;
697 }
698 for (cur = start, i = 0; i < slicelen; cur += step, i++)
699 self->ob_bytes[cur] = bytes[i];
700 return 0;
701 }
702 }
703}
704
705static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000706bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000707{
708 static char *kwlist[] = {"source", "encoding", "errors", 0};
709 PyObject *arg = NULL;
710 const char *encoding = NULL;
711 const char *errors = NULL;
712 Py_ssize_t count;
713 PyObject *it;
714 PyObject *(*iternext)(PyObject *);
715
716 if (Py_SIZE(self) != 0) {
717 /* Empty previous contents (yes, do this first of all!) */
718 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
719 return -1;
720 }
721
722 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000723 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000724 &arg, &encoding, &errors))
725 return -1;
726
727 /* Make a quick exit if no first argument */
728 if (arg == NULL) {
729 if (encoding != NULL || errors != NULL) {
730 PyErr_SetString(PyExc_TypeError,
731 "encoding or errors without sequence argument");
732 return -1;
733 }
734 return 0;
735 }
736
737 if (PyUnicode_Check(arg)) {
738 /* Encode via the codec registry */
739 PyObject *encoded, *new;
740 if (encoding == NULL) {
741 PyErr_SetString(PyExc_TypeError,
742 "string argument without an encoding");
743 return -1;
744 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000745 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000746 if (encoded == NULL)
747 return -1;
748 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000749 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000750 Py_DECREF(encoded);
751 if (new == NULL)
752 return -1;
753 Py_DECREF(new);
754 return 0;
755 }
756
757 /* If it's not unicode, there can't be encoding or errors */
758 if (encoding != NULL || errors != NULL) {
759 PyErr_SetString(PyExc_TypeError,
760 "encoding or errors without a string argument");
761 return -1;
762 }
763
764 /* Is it an int? */
765 count = PyNumber_AsSsize_t(arg, PyExc_ValueError);
766 if (count == -1 && PyErr_Occurred())
767 PyErr_Clear();
768 else {
769 if (count < 0) {
770 PyErr_SetString(PyExc_ValueError, "negative count");
771 return -1;
772 }
773 if (count > 0) {
774 if (PyByteArray_Resize((PyObject *)self, count))
775 return -1;
776 memset(self->ob_bytes, 0, count);
777 }
778 return 0;
779 }
780
781 /* Use the buffer API */
782 if (PyObject_CheckBuffer(arg)) {
783 Py_ssize_t size;
784 Py_buffer view;
785 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
786 return -1;
787 size = view.len;
788 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
789 if (PyBuffer_ToContiguous(self->ob_bytes, &view, size, 'C') < 0)
790 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000791 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000792 return 0;
793 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000794 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000795 return -1;
796 }
797
798 /* XXX Optimize this if the arguments is a list, tuple */
799
800 /* Get the iterator */
801 it = PyObject_GetIter(arg);
802 if (it == NULL)
803 return -1;
804 iternext = *Py_TYPE(it)->tp_iternext;
805
806 /* Run the iterator to exhaustion */
807 for (;;) {
808 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000809 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000810
811 /* Get the next item */
812 item = iternext(it);
813 if (item == NULL) {
814 if (PyErr_Occurred()) {
815 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
816 goto error;
817 PyErr_Clear();
818 }
819 break;
820 }
821
822 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000823 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000824 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000825 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000826 goto error;
827
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000828 /* Append the byte */
829 if (Py_SIZE(self) < self->ob_alloc)
830 Py_SIZE(self)++;
831 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
832 goto error;
833 self->ob_bytes[Py_SIZE(self)-1] = value;
834 }
835
836 /* Clean up and return success */
837 Py_DECREF(it);
838 return 0;
839
840 error:
841 /* Error handling when it != NULL */
842 Py_DECREF(it);
843 return -1;
844}
845
846/* Mostly copied from string_repr, but without the
847 "smart quote" functionality. */
848static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000849bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000850{
851 static const char *hexdigits = "0123456789abcdef";
852 const char *quote_prefix = "bytearray(b";
853 const char *quote_postfix = ")";
854 Py_ssize_t length = Py_SIZE(self);
855 /* 14 == strlen(quote_prefix) + 2 + strlen(quote_postfix) */
856 size_t newsize = 14 + 4 * length;
857 PyObject *v;
858 if (newsize > PY_SSIZE_T_MAX || newsize / 4 - 3 != length) {
859 PyErr_SetString(PyExc_OverflowError,
860 "bytearray object is too large to make repr");
861 return NULL;
862 }
863 v = PyUnicode_FromUnicode(NULL, newsize);
864 if (v == NULL) {
865 return NULL;
866 }
867 else {
868 register Py_ssize_t i;
869 register Py_UNICODE c;
870 register Py_UNICODE *p;
871 int quote;
872
873 /* Figure out which quote to use; single is preferred */
874 quote = '\'';
875 {
876 char *test, *start;
877 start = PyByteArray_AS_STRING(self);
878 for (test = start; test < start+length; ++test) {
879 if (*test == '"') {
880 quote = '\''; /* back to single */
881 goto decided;
882 }
883 else if (*test == '\'')
884 quote = '"';
885 }
886 decided:
887 ;
888 }
889
890 p = PyUnicode_AS_UNICODE(v);
891 while (*quote_prefix)
892 *p++ = *quote_prefix++;
893 *p++ = quote;
894
895 for (i = 0; i < length; i++) {
896 /* There's at least enough room for a hex escape
897 and a closing quote. */
898 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5);
899 c = self->ob_bytes[i];
900 if (c == '\'' || c == '\\')
901 *p++ = '\\', *p++ = c;
902 else if (c == '\t')
903 *p++ = '\\', *p++ = 't';
904 else if (c == '\n')
905 *p++ = '\\', *p++ = 'n';
906 else if (c == '\r')
907 *p++ = '\\', *p++ = 'r';
908 else if (c == 0)
909 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
910 else if (c < ' ' || c >= 0x7f) {
911 *p++ = '\\';
912 *p++ = 'x';
913 *p++ = hexdigits[(c & 0xf0) >> 4];
914 *p++ = hexdigits[c & 0xf];
915 }
916 else
917 *p++ = c;
918 }
919 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1);
920 *p++ = quote;
921 while (*quote_postfix) {
922 *p++ = *quote_postfix++;
923 }
924 *p = '\0';
925 if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) {
926 Py_DECREF(v);
927 return NULL;
928 }
929 return v;
930 }
931}
932
933static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000934bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000935{
936 if (Py_BytesWarningFlag) {
937 if (PyErr_WarnEx(PyExc_BytesWarning,
938 "str() on a bytearray instance", 1))
939 return NULL;
940 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000941 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000942}
943
944static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000945bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000946{
947 Py_ssize_t self_size, other_size;
948 Py_buffer self_bytes, other_bytes;
949 PyObject *res;
950 Py_ssize_t minsize;
951 int cmp;
952
953 /* Bytes can be compared to anything that supports the (binary)
954 buffer API. Except that a comparison with Unicode is always an
955 error, even if the comparison is for equality. */
956 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
957 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
Barry Warsaw9e9dcd62008-10-17 01:50:37 +0000958 if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000959 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +0000960 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000961 return NULL;
962 }
963
964 Py_INCREF(Py_NotImplemented);
965 return Py_NotImplemented;
966 }
967
968 self_size = _getbuffer(self, &self_bytes);
969 if (self_size < 0) {
970 PyErr_Clear();
971 Py_INCREF(Py_NotImplemented);
972 return Py_NotImplemented;
973 }
974
975 other_size = _getbuffer(other, &other_bytes);
976 if (other_size < 0) {
977 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +0000978 PyBuffer_Release(&self_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000979 Py_INCREF(Py_NotImplemented);
980 return Py_NotImplemented;
981 }
982
983 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
984 /* Shortcut: if the lengths differ, the objects differ */
985 cmp = (op == Py_NE);
986 }
987 else {
988 minsize = self_size;
989 if (other_size < minsize)
990 minsize = other_size;
991
992 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
993 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
994
995 if (cmp == 0) {
996 if (self_size < other_size)
997 cmp = -1;
998 else if (self_size > other_size)
999 cmp = 1;
1000 }
1001
1002 switch (op) {
1003 case Py_LT: cmp = cmp < 0; break;
1004 case Py_LE: cmp = cmp <= 0; break;
1005 case Py_EQ: cmp = cmp == 0; break;
1006 case Py_NE: cmp = cmp != 0; break;
1007 case Py_GT: cmp = cmp > 0; break;
1008 case Py_GE: cmp = cmp >= 0; break;
1009 }
1010 }
1011
1012 res = cmp ? Py_True : Py_False;
Martin v. Löwis423be952008-08-13 15:53:07 +00001013 PyBuffer_Release(&self_bytes);
1014 PyBuffer_Release(&other_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001015 Py_INCREF(res);
1016 return res;
1017}
1018
1019static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001020bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001021{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001022 if (self->ob_exports > 0) {
1023 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001024 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001025 PyErr_Print();
1026 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001027 if (self->ob_bytes != 0) {
1028 PyMem_Free(self->ob_bytes);
1029 }
1030 Py_TYPE(self)->tp_free((PyObject *)self);
1031}
1032
1033
1034/* -------------------------------------------------------------------- */
1035/* Methods */
1036
1037#define STRINGLIB_CHAR char
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001038#define STRINGLIB_LEN PyByteArray_GET_SIZE
1039#define STRINGLIB_STR PyByteArray_AS_STRING
1040#define STRINGLIB_NEW PyByteArray_FromStringAndSize
1041#define STRINGLIB_EMPTY nullbytes
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001042#define STRINGLIB_ISSPACE Py_ISSPACE
1043#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001044#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1045#define STRINGLIB_MUTABLE 1
1046
1047#include "stringlib/fastsearch.h"
1048#include "stringlib/count.h"
1049#include "stringlib/find.h"
1050#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001051#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001052#include "stringlib/ctype.h"
1053#include "stringlib/transmogrify.h"
1054
1055
1056/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1057were copied from the old char* style string object. */
1058
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001059/* helper macro to fixup start/end slice values */
1060#define ADJUST_INDICES(start, end, len) \
1061 if (end > len) \
1062 end = len; \
1063 else if (end < 0) { \
1064 end += len; \
1065 if (end < 0) \
1066 end = 0; \
1067 } \
1068 if (start < 0) { \
1069 start += len; \
1070 if (start < 0) \
1071 start = 0; \
1072 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001073
1074Py_LOCAL_INLINE(Py_ssize_t)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001075bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001076{
1077 PyObject *subobj;
1078 Py_buffer subbuf;
1079 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1080 Py_ssize_t res;
1081
1082 if (!PyArg_ParseTuple(args, "O|O&O&:find/rfind/index/rindex", &subobj,
1083 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1084 return -2;
1085 if (_getbuffer(subobj, &subbuf) < 0)
1086 return -2;
1087 if (dir > 0)
1088 res = stringlib_find_slice(
1089 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1090 subbuf.buf, subbuf.len, start, end);
1091 else
1092 res = stringlib_rfind_slice(
1093 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1094 subbuf.buf, subbuf.len, start, end);
Martin v. Löwis423be952008-08-13 15:53:07 +00001095 PyBuffer_Release(&subbuf);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001096 return res;
1097}
1098
1099PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001100"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001101\n\
1102Return the lowest index in B where subsection sub is found,\n\
1103such that sub is contained within s[start,end]. Optional\n\
1104arguments start and end are interpreted as in slice notation.\n\
1105\n\
1106Return -1 on failure.");
1107
1108static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001109bytearray_find(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001110{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001111 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001112 if (result == -2)
1113 return NULL;
1114 return PyLong_FromSsize_t(result);
1115}
1116
1117PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001118"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001119\n\
1120Return the number of non-overlapping occurrences of subsection sub in\n\
1121bytes B[start:end]. Optional arguments start and end are interpreted\n\
1122as in slice notation.");
1123
1124static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001125bytearray_count(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001126{
1127 PyObject *sub_obj;
1128 const char *str = PyByteArray_AS_STRING(self);
1129 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
1130 Py_buffer vsub;
1131 PyObject *count_obj;
1132
1133 if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj,
1134 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1135 return NULL;
1136
1137 if (_getbuffer(sub_obj, &vsub) < 0)
1138 return NULL;
1139
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001140 ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001141
1142 count_obj = PyLong_FromSsize_t(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001143 stringlib_count(str + start, end - start, vsub.buf, vsub.len, PY_SSIZE_T_MAX)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001144 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001145 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001146 return count_obj;
1147}
1148
1149
1150PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001151"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001152\n\
1153Like B.find() but raise ValueError when the subsection is not found.");
1154
1155static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001156bytearray_index(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001157{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001158 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001159 if (result == -2)
1160 return NULL;
1161 if (result == -1) {
1162 PyErr_SetString(PyExc_ValueError,
1163 "subsection not found");
1164 return NULL;
1165 }
1166 return PyLong_FromSsize_t(result);
1167}
1168
1169
1170PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001171"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001172\n\
1173Return the highest index in B where subsection sub is found,\n\
1174such that sub is contained within s[start,end]. Optional\n\
1175arguments start and end are interpreted as in slice notation.\n\
1176\n\
1177Return -1 on failure.");
1178
1179static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001180bytearray_rfind(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001181{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001182 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001183 if (result == -2)
1184 return NULL;
1185 return PyLong_FromSsize_t(result);
1186}
1187
1188
1189PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001190"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001191\n\
1192Like B.rfind() but raise ValueError when the subsection is not found.");
1193
1194static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001195bytearray_rindex(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001196{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001197 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001198 if (result == -2)
1199 return NULL;
1200 if (result == -1) {
1201 PyErr_SetString(PyExc_ValueError,
1202 "subsection not found");
1203 return NULL;
1204 }
1205 return PyLong_FromSsize_t(result);
1206}
1207
1208
1209static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001210bytearray_contains(PyObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001211{
1212 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1213 if (ival == -1 && PyErr_Occurred()) {
1214 Py_buffer varg;
1215 int pos;
1216 PyErr_Clear();
1217 if (_getbuffer(arg, &varg) < 0)
1218 return -1;
1219 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1220 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001221 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001222 return pos >= 0;
1223 }
1224 if (ival < 0 || ival >= 256) {
1225 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1226 return -1;
1227 }
1228
1229 return memchr(PyByteArray_AS_STRING(self), ival, Py_SIZE(self)) != NULL;
1230}
1231
1232
1233/* Matches the end (direction >= 0) or start (direction < 0) of self
1234 * against substr, using the start and end arguments. Returns
1235 * -1 on error, 0 if not found and 1 if found.
1236 */
1237Py_LOCAL(int)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001238_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001239 Py_ssize_t end, int direction)
1240{
1241 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1242 const char* str;
1243 Py_buffer vsubstr;
1244 int rv = 0;
1245
1246 str = PyByteArray_AS_STRING(self);
1247
1248 if (_getbuffer(substr, &vsubstr) < 0)
1249 return -1;
1250
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001251 ADJUST_INDICES(start, end, len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001252
1253 if (direction < 0) {
1254 /* startswith */
1255 if (start+vsubstr.len > len) {
1256 goto done;
1257 }
1258 } else {
1259 /* endswith */
1260 if (end-start < vsubstr.len || start > len) {
1261 goto done;
1262 }
1263
1264 if (end-vsubstr.len > start)
1265 start = end - vsubstr.len;
1266 }
1267 if (end-start >= vsubstr.len)
1268 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1269
1270done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001271 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001272 return rv;
1273}
1274
1275
1276PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001277"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001278\n\
1279Return True if B starts with the specified prefix, False otherwise.\n\
1280With optional start, test B beginning at that position.\n\
1281With optional end, stop comparing B at that position.\n\
1282prefix can also be a tuple of strings to try.");
1283
1284static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001285bytearray_startswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001286{
1287 Py_ssize_t start = 0;
1288 Py_ssize_t end = PY_SSIZE_T_MAX;
1289 PyObject *subobj;
1290 int result;
1291
1292 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
1293 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1294 return NULL;
1295 if (PyTuple_Check(subobj)) {
1296 Py_ssize_t i;
1297 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001298 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001299 PyTuple_GET_ITEM(subobj, i),
1300 start, end, -1);
1301 if (result == -1)
1302 return NULL;
1303 else if (result) {
1304 Py_RETURN_TRUE;
1305 }
1306 }
1307 Py_RETURN_FALSE;
1308 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001309 result = _bytearray_tailmatch(self, subobj, start, end, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001310 if (result == -1)
1311 return NULL;
1312 else
1313 return PyBool_FromLong(result);
1314}
1315
1316PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001317"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001318\n\
1319Return True if B ends with the specified suffix, False otherwise.\n\
1320With optional start, test B beginning at that position.\n\
1321With optional end, stop comparing B at that position.\n\
1322suffix can also be a tuple of strings to try.");
1323
1324static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001325bytearray_endswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001326{
1327 Py_ssize_t start = 0;
1328 Py_ssize_t end = PY_SSIZE_T_MAX;
1329 PyObject *subobj;
1330 int result;
1331
1332 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
1333 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1334 return NULL;
1335 if (PyTuple_Check(subobj)) {
1336 Py_ssize_t i;
1337 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001338 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001339 PyTuple_GET_ITEM(subobj, i),
1340 start, end, +1);
1341 if (result == -1)
1342 return NULL;
1343 else if (result) {
1344 Py_RETURN_TRUE;
1345 }
1346 }
1347 Py_RETURN_FALSE;
1348 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001349 result = _bytearray_tailmatch(self, subobj, start, end, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001350 if (result == -1)
1351 return NULL;
1352 else
1353 return PyBool_FromLong(result);
1354}
1355
1356
1357PyDoc_STRVAR(translate__doc__,
1358"B.translate(table[, deletechars]) -> bytearray\n\
1359\n\
1360Return a copy of B, where all characters occurring in the\n\
1361optional argument deletechars are removed, and the remaining\n\
1362characters have been mapped through the given translation\n\
1363table, which must be a bytes object of length 256.");
1364
1365static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001366bytearray_translate(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001367{
1368 register char *input, *output;
1369 register const char *table;
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001370 register Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001371 PyObject *input_obj = (PyObject*)self;
1372 const char *output_start;
1373 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001374 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001375 int trans_table[256];
Georg Brandlccc47b62008-12-28 11:44:14 +00001376 PyObject *tableobj = NULL, *delobj = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001377 Py_buffer vtable, vdel;
1378
1379 if (!PyArg_UnpackTuple(args, "translate", 1, 2,
1380 &tableobj, &delobj))
1381 return NULL;
1382
Georg Brandlccc47b62008-12-28 11:44:14 +00001383 if (tableobj == Py_None) {
1384 table = NULL;
1385 tableobj = NULL;
1386 } else if (_getbuffer(tableobj, &vtable) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001387 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001388 } else {
1389 if (vtable.len != 256) {
1390 PyErr_SetString(PyExc_ValueError,
1391 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001392 PyBuffer_Release(&vtable);
1393 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001394 }
1395 table = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001396 }
1397
1398 if (delobj != NULL) {
1399 if (_getbuffer(delobj, &vdel) < 0) {
Georg Brandl953152f2009-07-22 12:03:59 +00001400 if (tableobj != NULL)
1401 PyBuffer_Release(&vtable);
1402 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001403 }
1404 }
1405 else {
1406 vdel.buf = NULL;
1407 vdel.len = 0;
1408 }
1409
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001410 inlen = PyByteArray_GET_SIZE(input_obj);
1411 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1412 if (result == NULL)
1413 goto done;
1414 output_start = output = PyByteArray_AsString(result);
1415 input = PyByteArray_AS_STRING(input_obj);
1416
Georg Brandlccc47b62008-12-28 11:44:14 +00001417 if (vdel.len == 0 && table != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001418 /* If no deletions are required, use faster code */
1419 for (i = inlen; --i >= 0; ) {
1420 c = Py_CHARMASK(*input++);
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001421 *output++ = table[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001422 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001423 goto done;
1424 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001425
1426 if (table == NULL) {
1427 for (i = 0; i < 256; i++)
1428 trans_table[i] = Py_CHARMASK(i);
1429 } else {
1430 for (i = 0; i < 256; i++)
1431 trans_table[i] = Py_CHARMASK(table[i]);
1432 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001433
1434 for (i = 0; i < vdel.len; i++)
1435 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1436
1437 for (i = inlen; --i >= 0; ) {
1438 c = Py_CHARMASK(*input++);
1439 if (trans_table[c] != -1)
1440 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1441 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001442 }
1443 /* Fix the size of the resulting string */
1444 if (inlen > 0)
1445 PyByteArray_Resize(result, output - output_start);
1446
1447done:
Georg Brandlccc47b62008-12-28 11:44:14 +00001448 if (tableobj != NULL)
1449 PyBuffer_Release(&vtable);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001450 if (delobj != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001451 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001452 return result;
1453}
1454
1455
Georg Brandlabc38772009-04-12 15:51:51 +00001456static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001457bytearray_maketrans(PyObject *null, PyObject *args)
Georg Brandlabc38772009-04-12 15:51:51 +00001458{
1459 return _Py_bytes_maketrans(args);
1460}
1461
1462
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001463/* find and count characters and substrings */
1464
1465#define findchar(target, target_len, c) \
1466 ((char *)memchr((const void *)(target), c, target_len))
1467
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001468
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001469/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001470Py_LOCAL(PyByteArrayObject *)
1471return_self(PyByteArrayObject *self)
1472{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001473 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001474 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1475 PyByteArray_AS_STRING(self),
1476 PyByteArray_GET_SIZE(self));
1477}
1478
1479Py_LOCAL_INLINE(Py_ssize_t)
1480countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1481{
1482 Py_ssize_t count=0;
1483 const char *start=target;
1484 const char *end=target+target_len;
1485
1486 while ( (start=findchar(start, end-start, c)) != NULL ) {
1487 count++;
1488 if (count >= maxcount)
1489 break;
1490 start += 1;
1491 }
1492 return count;
1493}
1494
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001495
1496/* Algorithms for different cases of string replacement */
1497
1498/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1499Py_LOCAL(PyByteArrayObject *)
1500replace_interleave(PyByteArrayObject *self,
1501 const char *to_s, Py_ssize_t to_len,
1502 Py_ssize_t maxcount)
1503{
1504 char *self_s, *result_s;
1505 Py_ssize_t self_len, result_len;
1506 Py_ssize_t count, i, product;
1507 PyByteArrayObject *result;
1508
1509 self_len = PyByteArray_GET_SIZE(self);
1510
1511 /* 1 at the end plus 1 after every character */
1512 count = self_len+1;
1513 if (maxcount < count)
1514 count = maxcount;
1515
1516 /* Check for overflow */
1517 /* result_len = count * to_len + self_len; */
1518 product = count * to_len;
1519 if (product / to_len != count) {
1520 PyErr_SetString(PyExc_OverflowError,
1521 "replace string is too long");
1522 return NULL;
1523 }
1524 result_len = product + self_len;
1525 if (result_len < 0) {
1526 PyErr_SetString(PyExc_OverflowError,
1527 "replace string is too long");
1528 return NULL;
1529 }
1530
1531 if (! (result = (PyByteArrayObject *)
1532 PyByteArray_FromStringAndSize(NULL, result_len)) )
1533 return NULL;
1534
1535 self_s = PyByteArray_AS_STRING(self);
1536 result_s = PyByteArray_AS_STRING(result);
1537
1538 /* TODO: special case single character, which doesn't need memcpy */
1539
1540 /* Lay the first one down (guaranteed this will occur) */
1541 Py_MEMCPY(result_s, to_s, to_len);
1542 result_s += to_len;
1543 count -= 1;
1544
1545 for (i=0; i<count; i++) {
1546 *result_s++ = *self_s++;
1547 Py_MEMCPY(result_s, to_s, to_len);
1548 result_s += to_len;
1549 }
1550
1551 /* Copy the rest of the original string */
1552 Py_MEMCPY(result_s, self_s, self_len-i);
1553
1554 return result;
1555}
1556
1557/* Special case for deleting a single character */
1558/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1559Py_LOCAL(PyByteArrayObject *)
1560replace_delete_single_character(PyByteArrayObject *self,
1561 char from_c, Py_ssize_t maxcount)
1562{
1563 char *self_s, *result_s;
1564 char *start, *next, *end;
1565 Py_ssize_t self_len, result_len;
1566 Py_ssize_t count;
1567 PyByteArrayObject *result;
1568
1569 self_len = PyByteArray_GET_SIZE(self);
1570 self_s = PyByteArray_AS_STRING(self);
1571
1572 count = countchar(self_s, self_len, from_c, maxcount);
1573 if (count == 0) {
1574 return return_self(self);
1575 }
1576
1577 result_len = self_len - count; /* from_len == 1 */
1578 assert(result_len>=0);
1579
1580 if ( (result = (PyByteArrayObject *)
1581 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1582 return NULL;
1583 result_s = PyByteArray_AS_STRING(result);
1584
1585 start = self_s;
1586 end = self_s + self_len;
1587 while (count-- > 0) {
1588 next = findchar(start, end-start, from_c);
1589 if (next == NULL)
1590 break;
1591 Py_MEMCPY(result_s, start, next-start);
1592 result_s += (next-start);
1593 start = next+1;
1594 }
1595 Py_MEMCPY(result_s, start, end-start);
1596
1597 return result;
1598}
1599
1600/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1601
1602Py_LOCAL(PyByteArrayObject *)
1603replace_delete_substring(PyByteArrayObject *self,
1604 const char *from_s, Py_ssize_t from_len,
1605 Py_ssize_t maxcount)
1606{
1607 char *self_s, *result_s;
1608 char *start, *next, *end;
1609 Py_ssize_t self_len, result_len;
1610 Py_ssize_t count, offset;
1611 PyByteArrayObject *result;
1612
1613 self_len = PyByteArray_GET_SIZE(self);
1614 self_s = PyByteArray_AS_STRING(self);
1615
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001616 count = stringlib_count(self_s, self_len,
1617 from_s, from_len,
1618 maxcount);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001619
1620 if (count == 0) {
1621 /* no matches */
1622 return return_self(self);
1623 }
1624
1625 result_len = self_len - (count * from_len);
1626 assert (result_len>=0);
1627
1628 if ( (result = (PyByteArrayObject *)
1629 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1630 return NULL;
1631
1632 result_s = PyByteArray_AS_STRING(result);
1633
1634 start = self_s;
1635 end = self_s + self_len;
1636 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001637 offset = stringlib_find(start, end-start,
1638 from_s, from_len,
1639 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001640 if (offset == -1)
1641 break;
1642 next = start + offset;
1643
1644 Py_MEMCPY(result_s, start, next-start);
1645
1646 result_s += (next-start);
1647 start = next+from_len;
1648 }
1649 Py_MEMCPY(result_s, start, end-start);
1650 return result;
1651}
1652
1653/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1654Py_LOCAL(PyByteArrayObject *)
1655replace_single_character_in_place(PyByteArrayObject *self,
1656 char from_c, char to_c,
1657 Py_ssize_t maxcount)
1658{
1659 char *self_s, *result_s, *start, *end, *next;
1660 Py_ssize_t self_len;
1661 PyByteArrayObject *result;
1662
1663 /* The result string will be the same size */
1664 self_s = PyByteArray_AS_STRING(self);
1665 self_len = PyByteArray_GET_SIZE(self);
1666
1667 next = findchar(self_s, self_len, from_c);
1668
1669 if (next == NULL) {
1670 /* No matches; return the original bytes */
1671 return return_self(self);
1672 }
1673
1674 /* Need to make a new bytes */
1675 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1676 if (result == NULL)
1677 return NULL;
1678 result_s = PyByteArray_AS_STRING(result);
1679 Py_MEMCPY(result_s, self_s, self_len);
1680
1681 /* change everything in-place, starting with this one */
1682 start = result_s + (next-self_s);
1683 *start = to_c;
1684 start++;
1685 end = result_s + self_len;
1686
1687 while (--maxcount > 0) {
1688 next = findchar(start, end-start, from_c);
1689 if (next == NULL)
1690 break;
1691 *next = to_c;
1692 start = next+1;
1693 }
1694
1695 return result;
1696}
1697
1698/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1699Py_LOCAL(PyByteArrayObject *)
1700replace_substring_in_place(PyByteArrayObject *self,
1701 const char *from_s, Py_ssize_t from_len,
1702 const char *to_s, Py_ssize_t to_len,
1703 Py_ssize_t maxcount)
1704{
1705 char *result_s, *start, *end;
1706 char *self_s;
1707 Py_ssize_t self_len, offset;
1708 PyByteArrayObject *result;
1709
1710 /* The result bytes will be the same size */
1711
1712 self_s = PyByteArray_AS_STRING(self);
1713 self_len = PyByteArray_GET_SIZE(self);
1714
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001715 offset = stringlib_find(self_s, self_len,
1716 from_s, from_len,
1717 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001718 if (offset == -1) {
1719 /* No matches; return the original bytes */
1720 return return_self(self);
1721 }
1722
1723 /* Need to make a new bytes */
1724 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1725 if (result == NULL)
1726 return NULL;
1727 result_s = PyByteArray_AS_STRING(result);
1728 Py_MEMCPY(result_s, self_s, self_len);
1729
1730 /* change everything in-place, starting with this one */
1731 start = result_s + offset;
1732 Py_MEMCPY(start, to_s, from_len);
1733 start += from_len;
1734 end = result_s + self_len;
1735
1736 while ( --maxcount > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001737 offset = stringlib_find(start, end-start,
1738 from_s, from_len,
1739 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001740 if (offset==-1)
1741 break;
1742 Py_MEMCPY(start+offset, to_s, from_len);
1743 start += offset+from_len;
1744 }
1745
1746 return result;
1747}
1748
1749/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
1750Py_LOCAL(PyByteArrayObject *)
1751replace_single_character(PyByteArrayObject *self,
1752 char from_c,
1753 const char *to_s, Py_ssize_t to_len,
1754 Py_ssize_t maxcount)
1755{
1756 char *self_s, *result_s;
1757 char *start, *next, *end;
1758 Py_ssize_t self_len, result_len;
1759 Py_ssize_t count, product;
1760 PyByteArrayObject *result;
1761
1762 self_s = PyByteArray_AS_STRING(self);
1763 self_len = PyByteArray_GET_SIZE(self);
1764
1765 count = countchar(self_s, self_len, from_c, maxcount);
1766 if (count == 0) {
1767 /* no matches, return unchanged */
1768 return return_self(self);
1769 }
1770
1771 /* use the difference between current and new, hence the "-1" */
1772 /* result_len = self_len + count * (to_len-1) */
1773 product = count * (to_len-1);
1774 if (product / (to_len-1) != count) {
1775 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1776 return NULL;
1777 }
1778 result_len = self_len + product;
1779 if (result_len < 0) {
1780 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1781 return NULL;
1782 }
1783
1784 if ( (result = (PyByteArrayObject *)
1785 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1786 return NULL;
1787 result_s = PyByteArray_AS_STRING(result);
1788
1789 start = self_s;
1790 end = self_s + self_len;
1791 while (count-- > 0) {
1792 next = findchar(start, end-start, from_c);
1793 if (next == NULL)
1794 break;
1795
1796 if (next == start) {
1797 /* replace with the 'to' */
1798 Py_MEMCPY(result_s, to_s, to_len);
1799 result_s += to_len;
1800 start += 1;
1801 } else {
1802 /* copy the unchanged old then the 'to' */
1803 Py_MEMCPY(result_s, start, next-start);
1804 result_s += (next-start);
1805 Py_MEMCPY(result_s, to_s, to_len);
1806 result_s += to_len;
1807 start = next+1;
1808 }
1809 }
1810 /* Copy the remainder of the remaining bytes */
1811 Py_MEMCPY(result_s, start, end-start);
1812
1813 return result;
1814}
1815
1816/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
1817Py_LOCAL(PyByteArrayObject *)
1818replace_substring(PyByteArrayObject *self,
1819 const char *from_s, Py_ssize_t from_len,
1820 const char *to_s, Py_ssize_t to_len,
1821 Py_ssize_t maxcount)
1822{
1823 char *self_s, *result_s;
1824 char *start, *next, *end;
1825 Py_ssize_t self_len, result_len;
1826 Py_ssize_t count, offset, product;
1827 PyByteArrayObject *result;
1828
1829 self_s = PyByteArray_AS_STRING(self);
1830 self_len = PyByteArray_GET_SIZE(self);
1831
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001832 count = stringlib_count(self_s, self_len,
1833 from_s, from_len,
1834 maxcount);
1835
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001836 if (count == 0) {
1837 /* no matches, return unchanged */
1838 return return_self(self);
1839 }
1840
1841 /* Check for overflow */
1842 /* result_len = self_len + count * (to_len-from_len) */
1843 product = count * (to_len-from_len);
1844 if (product / (to_len-from_len) != count) {
1845 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1846 return NULL;
1847 }
1848 result_len = self_len + product;
1849 if (result_len < 0) {
1850 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1851 return NULL;
1852 }
1853
1854 if ( (result = (PyByteArrayObject *)
1855 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1856 return NULL;
1857 result_s = PyByteArray_AS_STRING(result);
1858
1859 start = self_s;
1860 end = self_s + self_len;
1861 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001862 offset = stringlib_find(start, end-start,
1863 from_s, from_len,
1864 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001865 if (offset == -1)
1866 break;
1867 next = start+offset;
1868 if (next == start) {
1869 /* replace with the 'to' */
1870 Py_MEMCPY(result_s, to_s, to_len);
1871 result_s += to_len;
1872 start += from_len;
1873 } else {
1874 /* copy the unchanged old then the 'to' */
1875 Py_MEMCPY(result_s, start, next-start);
1876 result_s += (next-start);
1877 Py_MEMCPY(result_s, to_s, to_len);
1878 result_s += to_len;
1879 start = next+from_len;
1880 }
1881 }
1882 /* Copy the remainder of the remaining bytes */
1883 Py_MEMCPY(result_s, start, end-start);
1884
1885 return result;
1886}
1887
1888
1889Py_LOCAL(PyByteArrayObject *)
1890replace(PyByteArrayObject *self,
1891 const char *from_s, Py_ssize_t from_len,
1892 const char *to_s, Py_ssize_t to_len,
1893 Py_ssize_t maxcount)
1894{
1895 if (maxcount < 0) {
1896 maxcount = PY_SSIZE_T_MAX;
1897 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
1898 /* nothing to do; return the original bytes */
1899 return return_self(self);
1900 }
1901
1902 if (maxcount == 0 ||
1903 (from_len == 0 && to_len == 0)) {
1904 /* nothing to do; return the original bytes */
1905 return return_self(self);
1906 }
1907
1908 /* Handle zero-length special cases */
1909
1910 if (from_len == 0) {
1911 /* insert the 'to' bytes everywhere. */
1912 /* >>> "Python".replace("", ".") */
1913 /* '.P.y.t.h.o.n.' */
1914 return replace_interleave(self, to_s, to_len, maxcount);
1915 }
1916
1917 /* Except for "".replace("", "A") == "A" there is no way beyond this */
1918 /* point for an empty self bytes to generate a non-empty bytes */
1919 /* Special case so the remaining code always gets a non-empty bytes */
1920 if (PyByteArray_GET_SIZE(self) == 0) {
1921 return return_self(self);
1922 }
1923
1924 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00001925 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001926 if (from_len == 1) {
1927 return replace_delete_single_character(
1928 self, from_s[0], maxcount);
1929 } else {
1930 return replace_delete_substring(self, from_s, from_len, maxcount);
1931 }
1932 }
1933
1934 /* Handle special case where both bytes have the same length */
1935
1936 if (from_len == to_len) {
1937 if (from_len == 1) {
1938 return replace_single_character_in_place(
1939 self,
1940 from_s[0],
1941 to_s[0],
1942 maxcount);
1943 } else {
1944 return replace_substring_in_place(
1945 self, from_s, from_len, to_s, to_len, maxcount);
1946 }
1947 }
1948
1949 /* Otherwise use the more generic algorithms */
1950 if (from_len == 1) {
1951 return replace_single_character(self, from_s[0],
1952 to_s, to_len, maxcount);
1953 } else {
1954 /* len('from')>=2, len('to')>=1 */
1955 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
1956 }
1957}
1958
1959
1960PyDoc_STRVAR(replace__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001961"B.replace(old, new[, count]) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001962\n\
1963Return a copy of B with all occurrences of subsection\n\
1964old replaced by new. If the optional argument count is\n\
1965given, only the first count occurrences are replaced.");
1966
1967static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001968bytearray_replace(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001969{
1970 Py_ssize_t count = -1;
1971 PyObject *from, *to, *res;
1972 Py_buffer vfrom, vto;
1973
1974 if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
1975 return NULL;
1976
1977 if (_getbuffer(from, &vfrom) < 0)
1978 return NULL;
1979 if (_getbuffer(to, &vto) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +00001980 PyBuffer_Release(&vfrom);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001981 return NULL;
1982 }
1983
1984 res = (PyObject *)replace((PyByteArrayObject *) self,
1985 vfrom.buf, vfrom.len,
1986 vto.buf, vto.len, count);
1987
Martin v. Löwis423be952008-08-13 15:53:07 +00001988 PyBuffer_Release(&vfrom);
1989 PyBuffer_Release(&vto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001990 return res;
1991}
1992
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001993PyDoc_STRVAR(split__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001994"B.split([sep[, maxsplit]]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001995\n\
1996Return a list of the sections in B, using sep as the delimiter.\n\
1997If sep is not given, B is split on ASCII whitespace characters\n\
1998(space, tab, return, newline, formfeed, vertical tab).\n\
1999If maxsplit is given, at most maxsplit splits are done.");
2000
2001static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002002bytearray_split(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002003{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002004 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
2005 Py_ssize_t maxsplit = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002006 const char *s = PyByteArray_AS_STRING(self), *sub;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002007 PyObject *list, *subobj = Py_None;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002008 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002009
2010 if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
2011 return NULL;
2012 if (maxsplit < 0)
2013 maxsplit = PY_SSIZE_T_MAX;
2014
2015 if (subobj == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002016 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002017
2018 if (_getbuffer(subobj, &vsub) < 0)
2019 return NULL;
2020 sub = vsub.buf;
2021 n = vsub.len;
2022
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002023 list = stringlib_split(
2024 (PyObject*) self, s, len, sub, n, maxsplit
2025 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002026 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002027 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002028}
2029
2030PyDoc_STRVAR(partition__doc__,
2031"B.partition(sep) -> (head, sep, tail)\n\
2032\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002033Search for the separator sep in B, and return the part before it,\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002034the separator itself, and the part after it. If the separator is not\n\
2035found, returns B and two empty bytearray objects.");
2036
2037static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002038bytearray_partition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002039{
2040 PyObject *bytesep, *result;
2041
2042 bytesep = PyByteArray_FromObject(sep_obj);
2043 if (! bytesep)
2044 return NULL;
2045
2046 result = stringlib_partition(
2047 (PyObject*) self,
2048 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2049 bytesep,
2050 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2051 );
2052
2053 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002054 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002055}
2056
2057PyDoc_STRVAR(rpartition__doc__,
2058"B.rpartition(sep) -> (tail, sep, head)\n\
2059\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002060Search for the separator sep in B, starting at the end of B,\n\
2061and return the part before it, the separator itself, and the\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002062part after it. If the separator is not found, returns two empty\n\
2063bytearray objects and B.");
2064
2065static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002066bytearray_rpartition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002067{
2068 PyObject *bytesep, *result;
2069
2070 bytesep = PyByteArray_FromObject(sep_obj);
2071 if (! bytesep)
2072 return NULL;
2073
2074 result = stringlib_rpartition(
2075 (PyObject*) self,
2076 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2077 bytesep,
2078 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2079 );
2080
2081 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002082 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002083}
2084
2085PyDoc_STRVAR(rsplit__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002086"B.rsplit(sep[, maxsplit]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002087\n\
2088Return a list of the sections in B, using sep as the delimiter,\n\
2089starting at the end of B and working to the front.\n\
2090If sep is not given, B is split on ASCII whitespace characters\n\
2091(space, tab, return, newline, formfeed, vertical tab).\n\
2092If maxsplit is given, at most maxsplit splits are done.");
2093
2094static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002095bytearray_rsplit(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002096{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002097 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
2098 Py_ssize_t maxsplit = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002099 const char *s = PyByteArray_AS_STRING(self), *sub;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002100 PyObject *list, *subobj = Py_None;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002101 Py_buffer vsub;
2102
2103 if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
2104 return NULL;
2105 if (maxsplit < 0)
2106 maxsplit = PY_SSIZE_T_MAX;
2107
2108 if (subobj == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002109 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002110
2111 if (_getbuffer(subobj, &vsub) < 0)
2112 return NULL;
2113 sub = vsub.buf;
2114 n = vsub.len;
2115
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002116 list = stringlib_rsplit(
2117 (PyObject*) self, s, len, sub, n, maxsplit
2118 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002119 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002120 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002121}
2122
2123PyDoc_STRVAR(reverse__doc__,
2124"B.reverse() -> None\n\
2125\n\
2126Reverse the order of the values in B in place.");
2127static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002128bytearray_reverse(PyByteArrayObject *self, PyObject *unused)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002129{
2130 char swap, *head, *tail;
2131 Py_ssize_t i, j, n = Py_SIZE(self);
2132
2133 j = n / 2;
2134 head = self->ob_bytes;
2135 tail = head + n - 1;
2136 for (i = 0; i < j; i++) {
2137 swap = *head;
2138 *head++ = *tail;
2139 *tail-- = swap;
2140 }
2141
2142 Py_RETURN_NONE;
2143}
2144
2145PyDoc_STRVAR(insert__doc__,
2146"B.insert(index, int) -> None\n\
2147\n\
2148Insert a single item into the bytearray before the given index.");
2149static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002150bytearray_insert(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002151{
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002152 PyObject *value;
2153 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002154 Py_ssize_t where, n = Py_SIZE(self);
2155
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002156 if (!PyArg_ParseTuple(args, "nO:insert", &where, &value))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002157 return NULL;
2158
2159 if (n == PY_SSIZE_T_MAX) {
2160 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002161 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002162 return NULL;
2163 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002164 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002165 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002166 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2167 return NULL;
2168
2169 if (where < 0) {
2170 where += n;
2171 if (where < 0)
2172 where = 0;
2173 }
2174 if (where > n)
2175 where = n;
2176 memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where);
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002177 self->ob_bytes[where] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002178
2179 Py_RETURN_NONE;
2180}
2181
2182PyDoc_STRVAR(append__doc__,
2183"B.append(int) -> None\n\
2184\n\
2185Append a single item to the end of B.");
2186static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002187bytearray_append(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002188{
2189 int value;
2190 Py_ssize_t n = Py_SIZE(self);
2191
2192 if (! _getbytevalue(arg, &value))
2193 return NULL;
2194 if (n == PY_SSIZE_T_MAX) {
2195 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002196 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002197 return NULL;
2198 }
2199 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2200 return NULL;
2201
2202 self->ob_bytes[n] = value;
2203
2204 Py_RETURN_NONE;
2205}
2206
2207PyDoc_STRVAR(extend__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002208"B.extend(iterable_of_ints) -> None\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002209\n\
2210Append all the elements from the iterator or sequence to the\n\
2211end of B.");
2212static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002213bytearray_extend(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002214{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002215 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002216 Py_ssize_t buf_size = 0, len = 0;
2217 int value;
2218 char *buf;
2219
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002220 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002221 if (PyObject_CheckBuffer(arg)) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002222 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), arg) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002223 return NULL;
2224
2225 Py_RETURN_NONE;
2226 }
2227
2228 it = PyObject_GetIter(arg);
2229 if (it == NULL)
2230 return NULL;
2231
2232 /* Try to determine the length of the argument. 32 is abitrary. */
2233 buf_size = _PyObject_LengthHint(arg, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002234 if (buf_size == -1) {
2235 Py_DECREF(it);
2236 return NULL;
2237 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002238
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002239 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
2240 if (bytearray_obj == NULL)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002241 return NULL;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002242 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002243
2244 while ((item = PyIter_Next(it)) != NULL) {
2245 if (! _getbytevalue(item, &value)) {
2246 Py_DECREF(item);
2247 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002248 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002249 return NULL;
2250 }
2251 buf[len++] = value;
2252 Py_DECREF(item);
2253
2254 if (len >= buf_size) {
2255 buf_size = len + (len >> 1) + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002256 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002257 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002258 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002259 return NULL;
2260 }
2261 /* Recompute the `buf' pointer, since the resizing operation may
2262 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002263 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002264 }
2265 }
2266 Py_DECREF(it);
2267
2268 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002269 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
2270 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002271 return NULL;
2272 }
2273
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002274 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002275 return NULL;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002276 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002277
2278 Py_RETURN_NONE;
2279}
2280
2281PyDoc_STRVAR(pop__doc__,
2282"B.pop([index]) -> int\n\
2283\n\
2284Remove and return a single item from B. If no index\n\
Benjamin Petersondcf97b92008-07-02 17:30:14 +00002285argument is given, will pop the last value.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002286static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002287bytearray_pop(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002288{
2289 int value;
2290 Py_ssize_t where = -1, n = Py_SIZE(self);
2291
2292 if (!PyArg_ParseTuple(args, "|n:pop", &where))
2293 return NULL;
2294
2295 if (n == 0) {
2296 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002297 "cannot pop an empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002298 return NULL;
2299 }
2300 if (where < 0)
2301 where += Py_SIZE(self);
2302 if (where < 0 || where >= Py_SIZE(self)) {
2303 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2304 return NULL;
2305 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002306 if (!_canresize(self))
2307 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002308
2309 value = self->ob_bytes[where];
2310 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2311 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2312 return NULL;
2313
Mark Dickinson54a3db92009-09-06 10:19:23 +00002314 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002315}
2316
2317PyDoc_STRVAR(remove__doc__,
2318"B.remove(int) -> None\n\
2319\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002320Remove the first occurrence of a value in B.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002321static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002322bytearray_remove(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002323{
2324 int value;
2325 Py_ssize_t where, n = Py_SIZE(self);
2326
2327 if (! _getbytevalue(arg, &value))
2328 return NULL;
2329
2330 for (where = 0; where < n; where++) {
2331 if (self->ob_bytes[where] == value)
2332 break;
2333 }
2334 if (where == n) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002335 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002336 return NULL;
2337 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002338 if (!_canresize(self))
2339 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002340
2341 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2342 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2343 return NULL;
2344
2345 Py_RETURN_NONE;
2346}
2347
2348/* XXX These two helpers could be optimized if argsize == 1 */
2349
2350static Py_ssize_t
2351lstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2352 void *argptr, Py_ssize_t argsize)
2353{
2354 Py_ssize_t i = 0;
2355 while (i < mysize && memchr(argptr, myptr[i], argsize))
2356 i++;
2357 return i;
2358}
2359
2360static Py_ssize_t
2361rstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2362 void *argptr, Py_ssize_t argsize)
2363{
2364 Py_ssize_t i = mysize - 1;
2365 while (i >= 0 && memchr(argptr, myptr[i], argsize))
2366 i--;
2367 return i + 1;
2368}
2369
2370PyDoc_STRVAR(strip__doc__,
2371"B.strip([bytes]) -> bytearray\n\
2372\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002373Strip leading and trailing bytes contained in the argument\n\
2374and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002375If the argument is omitted, strip ASCII whitespace.");
2376static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002377bytearray_strip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002378{
2379 Py_ssize_t left, right, mysize, argsize;
2380 void *myptr, *argptr;
2381 PyObject *arg = Py_None;
2382 Py_buffer varg;
2383 if (!PyArg_ParseTuple(args, "|O:strip", &arg))
2384 return NULL;
2385 if (arg == Py_None) {
2386 argptr = "\t\n\r\f\v ";
2387 argsize = 6;
2388 }
2389 else {
2390 if (_getbuffer(arg, &varg) < 0)
2391 return NULL;
2392 argptr = varg.buf;
2393 argsize = varg.len;
2394 }
2395 myptr = self->ob_bytes;
2396 mysize = Py_SIZE(self);
2397 left = lstrip_helper(myptr, mysize, argptr, argsize);
2398 if (left == mysize)
2399 right = left;
2400 else
2401 right = rstrip_helper(myptr, mysize, argptr, argsize);
2402 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002403 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002404 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2405}
2406
2407PyDoc_STRVAR(lstrip__doc__,
2408"B.lstrip([bytes]) -> bytearray\n\
2409\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002410Strip leading bytes contained in the argument\n\
2411and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002412If the argument is omitted, strip leading ASCII whitespace.");
2413static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002414bytearray_lstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002415{
2416 Py_ssize_t left, right, mysize, argsize;
2417 void *myptr, *argptr;
2418 PyObject *arg = Py_None;
2419 Py_buffer varg;
2420 if (!PyArg_ParseTuple(args, "|O:lstrip", &arg))
2421 return NULL;
2422 if (arg == Py_None) {
2423 argptr = "\t\n\r\f\v ";
2424 argsize = 6;
2425 }
2426 else {
2427 if (_getbuffer(arg, &varg) < 0)
2428 return NULL;
2429 argptr = varg.buf;
2430 argsize = varg.len;
2431 }
2432 myptr = self->ob_bytes;
2433 mysize = Py_SIZE(self);
2434 left = lstrip_helper(myptr, mysize, argptr, argsize);
2435 right = mysize;
2436 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002437 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002438 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2439}
2440
2441PyDoc_STRVAR(rstrip__doc__,
2442"B.rstrip([bytes]) -> bytearray\n\
2443\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002444Strip trailing bytes contained in the argument\n\
2445and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002446If the argument is omitted, strip trailing ASCII whitespace.");
2447static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002448bytearray_rstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002449{
2450 Py_ssize_t left, right, mysize, argsize;
2451 void *myptr, *argptr;
2452 PyObject *arg = Py_None;
2453 Py_buffer varg;
2454 if (!PyArg_ParseTuple(args, "|O:rstrip", &arg))
2455 return NULL;
2456 if (arg == Py_None) {
2457 argptr = "\t\n\r\f\v ";
2458 argsize = 6;
2459 }
2460 else {
2461 if (_getbuffer(arg, &varg) < 0)
2462 return NULL;
2463 argptr = varg.buf;
2464 argsize = varg.len;
2465 }
2466 myptr = self->ob_bytes;
2467 mysize = Py_SIZE(self);
2468 left = 0;
2469 right = rstrip_helper(myptr, mysize, argptr, argsize);
2470 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002471 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002472 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2473}
2474
2475PyDoc_STRVAR(decode_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002476"B.decode([encoding[, errors]]) -> str\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002477\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002478Decode B using the codec registered for encoding. encoding defaults\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002479to the default encoding. errors may be given to set a different error\n\
2480handling scheme. Default is 'strict' meaning that encoding errors raise\n\
2481a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
2482as well as any other name registered with codecs.register_error that is\n\
2483able to handle UnicodeDecodeErrors.");
2484
2485static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00002486bytearray_decode(PyObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002487{
2488 const char *encoding = NULL;
2489 const char *errors = NULL;
Benjamin Peterson308d6372009-09-18 21:42:35 +00002490 static char *kwlist[] = {"encoding", "errors", 0};
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002491
Benjamin Peterson308d6372009-09-18 21:42:35 +00002492 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode", kwlist, &encoding, &errors))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002493 return NULL;
2494 if (encoding == NULL)
2495 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002496 return PyUnicode_FromEncodedObject(self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002497}
2498
2499PyDoc_STRVAR(alloc_doc,
2500"B.__alloc__() -> int\n\
2501\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002502Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002503
2504static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002505bytearray_alloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002506{
2507 return PyLong_FromSsize_t(self->ob_alloc);
2508}
2509
2510PyDoc_STRVAR(join_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002511"B.join(iterable_of_bytes) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002512\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002513Concatenate any number of bytes/bytearray objects, with B\n\
2514in between each pair, and return the result as a new bytearray.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002515
2516static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002517bytearray_join(PyByteArrayObject *self, PyObject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002518{
2519 PyObject *seq;
2520 Py_ssize_t mysize = Py_SIZE(self);
2521 Py_ssize_t i;
2522 Py_ssize_t n;
2523 PyObject **items;
2524 Py_ssize_t totalsize = 0;
2525 PyObject *result;
2526 char *dest;
2527
2528 seq = PySequence_Fast(it, "can only join an iterable");
2529 if (seq == NULL)
2530 return NULL;
2531 n = PySequence_Fast_GET_SIZE(seq);
2532 items = PySequence_Fast_ITEMS(seq);
2533
2534 /* Compute the total size, and check that they are all bytes */
2535 /* XXX Shouldn't we use _getbuffer() on these items instead? */
2536 for (i = 0; i < n; i++) {
2537 PyObject *obj = items[i];
2538 if (!PyByteArray_Check(obj) && !PyBytes_Check(obj)) {
2539 PyErr_Format(PyExc_TypeError,
2540 "can only join an iterable of bytes "
2541 "(item %ld has type '%.100s')",
2542 /* XXX %ld isn't right on Win64 */
2543 (long)i, Py_TYPE(obj)->tp_name);
2544 goto error;
2545 }
2546 if (i > 0)
2547 totalsize += mysize;
2548 totalsize += Py_SIZE(obj);
2549 if (totalsize < 0) {
2550 PyErr_NoMemory();
2551 goto error;
2552 }
2553 }
2554
2555 /* Allocate the result, and copy the bytes */
2556 result = PyByteArray_FromStringAndSize(NULL, totalsize);
2557 if (result == NULL)
2558 goto error;
2559 dest = PyByteArray_AS_STRING(result);
2560 for (i = 0; i < n; i++) {
2561 PyObject *obj = items[i];
2562 Py_ssize_t size = Py_SIZE(obj);
2563 char *buf;
2564 if (PyByteArray_Check(obj))
2565 buf = PyByteArray_AS_STRING(obj);
2566 else
2567 buf = PyBytes_AS_STRING(obj);
2568 if (i) {
2569 memcpy(dest, self->ob_bytes, mysize);
2570 dest += mysize;
2571 }
2572 memcpy(dest, buf, size);
2573 dest += size;
2574 }
2575
2576 /* Done */
2577 Py_DECREF(seq);
2578 return result;
2579
2580 /* Error handling */
2581 error:
2582 Py_DECREF(seq);
2583 return NULL;
2584}
2585
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002586PyDoc_STRVAR(splitlines__doc__,
2587"B.splitlines([keepends]) -> list of lines\n\
2588\n\
2589Return a list of the lines in B, breaking at line boundaries.\n\
2590Line breaks are not included in the resulting list unless keepends\n\
2591is given and true.");
2592
2593static PyObject*
2594bytearray_splitlines(PyObject *self, PyObject *args)
2595{
2596 int keepends = 0;
2597
2598 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
2599 return NULL;
2600
2601 return stringlib_splitlines(
2602 (PyObject*) self, PyByteArray_AS_STRING(self),
2603 PyByteArray_GET_SIZE(self), keepends
2604 );
2605}
2606
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002607PyDoc_STRVAR(fromhex_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002608"bytearray.fromhex(string) -> bytearray (static method)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002609\n\
2610Create a bytearray object from a string of hexadecimal numbers.\n\
2611Spaces between two numbers are accepted.\n\
2612Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef').");
2613
2614static int
2615hex_digit_to_int(Py_UNICODE c)
2616{
2617 if (c >= 128)
2618 return -1;
Eric Smith6dc46f52009-04-27 20:39:49 +00002619 if (Py_ISDIGIT(c))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002620 return c - '0';
2621 else {
Eric Smith6dc46f52009-04-27 20:39:49 +00002622 if (Py_ISUPPER(c))
2623 c = Py_TOLOWER(c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002624 if (c >= 'a' && c <= 'f')
2625 return c - 'a' + 10;
2626 }
2627 return -1;
2628}
2629
2630static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002631bytearray_fromhex(PyObject *cls, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002632{
2633 PyObject *newbytes, *hexobj;
2634 char *buf;
2635 Py_UNICODE *hex;
2636 Py_ssize_t hexlen, byteslen, i, j;
2637 int top, bot;
2638
2639 if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj))
2640 return NULL;
2641 assert(PyUnicode_Check(hexobj));
2642 hexlen = PyUnicode_GET_SIZE(hexobj);
2643 hex = PyUnicode_AS_UNICODE(hexobj);
2644 byteslen = hexlen/2; /* This overestimates if there are spaces */
2645 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
2646 if (!newbytes)
2647 return NULL;
2648 buf = PyByteArray_AS_STRING(newbytes);
2649 for (i = j = 0; i < hexlen; i += 2) {
2650 /* skip over spaces in the input */
2651 while (hex[i] == ' ')
2652 i++;
2653 if (i >= hexlen)
2654 break;
2655 top = hex_digit_to_int(hex[i]);
2656 bot = hex_digit_to_int(hex[i+1]);
2657 if (top == -1 || bot == -1) {
2658 PyErr_Format(PyExc_ValueError,
2659 "non-hexadecimal number found in "
2660 "fromhex() arg at position %zd", i);
2661 goto error;
2662 }
2663 buf[j++] = (top << 4) + bot;
2664 }
2665 if (PyByteArray_Resize(newbytes, j) < 0)
2666 goto error;
2667 return newbytes;
2668
2669 error:
2670 Py_DECREF(newbytes);
2671 return NULL;
2672}
2673
2674PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2675
2676static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002677bytearray_reduce(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002678{
2679 PyObject *latin1, *dict;
2680 if (self->ob_bytes)
2681 latin1 = PyUnicode_DecodeLatin1(self->ob_bytes,
2682 Py_SIZE(self), NULL);
2683 else
2684 latin1 = PyUnicode_FromString("");
2685
2686 dict = PyObject_GetAttrString((PyObject *)self, "__dict__");
2687 if (dict == NULL) {
2688 PyErr_Clear();
2689 dict = Py_None;
2690 Py_INCREF(dict);
2691 }
2692
2693 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
2694}
2695
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002696PyDoc_STRVAR(sizeof_doc,
2697"B.__sizeof__() -> int\n\
2698 \n\
2699Returns the size of B in memory, in bytes");
2700static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002701bytearray_sizeof(PyByteArrayObject *self)
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002702{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002703 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002704
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002705 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
2706 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002707}
2708
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002709static PySequenceMethods bytearray_as_sequence = {
2710 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002711 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002712 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
2713 (ssizeargfunc)bytearray_getitem, /* sq_item */
2714 0, /* sq_slice */
2715 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
2716 0, /* sq_ass_slice */
2717 (objobjproc)bytearray_contains, /* sq_contains */
2718 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
2719 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002720};
2721
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002722static PyMappingMethods bytearray_as_mapping = {
2723 (lenfunc)bytearray_length,
2724 (binaryfunc)bytearray_subscript,
2725 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002726};
2727
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002728static PyBufferProcs bytearray_as_buffer = {
2729 (getbufferproc)bytearray_getbuffer,
2730 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002731};
2732
2733static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002734bytearray_methods[] = {
2735 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
2736 {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, reduce_doc},
2737 {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, sizeof_doc},
2738 {"append", (PyCFunction)bytearray_append, METH_O, append__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002739 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
2740 _Py_capitalize__doc__},
2741 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002742 {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
Benjamin Peterson308d6372009-09-18 21:42:35 +00002743 {"decode", (PyCFunction)bytearray_decode, METH_VARARGS | METH_KEYWORDS, decode_doc},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002744 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002745 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS,
2746 expandtabs__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002747 {"extend", (PyCFunction)bytearray_extend, METH_O, extend__doc__},
2748 {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
2749 {"fromhex", (PyCFunction)bytearray_fromhex, METH_VARARGS|METH_CLASS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002750 fromhex_doc},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002751 {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
2752 {"insert", (PyCFunction)bytearray_insert, METH_VARARGS, insert__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002753 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
2754 _Py_isalnum__doc__},
2755 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
2756 _Py_isalpha__doc__},
2757 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
2758 _Py_isdigit__doc__},
2759 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
2760 _Py_islower__doc__},
2761 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
2762 _Py_isspace__doc__},
2763 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
2764 _Py_istitle__doc__},
2765 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
2766 _Py_isupper__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002767 {"join", (PyCFunction)bytearray_join, METH_O, join_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002768 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
2769 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002770 {"lstrip", (PyCFunction)bytearray_lstrip, METH_VARARGS, lstrip__doc__},
2771 {"maketrans", (PyCFunction)bytearray_maketrans, METH_VARARGS|METH_STATIC,
Georg Brandlabc38772009-04-12 15:51:51 +00002772 _Py_maketrans__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002773 {"partition", (PyCFunction)bytearray_partition, METH_O, partition__doc__},
2774 {"pop", (PyCFunction)bytearray_pop, METH_VARARGS, pop__doc__},
2775 {"remove", (PyCFunction)bytearray_remove, METH_O, remove__doc__},
2776 {"replace", (PyCFunction)bytearray_replace, METH_VARARGS, replace__doc__},
2777 {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, reverse__doc__},
2778 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
2779 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002780 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002781 {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, rpartition__doc__},
2782 {"rsplit", (PyCFunction)bytearray_rsplit, METH_VARARGS, rsplit__doc__},
2783 {"rstrip", (PyCFunction)bytearray_rstrip, METH_VARARGS, rstrip__doc__},
2784 {"split", (PyCFunction)bytearray_split, METH_VARARGS, split__doc__},
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002785 {"splitlines", (PyCFunction)bytearray_splitlines, METH_VARARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002786 splitlines__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002787 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002788 startswith__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002789 {"strip", (PyCFunction)bytearray_strip, METH_VARARGS, strip__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002790 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
2791 _Py_swapcase__doc__},
2792 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002793 {"translate", (PyCFunction)bytearray_translate, METH_VARARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002794 translate__doc__},
2795 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
2796 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
2797 {NULL}
2798};
2799
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002800PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002801"bytearray(iterable_of_ints) -> bytearray\n\
2802bytearray(string, encoding[, errors]) -> bytearray\n\
2803bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray\n\
2804bytearray(memory_view) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002805\n\
2806Construct an mutable bytearray object from:\n\
2807 - an iterable yielding integers in range(256)\n\
2808 - a text string encoded using the specified encoding\n\
2809 - a bytes or a bytearray object\n\
2810 - any object implementing the buffer API.\n\
2811\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002812bytearray(int) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002813\n\
2814Construct a zero-initialized bytearray of the given length.");
2815
2816
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002817static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002818
2819PyTypeObject PyByteArray_Type = {
2820 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2821 "bytearray",
2822 sizeof(PyByteArrayObject),
2823 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002824 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002825 0, /* tp_print */
2826 0, /* tp_getattr */
2827 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002828 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002829 (reprfunc)bytearray_repr, /* tp_repr */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002830 0, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002831 &bytearray_as_sequence, /* tp_as_sequence */
2832 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002833 0, /* tp_hash */
2834 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002835 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002836 PyObject_GenericGetAttr, /* tp_getattro */
2837 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002838 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002839 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002840 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002841 0, /* tp_traverse */
2842 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002843 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002844 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002845 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002846 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002847 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002848 0, /* tp_members */
2849 0, /* tp_getset */
2850 0, /* tp_base */
2851 0, /* tp_dict */
2852 0, /* tp_descr_get */
2853 0, /* tp_descr_set */
2854 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002855 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002856 PyType_GenericAlloc, /* tp_alloc */
2857 PyType_GenericNew, /* tp_new */
2858 PyObject_Del, /* tp_free */
2859};
2860
2861/*********************** Bytes Iterator ****************************/
2862
2863typedef struct {
2864 PyObject_HEAD
2865 Py_ssize_t it_index;
2866 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
2867} bytesiterobject;
2868
2869static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002870bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002871{
2872 _PyObject_GC_UNTRACK(it);
2873 Py_XDECREF(it->it_seq);
2874 PyObject_GC_Del(it);
2875}
2876
2877static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002878bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002879{
2880 Py_VISIT(it->it_seq);
2881 return 0;
2882}
2883
2884static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002885bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002886{
2887 PyByteArrayObject *seq;
2888 PyObject *item;
2889
2890 assert(it != NULL);
2891 seq = it->it_seq;
2892 if (seq == NULL)
2893 return NULL;
2894 assert(PyByteArray_Check(seq));
2895
2896 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
2897 item = PyLong_FromLong(
2898 (unsigned char)seq->ob_bytes[it->it_index]);
2899 if (item != NULL)
2900 ++it->it_index;
2901 return item;
2902 }
2903
2904 Py_DECREF(seq);
2905 it->it_seq = NULL;
2906 return NULL;
2907}
2908
2909static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002910bytesarrayiter_length_hint(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002911{
2912 Py_ssize_t len = 0;
2913 if (it->it_seq)
2914 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
2915 return PyLong_FromSsize_t(len);
2916}
2917
2918PyDoc_STRVAR(length_hint_doc,
2919 "Private method returning an estimate of len(list(it)).");
2920
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002921static PyMethodDef bytearrayiter_methods[] = {
2922 {"__length_hint__", (PyCFunction)bytesarrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002923 length_hint_doc},
2924 {NULL, NULL} /* sentinel */
2925};
2926
2927PyTypeObject PyByteArrayIter_Type = {
2928 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2929 "bytearray_iterator", /* tp_name */
2930 sizeof(bytesiterobject), /* tp_basicsize */
2931 0, /* tp_itemsize */
2932 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002933 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002934 0, /* tp_print */
2935 0, /* tp_getattr */
2936 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002937 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002938 0, /* tp_repr */
2939 0, /* tp_as_number */
2940 0, /* tp_as_sequence */
2941 0, /* tp_as_mapping */
2942 0, /* tp_hash */
2943 0, /* tp_call */
2944 0, /* tp_str */
2945 PyObject_GenericGetAttr, /* tp_getattro */
2946 0, /* tp_setattro */
2947 0, /* tp_as_buffer */
2948 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2949 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002950 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002951 0, /* tp_clear */
2952 0, /* tp_richcompare */
2953 0, /* tp_weaklistoffset */
2954 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002955 (iternextfunc)bytearrayiter_next, /* tp_iternext */
2956 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002957 0,
2958};
2959
2960static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002961bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002962{
2963 bytesiterobject *it;
2964
2965 if (!PyByteArray_Check(seq)) {
2966 PyErr_BadInternalCall();
2967 return NULL;
2968 }
2969 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
2970 if (it == NULL)
2971 return NULL;
2972 it->it_index = 0;
2973 Py_INCREF(seq);
2974 it->it_seq = (PyByteArrayObject *)seq;
2975 _PyObject_GC_TRACK(it);
2976 return (PyObject *)it;
2977}