blob: 42f1ed6e6f436c0d1483dcf248ebcf9e473740c0 [file] [log] [blame]
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001/* PyByteArray (bytearray) implementation */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
5#include "structmember.h"
6#include "bytes_methods.h"
7
Antoine Pitroufc8d6f42010-01-17 12:38:54 +00008char _PyByteArray_empty_string[] = "";
Christian Heimes2c9c7a52008-05-26 13:42:13 +00009
10void
11PyByteArray_Fini(void)
12{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000013}
14
15int
16PyByteArray_Init(void)
17{
Christian Heimes2c9c7a52008-05-26 13:42:13 +000018 return 1;
19}
20
21/* end nullbytes support */
22
23/* Helpers */
24
25static int
26_getbytevalue(PyObject* arg, int *value)
27{
28 long face_value;
29
30 if (PyLong_Check(arg)) {
31 face_value = PyLong_AsLong(arg);
Georg Brandl9a54d7c2008-07-16 23:15:30 +000032 } else {
33 PyObject *index = PyNumber_Index(arg);
34 if (index == NULL) {
35 PyErr_Format(PyExc_TypeError, "an integer is required");
Christian Heimes2c9c7a52008-05-26 13:42:13 +000036 return 0;
37 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +000038 face_value = PyLong_AsLong(index);
39 Py_DECREF(index);
40 }
41
42 if (face_value < 0 || face_value >= 256) {
43 /* this includes the OverflowError in case the long is too large */
44 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
Christian Heimes2c9c7a52008-05-26 13:42:13 +000045 return 0;
46 }
47
48 *value = face_value;
49 return 1;
50}
51
52static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +000053bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000054{
55 int ret;
56 void *ptr;
57 if (view == NULL) {
58 obj->ob_exports++;
59 return 0;
60 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +000061 ptr = (void *) PyByteArray_AS_STRING(obj);
Martin v. Löwis423be952008-08-13 15:53:07 +000062 ret = PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
Christian Heimes2c9c7a52008-05-26 13:42:13 +000063 if (ret >= 0) {
64 obj->ob_exports++;
65 }
66 return ret;
67}
68
69static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +000070bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
Christian Heimes2c9c7a52008-05-26 13:42:13 +000071{
72 obj->ob_exports--;
73}
74
75static Py_ssize_t
76_getbuffer(PyObject *obj, Py_buffer *view)
77{
78 PyBufferProcs *buffer = Py_TYPE(obj)->tp_as_buffer;
79
80 if (buffer == NULL || buffer->bf_getbuffer == NULL)
81 {
82 PyErr_Format(PyExc_TypeError,
83 "Type %.100s doesn't support the buffer API",
84 Py_TYPE(obj)->tp_name);
85 return -1;
86 }
87
88 if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0)
89 return -1;
90 return view->len;
91}
92
Antoine Pitrou5504e892008-12-06 21:27:53 +000093static int
94_canresize(PyByteArrayObject *self)
95{
96 if (self->ob_exports > 0) {
97 PyErr_SetString(PyExc_BufferError,
98 "Existing exports of data: object cannot be re-sized");
99 return 0;
100 }
101 return 1;
102}
103
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000104/* Direct API functions */
105
106PyObject *
107PyByteArray_FromObject(PyObject *input)
108{
109 return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
110 input, NULL);
111}
112
113PyObject *
114PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
115{
116 PyByteArrayObject *new;
117 Py_ssize_t alloc;
118
119 if (size < 0) {
120 PyErr_SetString(PyExc_SystemError,
121 "Negative size passed to PyByteArray_FromStringAndSize");
122 return NULL;
123 }
124
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000125 /* Prevent buffer overflow when setting alloc to size+1. */
126 if (size == PY_SSIZE_T_MAX) {
127 return PyErr_NoMemory();
128 }
129
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000130 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
131 if (new == NULL)
132 return NULL;
133
134 if (size == 0) {
135 new->ob_bytes = NULL;
136 alloc = 0;
137 }
138 else {
139 alloc = size + 1;
140 new->ob_bytes = PyMem_Malloc(alloc);
141 if (new->ob_bytes == NULL) {
142 Py_DECREF(new);
143 return PyErr_NoMemory();
144 }
Antoine Pitroufc8d6f42010-01-17 12:38:54 +0000145 if (bytes != NULL && size > 0)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000146 memcpy(new->ob_bytes, bytes, size);
147 new->ob_bytes[size] = '\0'; /* Trailing null byte */
148 }
149 Py_SIZE(new) = size;
150 new->ob_alloc = alloc;
151 new->ob_exports = 0;
152
153 return (PyObject *)new;
154}
155
156Py_ssize_t
157PyByteArray_Size(PyObject *self)
158{
159 assert(self != NULL);
160 assert(PyByteArray_Check(self));
161
162 return PyByteArray_GET_SIZE(self);
163}
164
165char *
166PyByteArray_AsString(PyObject *self)
167{
168 assert(self != NULL);
169 assert(PyByteArray_Check(self));
170
171 return PyByteArray_AS_STRING(self);
172}
173
174int
175PyByteArray_Resize(PyObject *self, Py_ssize_t size)
176{
177 void *sval;
178 Py_ssize_t alloc = ((PyByteArrayObject *)self)->ob_alloc;
179
180 assert(self != NULL);
181 assert(PyByteArray_Check(self));
182 assert(size >= 0);
183
Antoine Pitrou5504e892008-12-06 21:27:53 +0000184 if (size == Py_SIZE(self)) {
185 return 0;
186 }
187 if (!_canresize((PyByteArrayObject *)self)) {
188 return -1;
189 }
190
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000191 if (size < alloc / 2) {
192 /* Major downsize; resize down to exact size */
193 alloc = size + 1;
194 }
195 else if (size < alloc) {
196 /* Within allocated size; quick exit */
197 Py_SIZE(self) = size;
198 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null */
199 return 0;
200 }
201 else if (size <= alloc * 1.125) {
202 /* Moderate upsize; overallocate similar to list_resize() */
203 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
204 }
205 else {
206 /* Major upsize; resize up to exact size */
207 alloc = size + 1;
208 }
209
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000210 sval = PyMem_Realloc(((PyByteArrayObject *)self)->ob_bytes, alloc);
211 if (sval == NULL) {
212 PyErr_NoMemory();
213 return -1;
214 }
215
216 ((PyByteArrayObject *)self)->ob_bytes = sval;
217 Py_SIZE(self) = size;
218 ((PyByteArrayObject *)self)->ob_alloc = alloc;
219 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null byte */
220
221 return 0;
222}
223
224PyObject *
225PyByteArray_Concat(PyObject *a, PyObject *b)
226{
227 Py_ssize_t size;
228 Py_buffer va, vb;
229 PyByteArrayObject *result = NULL;
230
231 va.len = -1;
232 vb.len = -1;
233 if (_getbuffer(a, &va) < 0 ||
234 _getbuffer(b, &vb) < 0) {
235 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
236 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
237 goto done;
238 }
239
240 size = va.len + vb.len;
241 if (size < 0) {
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000242 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000243 goto done;
244 }
245
246 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
247 if (result != NULL) {
248 memcpy(result->ob_bytes, va.buf, va.len);
249 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
250 }
251
252 done:
253 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000254 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000255 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000256 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000257 return (PyObject *)result;
258}
259
260/* Functions stuffed into the type object */
261
262static Py_ssize_t
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000263bytearray_length(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000264{
265 return Py_SIZE(self);
266}
267
268static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000269bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000270{
271 Py_ssize_t mysize;
272 Py_ssize_t size;
273 Py_buffer vo;
274
275 if (_getbuffer(other, &vo) < 0) {
276 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
277 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
278 return NULL;
279 }
280
281 mysize = Py_SIZE(self);
282 size = mysize + vo.len;
283 if (size < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000284 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000285 return PyErr_NoMemory();
286 }
287 if (size < self->ob_alloc) {
288 Py_SIZE(self) = size;
289 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
290 }
291 else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000292 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000293 return NULL;
294 }
295 memcpy(self->ob_bytes + mysize, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000296 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000297 Py_INCREF(self);
298 return (PyObject *)self;
299}
300
301static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000302bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000303{
304 PyByteArrayObject *result;
305 Py_ssize_t mysize;
306 Py_ssize_t size;
307
308 if (count < 0)
309 count = 0;
310 mysize = Py_SIZE(self);
311 size = mysize * count;
312 if (count != 0 && size / count != mysize)
313 return PyErr_NoMemory();
314 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
315 if (result != NULL && size != 0) {
316 if (mysize == 1)
317 memset(result->ob_bytes, self->ob_bytes[0], size);
318 else {
319 Py_ssize_t i;
320 for (i = 0; i < count; i++)
321 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
322 }
323 }
324 return (PyObject *)result;
325}
326
327static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000328bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000329{
330 Py_ssize_t mysize;
331 Py_ssize_t size;
332
333 if (count < 0)
334 count = 0;
335 mysize = Py_SIZE(self);
336 size = mysize * count;
337 if (count != 0 && size / count != mysize)
338 return PyErr_NoMemory();
339 if (size < self->ob_alloc) {
340 Py_SIZE(self) = size;
341 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
342 }
343 else if (PyByteArray_Resize((PyObject *)self, size) < 0)
344 return NULL;
345
346 if (mysize == 1)
347 memset(self->ob_bytes, self->ob_bytes[0], size);
348 else {
349 Py_ssize_t i;
350 for (i = 1; i < count; i++)
351 memcpy(self->ob_bytes + i*mysize, self->ob_bytes, mysize);
352 }
353
354 Py_INCREF(self);
355 return (PyObject *)self;
356}
357
358static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000359bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000360{
361 if (i < 0)
362 i += Py_SIZE(self);
363 if (i < 0 || i >= Py_SIZE(self)) {
364 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
365 return NULL;
366 }
367 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
368}
369
370static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000371bytearray_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000372{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000373 if (PyIndex_Check(index)) {
374 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000375
376 if (i == -1 && PyErr_Occurred())
377 return NULL;
378
379 if (i < 0)
380 i += PyByteArray_GET_SIZE(self);
381
382 if (i < 0 || i >= Py_SIZE(self)) {
383 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
384 return NULL;
385 }
386 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
387 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000388 else if (PySlice_Check(index)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000389 Py_ssize_t start, stop, step, slicelength, cur, i;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000390 if (PySlice_GetIndicesEx((PySliceObject *)index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000391 PyByteArray_GET_SIZE(self),
392 &start, &stop, &step, &slicelength) < 0) {
393 return NULL;
394 }
395
396 if (slicelength <= 0)
397 return PyByteArray_FromStringAndSize("", 0);
398 else if (step == 1) {
399 return PyByteArray_FromStringAndSize(self->ob_bytes + start,
400 slicelength);
401 }
402 else {
403 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000404 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000405 PyObject *result;
406
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000407 result = PyByteArray_FromStringAndSize(NULL, slicelength);
408 if (result == NULL)
409 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000410
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000411 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000412 for (cur = start, i = 0; i < slicelength;
413 cur += step, i++) {
414 result_buf[i] = source_buf[cur];
415 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000416 return result;
417 }
418 }
419 else {
420 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integers");
421 return NULL;
422 }
423}
424
425static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000426bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000427 PyObject *values)
428{
429 Py_ssize_t avail, needed;
430 void *bytes;
431 Py_buffer vbytes;
432 int res = 0;
433
434 vbytes.len = -1;
435 if (values == (PyObject *)self) {
436 /* Make a copy and call this function recursively */
437 int err;
438 values = PyByteArray_FromObject(values);
439 if (values == NULL)
440 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000441 err = bytearray_setslice(self, lo, hi, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000442 Py_DECREF(values);
443 return err;
444 }
445 if (values == NULL) {
446 /* del b[lo:hi] */
447 bytes = NULL;
448 needed = 0;
449 }
450 else {
451 if (_getbuffer(values, &vbytes) < 0) {
452 PyErr_Format(PyExc_TypeError,
Georg Brandl3dbca812008-07-23 16:10:53 +0000453 "can't set bytearray slice from %.100s",
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000454 Py_TYPE(values)->tp_name);
455 return -1;
456 }
457 needed = vbytes.len;
458 bytes = vbytes.buf;
459 }
460
461 if (lo < 0)
462 lo = 0;
463 if (hi < lo)
464 hi = lo;
465 if (hi > Py_SIZE(self))
466 hi = Py_SIZE(self);
467
468 avail = hi - lo;
469 if (avail < 0)
470 lo = hi = avail = 0;
471
472 if (avail != needed) {
473 if (avail > needed) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000474 if (!_canresize(self)) {
475 res = -1;
476 goto finish;
477 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000478 /*
479 0 lo hi old_size
480 | |<----avail----->|<-----tomove------>|
481 | |<-needed->|<-----tomove------>|
482 0 lo new_hi new_size
483 */
484 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
485 Py_SIZE(self) - hi);
486 }
487 /* XXX(nnorwitz): need to verify this can't overflow! */
488 if (PyByteArray_Resize((PyObject *)self,
489 Py_SIZE(self) + needed - avail) < 0) {
490 res = -1;
491 goto finish;
492 }
493 if (avail < needed) {
494 /*
495 0 lo hi old_size
496 | |<-avail->|<-----tomove------>|
497 | |<----needed---->|<-----tomove------>|
498 0 lo new_hi new_size
499 */
500 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
501 Py_SIZE(self) - lo - needed);
502 }
503 }
504
505 if (needed > 0)
506 memcpy(self->ob_bytes + lo, bytes, needed);
507
508
509 finish:
510 if (vbytes.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000511 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000512 return res;
513}
514
515static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000516bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000517{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000518 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000519
520 if (i < 0)
521 i += Py_SIZE(self);
522
523 if (i < 0 || i >= Py_SIZE(self)) {
524 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
525 return -1;
526 }
527
528 if (value == NULL)
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000529 return bytearray_setslice(self, i, i+1, NULL);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000530
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000531 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000532 return -1;
533
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000534 self->ob_bytes[i] = ival;
535 return 0;
536}
537
538static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000539bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000540{
541 Py_ssize_t start, stop, step, slicelen, needed;
542 char *bytes;
543
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000544 if (PyIndex_Check(index)) {
545 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000546
547 if (i == -1 && PyErr_Occurred())
548 return -1;
549
550 if (i < 0)
551 i += PyByteArray_GET_SIZE(self);
552
553 if (i < 0 || i >= Py_SIZE(self)) {
554 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
555 return -1;
556 }
557
558 if (values == NULL) {
559 /* Fall through to slice assignment */
560 start = i;
561 stop = i + 1;
562 step = 1;
563 slicelen = 1;
564 }
565 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000566 int ival;
567 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000568 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000569 self->ob_bytes[i] = (char)ival;
570 return 0;
571 }
572 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000573 else if (PySlice_Check(index)) {
574 if (PySlice_GetIndicesEx((PySliceObject *)index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000575 PyByteArray_GET_SIZE(self),
576 &start, &stop, &step, &slicelen) < 0) {
577 return -1;
578 }
579 }
580 else {
581 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integer");
582 return -1;
583 }
584
585 if (values == NULL) {
586 bytes = NULL;
587 needed = 0;
588 }
589 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
590 /* Make a copy an call this function recursively */
591 int err;
592 values = PyByteArray_FromObject(values);
593 if (values == NULL)
594 return -1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000595 err = bytearray_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000596 Py_DECREF(values);
597 return err;
598 }
599 else {
600 assert(PyByteArray_Check(values));
601 bytes = ((PyByteArrayObject *)values)->ob_bytes;
602 needed = Py_SIZE(values);
603 }
604 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
605 if ((step < 0 && start < stop) ||
606 (step > 0 && start > stop))
607 stop = start;
608 if (step == 1) {
609 if (slicelen != needed) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000610 if (!_canresize(self))
611 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000612 if (slicelen > needed) {
613 /*
614 0 start stop old_size
615 | |<---slicelen--->|<-----tomove------>|
616 | |<-needed->|<-----tomove------>|
617 0 lo new_hi new_size
618 */
619 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
620 Py_SIZE(self) - stop);
621 }
622 if (PyByteArray_Resize((PyObject *)self,
623 Py_SIZE(self) + needed - slicelen) < 0)
624 return -1;
625 if (slicelen < needed) {
626 /*
627 0 lo hi old_size
628 | |<-avail->|<-----tomove------>|
629 | |<----needed---->|<-----tomove------>|
630 0 lo new_hi new_size
631 */
632 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
633 Py_SIZE(self) - start - needed);
634 }
635 }
636
637 if (needed > 0)
638 memcpy(self->ob_bytes + start, bytes, needed);
639
640 return 0;
641 }
642 else {
643 if (needed == 0) {
644 /* Delete slice */
Mark Dickinsonbc099642010-01-29 17:27:24 +0000645 size_t cur;
646 Py_ssize_t i;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000647
Antoine Pitrou5504e892008-12-06 21:27:53 +0000648 if (!_canresize(self))
649 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000650 if (step < 0) {
651 stop = start + 1;
652 start = stop + step * (slicelen - 1) - 1;
653 step = -step;
654 }
655 for (cur = start, i = 0;
656 i < slicelen; cur += step, i++) {
657 Py_ssize_t lim = step - 1;
658
659 if (cur + step >= PyByteArray_GET_SIZE(self))
660 lim = PyByteArray_GET_SIZE(self) - cur - 1;
661
662 memmove(self->ob_bytes + cur - i,
663 self->ob_bytes + cur + 1, lim);
664 }
665 /* Move the tail of the bytes, in one chunk */
666 cur = start + slicelen*step;
667 if (cur < PyByteArray_GET_SIZE(self)) {
668 memmove(self->ob_bytes + cur - slicelen,
669 self->ob_bytes + cur,
670 PyByteArray_GET_SIZE(self) - cur);
671 }
672 if (PyByteArray_Resize((PyObject *)self,
673 PyByteArray_GET_SIZE(self) - slicelen) < 0)
674 return -1;
675
676 return 0;
677 }
678 else {
679 /* Assign slice */
680 Py_ssize_t cur, i;
681
682 if (needed != slicelen) {
683 PyErr_Format(PyExc_ValueError,
684 "attempt to assign bytes of size %zd "
685 "to extended slice of size %zd",
686 needed, slicelen);
687 return -1;
688 }
689 for (cur = start, i = 0; i < slicelen; cur += step, i++)
690 self->ob_bytes[cur] = bytes[i];
691 return 0;
692 }
693 }
694}
695
696static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000697bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000698{
699 static char *kwlist[] = {"source", "encoding", "errors", 0};
700 PyObject *arg = NULL;
701 const char *encoding = NULL;
702 const char *errors = NULL;
703 Py_ssize_t count;
704 PyObject *it;
705 PyObject *(*iternext)(PyObject *);
706
707 if (Py_SIZE(self) != 0) {
708 /* Empty previous contents (yes, do this first of all!) */
709 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
710 return -1;
711 }
712
713 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000714 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000715 &arg, &encoding, &errors))
716 return -1;
717
718 /* Make a quick exit if no first argument */
719 if (arg == NULL) {
720 if (encoding != NULL || errors != NULL) {
721 PyErr_SetString(PyExc_TypeError,
722 "encoding or errors without sequence argument");
723 return -1;
724 }
725 return 0;
726 }
727
728 if (PyUnicode_Check(arg)) {
729 /* Encode via the codec registry */
730 PyObject *encoded, *new;
731 if (encoding == NULL) {
732 PyErr_SetString(PyExc_TypeError,
733 "string argument without an encoding");
734 return -1;
735 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000736 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000737 if (encoded == NULL)
738 return -1;
739 assert(PyBytes_Check(encoded));
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000740 new = bytearray_iconcat(self, encoded);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000741 Py_DECREF(encoded);
742 if (new == NULL)
743 return -1;
744 Py_DECREF(new);
745 return 0;
746 }
747
748 /* If it's not unicode, there can't be encoding or errors */
749 if (encoding != NULL || errors != NULL) {
750 PyErr_SetString(PyExc_TypeError,
751 "encoding or errors without a string argument");
752 return -1;
753 }
754
755 /* Is it an int? */
756 count = PyNumber_AsSsize_t(arg, PyExc_ValueError);
757 if (count == -1 && PyErr_Occurred())
758 PyErr_Clear();
759 else {
760 if (count < 0) {
761 PyErr_SetString(PyExc_ValueError, "negative count");
762 return -1;
763 }
764 if (count > 0) {
765 if (PyByteArray_Resize((PyObject *)self, count))
766 return -1;
767 memset(self->ob_bytes, 0, count);
768 }
769 return 0;
770 }
771
772 /* Use the buffer API */
773 if (PyObject_CheckBuffer(arg)) {
774 Py_ssize_t size;
775 Py_buffer view;
776 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
777 return -1;
778 size = view.len;
779 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
780 if (PyBuffer_ToContiguous(self->ob_bytes, &view, size, 'C') < 0)
781 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000782 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000783 return 0;
784 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000785 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000786 return -1;
787 }
788
789 /* XXX Optimize this if the arguments is a list, tuple */
790
791 /* Get the iterator */
792 it = PyObject_GetIter(arg);
793 if (it == NULL)
794 return -1;
795 iternext = *Py_TYPE(it)->tp_iternext;
796
797 /* Run the iterator to exhaustion */
798 for (;;) {
799 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000800 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000801
802 /* Get the next item */
803 item = iternext(it);
804 if (item == NULL) {
805 if (PyErr_Occurred()) {
806 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
807 goto error;
808 PyErr_Clear();
809 }
810 break;
811 }
812
813 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000814 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000815 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000816 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000817 goto error;
818
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000819 /* Append the byte */
820 if (Py_SIZE(self) < self->ob_alloc)
821 Py_SIZE(self)++;
822 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
823 goto error;
824 self->ob_bytes[Py_SIZE(self)-1] = value;
825 }
826
827 /* Clean up and return success */
828 Py_DECREF(it);
829 return 0;
830
831 error:
832 /* Error handling when it != NULL */
833 Py_DECREF(it);
834 return -1;
835}
836
837/* Mostly copied from string_repr, but without the
838 "smart quote" functionality. */
839static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000840bytearray_repr(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000841{
842 static const char *hexdigits = "0123456789abcdef";
843 const char *quote_prefix = "bytearray(b";
844 const char *quote_postfix = ")";
845 Py_ssize_t length = Py_SIZE(self);
846 /* 14 == strlen(quote_prefix) + 2 + strlen(quote_postfix) */
847 size_t newsize = 14 + 4 * length;
848 PyObject *v;
849 if (newsize > PY_SSIZE_T_MAX || newsize / 4 - 3 != length) {
850 PyErr_SetString(PyExc_OverflowError,
851 "bytearray object is too large to make repr");
852 return NULL;
853 }
854 v = PyUnicode_FromUnicode(NULL, newsize);
855 if (v == NULL) {
856 return NULL;
857 }
858 else {
859 register Py_ssize_t i;
860 register Py_UNICODE c;
861 register Py_UNICODE *p;
862 int quote;
863
864 /* Figure out which quote to use; single is preferred */
865 quote = '\'';
866 {
867 char *test, *start;
868 start = PyByteArray_AS_STRING(self);
869 for (test = start; test < start+length; ++test) {
870 if (*test == '"') {
871 quote = '\''; /* back to single */
872 goto decided;
873 }
874 else if (*test == '\'')
875 quote = '"';
876 }
877 decided:
878 ;
879 }
880
881 p = PyUnicode_AS_UNICODE(v);
882 while (*quote_prefix)
883 *p++ = *quote_prefix++;
884 *p++ = quote;
885
886 for (i = 0; i < length; i++) {
887 /* There's at least enough room for a hex escape
888 and a closing quote. */
889 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5);
890 c = self->ob_bytes[i];
891 if (c == '\'' || c == '\\')
892 *p++ = '\\', *p++ = c;
893 else if (c == '\t')
894 *p++ = '\\', *p++ = 't';
895 else if (c == '\n')
896 *p++ = '\\', *p++ = 'n';
897 else if (c == '\r')
898 *p++ = '\\', *p++ = 'r';
899 else if (c == 0)
900 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
901 else if (c < ' ' || c >= 0x7f) {
902 *p++ = '\\';
903 *p++ = 'x';
904 *p++ = hexdigits[(c & 0xf0) >> 4];
905 *p++ = hexdigits[c & 0xf];
906 }
907 else
908 *p++ = c;
909 }
910 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1);
911 *p++ = quote;
912 while (*quote_postfix) {
913 *p++ = *quote_postfix++;
914 }
915 *p = '\0';
916 if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) {
917 Py_DECREF(v);
918 return NULL;
919 }
920 return v;
921 }
922}
923
924static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000925bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000926{
927 if (Py_BytesWarningFlag) {
928 if (PyErr_WarnEx(PyExc_BytesWarning,
929 "str() on a bytearray instance", 1))
930 return NULL;
931 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000932 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000933}
934
935static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000936bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000937{
938 Py_ssize_t self_size, other_size;
939 Py_buffer self_bytes, other_bytes;
940 PyObject *res;
941 Py_ssize_t minsize;
942 int cmp;
943
944 /* Bytes can be compared to anything that supports the (binary)
945 buffer API. Except that a comparison with Unicode is always an
946 error, even if the comparison is for equality. */
947 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
948 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
Barry Warsaw9e9dcd62008-10-17 01:50:37 +0000949 if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000950 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +0000951 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000952 return NULL;
953 }
954
955 Py_INCREF(Py_NotImplemented);
956 return Py_NotImplemented;
957 }
958
959 self_size = _getbuffer(self, &self_bytes);
960 if (self_size < 0) {
961 PyErr_Clear();
962 Py_INCREF(Py_NotImplemented);
963 return Py_NotImplemented;
964 }
965
966 other_size = _getbuffer(other, &other_bytes);
967 if (other_size < 0) {
968 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +0000969 PyBuffer_Release(&self_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000970 Py_INCREF(Py_NotImplemented);
971 return Py_NotImplemented;
972 }
973
974 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
975 /* Shortcut: if the lengths differ, the objects differ */
976 cmp = (op == Py_NE);
977 }
978 else {
979 minsize = self_size;
980 if (other_size < minsize)
981 minsize = other_size;
982
983 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
984 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
985
986 if (cmp == 0) {
987 if (self_size < other_size)
988 cmp = -1;
989 else if (self_size > other_size)
990 cmp = 1;
991 }
992
993 switch (op) {
994 case Py_LT: cmp = cmp < 0; break;
995 case Py_LE: cmp = cmp <= 0; break;
996 case Py_EQ: cmp = cmp == 0; break;
997 case Py_NE: cmp = cmp != 0; break;
998 case Py_GT: cmp = cmp > 0; break;
999 case Py_GE: cmp = cmp >= 0; break;
1000 }
1001 }
1002
1003 res = cmp ? Py_True : Py_False;
Martin v. Löwis423be952008-08-13 15:53:07 +00001004 PyBuffer_Release(&self_bytes);
1005 PyBuffer_Release(&other_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001006 Py_INCREF(res);
1007 return res;
1008}
1009
1010static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001011bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001012{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001013 if (self->ob_exports > 0) {
1014 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001015 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001016 PyErr_Print();
1017 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001018 if (self->ob_bytes != 0) {
1019 PyMem_Free(self->ob_bytes);
1020 }
1021 Py_TYPE(self)->tp_free((PyObject *)self);
1022}
1023
1024
1025/* -------------------------------------------------------------------- */
1026/* Methods */
1027
1028#define STRINGLIB_CHAR char
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001029#define STRINGLIB_LEN PyByteArray_GET_SIZE
1030#define STRINGLIB_STR PyByteArray_AS_STRING
1031#define STRINGLIB_NEW PyByteArray_FromStringAndSize
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001032#define STRINGLIB_ISSPACE Py_ISSPACE
1033#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001034#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1035#define STRINGLIB_MUTABLE 1
1036
1037#include "stringlib/fastsearch.h"
1038#include "stringlib/count.h"
1039#include "stringlib/find.h"
1040#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001041#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001042#include "stringlib/ctype.h"
1043#include "stringlib/transmogrify.h"
1044
1045
1046/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1047were copied from the old char* style string object. */
1048
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001049/* helper macro to fixup start/end slice values */
1050#define ADJUST_INDICES(start, end, len) \
1051 if (end > len) \
1052 end = len; \
1053 else if (end < 0) { \
1054 end += len; \
1055 if (end < 0) \
1056 end = 0; \
1057 } \
1058 if (start < 0) { \
1059 start += len; \
1060 if (start < 0) \
1061 start = 0; \
1062 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001063
1064Py_LOCAL_INLINE(Py_ssize_t)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001065bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001066{
1067 PyObject *subobj;
1068 Py_buffer subbuf;
1069 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1070 Py_ssize_t res;
1071
1072 if (!PyArg_ParseTuple(args, "O|O&O&:find/rfind/index/rindex", &subobj,
1073 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1074 return -2;
1075 if (_getbuffer(subobj, &subbuf) < 0)
1076 return -2;
1077 if (dir > 0)
1078 res = stringlib_find_slice(
1079 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1080 subbuf.buf, subbuf.len, start, end);
1081 else
1082 res = stringlib_rfind_slice(
1083 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1084 subbuf.buf, subbuf.len, start, end);
Martin v. Löwis423be952008-08-13 15:53:07 +00001085 PyBuffer_Release(&subbuf);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001086 return res;
1087}
1088
1089PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001090"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001091\n\
1092Return the lowest index in B where subsection sub is found,\n\
1093such that sub is contained within s[start,end]. Optional\n\
1094arguments start and end are interpreted as in slice notation.\n\
1095\n\
1096Return -1 on failure.");
1097
1098static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001099bytearray_find(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001100{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001101 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001102 if (result == -2)
1103 return NULL;
1104 return PyLong_FromSsize_t(result);
1105}
1106
1107PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001108"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001109\n\
1110Return the number of non-overlapping occurrences of subsection sub in\n\
1111bytes B[start:end]. Optional arguments start and end are interpreted\n\
1112as in slice notation.");
1113
1114static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001115bytearray_count(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001116{
1117 PyObject *sub_obj;
1118 const char *str = PyByteArray_AS_STRING(self);
1119 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
1120 Py_buffer vsub;
1121 PyObject *count_obj;
1122
1123 if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj,
1124 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1125 return NULL;
1126
1127 if (_getbuffer(sub_obj, &vsub) < 0)
1128 return NULL;
1129
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001130 ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001131
1132 count_obj = PyLong_FromSsize_t(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001133 stringlib_count(str + start, end - start, vsub.buf, vsub.len, PY_SSIZE_T_MAX)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001134 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001135 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001136 return count_obj;
1137}
1138
1139
1140PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001141"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001142\n\
1143Like B.find() but raise ValueError when the subsection is not found.");
1144
1145static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001146bytearray_index(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001147{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001148 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001149 if (result == -2)
1150 return NULL;
1151 if (result == -1) {
1152 PyErr_SetString(PyExc_ValueError,
1153 "subsection not found");
1154 return NULL;
1155 }
1156 return PyLong_FromSsize_t(result);
1157}
1158
1159
1160PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001161"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001162\n\
1163Return the highest index in B where subsection sub is found,\n\
1164such that sub is contained within s[start,end]. Optional\n\
1165arguments start and end are interpreted as in slice notation.\n\
1166\n\
1167Return -1 on failure.");
1168
1169static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001170bytearray_rfind(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001171{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001172 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001173 if (result == -2)
1174 return NULL;
1175 return PyLong_FromSsize_t(result);
1176}
1177
1178
1179PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001180"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001181\n\
1182Like B.rfind() but raise ValueError when the subsection is not found.");
1183
1184static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001185bytearray_rindex(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001186{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001187 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001188 if (result == -2)
1189 return NULL;
1190 if (result == -1) {
1191 PyErr_SetString(PyExc_ValueError,
1192 "subsection not found");
1193 return NULL;
1194 }
1195 return PyLong_FromSsize_t(result);
1196}
1197
1198
1199static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001200bytearray_contains(PyObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001201{
1202 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1203 if (ival == -1 && PyErr_Occurred()) {
1204 Py_buffer varg;
1205 int pos;
1206 PyErr_Clear();
1207 if (_getbuffer(arg, &varg) < 0)
1208 return -1;
1209 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1210 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001211 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001212 return pos >= 0;
1213 }
1214 if (ival < 0 || ival >= 256) {
1215 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1216 return -1;
1217 }
1218
1219 return memchr(PyByteArray_AS_STRING(self), ival, Py_SIZE(self)) != NULL;
1220}
1221
1222
1223/* Matches the end (direction >= 0) or start (direction < 0) of self
1224 * against substr, using the start and end arguments. Returns
1225 * -1 on error, 0 if not found and 1 if found.
1226 */
1227Py_LOCAL(int)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001228_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001229 Py_ssize_t end, int direction)
1230{
1231 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1232 const char* str;
1233 Py_buffer vsubstr;
1234 int rv = 0;
1235
1236 str = PyByteArray_AS_STRING(self);
1237
1238 if (_getbuffer(substr, &vsubstr) < 0)
1239 return -1;
1240
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001241 ADJUST_INDICES(start, end, len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001242
1243 if (direction < 0) {
1244 /* startswith */
1245 if (start+vsubstr.len > len) {
1246 goto done;
1247 }
1248 } else {
1249 /* endswith */
1250 if (end-start < vsubstr.len || start > len) {
1251 goto done;
1252 }
1253
1254 if (end-vsubstr.len > start)
1255 start = end - vsubstr.len;
1256 }
1257 if (end-start >= vsubstr.len)
1258 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1259
1260done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001261 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001262 return rv;
1263}
1264
1265
1266PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001267"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001268\n\
1269Return True if B starts with the specified prefix, False otherwise.\n\
1270With optional start, test B beginning at that position.\n\
1271With optional end, stop comparing B at that position.\n\
1272prefix can also be a tuple of strings to try.");
1273
1274static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001275bytearray_startswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001276{
1277 Py_ssize_t start = 0;
1278 Py_ssize_t end = PY_SSIZE_T_MAX;
1279 PyObject *subobj;
1280 int result;
1281
1282 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
1283 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1284 return NULL;
1285 if (PyTuple_Check(subobj)) {
1286 Py_ssize_t i;
1287 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001288 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001289 PyTuple_GET_ITEM(subobj, i),
1290 start, end, -1);
1291 if (result == -1)
1292 return NULL;
1293 else if (result) {
1294 Py_RETURN_TRUE;
1295 }
1296 }
1297 Py_RETURN_FALSE;
1298 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001299 result = _bytearray_tailmatch(self, subobj, start, end, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001300 if (result == -1)
1301 return NULL;
1302 else
1303 return PyBool_FromLong(result);
1304}
1305
1306PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001307"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001308\n\
1309Return True if B ends with the specified suffix, False otherwise.\n\
1310With optional start, test B beginning at that position.\n\
1311With optional end, stop comparing B at that position.\n\
1312suffix can also be a tuple of strings to try.");
1313
1314static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001315bytearray_endswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001316{
1317 Py_ssize_t start = 0;
1318 Py_ssize_t end = PY_SSIZE_T_MAX;
1319 PyObject *subobj;
1320 int result;
1321
1322 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
1323 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1324 return NULL;
1325 if (PyTuple_Check(subobj)) {
1326 Py_ssize_t i;
1327 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001328 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001329 PyTuple_GET_ITEM(subobj, i),
1330 start, end, +1);
1331 if (result == -1)
1332 return NULL;
1333 else if (result) {
1334 Py_RETURN_TRUE;
1335 }
1336 }
1337 Py_RETURN_FALSE;
1338 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001339 result = _bytearray_tailmatch(self, subobj, start, end, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001340 if (result == -1)
1341 return NULL;
1342 else
1343 return PyBool_FromLong(result);
1344}
1345
1346
1347PyDoc_STRVAR(translate__doc__,
1348"B.translate(table[, deletechars]) -> bytearray\n\
1349\n\
1350Return a copy of B, where all characters occurring in the\n\
1351optional argument deletechars are removed, and the remaining\n\
1352characters have been mapped through the given translation\n\
1353table, which must be a bytes object of length 256.");
1354
1355static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001356bytearray_translate(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001357{
1358 register char *input, *output;
1359 register const char *table;
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001360 register Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001361 PyObject *input_obj = (PyObject*)self;
1362 const char *output_start;
1363 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001364 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001365 int trans_table[256];
Georg Brandlccc47b62008-12-28 11:44:14 +00001366 PyObject *tableobj = NULL, *delobj = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001367 Py_buffer vtable, vdel;
1368
1369 if (!PyArg_UnpackTuple(args, "translate", 1, 2,
1370 &tableobj, &delobj))
1371 return NULL;
1372
Georg Brandlccc47b62008-12-28 11:44:14 +00001373 if (tableobj == Py_None) {
1374 table = NULL;
1375 tableobj = NULL;
1376 } else if (_getbuffer(tableobj, &vtable) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001377 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001378 } else {
1379 if (vtable.len != 256) {
1380 PyErr_SetString(PyExc_ValueError,
1381 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001382 PyBuffer_Release(&vtable);
1383 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001384 }
1385 table = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001386 }
1387
1388 if (delobj != NULL) {
1389 if (_getbuffer(delobj, &vdel) < 0) {
Georg Brandl953152f2009-07-22 12:03:59 +00001390 if (tableobj != NULL)
1391 PyBuffer_Release(&vtable);
1392 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001393 }
1394 }
1395 else {
1396 vdel.buf = NULL;
1397 vdel.len = 0;
1398 }
1399
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001400 inlen = PyByteArray_GET_SIZE(input_obj);
1401 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1402 if (result == NULL)
1403 goto done;
1404 output_start = output = PyByteArray_AsString(result);
1405 input = PyByteArray_AS_STRING(input_obj);
1406
Georg Brandlccc47b62008-12-28 11:44:14 +00001407 if (vdel.len == 0 && table != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001408 /* If no deletions are required, use faster code */
1409 for (i = inlen; --i >= 0; ) {
1410 c = Py_CHARMASK(*input++);
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001411 *output++ = table[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001412 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001413 goto done;
1414 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001415
1416 if (table == NULL) {
1417 for (i = 0; i < 256; i++)
1418 trans_table[i] = Py_CHARMASK(i);
1419 } else {
1420 for (i = 0; i < 256; i++)
1421 trans_table[i] = Py_CHARMASK(table[i]);
1422 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001423
1424 for (i = 0; i < vdel.len; i++)
1425 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1426
1427 for (i = inlen; --i >= 0; ) {
1428 c = Py_CHARMASK(*input++);
1429 if (trans_table[c] != -1)
1430 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1431 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001432 }
1433 /* Fix the size of the resulting string */
1434 if (inlen > 0)
1435 PyByteArray_Resize(result, output - output_start);
1436
1437done:
Georg Brandlccc47b62008-12-28 11:44:14 +00001438 if (tableobj != NULL)
1439 PyBuffer_Release(&vtable);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001440 if (delobj != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001441 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001442 return result;
1443}
1444
1445
Georg Brandlabc38772009-04-12 15:51:51 +00001446static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001447bytearray_maketrans(PyObject *null, PyObject *args)
Georg Brandlabc38772009-04-12 15:51:51 +00001448{
1449 return _Py_bytes_maketrans(args);
1450}
1451
1452
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001453/* find and count characters and substrings */
1454
1455#define findchar(target, target_len, c) \
1456 ((char *)memchr((const void *)(target), c, target_len))
1457
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001458
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001459/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001460Py_LOCAL(PyByteArrayObject *)
1461return_self(PyByteArrayObject *self)
1462{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001463 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001464 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1465 PyByteArray_AS_STRING(self),
1466 PyByteArray_GET_SIZE(self));
1467}
1468
1469Py_LOCAL_INLINE(Py_ssize_t)
1470countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1471{
1472 Py_ssize_t count=0;
1473 const char *start=target;
1474 const char *end=target+target_len;
1475
1476 while ( (start=findchar(start, end-start, c)) != NULL ) {
1477 count++;
1478 if (count >= maxcount)
1479 break;
1480 start += 1;
1481 }
1482 return count;
1483}
1484
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001485
1486/* Algorithms for different cases of string replacement */
1487
1488/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1489Py_LOCAL(PyByteArrayObject *)
1490replace_interleave(PyByteArrayObject *self,
1491 const char *to_s, Py_ssize_t to_len,
1492 Py_ssize_t maxcount)
1493{
1494 char *self_s, *result_s;
1495 Py_ssize_t self_len, result_len;
1496 Py_ssize_t count, i, product;
1497 PyByteArrayObject *result;
1498
1499 self_len = PyByteArray_GET_SIZE(self);
1500
1501 /* 1 at the end plus 1 after every character */
1502 count = self_len+1;
1503 if (maxcount < count)
1504 count = maxcount;
1505
1506 /* Check for overflow */
1507 /* result_len = count * to_len + self_len; */
1508 product = count * to_len;
1509 if (product / to_len != count) {
1510 PyErr_SetString(PyExc_OverflowError,
1511 "replace string is too long");
1512 return NULL;
1513 }
1514 result_len = product + self_len;
1515 if (result_len < 0) {
1516 PyErr_SetString(PyExc_OverflowError,
1517 "replace string is too long");
1518 return NULL;
1519 }
1520
1521 if (! (result = (PyByteArrayObject *)
1522 PyByteArray_FromStringAndSize(NULL, result_len)) )
1523 return NULL;
1524
1525 self_s = PyByteArray_AS_STRING(self);
1526 result_s = PyByteArray_AS_STRING(result);
1527
1528 /* TODO: special case single character, which doesn't need memcpy */
1529
1530 /* Lay the first one down (guaranteed this will occur) */
1531 Py_MEMCPY(result_s, to_s, to_len);
1532 result_s += to_len;
1533 count -= 1;
1534
1535 for (i=0; i<count; i++) {
1536 *result_s++ = *self_s++;
1537 Py_MEMCPY(result_s, to_s, to_len);
1538 result_s += to_len;
1539 }
1540
1541 /* Copy the rest of the original string */
1542 Py_MEMCPY(result_s, self_s, self_len-i);
1543
1544 return result;
1545}
1546
1547/* Special case for deleting a single character */
1548/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1549Py_LOCAL(PyByteArrayObject *)
1550replace_delete_single_character(PyByteArrayObject *self,
1551 char from_c, Py_ssize_t maxcount)
1552{
1553 char *self_s, *result_s;
1554 char *start, *next, *end;
1555 Py_ssize_t self_len, result_len;
1556 Py_ssize_t count;
1557 PyByteArrayObject *result;
1558
1559 self_len = PyByteArray_GET_SIZE(self);
1560 self_s = PyByteArray_AS_STRING(self);
1561
1562 count = countchar(self_s, self_len, from_c, maxcount);
1563 if (count == 0) {
1564 return return_self(self);
1565 }
1566
1567 result_len = self_len - count; /* from_len == 1 */
1568 assert(result_len>=0);
1569
1570 if ( (result = (PyByteArrayObject *)
1571 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1572 return NULL;
1573 result_s = PyByteArray_AS_STRING(result);
1574
1575 start = self_s;
1576 end = self_s + self_len;
1577 while (count-- > 0) {
1578 next = findchar(start, end-start, from_c);
1579 if (next == NULL)
1580 break;
1581 Py_MEMCPY(result_s, start, next-start);
1582 result_s += (next-start);
1583 start = next+1;
1584 }
1585 Py_MEMCPY(result_s, start, end-start);
1586
1587 return result;
1588}
1589
1590/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1591
1592Py_LOCAL(PyByteArrayObject *)
1593replace_delete_substring(PyByteArrayObject *self,
1594 const char *from_s, Py_ssize_t from_len,
1595 Py_ssize_t maxcount)
1596{
1597 char *self_s, *result_s;
1598 char *start, *next, *end;
1599 Py_ssize_t self_len, result_len;
1600 Py_ssize_t count, offset;
1601 PyByteArrayObject *result;
1602
1603 self_len = PyByteArray_GET_SIZE(self);
1604 self_s = PyByteArray_AS_STRING(self);
1605
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001606 count = stringlib_count(self_s, self_len,
1607 from_s, from_len,
1608 maxcount);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001609
1610 if (count == 0) {
1611 /* no matches */
1612 return return_self(self);
1613 }
1614
1615 result_len = self_len - (count * from_len);
1616 assert (result_len>=0);
1617
1618 if ( (result = (PyByteArrayObject *)
1619 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1620 return NULL;
1621
1622 result_s = PyByteArray_AS_STRING(result);
1623
1624 start = self_s;
1625 end = self_s + self_len;
1626 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001627 offset = stringlib_find(start, end-start,
1628 from_s, from_len,
1629 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001630 if (offset == -1)
1631 break;
1632 next = start + offset;
1633
1634 Py_MEMCPY(result_s, start, next-start);
1635
1636 result_s += (next-start);
1637 start = next+from_len;
1638 }
1639 Py_MEMCPY(result_s, start, end-start);
1640 return result;
1641}
1642
1643/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1644Py_LOCAL(PyByteArrayObject *)
1645replace_single_character_in_place(PyByteArrayObject *self,
1646 char from_c, char to_c,
1647 Py_ssize_t maxcount)
1648{
1649 char *self_s, *result_s, *start, *end, *next;
1650 Py_ssize_t self_len;
1651 PyByteArrayObject *result;
1652
1653 /* The result string will be the same size */
1654 self_s = PyByteArray_AS_STRING(self);
1655 self_len = PyByteArray_GET_SIZE(self);
1656
1657 next = findchar(self_s, self_len, from_c);
1658
1659 if (next == NULL) {
1660 /* No matches; return the original bytes */
1661 return return_self(self);
1662 }
1663
1664 /* Need to make a new bytes */
1665 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1666 if (result == NULL)
1667 return NULL;
1668 result_s = PyByteArray_AS_STRING(result);
1669 Py_MEMCPY(result_s, self_s, self_len);
1670
1671 /* change everything in-place, starting with this one */
1672 start = result_s + (next-self_s);
1673 *start = to_c;
1674 start++;
1675 end = result_s + self_len;
1676
1677 while (--maxcount > 0) {
1678 next = findchar(start, end-start, from_c);
1679 if (next == NULL)
1680 break;
1681 *next = to_c;
1682 start = next+1;
1683 }
1684
1685 return result;
1686}
1687
1688/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1689Py_LOCAL(PyByteArrayObject *)
1690replace_substring_in_place(PyByteArrayObject *self,
1691 const char *from_s, Py_ssize_t from_len,
1692 const char *to_s, Py_ssize_t to_len,
1693 Py_ssize_t maxcount)
1694{
1695 char *result_s, *start, *end;
1696 char *self_s;
1697 Py_ssize_t self_len, offset;
1698 PyByteArrayObject *result;
1699
1700 /* The result bytes will be the same size */
1701
1702 self_s = PyByteArray_AS_STRING(self);
1703 self_len = PyByteArray_GET_SIZE(self);
1704
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001705 offset = stringlib_find(self_s, self_len,
1706 from_s, from_len,
1707 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001708 if (offset == -1) {
1709 /* No matches; return the original bytes */
1710 return return_self(self);
1711 }
1712
1713 /* Need to make a new bytes */
1714 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1715 if (result == NULL)
1716 return NULL;
1717 result_s = PyByteArray_AS_STRING(result);
1718 Py_MEMCPY(result_s, self_s, self_len);
1719
1720 /* change everything in-place, starting with this one */
1721 start = result_s + offset;
1722 Py_MEMCPY(start, to_s, from_len);
1723 start += from_len;
1724 end = result_s + self_len;
1725
1726 while ( --maxcount > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001727 offset = stringlib_find(start, end-start,
1728 from_s, from_len,
1729 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001730 if (offset==-1)
1731 break;
1732 Py_MEMCPY(start+offset, to_s, from_len);
1733 start += offset+from_len;
1734 }
1735
1736 return result;
1737}
1738
1739/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
1740Py_LOCAL(PyByteArrayObject *)
1741replace_single_character(PyByteArrayObject *self,
1742 char from_c,
1743 const char *to_s, Py_ssize_t to_len,
1744 Py_ssize_t maxcount)
1745{
1746 char *self_s, *result_s;
1747 char *start, *next, *end;
1748 Py_ssize_t self_len, result_len;
1749 Py_ssize_t count, product;
1750 PyByteArrayObject *result;
1751
1752 self_s = PyByteArray_AS_STRING(self);
1753 self_len = PyByteArray_GET_SIZE(self);
1754
1755 count = countchar(self_s, self_len, from_c, maxcount);
1756 if (count == 0) {
1757 /* no matches, return unchanged */
1758 return return_self(self);
1759 }
1760
1761 /* use the difference between current and new, hence the "-1" */
1762 /* result_len = self_len + count * (to_len-1) */
1763 product = count * (to_len-1);
1764 if (product / (to_len-1) != count) {
1765 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1766 return NULL;
1767 }
1768 result_len = self_len + product;
1769 if (result_len < 0) {
1770 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1771 return NULL;
1772 }
1773
1774 if ( (result = (PyByteArrayObject *)
1775 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1776 return NULL;
1777 result_s = PyByteArray_AS_STRING(result);
1778
1779 start = self_s;
1780 end = self_s + self_len;
1781 while (count-- > 0) {
1782 next = findchar(start, end-start, from_c);
1783 if (next == NULL)
1784 break;
1785
1786 if (next == start) {
1787 /* replace with the 'to' */
1788 Py_MEMCPY(result_s, to_s, to_len);
1789 result_s += to_len;
1790 start += 1;
1791 } else {
1792 /* copy the unchanged old then the 'to' */
1793 Py_MEMCPY(result_s, start, next-start);
1794 result_s += (next-start);
1795 Py_MEMCPY(result_s, to_s, to_len);
1796 result_s += to_len;
1797 start = next+1;
1798 }
1799 }
1800 /* Copy the remainder of the remaining bytes */
1801 Py_MEMCPY(result_s, start, end-start);
1802
1803 return result;
1804}
1805
1806/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
1807Py_LOCAL(PyByteArrayObject *)
1808replace_substring(PyByteArrayObject *self,
1809 const char *from_s, Py_ssize_t from_len,
1810 const char *to_s, Py_ssize_t to_len,
1811 Py_ssize_t maxcount)
1812{
1813 char *self_s, *result_s;
1814 char *start, *next, *end;
1815 Py_ssize_t self_len, result_len;
1816 Py_ssize_t count, offset, product;
1817 PyByteArrayObject *result;
1818
1819 self_s = PyByteArray_AS_STRING(self);
1820 self_len = PyByteArray_GET_SIZE(self);
1821
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001822 count = stringlib_count(self_s, self_len,
1823 from_s, from_len,
1824 maxcount);
1825
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001826 if (count == 0) {
1827 /* no matches, return unchanged */
1828 return return_self(self);
1829 }
1830
1831 /* Check for overflow */
1832 /* result_len = self_len + count * (to_len-from_len) */
1833 product = count * (to_len-from_len);
1834 if (product / (to_len-from_len) != count) {
1835 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1836 return NULL;
1837 }
1838 result_len = self_len + product;
1839 if (result_len < 0) {
1840 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1841 return NULL;
1842 }
1843
1844 if ( (result = (PyByteArrayObject *)
1845 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1846 return NULL;
1847 result_s = PyByteArray_AS_STRING(result);
1848
1849 start = self_s;
1850 end = self_s + self_len;
1851 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001852 offset = stringlib_find(start, end-start,
1853 from_s, from_len,
1854 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001855 if (offset == -1)
1856 break;
1857 next = start+offset;
1858 if (next == start) {
1859 /* replace with the 'to' */
1860 Py_MEMCPY(result_s, to_s, to_len);
1861 result_s += to_len;
1862 start += from_len;
1863 } else {
1864 /* copy the unchanged old then the 'to' */
1865 Py_MEMCPY(result_s, start, next-start);
1866 result_s += (next-start);
1867 Py_MEMCPY(result_s, to_s, to_len);
1868 result_s += to_len;
1869 start = next+from_len;
1870 }
1871 }
1872 /* Copy the remainder of the remaining bytes */
1873 Py_MEMCPY(result_s, start, end-start);
1874
1875 return result;
1876}
1877
1878
1879Py_LOCAL(PyByteArrayObject *)
1880replace(PyByteArrayObject *self,
1881 const char *from_s, Py_ssize_t from_len,
1882 const char *to_s, Py_ssize_t to_len,
1883 Py_ssize_t maxcount)
1884{
1885 if (maxcount < 0) {
1886 maxcount = PY_SSIZE_T_MAX;
1887 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
1888 /* nothing to do; return the original bytes */
1889 return return_self(self);
1890 }
1891
1892 if (maxcount == 0 ||
1893 (from_len == 0 && to_len == 0)) {
1894 /* nothing to do; return the original bytes */
1895 return return_self(self);
1896 }
1897
1898 /* Handle zero-length special cases */
1899
1900 if (from_len == 0) {
1901 /* insert the 'to' bytes everywhere. */
1902 /* >>> "Python".replace("", ".") */
1903 /* '.P.y.t.h.o.n.' */
1904 return replace_interleave(self, to_s, to_len, maxcount);
1905 }
1906
1907 /* Except for "".replace("", "A") == "A" there is no way beyond this */
1908 /* point for an empty self bytes to generate a non-empty bytes */
1909 /* Special case so the remaining code always gets a non-empty bytes */
1910 if (PyByteArray_GET_SIZE(self) == 0) {
1911 return return_self(self);
1912 }
1913
1914 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00001915 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001916 if (from_len == 1) {
1917 return replace_delete_single_character(
1918 self, from_s[0], maxcount);
1919 } else {
1920 return replace_delete_substring(self, from_s, from_len, maxcount);
1921 }
1922 }
1923
1924 /* Handle special case where both bytes have the same length */
1925
1926 if (from_len == to_len) {
1927 if (from_len == 1) {
1928 return replace_single_character_in_place(
1929 self,
1930 from_s[0],
1931 to_s[0],
1932 maxcount);
1933 } else {
1934 return replace_substring_in_place(
1935 self, from_s, from_len, to_s, to_len, maxcount);
1936 }
1937 }
1938
1939 /* Otherwise use the more generic algorithms */
1940 if (from_len == 1) {
1941 return replace_single_character(self, from_s[0],
1942 to_s, to_len, maxcount);
1943 } else {
1944 /* len('from')>=2, len('to')>=1 */
1945 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
1946 }
1947}
1948
1949
1950PyDoc_STRVAR(replace__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001951"B.replace(old, new[, count]) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001952\n\
1953Return a copy of B with all occurrences of subsection\n\
1954old replaced by new. If the optional argument count is\n\
1955given, only the first count occurrences are replaced.");
1956
1957static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001958bytearray_replace(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001959{
1960 Py_ssize_t count = -1;
1961 PyObject *from, *to, *res;
1962 Py_buffer vfrom, vto;
1963
1964 if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
1965 return NULL;
1966
1967 if (_getbuffer(from, &vfrom) < 0)
1968 return NULL;
1969 if (_getbuffer(to, &vto) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +00001970 PyBuffer_Release(&vfrom);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001971 return NULL;
1972 }
1973
1974 res = (PyObject *)replace((PyByteArrayObject *) self,
1975 vfrom.buf, vfrom.len,
1976 vto.buf, vto.len, count);
1977
Martin v. Löwis423be952008-08-13 15:53:07 +00001978 PyBuffer_Release(&vfrom);
1979 PyBuffer_Release(&vto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001980 return res;
1981}
1982
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001983PyDoc_STRVAR(split__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001984"B.split([sep[, maxsplit]]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001985\n\
1986Return a list of the sections in B, using sep as the delimiter.\n\
1987If sep is not given, B is split on ASCII whitespace characters\n\
1988(space, tab, return, newline, formfeed, vertical tab).\n\
1989If maxsplit is given, at most maxsplit splits are done.");
1990
1991static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001992bytearray_split(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001993{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001994 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
1995 Py_ssize_t maxsplit = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001996 const char *s = PyByteArray_AS_STRING(self), *sub;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001997 PyObject *list, *subobj = Py_None;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001998 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001999
2000 if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
2001 return NULL;
2002 if (maxsplit < 0)
2003 maxsplit = PY_SSIZE_T_MAX;
2004
2005 if (subobj == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002006 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002007
2008 if (_getbuffer(subobj, &vsub) < 0)
2009 return NULL;
2010 sub = vsub.buf;
2011 n = vsub.len;
2012
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002013 list = stringlib_split(
2014 (PyObject*) self, s, len, sub, n, maxsplit
2015 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002016 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002017 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002018}
2019
2020PyDoc_STRVAR(partition__doc__,
2021"B.partition(sep) -> (head, sep, tail)\n\
2022\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002023Search for the separator sep in B, and return the part before it,\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002024the separator itself, and the part after it. If the separator is not\n\
2025found, returns B and two empty bytearray objects.");
2026
2027static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002028bytearray_partition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002029{
2030 PyObject *bytesep, *result;
2031
2032 bytesep = PyByteArray_FromObject(sep_obj);
2033 if (! bytesep)
2034 return NULL;
2035
2036 result = stringlib_partition(
2037 (PyObject*) self,
2038 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2039 bytesep,
2040 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2041 );
2042
2043 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002044 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002045}
2046
2047PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +00002048"B.rpartition(sep) -> (head, sep, tail)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002049\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002050Search for the separator sep in B, starting at the end of B,\n\
2051and return the part before it, the separator itself, and the\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002052part after it. If the separator is not found, returns two empty\n\
2053bytearray objects and B.");
2054
2055static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002056bytearray_rpartition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002057{
2058 PyObject *bytesep, *result;
2059
2060 bytesep = PyByteArray_FromObject(sep_obj);
2061 if (! bytesep)
2062 return NULL;
2063
2064 result = stringlib_rpartition(
2065 (PyObject*) self,
2066 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2067 bytesep,
2068 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2069 );
2070
2071 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002072 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002073}
2074
2075PyDoc_STRVAR(rsplit__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002076"B.rsplit(sep[, maxsplit]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002077\n\
2078Return a list of the sections in B, using sep as the delimiter,\n\
2079starting at the end of B and working to the front.\n\
2080If sep is not given, B is split on ASCII whitespace characters\n\
2081(space, tab, return, newline, formfeed, vertical tab).\n\
2082If maxsplit is given, at most maxsplit splits are done.");
2083
2084static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002085bytearray_rsplit(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002086{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002087 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
2088 Py_ssize_t maxsplit = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002089 const char *s = PyByteArray_AS_STRING(self), *sub;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002090 PyObject *list, *subobj = Py_None;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002091 Py_buffer vsub;
2092
2093 if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
2094 return NULL;
2095 if (maxsplit < 0)
2096 maxsplit = PY_SSIZE_T_MAX;
2097
2098 if (subobj == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002099 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002100
2101 if (_getbuffer(subobj, &vsub) < 0)
2102 return NULL;
2103 sub = vsub.buf;
2104 n = vsub.len;
2105
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002106 list = stringlib_rsplit(
2107 (PyObject*) self, s, len, sub, n, maxsplit
2108 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002109 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002110 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002111}
2112
2113PyDoc_STRVAR(reverse__doc__,
2114"B.reverse() -> None\n\
2115\n\
2116Reverse the order of the values in B in place.");
2117static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002118bytearray_reverse(PyByteArrayObject *self, PyObject *unused)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002119{
2120 char swap, *head, *tail;
2121 Py_ssize_t i, j, n = Py_SIZE(self);
2122
2123 j = n / 2;
2124 head = self->ob_bytes;
2125 tail = head + n - 1;
2126 for (i = 0; i < j; i++) {
2127 swap = *head;
2128 *head++ = *tail;
2129 *tail-- = swap;
2130 }
2131
2132 Py_RETURN_NONE;
2133}
2134
2135PyDoc_STRVAR(insert__doc__,
2136"B.insert(index, int) -> None\n\
2137\n\
2138Insert a single item into the bytearray before the given index.");
2139static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002140bytearray_insert(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002141{
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002142 PyObject *value;
2143 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002144 Py_ssize_t where, n = Py_SIZE(self);
2145
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002146 if (!PyArg_ParseTuple(args, "nO:insert", &where, &value))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002147 return NULL;
2148
2149 if (n == PY_SSIZE_T_MAX) {
2150 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002151 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002152 return NULL;
2153 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002154 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002155 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002156 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2157 return NULL;
2158
2159 if (where < 0) {
2160 where += n;
2161 if (where < 0)
2162 where = 0;
2163 }
2164 if (where > n)
2165 where = n;
2166 memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where);
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002167 self->ob_bytes[where] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002168
2169 Py_RETURN_NONE;
2170}
2171
2172PyDoc_STRVAR(append__doc__,
2173"B.append(int) -> None\n\
2174\n\
2175Append a single item to the end of B.");
2176static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002177bytearray_append(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002178{
2179 int value;
2180 Py_ssize_t n = Py_SIZE(self);
2181
2182 if (! _getbytevalue(arg, &value))
2183 return NULL;
2184 if (n == PY_SSIZE_T_MAX) {
2185 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002186 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002187 return NULL;
2188 }
2189 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2190 return NULL;
2191
2192 self->ob_bytes[n] = value;
2193
2194 Py_RETURN_NONE;
2195}
2196
2197PyDoc_STRVAR(extend__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002198"B.extend(iterable_of_ints) -> None\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002199\n\
2200Append all the elements from the iterator or sequence to the\n\
2201end of B.");
2202static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002203bytearray_extend(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002204{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002205 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002206 Py_ssize_t buf_size = 0, len = 0;
2207 int value;
2208 char *buf;
2209
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002210 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002211 if (PyObject_CheckBuffer(arg)) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002212 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), arg) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002213 return NULL;
2214
2215 Py_RETURN_NONE;
2216 }
2217
2218 it = PyObject_GetIter(arg);
2219 if (it == NULL)
2220 return NULL;
2221
2222 /* Try to determine the length of the argument. 32 is abitrary. */
2223 buf_size = _PyObject_LengthHint(arg, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002224 if (buf_size == -1) {
2225 Py_DECREF(it);
2226 return NULL;
2227 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002228
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002229 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
2230 if (bytearray_obj == NULL)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002231 return NULL;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002232 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002233
2234 while ((item = PyIter_Next(it)) != NULL) {
2235 if (! _getbytevalue(item, &value)) {
2236 Py_DECREF(item);
2237 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002238 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002239 return NULL;
2240 }
2241 buf[len++] = value;
2242 Py_DECREF(item);
2243
2244 if (len >= buf_size) {
2245 buf_size = len + (len >> 1) + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002246 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002247 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 /* Recompute the `buf' pointer, since the resizing operation may
2252 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002253 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002254 }
2255 }
2256 Py_DECREF(it);
2257
2258 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002259 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
2260 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002261 return NULL;
2262 }
2263
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002264 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002265 return NULL;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002266 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002267
2268 Py_RETURN_NONE;
2269}
2270
2271PyDoc_STRVAR(pop__doc__,
2272"B.pop([index]) -> int\n\
2273\n\
2274Remove and return a single item from B. If no index\n\
Benjamin Petersondcf97b92008-07-02 17:30:14 +00002275argument is given, will pop the last value.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002276static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002277bytearray_pop(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002278{
2279 int value;
2280 Py_ssize_t where = -1, n = Py_SIZE(self);
2281
2282 if (!PyArg_ParseTuple(args, "|n:pop", &where))
2283 return NULL;
2284
2285 if (n == 0) {
2286 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002287 "cannot pop an empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002288 return NULL;
2289 }
2290 if (where < 0)
2291 where += Py_SIZE(self);
2292 if (where < 0 || where >= Py_SIZE(self)) {
2293 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2294 return NULL;
2295 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002296 if (!_canresize(self))
2297 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002298
2299 value = self->ob_bytes[where];
2300 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2301 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2302 return NULL;
2303
Mark Dickinson54a3db92009-09-06 10:19:23 +00002304 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002305}
2306
2307PyDoc_STRVAR(remove__doc__,
2308"B.remove(int) -> None\n\
2309\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002310Remove the first occurrence of a value in B.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002311static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002312bytearray_remove(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002313{
2314 int value;
2315 Py_ssize_t where, n = Py_SIZE(self);
2316
2317 if (! _getbytevalue(arg, &value))
2318 return NULL;
2319
2320 for (where = 0; where < n; where++) {
2321 if (self->ob_bytes[where] == value)
2322 break;
2323 }
2324 if (where == n) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002325 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002326 return NULL;
2327 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002328 if (!_canresize(self))
2329 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002330
2331 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2332 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2333 return NULL;
2334
2335 Py_RETURN_NONE;
2336}
2337
2338/* XXX These two helpers could be optimized if argsize == 1 */
2339
2340static Py_ssize_t
2341lstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2342 void *argptr, Py_ssize_t argsize)
2343{
2344 Py_ssize_t i = 0;
2345 while (i < mysize && memchr(argptr, myptr[i], argsize))
2346 i++;
2347 return i;
2348}
2349
2350static Py_ssize_t
2351rstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2352 void *argptr, Py_ssize_t argsize)
2353{
2354 Py_ssize_t i = mysize - 1;
2355 while (i >= 0 && memchr(argptr, myptr[i], argsize))
2356 i--;
2357 return i + 1;
2358}
2359
2360PyDoc_STRVAR(strip__doc__,
2361"B.strip([bytes]) -> bytearray\n\
2362\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002363Strip leading and trailing bytes contained in the argument\n\
2364and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002365If the argument is omitted, strip ASCII whitespace.");
2366static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002367bytearray_strip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002368{
2369 Py_ssize_t left, right, mysize, argsize;
2370 void *myptr, *argptr;
2371 PyObject *arg = Py_None;
2372 Py_buffer varg;
2373 if (!PyArg_ParseTuple(args, "|O:strip", &arg))
2374 return NULL;
2375 if (arg == Py_None) {
2376 argptr = "\t\n\r\f\v ";
2377 argsize = 6;
2378 }
2379 else {
2380 if (_getbuffer(arg, &varg) < 0)
2381 return NULL;
2382 argptr = varg.buf;
2383 argsize = varg.len;
2384 }
2385 myptr = self->ob_bytes;
2386 mysize = Py_SIZE(self);
2387 left = lstrip_helper(myptr, mysize, argptr, argsize);
2388 if (left == mysize)
2389 right = left;
2390 else
2391 right = rstrip_helper(myptr, mysize, argptr, argsize);
2392 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002393 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002394 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2395}
2396
2397PyDoc_STRVAR(lstrip__doc__,
2398"B.lstrip([bytes]) -> bytearray\n\
2399\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002400Strip leading bytes contained in the argument\n\
2401and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002402If the argument is omitted, strip leading ASCII whitespace.");
2403static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002404bytearray_lstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002405{
2406 Py_ssize_t left, right, mysize, argsize;
2407 void *myptr, *argptr;
2408 PyObject *arg = Py_None;
2409 Py_buffer varg;
2410 if (!PyArg_ParseTuple(args, "|O:lstrip", &arg))
2411 return NULL;
2412 if (arg == Py_None) {
2413 argptr = "\t\n\r\f\v ";
2414 argsize = 6;
2415 }
2416 else {
2417 if (_getbuffer(arg, &varg) < 0)
2418 return NULL;
2419 argptr = varg.buf;
2420 argsize = varg.len;
2421 }
2422 myptr = self->ob_bytes;
2423 mysize = Py_SIZE(self);
2424 left = lstrip_helper(myptr, mysize, argptr, argsize);
2425 right = mysize;
2426 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002427 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002428 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2429}
2430
2431PyDoc_STRVAR(rstrip__doc__,
2432"B.rstrip([bytes]) -> bytearray\n\
2433\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002434Strip trailing bytes contained in the argument\n\
2435and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002436If the argument is omitted, strip trailing ASCII whitespace.");
2437static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002438bytearray_rstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002439{
2440 Py_ssize_t left, right, mysize, argsize;
2441 void *myptr, *argptr;
2442 PyObject *arg = Py_None;
2443 Py_buffer varg;
2444 if (!PyArg_ParseTuple(args, "|O:rstrip", &arg))
2445 return NULL;
2446 if (arg == Py_None) {
2447 argptr = "\t\n\r\f\v ";
2448 argsize = 6;
2449 }
2450 else {
2451 if (_getbuffer(arg, &varg) < 0)
2452 return NULL;
2453 argptr = varg.buf;
2454 argsize = varg.len;
2455 }
2456 myptr = self->ob_bytes;
2457 mysize = Py_SIZE(self);
2458 left = 0;
2459 right = rstrip_helper(myptr, mysize, argptr, argsize);
2460 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002461 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002462 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2463}
2464
2465PyDoc_STRVAR(decode_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002466"B.decode([encoding[, errors]]) -> str\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002467\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002468Decode B using the codec registered for encoding. encoding defaults\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002469to the default encoding. errors may be given to set a different error\n\
2470handling scheme. Default is 'strict' meaning that encoding errors raise\n\
2471a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
2472as well as any other name registered with codecs.register_error that is\n\
2473able to handle UnicodeDecodeErrors.");
2474
2475static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00002476bytearray_decode(PyObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002477{
2478 const char *encoding = NULL;
2479 const char *errors = NULL;
Benjamin Peterson308d6372009-09-18 21:42:35 +00002480 static char *kwlist[] = {"encoding", "errors", 0};
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002481
Benjamin Peterson308d6372009-09-18 21:42:35 +00002482 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode", kwlist, &encoding, &errors))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002483 return NULL;
2484 if (encoding == NULL)
2485 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002486 return PyUnicode_FromEncodedObject(self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002487}
2488
2489PyDoc_STRVAR(alloc_doc,
2490"B.__alloc__() -> int\n\
2491\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002492Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002493
2494static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002495bytearray_alloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002496{
2497 return PyLong_FromSsize_t(self->ob_alloc);
2498}
2499
2500PyDoc_STRVAR(join_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002501"B.join(iterable_of_bytes) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002502\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002503Concatenate any number of bytes/bytearray objects, with B\n\
2504in between each pair, and return the result as a new bytearray.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002505
2506static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002507bytearray_join(PyByteArrayObject *self, PyObject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002508{
2509 PyObject *seq;
2510 Py_ssize_t mysize = Py_SIZE(self);
2511 Py_ssize_t i;
2512 Py_ssize_t n;
2513 PyObject **items;
2514 Py_ssize_t totalsize = 0;
2515 PyObject *result;
2516 char *dest;
2517
2518 seq = PySequence_Fast(it, "can only join an iterable");
2519 if (seq == NULL)
2520 return NULL;
2521 n = PySequence_Fast_GET_SIZE(seq);
2522 items = PySequence_Fast_ITEMS(seq);
2523
2524 /* Compute the total size, and check that they are all bytes */
2525 /* XXX Shouldn't we use _getbuffer() on these items instead? */
2526 for (i = 0; i < n; i++) {
2527 PyObject *obj = items[i];
2528 if (!PyByteArray_Check(obj) && !PyBytes_Check(obj)) {
2529 PyErr_Format(PyExc_TypeError,
2530 "can only join an iterable of bytes "
2531 "(item %ld has type '%.100s')",
2532 /* XXX %ld isn't right on Win64 */
2533 (long)i, Py_TYPE(obj)->tp_name);
2534 goto error;
2535 }
2536 if (i > 0)
2537 totalsize += mysize;
2538 totalsize += Py_SIZE(obj);
2539 if (totalsize < 0) {
2540 PyErr_NoMemory();
2541 goto error;
2542 }
2543 }
2544
2545 /* Allocate the result, and copy the bytes */
2546 result = PyByteArray_FromStringAndSize(NULL, totalsize);
2547 if (result == NULL)
2548 goto error;
2549 dest = PyByteArray_AS_STRING(result);
2550 for (i = 0; i < n; i++) {
2551 PyObject *obj = items[i];
2552 Py_ssize_t size = Py_SIZE(obj);
2553 char *buf;
2554 if (PyByteArray_Check(obj))
2555 buf = PyByteArray_AS_STRING(obj);
2556 else
2557 buf = PyBytes_AS_STRING(obj);
2558 if (i) {
2559 memcpy(dest, self->ob_bytes, mysize);
2560 dest += mysize;
2561 }
2562 memcpy(dest, buf, size);
2563 dest += size;
2564 }
2565
2566 /* Done */
2567 Py_DECREF(seq);
2568 return result;
2569
2570 /* Error handling */
2571 error:
2572 Py_DECREF(seq);
2573 return NULL;
2574}
2575
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002576PyDoc_STRVAR(splitlines__doc__,
2577"B.splitlines([keepends]) -> list of lines\n\
2578\n\
2579Return a list of the lines in B, breaking at line boundaries.\n\
2580Line breaks are not included in the resulting list unless keepends\n\
2581is given and true.");
2582
2583static PyObject*
2584bytearray_splitlines(PyObject *self, PyObject *args)
2585{
2586 int keepends = 0;
2587
2588 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
2589 return NULL;
2590
2591 return stringlib_splitlines(
2592 (PyObject*) self, PyByteArray_AS_STRING(self),
2593 PyByteArray_GET_SIZE(self), keepends
2594 );
2595}
2596
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002597PyDoc_STRVAR(fromhex_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002598"bytearray.fromhex(string) -> bytearray (static method)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002599\n\
2600Create a bytearray object from a string of hexadecimal numbers.\n\
2601Spaces between two numbers are accepted.\n\
2602Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef').");
2603
2604static int
2605hex_digit_to_int(Py_UNICODE c)
2606{
2607 if (c >= 128)
2608 return -1;
Eric Smith6dc46f52009-04-27 20:39:49 +00002609 if (Py_ISDIGIT(c))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002610 return c - '0';
2611 else {
Eric Smith6dc46f52009-04-27 20:39:49 +00002612 if (Py_ISUPPER(c))
2613 c = Py_TOLOWER(c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002614 if (c >= 'a' && c <= 'f')
2615 return c - 'a' + 10;
2616 }
2617 return -1;
2618}
2619
2620static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002621bytearray_fromhex(PyObject *cls, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002622{
2623 PyObject *newbytes, *hexobj;
2624 char *buf;
2625 Py_UNICODE *hex;
2626 Py_ssize_t hexlen, byteslen, i, j;
2627 int top, bot;
2628
2629 if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj))
2630 return NULL;
2631 assert(PyUnicode_Check(hexobj));
2632 hexlen = PyUnicode_GET_SIZE(hexobj);
2633 hex = PyUnicode_AS_UNICODE(hexobj);
2634 byteslen = hexlen/2; /* This overestimates if there are spaces */
2635 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
2636 if (!newbytes)
2637 return NULL;
2638 buf = PyByteArray_AS_STRING(newbytes);
2639 for (i = j = 0; i < hexlen; i += 2) {
2640 /* skip over spaces in the input */
2641 while (hex[i] == ' ')
2642 i++;
2643 if (i >= hexlen)
2644 break;
2645 top = hex_digit_to_int(hex[i]);
2646 bot = hex_digit_to_int(hex[i+1]);
2647 if (top == -1 || bot == -1) {
2648 PyErr_Format(PyExc_ValueError,
2649 "non-hexadecimal number found in "
2650 "fromhex() arg at position %zd", i);
2651 goto error;
2652 }
2653 buf[j++] = (top << 4) + bot;
2654 }
2655 if (PyByteArray_Resize(newbytes, j) < 0)
2656 goto error;
2657 return newbytes;
2658
2659 error:
2660 Py_DECREF(newbytes);
2661 return NULL;
2662}
2663
2664PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2665
2666static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002667bytearray_reduce(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002668{
2669 PyObject *latin1, *dict;
2670 if (self->ob_bytes)
2671 latin1 = PyUnicode_DecodeLatin1(self->ob_bytes,
2672 Py_SIZE(self), NULL);
2673 else
2674 latin1 = PyUnicode_FromString("");
2675
2676 dict = PyObject_GetAttrString((PyObject *)self, "__dict__");
2677 if (dict == NULL) {
2678 PyErr_Clear();
2679 dict = Py_None;
2680 Py_INCREF(dict);
2681 }
2682
2683 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
2684}
2685
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002686PyDoc_STRVAR(sizeof_doc,
2687"B.__sizeof__() -> int\n\
2688 \n\
2689Returns the size of B in memory, in bytes");
2690static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002691bytearray_sizeof(PyByteArrayObject *self)
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002692{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002693 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002694
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002695 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
2696 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002697}
2698
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002699static PySequenceMethods bytearray_as_sequence = {
2700 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002701 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002702 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
2703 (ssizeargfunc)bytearray_getitem, /* sq_item */
2704 0, /* sq_slice */
2705 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
2706 0, /* sq_ass_slice */
2707 (objobjproc)bytearray_contains, /* sq_contains */
2708 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
2709 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002710};
2711
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002712static PyMappingMethods bytearray_as_mapping = {
2713 (lenfunc)bytearray_length,
2714 (binaryfunc)bytearray_subscript,
2715 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002716};
2717
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002718static PyBufferProcs bytearray_as_buffer = {
2719 (getbufferproc)bytearray_getbuffer,
2720 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002721};
2722
2723static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002724bytearray_methods[] = {
2725 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
2726 {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, reduce_doc},
2727 {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, sizeof_doc},
2728 {"append", (PyCFunction)bytearray_append, METH_O, append__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002729 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
2730 _Py_capitalize__doc__},
2731 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002732 {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
Benjamin Peterson308d6372009-09-18 21:42:35 +00002733 {"decode", (PyCFunction)bytearray_decode, METH_VARARGS | METH_KEYWORDS, decode_doc},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002734 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002735 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS,
2736 expandtabs__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002737 {"extend", (PyCFunction)bytearray_extend, METH_O, extend__doc__},
2738 {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
2739 {"fromhex", (PyCFunction)bytearray_fromhex, METH_VARARGS|METH_CLASS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002740 fromhex_doc},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002741 {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
2742 {"insert", (PyCFunction)bytearray_insert, METH_VARARGS, insert__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002743 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
2744 _Py_isalnum__doc__},
2745 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
2746 _Py_isalpha__doc__},
2747 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
2748 _Py_isdigit__doc__},
2749 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
2750 _Py_islower__doc__},
2751 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
2752 _Py_isspace__doc__},
2753 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
2754 _Py_istitle__doc__},
2755 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
2756 _Py_isupper__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002757 {"join", (PyCFunction)bytearray_join, METH_O, join_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002758 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
2759 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002760 {"lstrip", (PyCFunction)bytearray_lstrip, METH_VARARGS, lstrip__doc__},
2761 {"maketrans", (PyCFunction)bytearray_maketrans, METH_VARARGS|METH_STATIC,
Georg Brandlabc38772009-04-12 15:51:51 +00002762 _Py_maketrans__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002763 {"partition", (PyCFunction)bytearray_partition, METH_O, partition__doc__},
2764 {"pop", (PyCFunction)bytearray_pop, METH_VARARGS, pop__doc__},
2765 {"remove", (PyCFunction)bytearray_remove, METH_O, remove__doc__},
2766 {"replace", (PyCFunction)bytearray_replace, METH_VARARGS, replace__doc__},
2767 {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, reverse__doc__},
2768 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
2769 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002770 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002771 {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, rpartition__doc__},
2772 {"rsplit", (PyCFunction)bytearray_rsplit, METH_VARARGS, rsplit__doc__},
2773 {"rstrip", (PyCFunction)bytearray_rstrip, METH_VARARGS, rstrip__doc__},
2774 {"split", (PyCFunction)bytearray_split, METH_VARARGS, split__doc__},
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002775 {"splitlines", (PyCFunction)bytearray_splitlines, METH_VARARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002776 splitlines__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002777 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002778 startswith__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002779 {"strip", (PyCFunction)bytearray_strip, METH_VARARGS, strip__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002780 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
2781 _Py_swapcase__doc__},
2782 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002783 {"translate", (PyCFunction)bytearray_translate, METH_VARARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002784 translate__doc__},
2785 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
2786 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
2787 {NULL}
2788};
2789
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002790PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002791"bytearray(iterable_of_ints) -> bytearray\n\
2792bytearray(string, encoding[, errors]) -> bytearray\n\
2793bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray\n\
2794bytearray(memory_view) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002795\n\
2796Construct an mutable bytearray object from:\n\
2797 - an iterable yielding integers in range(256)\n\
2798 - a text string encoded using the specified encoding\n\
2799 - a bytes or a bytearray object\n\
2800 - any object implementing the buffer API.\n\
2801\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002802bytearray(int) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002803\n\
2804Construct a zero-initialized bytearray of the given length.");
2805
2806
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002807static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002808
2809PyTypeObject PyByteArray_Type = {
2810 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2811 "bytearray",
2812 sizeof(PyByteArrayObject),
2813 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002814 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002815 0, /* tp_print */
2816 0, /* tp_getattr */
2817 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002818 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002819 (reprfunc)bytearray_repr, /* tp_repr */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002820 0, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002821 &bytearray_as_sequence, /* tp_as_sequence */
2822 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002823 0, /* tp_hash */
2824 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002825 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002826 PyObject_GenericGetAttr, /* tp_getattro */
2827 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002828 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002829 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002830 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002831 0, /* tp_traverse */
2832 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002833 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002834 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002835 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002836 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002837 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002838 0, /* tp_members */
2839 0, /* tp_getset */
2840 0, /* tp_base */
2841 0, /* tp_dict */
2842 0, /* tp_descr_get */
2843 0, /* tp_descr_set */
2844 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002845 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002846 PyType_GenericAlloc, /* tp_alloc */
2847 PyType_GenericNew, /* tp_new */
2848 PyObject_Del, /* tp_free */
2849};
2850
2851/*********************** Bytes Iterator ****************************/
2852
2853typedef struct {
2854 PyObject_HEAD
2855 Py_ssize_t it_index;
2856 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
2857} bytesiterobject;
2858
2859static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002860bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002861{
2862 _PyObject_GC_UNTRACK(it);
2863 Py_XDECREF(it->it_seq);
2864 PyObject_GC_Del(it);
2865}
2866
2867static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002868bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002869{
2870 Py_VISIT(it->it_seq);
2871 return 0;
2872}
2873
2874static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002875bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002876{
2877 PyByteArrayObject *seq;
2878 PyObject *item;
2879
2880 assert(it != NULL);
2881 seq = it->it_seq;
2882 if (seq == NULL)
2883 return NULL;
2884 assert(PyByteArray_Check(seq));
2885
2886 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
2887 item = PyLong_FromLong(
2888 (unsigned char)seq->ob_bytes[it->it_index]);
2889 if (item != NULL)
2890 ++it->it_index;
2891 return item;
2892 }
2893
2894 Py_DECREF(seq);
2895 it->it_seq = NULL;
2896 return NULL;
2897}
2898
2899static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002900bytesarrayiter_length_hint(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002901{
2902 Py_ssize_t len = 0;
2903 if (it->it_seq)
2904 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
2905 return PyLong_FromSsize_t(len);
2906}
2907
2908PyDoc_STRVAR(length_hint_doc,
2909 "Private method returning an estimate of len(list(it)).");
2910
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002911static PyMethodDef bytearrayiter_methods[] = {
2912 {"__length_hint__", (PyCFunction)bytesarrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002913 length_hint_doc},
2914 {NULL, NULL} /* sentinel */
2915};
2916
2917PyTypeObject PyByteArrayIter_Type = {
2918 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2919 "bytearray_iterator", /* tp_name */
2920 sizeof(bytesiterobject), /* tp_basicsize */
2921 0, /* tp_itemsize */
2922 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002923 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002924 0, /* tp_print */
2925 0, /* tp_getattr */
2926 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002927 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002928 0, /* tp_repr */
2929 0, /* tp_as_number */
2930 0, /* tp_as_sequence */
2931 0, /* tp_as_mapping */
2932 0, /* tp_hash */
2933 0, /* tp_call */
2934 0, /* tp_str */
2935 PyObject_GenericGetAttr, /* tp_getattro */
2936 0, /* tp_setattro */
2937 0, /* tp_as_buffer */
2938 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2939 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002940 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002941 0, /* tp_clear */
2942 0, /* tp_richcompare */
2943 0, /* tp_weaklistoffset */
2944 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002945 (iternextfunc)bytearrayiter_next, /* tp_iternext */
2946 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002947 0,
2948};
2949
2950static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002951bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002952{
2953 bytesiterobject *it;
2954
2955 if (!PyByteArray_Check(seq)) {
2956 PyErr_BadInternalCall();
2957 return NULL;
2958 }
2959 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
2960 if (it == NULL)
2961 return NULL;
2962 it->it_index = 0;
2963 Py_INCREF(seq);
2964 it->it_seq = (PyByteArrayObject *)seq;
2965 _PyObject_GC_TRACK(it);
2966 return (PyObject *)it;
2967}