blob: 8f833d8efdd496bcf29f8db85c9c3d4f0cf9a1d3 [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
Mark Dickinson66f575b2010-02-14 12:53:32 +0000659 if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000660 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;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000667 if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000668 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) */
Mark Dickinson66f575b2010-02-14 12:53:32 +0000847 size_t newsize;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000848 PyObject *v;
Mark Dickinson66f575b2010-02-14 12:53:32 +0000849 if (length > (PY_SSIZE_T_MAX - 14) / 4) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000850 PyErr_SetString(PyExc_OverflowError,
851 "bytearray object is too large to make repr");
852 return NULL;
853 }
Mark Dickinson66f575b2010-02-14 12:53:32 +0000854 newsize = 14 + 4 * length;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000855 v = PyUnicode_FromUnicode(NULL, newsize);
856 if (v == NULL) {
857 return NULL;
858 }
859 else {
860 register Py_ssize_t i;
861 register Py_UNICODE c;
862 register Py_UNICODE *p;
863 int quote;
864
865 /* Figure out which quote to use; single is preferred */
866 quote = '\'';
867 {
868 char *test, *start;
869 start = PyByteArray_AS_STRING(self);
870 for (test = start; test < start+length; ++test) {
871 if (*test == '"') {
872 quote = '\''; /* back to single */
873 goto decided;
874 }
875 else if (*test == '\'')
876 quote = '"';
877 }
878 decided:
879 ;
880 }
881
882 p = PyUnicode_AS_UNICODE(v);
883 while (*quote_prefix)
884 *p++ = *quote_prefix++;
885 *p++ = quote;
886
887 for (i = 0; i < length; i++) {
888 /* There's at least enough room for a hex escape
889 and a closing quote. */
890 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5);
891 c = self->ob_bytes[i];
892 if (c == '\'' || c == '\\')
893 *p++ = '\\', *p++ = c;
894 else if (c == '\t')
895 *p++ = '\\', *p++ = 't';
896 else if (c == '\n')
897 *p++ = '\\', *p++ = 'n';
898 else if (c == '\r')
899 *p++ = '\\', *p++ = 'r';
900 else if (c == 0)
901 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
902 else if (c < ' ' || c >= 0x7f) {
903 *p++ = '\\';
904 *p++ = 'x';
905 *p++ = hexdigits[(c & 0xf0) >> 4];
906 *p++ = hexdigits[c & 0xf];
907 }
908 else
909 *p++ = c;
910 }
911 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1);
912 *p++ = quote;
913 while (*quote_postfix) {
914 *p++ = *quote_postfix++;
915 }
916 *p = '\0';
917 if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) {
918 Py_DECREF(v);
919 return NULL;
920 }
921 return v;
922 }
923}
924
925static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000926bytearray_str(PyObject *op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000927{
928 if (Py_BytesWarningFlag) {
929 if (PyErr_WarnEx(PyExc_BytesWarning,
930 "str() on a bytearray instance", 1))
931 return NULL;
932 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000933 return bytearray_repr((PyByteArrayObject*)op);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000934}
935
936static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +0000937bytearray_richcompare(PyObject *self, PyObject *other, int op)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000938{
939 Py_ssize_t self_size, other_size;
940 Py_buffer self_bytes, other_bytes;
941 PyObject *res;
942 Py_ssize_t minsize;
943 int cmp;
944
945 /* Bytes can be compared to anything that supports the (binary)
946 buffer API. Except that a comparison with Unicode is always an
947 error, even if the comparison is for equality. */
948 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
949 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
Barry Warsaw9e9dcd62008-10-17 01:50:37 +0000950 if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000951 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +0000952 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000953 return NULL;
954 }
955
956 Py_INCREF(Py_NotImplemented);
957 return Py_NotImplemented;
958 }
959
960 self_size = _getbuffer(self, &self_bytes);
961 if (self_size < 0) {
962 PyErr_Clear();
963 Py_INCREF(Py_NotImplemented);
964 return Py_NotImplemented;
965 }
966
967 other_size = _getbuffer(other, &other_bytes);
968 if (other_size < 0) {
969 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +0000970 PyBuffer_Release(&self_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000971 Py_INCREF(Py_NotImplemented);
972 return Py_NotImplemented;
973 }
974
975 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
976 /* Shortcut: if the lengths differ, the objects differ */
977 cmp = (op == Py_NE);
978 }
979 else {
980 minsize = self_size;
981 if (other_size < minsize)
982 minsize = other_size;
983
984 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
985 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
986
987 if (cmp == 0) {
988 if (self_size < other_size)
989 cmp = -1;
990 else if (self_size > other_size)
991 cmp = 1;
992 }
993
994 switch (op) {
995 case Py_LT: cmp = cmp < 0; break;
996 case Py_LE: cmp = cmp <= 0; break;
997 case Py_EQ: cmp = cmp == 0; break;
998 case Py_NE: cmp = cmp != 0; break;
999 case Py_GT: cmp = cmp > 0; break;
1000 case Py_GE: cmp = cmp >= 0; break;
1001 }
1002 }
1003
1004 res = cmp ? Py_True : Py_False;
Martin v. Löwis423be952008-08-13 15:53:07 +00001005 PyBuffer_Release(&self_bytes);
1006 PyBuffer_Release(&other_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001007 Py_INCREF(res);
1008 return res;
1009}
1010
1011static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001012bytearray_dealloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001013{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001014 if (self->ob_exports > 0) {
1015 PyErr_SetString(PyExc_SystemError,
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00001016 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001017 PyErr_Print();
1018 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001019 if (self->ob_bytes != 0) {
1020 PyMem_Free(self->ob_bytes);
1021 }
1022 Py_TYPE(self)->tp_free((PyObject *)self);
1023}
1024
1025
1026/* -------------------------------------------------------------------- */
1027/* Methods */
1028
1029#define STRINGLIB_CHAR char
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001030#define STRINGLIB_LEN PyByteArray_GET_SIZE
1031#define STRINGLIB_STR PyByteArray_AS_STRING
1032#define STRINGLIB_NEW PyByteArray_FromStringAndSize
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001033#define STRINGLIB_ISSPACE Py_ISSPACE
1034#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001035#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1036#define STRINGLIB_MUTABLE 1
1037
1038#include "stringlib/fastsearch.h"
1039#include "stringlib/count.h"
1040#include "stringlib/find.h"
1041#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001042#include "stringlib/split.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001043#include "stringlib/ctype.h"
1044#include "stringlib/transmogrify.h"
1045
1046
1047/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1048were copied from the old char* style string object. */
1049
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001050/* helper macro to fixup start/end slice values */
1051#define ADJUST_INDICES(start, end, len) \
1052 if (end > len) \
1053 end = len; \
1054 else if (end < 0) { \
1055 end += len; \
1056 if (end < 0) \
1057 end = 0; \
1058 } \
1059 if (start < 0) { \
1060 start += len; \
1061 if (start < 0) \
1062 start = 0; \
1063 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001064
1065Py_LOCAL_INLINE(Py_ssize_t)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001066bytearray_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001067{
1068 PyObject *subobj;
1069 Py_buffer subbuf;
1070 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1071 Py_ssize_t res;
1072
1073 if (!PyArg_ParseTuple(args, "O|O&O&:find/rfind/index/rindex", &subobj,
1074 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1075 return -2;
1076 if (_getbuffer(subobj, &subbuf) < 0)
1077 return -2;
1078 if (dir > 0)
1079 res = stringlib_find_slice(
1080 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1081 subbuf.buf, subbuf.len, start, end);
1082 else
1083 res = stringlib_rfind_slice(
1084 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1085 subbuf.buf, subbuf.len, start, end);
Martin v. Löwis423be952008-08-13 15:53:07 +00001086 PyBuffer_Release(&subbuf);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001087 return res;
1088}
1089
1090PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001091"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001092\n\
1093Return the lowest index in B where subsection sub is found,\n\
1094such that sub is contained within s[start,end]. Optional\n\
1095arguments start and end are interpreted as in slice notation.\n\
1096\n\
1097Return -1 on failure.");
1098
1099static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001100bytearray_find(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001101{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001102 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001103 if (result == -2)
1104 return NULL;
1105 return PyLong_FromSsize_t(result);
1106}
1107
1108PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001109"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001110\n\
1111Return the number of non-overlapping occurrences of subsection sub in\n\
1112bytes B[start:end]. Optional arguments start and end are interpreted\n\
1113as in slice notation.");
1114
1115static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001116bytearray_count(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001117{
1118 PyObject *sub_obj;
1119 const char *str = PyByteArray_AS_STRING(self);
1120 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
1121 Py_buffer vsub;
1122 PyObject *count_obj;
1123
1124 if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj,
1125 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1126 return NULL;
1127
1128 if (_getbuffer(sub_obj, &vsub) < 0)
1129 return NULL;
1130
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001131 ADJUST_INDICES(start, end, PyByteArray_GET_SIZE(self));
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001132
1133 count_obj = PyLong_FromSsize_t(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001134 stringlib_count(str + start, end - start, vsub.buf, vsub.len, PY_SSIZE_T_MAX)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001135 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001136 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001137 return count_obj;
1138}
1139
1140
1141PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001142"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001143\n\
1144Like B.find() but raise ValueError when the subsection is not found.");
1145
1146static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001147bytearray_index(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001148{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001149 Py_ssize_t result = bytearray_find_internal(self, args, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001150 if (result == -2)
1151 return NULL;
1152 if (result == -1) {
1153 PyErr_SetString(PyExc_ValueError,
1154 "subsection not found");
1155 return NULL;
1156 }
1157 return PyLong_FromSsize_t(result);
1158}
1159
1160
1161PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001162"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001163\n\
1164Return the highest index in B where subsection sub is found,\n\
1165such that sub is contained within s[start,end]. Optional\n\
1166arguments start and end are interpreted as in slice notation.\n\
1167\n\
1168Return -1 on failure.");
1169
1170static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001171bytearray_rfind(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001172{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001173 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001174 if (result == -2)
1175 return NULL;
1176 return PyLong_FromSsize_t(result);
1177}
1178
1179
1180PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001181"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001182\n\
1183Like B.rfind() but raise ValueError when the subsection is not found.");
1184
1185static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001186bytearray_rindex(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001187{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001188 Py_ssize_t result = bytearray_find_internal(self, args, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001189 if (result == -2)
1190 return NULL;
1191 if (result == -1) {
1192 PyErr_SetString(PyExc_ValueError,
1193 "subsection not found");
1194 return NULL;
1195 }
1196 return PyLong_FromSsize_t(result);
1197}
1198
1199
1200static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001201bytearray_contains(PyObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001202{
1203 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1204 if (ival == -1 && PyErr_Occurred()) {
1205 Py_buffer varg;
1206 int pos;
1207 PyErr_Clear();
1208 if (_getbuffer(arg, &varg) < 0)
1209 return -1;
1210 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1211 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001212 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001213 return pos >= 0;
1214 }
1215 if (ival < 0 || ival >= 256) {
1216 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1217 return -1;
1218 }
1219
1220 return memchr(PyByteArray_AS_STRING(self), ival, Py_SIZE(self)) != NULL;
1221}
1222
1223
1224/* Matches the end (direction >= 0) or start (direction < 0) of self
1225 * against substr, using the start and end arguments. Returns
1226 * -1 on error, 0 if not found and 1 if found.
1227 */
1228Py_LOCAL(int)
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001229_bytearray_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001230 Py_ssize_t end, int direction)
1231{
1232 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1233 const char* str;
1234 Py_buffer vsubstr;
1235 int rv = 0;
1236
1237 str = PyByteArray_AS_STRING(self);
1238
1239 if (_getbuffer(substr, &vsubstr) < 0)
1240 return -1;
1241
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001242 ADJUST_INDICES(start, end, len);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001243
1244 if (direction < 0) {
1245 /* startswith */
1246 if (start+vsubstr.len > len) {
1247 goto done;
1248 }
1249 } else {
1250 /* endswith */
1251 if (end-start < vsubstr.len || start > len) {
1252 goto done;
1253 }
1254
1255 if (end-vsubstr.len > start)
1256 start = end - vsubstr.len;
1257 }
1258 if (end-start >= vsubstr.len)
1259 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1260
1261done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001262 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001263 return rv;
1264}
1265
1266
1267PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001268"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001269\n\
1270Return True if B starts with the specified prefix, False otherwise.\n\
1271With optional start, test B beginning at that position.\n\
1272With optional end, stop comparing B at that position.\n\
1273prefix can also be a tuple of strings to try.");
1274
1275static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001276bytearray_startswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001277{
1278 Py_ssize_t start = 0;
1279 Py_ssize_t end = PY_SSIZE_T_MAX;
1280 PyObject *subobj;
1281 int result;
1282
1283 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
1284 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1285 return NULL;
1286 if (PyTuple_Check(subobj)) {
1287 Py_ssize_t i;
1288 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001289 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001290 PyTuple_GET_ITEM(subobj, i),
1291 start, end, -1);
1292 if (result == -1)
1293 return NULL;
1294 else if (result) {
1295 Py_RETURN_TRUE;
1296 }
1297 }
1298 Py_RETURN_FALSE;
1299 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001300 result = _bytearray_tailmatch(self, subobj, start, end, -1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001301 if (result == -1)
1302 return NULL;
1303 else
1304 return PyBool_FromLong(result);
1305}
1306
1307PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001308"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001309\n\
1310Return True if B ends with the specified suffix, False otherwise.\n\
1311With optional start, test B beginning at that position.\n\
1312With optional end, stop comparing B at that position.\n\
1313suffix can also be a tuple of strings to try.");
1314
1315static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001316bytearray_endswith(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001317{
1318 Py_ssize_t start = 0;
1319 Py_ssize_t end = PY_SSIZE_T_MAX;
1320 PyObject *subobj;
1321 int result;
1322
1323 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
1324 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1325 return NULL;
1326 if (PyTuple_Check(subobj)) {
1327 Py_ssize_t i;
1328 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001329 result = _bytearray_tailmatch(self,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001330 PyTuple_GET_ITEM(subobj, i),
1331 start, end, +1);
1332 if (result == -1)
1333 return NULL;
1334 else if (result) {
1335 Py_RETURN_TRUE;
1336 }
1337 }
1338 Py_RETURN_FALSE;
1339 }
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001340 result = _bytearray_tailmatch(self, subobj, start, end, +1);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001341 if (result == -1)
1342 return NULL;
1343 else
1344 return PyBool_FromLong(result);
1345}
1346
1347
1348PyDoc_STRVAR(translate__doc__,
1349"B.translate(table[, deletechars]) -> bytearray\n\
1350\n\
1351Return a copy of B, where all characters occurring in the\n\
1352optional argument deletechars are removed, and the remaining\n\
1353characters have been mapped through the given translation\n\
1354table, which must be a bytes object of length 256.");
1355
1356static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001357bytearray_translate(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001358{
1359 register char *input, *output;
1360 register const char *table;
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001361 register Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001362 PyObject *input_obj = (PyObject*)self;
1363 const char *output_start;
1364 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001365 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001366 int trans_table[256];
Georg Brandlccc47b62008-12-28 11:44:14 +00001367 PyObject *tableobj = NULL, *delobj = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001368 Py_buffer vtable, vdel;
1369
1370 if (!PyArg_UnpackTuple(args, "translate", 1, 2,
1371 &tableobj, &delobj))
1372 return NULL;
1373
Georg Brandlccc47b62008-12-28 11:44:14 +00001374 if (tableobj == Py_None) {
1375 table = NULL;
1376 tableobj = NULL;
1377 } else if (_getbuffer(tableobj, &vtable) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001378 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001379 } else {
1380 if (vtable.len != 256) {
1381 PyErr_SetString(PyExc_ValueError,
1382 "translation table must be 256 characters long");
Georg Brandl953152f2009-07-22 12:03:59 +00001383 PyBuffer_Release(&vtable);
1384 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001385 }
1386 table = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001387 }
1388
1389 if (delobj != NULL) {
1390 if (_getbuffer(delobj, &vdel) < 0) {
Georg Brandl953152f2009-07-22 12:03:59 +00001391 if (tableobj != NULL)
1392 PyBuffer_Release(&vtable);
1393 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001394 }
1395 }
1396 else {
1397 vdel.buf = NULL;
1398 vdel.len = 0;
1399 }
1400
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001401 inlen = PyByteArray_GET_SIZE(input_obj);
1402 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1403 if (result == NULL)
1404 goto done;
1405 output_start = output = PyByteArray_AsString(result);
1406 input = PyByteArray_AS_STRING(input_obj);
1407
Georg Brandlccc47b62008-12-28 11:44:14 +00001408 if (vdel.len == 0 && table != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001409 /* If no deletions are required, use faster code */
1410 for (i = inlen; --i >= 0; ) {
1411 c = Py_CHARMASK(*input++);
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001412 *output++ = table[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001413 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001414 goto done;
1415 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001416
1417 if (table == NULL) {
1418 for (i = 0; i < 256; i++)
1419 trans_table[i] = Py_CHARMASK(i);
1420 } else {
1421 for (i = 0; i < 256; i++)
1422 trans_table[i] = Py_CHARMASK(table[i]);
1423 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001424
1425 for (i = 0; i < vdel.len; i++)
1426 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1427
1428 for (i = inlen; --i >= 0; ) {
1429 c = Py_CHARMASK(*input++);
1430 if (trans_table[c] != -1)
1431 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1432 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001433 }
1434 /* Fix the size of the resulting string */
1435 if (inlen > 0)
1436 PyByteArray_Resize(result, output - output_start);
1437
1438done:
Georg Brandlccc47b62008-12-28 11:44:14 +00001439 if (tableobj != NULL)
1440 PyBuffer_Release(&vtable);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001441 if (delobj != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001442 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001443 return result;
1444}
1445
1446
Georg Brandlabc38772009-04-12 15:51:51 +00001447static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001448bytearray_maketrans(PyObject *null, PyObject *args)
Georg Brandlabc38772009-04-12 15:51:51 +00001449{
1450 return _Py_bytes_maketrans(args);
1451}
1452
1453
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001454/* find and count characters and substrings */
1455
1456#define findchar(target, target_len, c) \
1457 ((char *)memchr((const void *)(target), c, target_len))
1458
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001459
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001460/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001461Py_LOCAL(PyByteArrayObject *)
1462return_self(PyByteArrayObject *self)
1463{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001464 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001465 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1466 PyByteArray_AS_STRING(self),
1467 PyByteArray_GET_SIZE(self));
1468}
1469
1470Py_LOCAL_INLINE(Py_ssize_t)
1471countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1472{
1473 Py_ssize_t count=0;
1474 const char *start=target;
1475 const char *end=target+target_len;
1476
1477 while ( (start=findchar(start, end-start, c)) != NULL ) {
1478 count++;
1479 if (count >= maxcount)
1480 break;
1481 start += 1;
1482 }
1483 return count;
1484}
1485
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001486
1487/* Algorithms for different cases of string replacement */
1488
1489/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1490Py_LOCAL(PyByteArrayObject *)
1491replace_interleave(PyByteArrayObject *self,
1492 const char *to_s, Py_ssize_t to_len,
1493 Py_ssize_t maxcount)
1494{
1495 char *self_s, *result_s;
1496 Py_ssize_t self_len, result_len;
1497 Py_ssize_t count, i, product;
1498 PyByteArrayObject *result;
1499
1500 self_len = PyByteArray_GET_SIZE(self);
1501
1502 /* 1 at the end plus 1 after every character */
1503 count = self_len+1;
1504 if (maxcount < count)
1505 count = maxcount;
1506
1507 /* Check for overflow */
1508 /* result_len = count * to_len + self_len; */
1509 product = count * to_len;
1510 if (product / to_len != count) {
1511 PyErr_SetString(PyExc_OverflowError,
1512 "replace string is too long");
1513 return NULL;
1514 }
1515 result_len = product + self_len;
1516 if (result_len < 0) {
1517 PyErr_SetString(PyExc_OverflowError,
1518 "replace string is too long");
1519 return NULL;
1520 }
1521
1522 if (! (result = (PyByteArrayObject *)
1523 PyByteArray_FromStringAndSize(NULL, result_len)) )
1524 return NULL;
1525
1526 self_s = PyByteArray_AS_STRING(self);
1527 result_s = PyByteArray_AS_STRING(result);
1528
1529 /* TODO: special case single character, which doesn't need memcpy */
1530
1531 /* Lay the first one down (guaranteed this will occur) */
1532 Py_MEMCPY(result_s, to_s, to_len);
1533 result_s += to_len;
1534 count -= 1;
1535
1536 for (i=0; i<count; i++) {
1537 *result_s++ = *self_s++;
1538 Py_MEMCPY(result_s, to_s, to_len);
1539 result_s += to_len;
1540 }
1541
1542 /* Copy the rest of the original string */
1543 Py_MEMCPY(result_s, self_s, self_len-i);
1544
1545 return result;
1546}
1547
1548/* Special case for deleting a single character */
1549/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1550Py_LOCAL(PyByteArrayObject *)
1551replace_delete_single_character(PyByteArrayObject *self,
1552 char from_c, Py_ssize_t maxcount)
1553{
1554 char *self_s, *result_s;
1555 char *start, *next, *end;
1556 Py_ssize_t self_len, result_len;
1557 Py_ssize_t count;
1558 PyByteArrayObject *result;
1559
1560 self_len = PyByteArray_GET_SIZE(self);
1561 self_s = PyByteArray_AS_STRING(self);
1562
1563 count = countchar(self_s, self_len, from_c, maxcount);
1564 if (count == 0) {
1565 return return_self(self);
1566 }
1567
1568 result_len = self_len - count; /* from_len == 1 */
1569 assert(result_len>=0);
1570
1571 if ( (result = (PyByteArrayObject *)
1572 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1573 return NULL;
1574 result_s = PyByteArray_AS_STRING(result);
1575
1576 start = self_s;
1577 end = self_s + self_len;
1578 while (count-- > 0) {
1579 next = findchar(start, end-start, from_c);
1580 if (next == NULL)
1581 break;
1582 Py_MEMCPY(result_s, start, next-start);
1583 result_s += (next-start);
1584 start = next+1;
1585 }
1586 Py_MEMCPY(result_s, start, end-start);
1587
1588 return result;
1589}
1590
1591/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1592
1593Py_LOCAL(PyByteArrayObject *)
1594replace_delete_substring(PyByteArrayObject *self,
1595 const char *from_s, Py_ssize_t from_len,
1596 Py_ssize_t maxcount)
1597{
1598 char *self_s, *result_s;
1599 char *start, *next, *end;
1600 Py_ssize_t self_len, result_len;
1601 Py_ssize_t count, offset;
1602 PyByteArrayObject *result;
1603
1604 self_len = PyByteArray_GET_SIZE(self);
1605 self_s = PyByteArray_AS_STRING(self);
1606
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001607 count = stringlib_count(self_s, self_len,
1608 from_s, from_len,
1609 maxcount);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001610
1611 if (count == 0) {
1612 /* no matches */
1613 return return_self(self);
1614 }
1615
1616 result_len = self_len - (count * from_len);
1617 assert (result_len>=0);
1618
1619 if ( (result = (PyByteArrayObject *)
1620 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1621 return NULL;
1622
1623 result_s = PyByteArray_AS_STRING(result);
1624
1625 start = self_s;
1626 end = self_s + self_len;
1627 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001628 offset = stringlib_find(start, end-start,
1629 from_s, from_len,
1630 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001631 if (offset == -1)
1632 break;
1633 next = start + offset;
1634
1635 Py_MEMCPY(result_s, start, next-start);
1636
1637 result_s += (next-start);
1638 start = next+from_len;
1639 }
1640 Py_MEMCPY(result_s, start, end-start);
1641 return result;
1642}
1643
1644/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1645Py_LOCAL(PyByteArrayObject *)
1646replace_single_character_in_place(PyByteArrayObject *self,
1647 char from_c, char to_c,
1648 Py_ssize_t maxcount)
1649{
1650 char *self_s, *result_s, *start, *end, *next;
1651 Py_ssize_t self_len;
1652 PyByteArrayObject *result;
1653
1654 /* The result string will be the same size */
1655 self_s = PyByteArray_AS_STRING(self);
1656 self_len = PyByteArray_GET_SIZE(self);
1657
1658 next = findchar(self_s, self_len, from_c);
1659
1660 if (next == NULL) {
1661 /* No matches; return the original bytes */
1662 return return_self(self);
1663 }
1664
1665 /* Need to make a new bytes */
1666 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1667 if (result == NULL)
1668 return NULL;
1669 result_s = PyByteArray_AS_STRING(result);
1670 Py_MEMCPY(result_s, self_s, self_len);
1671
1672 /* change everything in-place, starting with this one */
1673 start = result_s + (next-self_s);
1674 *start = to_c;
1675 start++;
1676 end = result_s + self_len;
1677
1678 while (--maxcount > 0) {
1679 next = findchar(start, end-start, from_c);
1680 if (next == NULL)
1681 break;
1682 *next = to_c;
1683 start = next+1;
1684 }
1685
1686 return result;
1687}
1688
1689/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1690Py_LOCAL(PyByteArrayObject *)
1691replace_substring_in_place(PyByteArrayObject *self,
1692 const char *from_s, Py_ssize_t from_len,
1693 const char *to_s, Py_ssize_t to_len,
1694 Py_ssize_t maxcount)
1695{
1696 char *result_s, *start, *end;
1697 char *self_s;
1698 Py_ssize_t self_len, offset;
1699 PyByteArrayObject *result;
1700
1701 /* The result bytes will be the same size */
1702
1703 self_s = PyByteArray_AS_STRING(self);
1704 self_len = PyByteArray_GET_SIZE(self);
1705
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001706 offset = stringlib_find(self_s, self_len,
1707 from_s, from_len,
1708 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001709 if (offset == -1) {
1710 /* No matches; return the original bytes */
1711 return return_self(self);
1712 }
1713
1714 /* Need to make a new bytes */
1715 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1716 if (result == NULL)
1717 return NULL;
1718 result_s = PyByteArray_AS_STRING(result);
1719 Py_MEMCPY(result_s, self_s, self_len);
1720
1721 /* change everything in-place, starting with this one */
1722 start = result_s + offset;
1723 Py_MEMCPY(start, to_s, from_len);
1724 start += from_len;
1725 end = result_s + self_len;
1726
1727 while ( --maxcount > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001728 offset = stringlib_find(start, end-start,
1729 from_s, from_len,
1730 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001731 if (offset==-1)
1732 break;
1733 Py_MEMCPY(start+offset, to_s, from_len);
1734 start += offset+from_len;
1735 }
1736
1737 return result;
1738}
1739
1740/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
1741Py_LOCAL(PyByteArrayObject *)
1742replace_single_character(PyByteArrayObject *self,
1743 char from_c,
1744 const char *to_s, Py_ssize_t to_len,
1745 Py_ssize_t maxcount)
1746{
1747 char *self_s, *result_s;
1748 char *start, *next, *end;
1749 Py_ssize_t self_len, result_len;
1750 Py_ssize_t count, product;
1751 PyByteArrayObject *result;
1752
1753 self_s = PyByteArray_AS_STRING(self);
1754 self_len = PyByteArray_GET_SIZE(self);
1755
1756 count = countchar(self_s, self_len, from_c, maxcount);
1757 if (count == 0) {
1758 /* no matches, return unchanged */
1759 return return_self(self);
1760 }
1761
1762 /* use the difference between current and new, hence the "-1" */
1763 /* result_len = self_len + count * (to_len-1) */
1764 product = count * (to_len-1);
1765 if (product / (to_len-1) != count) {
1766 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1767 return NULL;
1768 }
1769 result_len = self_len + product;
1770 if (result_len < 0) {
1771 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1772 return NULL;
1773 }
1774
1775 if ( (result = (PyByteArrayObject *)
1776 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1777 return NULL;
1778 result_s = PyByteArray_AS_STRING(result);
1779
1780 start = self_s;
1781 end = self_s + self_len;
1782 while (count-- > 0) {
1783 next = findchar(start, end-start, from_c);
1784 if (next == NULL)
1785 break;
1786
1787 if (next == start) {
1788 /* replace with the 'to' */
1789 Py_MEMCPY(result_s, to_s, to_len);
1790 result_s += to_len;
1791 start += 1;
1792 } else {
1793 /* copy the unchanged old then the 'to' */
1794 Py_MEMCPY(result_s, start, next-start);
1795 result_s += (next-start);
1796 Py_MEMCPY(result_s, to_s, to_len);
1797 result_s += to_len;
1798 start = next+1;
1799 }
1800 }
1801 /* Copy the remainder of the remaining bytes */
1802 Py_MEMCPY(result_s, start, end-start);
1803
1804 return result;
1805}
1806
1807/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
1808Py_LOCAL(PyByteArrayObject *)
1809replace_substring(PyByteArrayObject *self,
1810 const char *from_s, Py_ssize_t from_len,
1811 const char *to_s, Py_ssize_t to_len,
1812 Py_ssize_t maxcount)
1813{
1814 char *self_s, *result_s;
1815 char *start, *next, *end;
1816 Py_ssize_t self_len, result_len;
1817 Py_ssize_t count, offset, product;
1818 PyByteArrayObject *result;
1819
1820 self_s = PyByteArray_AS_STRING(self);
1821 self_len = PyByteArray_GET_SIZE(self);
1822
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001823 count = stringlib_count(self_s, self_len,
1824 from_s, from_len,
1825 maxcount);
1826
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001827 if (count == 0) {
1828 /* no matches, return unchanged */
1829 return return_self(self);
1830 }
1831
1832 /* Check for overflow */
1833 /* result_len = self_len + count * (to_len-from_len) */
1834 product = count * (to_len-from_len);
1835 if (product / (to_len-from_len) != count) {
1836 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1837 return NULL;
1838 }
1839 result_len = self_len + product;
1840 if (result_len < 0) {
1841 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1842 return NULL;
1843 }
1844
1845 if ( (result = (PyByteArrayObject *)
1846 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1847 return NULL;
1848 result_s = PyByteArray_AS_STRING(result);
1849
1850 start = self_s;
1851 end = self_s + self_len;
1852 while (count-- > 0) {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001853 offset = stringlib_find(start, end-start,
1854 from_s, from_len,
1855 0);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001856 if (offset == -1)
1857 break;
1858 next = start+offset;
1859 if (next == start) {
1860 /* replace with the 'to' */
1861 Py_MEMCPY(result_s, to_s, to_len);
1862 result_s += to_len;
1863 start += from_len;
1864 } else {
1865 /* copy the unchanged old then the 'to' */
1866 Py_MEMCPY(result_s, start, next-start);
1867 result_s += (next-start);
1868 Py_MEMCPY(result_s, to_s, to_len);
1869 result_s += to_len;
1870 start = next+from_len;
1871 }
1872 }
1873 /* Copy the remainder of the remaining bytes */
1874 Py_MEMCPY(result_s, start, end-start);
1875
1876 return result;
1877}
1878
1879
1880Py_LOCAL(PyByteArrayObject *)
1881replace(PyByteArrayObject *self,
1882 const char *from_s, Py_ssize_t from_len,
1883 const char *to_s, Py_ssize_t to_len,
1884 Py_ssize_t maxcount)
1885{
1886 if (maxcount < 0) {
1887 maxcount = PY_SSIZE_T_MAX;
1888 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
1889 /* nothing to do; return the original bytes */
1890 return return_self(self);
1891 }
1892
1893 if (maxcount == 0 ||
1894 (from_len == 0 && to_len == 0)) {
1895 /* nothing to do; return the original bytes */
1896 return return_self(self);
1897 }
1898
1899 /* Handle zero-length special cases */
1900
1901 if (from_len == 0) {
1902 /* insert the 'to' bytes everywhere. */
1903 /* >>> "Python".replace("", ".") */
1904 /* '.P.y.t.h.o.n.' */
1905 return replace_interleave(self, to_s, to_len, maxcount);
1906 }
1907
1908 /* Except for "".replace("", "A") == "A" there is no way beyond this */
1909 /* point for an empty self bytes to generate a non-empty bytes */
1910 /* Special case so the remaining code always gets a non-empty bytes */
1911 if (PyByteArray_GET_SIZE(self) == 0) {
1912 return return_self(self);
1913 }
1914
1915 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00001916 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001917 if (from_len == 1) {
1918 return replace_delete_single_character(
1919 self, from_s[0], maxcount);
1920 } else {
1921 return replace_delete_substring(self, from_s, from_len, maxcount);
1922 }
1923 }
1924
1925 /* Handle special case where both bytes have the same length */
1926
1927 if (from_len == to_len) {
1928 if (from_len == 1) {
1929 return replace_single_character_in_place(
1930 self,
1931 from_s[0],
1932 to_s[0],
1933 maxcount);
1934 } else {
1935 return replace_substring_in_place(
1936 self, from_s, from_len, to_s, to_len, maxcount);
1937 }
1938 }
1939
1940 /* Otherwise use the more generic algorithms */
1941 if (from_len == 1) {
1942 return replace_single_character(self, from_s[0],
1943 to_s, to_len, maxcount);
1944 } else {
1945 /* len('from')>=2, len('to')>=1 */
1946 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
1947 }
1948}
1949
1950
1951PyDoc_STRVAR(replace__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001952"B.replace(old, new[, count]) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001953\n\
1954Return a copy of B with all occurrences of subsection\n\
1955old replaced by new. If the optional argument count is\n\
1956given, only the first count occurrences are replaced.");
1957
1958static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001959bytearray_replace(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001960{
1961 Py_ssize_t count = -1;
1962 PyObject *from, *to, *res;
1963 Py_buffer vfrom, vto;
1964
1965 if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
1966 return NULL;
1967
1968 if (_getbuffer(from, &vfrom) < 0)
1969 return NULL;
1970 if (_getbuffer(to, &vto) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +00001971 PyBuffer_Release(&vfrom);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001972 return NULL;
1973 }
1974
1975 res = (PyObject *)replace((PyByteArrayObject *) self,
1976 vfrom.buf, vfrom.len,
1977 vto.buf, vto.len, count);
1978
Martin v. Löwis423be952008-08-13 15:53:07 +00001979 PyBuffer_Release(&vfrom);
1980 PyBuffer_Release(&vto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001981 return res;
1982}
1983
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001984PyDoc_STRVAR(split__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001985"B.split([sep[, maxsplit]]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001986\n\
1987Return a list of the sections in B, using sep as the delimiter.\n\
1988If sep is not given, B is split on ASCII whitespace characters\n\
1989(space, tab, return, newline, formfeed, vertical tab).\n\
1990If maxsplit is given, at most maxsplit splits are done.");
1991
1992static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00001993bytearray_split(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001994{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001995 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
1996 Py_ssize_t maxsplit = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001997 const char *s = PyByteArray_AS_STRING(self), *sub;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00001998 PyObject *list, *subobj = Py_None;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001999 Py_buffer vsub;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002000
2001 if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
2002 return NULL;
2003 if (maxsplit < 0)
2004 maxsplit = PY_SSIZE_T_MAX;
2005
2006 if (subobj == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002007 return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002008
2009 if (_getbuffer(subobj, &vsub) < 0)
2010 return NULL;
2011 sub = vsub.buf;
2012 n = vsub.len;
2013
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002014 list = stringlib_split(
2015 (PyObject*) self, s, len, sub, n, maxsplit
2016 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002017 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002018 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002019}
2020
2021PyDoc_STRVAR(partition__doc__,
2022"B.partition(sep) -> (head, sep, tail)\n\
2023\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002024Search for the separator sep in B, and return the part before it,\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002025the separator itself, and the part after it. If the separator is not\n\
2026found, returns B and two empty bytearray objects.");
2027
2028static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002029bytearray_partition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002030{
2031 PyObject *bytesep, *result;
2032
2033 bytesep = PyByteArray_FromObject(sep_obj);
2034 if (! bytesep)
2035 return NULL;
2036
2037 result = stringlib_partition(
2038 (PyObject*) self,
2039 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2040 bytesep,
2041 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2042 );
2043
2044 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002045 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002046}
2047
2048PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +00002049"B.rpartition(sep) -> (head, sep, tail)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002050\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002051Search for the separator sep in B, starting at the end of B,\n\
2052and return the part before it, the separator itself, and the\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002053part after it. If the separator is not found, returns two empty\n\
2054bytearray objects and B.");
2055
2056static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002057bytearray_rpartition(PyByteArrayObject *self, PyObject *sep_obj)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002058{
2059 PyObject *bytesep, *result;
2060
2061 bytesep = PyByteArray_FromObject(sep_obj);
2062 if (! bytesep)
2063 return NULL;
2064
2065 result = stringlib_rpartition(
2066 (PyObject*) self,
2067 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2068 bytesep,
2069 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2070 );
2071
2072 Py_DECREF(bytesep);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002073 return result;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002074}
2075
2076PyDoc_STRVAR(rsplit__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002077"B.rsplit(sep[, maxsplit]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002078\n\
2079Return a list of the sections in B, using sep as the delimiter,\n\
2080starting at the end of B and working to the front.\n\
2081If sep is not given, B is split on ASCII whitespace characters\n\
2082(space, tab, return, newline, formfeed, vertical tab).\n\
2083If maxsplit is given, at most maxsplit splits are done.");
2084
2085static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002086bytearray_rsplit(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002087{
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002088 Py_ssize_t len = PyByteArray_GET_SIZE(self), n;
2089 Py_ssize_t maxsplit = -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002090 const char *s = PyByteArray_AS_STRING(self), *sub;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002091 PyObject *list, *subobj = Py_None;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002092 Py_buffer vsub;
2093
2094 if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
2095 return NULL;
2096 if (maxsplit < 0)
2097 maxsplit = PY_SSIZE_T_MAX;
2098
2099 if (subobj == Py_None)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002100 return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002101
2102 if (_getbuffer(subobj, &vsub) < 0)
2103 return NULL;
2104 sub = vsub.buf;
2105 n = vsub.len;
2106
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002107 list = stringlib_rsplit(
2108 (PyObject*) self, s, len, sub, n, maxsplit
2109 );
Martin v. Löwis423be952008-08-13 15:53:07 +00002110 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002111 return list;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002112}
2113
2114PyDoc_STRVAR(reverse__doc__,
2115"B.reverse() -> None\n\
2116\n\
2117Reverse the order of the values in B in place.");
2118static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002119bytearray_reverse(PyByteArrayObject *self, PyObject *unused)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002120{
2121 char swap, *head, *tail;
2122 Py_ssize_t i, j, n = Py_SIZE(self);
2123
2124 j = n / 2;
2125 head = self->ob_bytes;
2126 tail = head + n - 1;
2127 for (i = 0; i < j; i++) {
2128 swap = *head;
2129 *head++ = *tail;
2130 *tail-- = swap;
2131 }
2132
2133 Py_RETURN_NONE;
2134}
2135
2136PyDoc_STRVAR(insert__doc__,
2137"B.insert(index, int) -> None\n\
2138\n\
2139Insert a single item into the bytearray before the given index.");
2140static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002141bytearray_insert(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002142{
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002143 PyObject *value;
2144 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002145 Py_ssize_t where, n = Py_SIZE(self);
2146
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002147 if (!PyArg_ParseTuple(args, "nO:insert", &where, &value))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002148 return NULL;
2149
2150 if (n == PY_SSIZE_T_MAX) {
2151 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002152 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002153 return NULL;
2154 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002155 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002156 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002157 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2158 return NULL;
2159
2160 if (where < 0) {
2161 where += n;
2162 if (where < 0)
2163 where = 0;
2164 }
2165 if (where > n)
2166 where = n;
2167 memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where);
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002168 self->ob_bytes[where] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002169
2170 Py_RETURN_NONE;
2171}
2172
2173PyDoc_STRVAR(append__doc__,
2174"B.append(int) -> None\n\
2175\n\
2176Append a single item to the end of B.");
2177static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002178bytearray_append(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002179{
2180 int value;
2181 Py_ssize_t n = Py_SIZE(self);
2182
2183 if (! _getbytevalue(arg, &value))
2184 return NULL;
2185 if (n == PY_SSIZE_T_MAX) {
2186 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002187 "cannot add more objects to bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002188 return NULL;
2189 }
2190 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2191 return NULL;
2192
2193 self->ob_bytes[n] = value;
2194
2195 Py_RETURN_NONE;
2196}
2197
2198PyDoc_STRVAR(extend__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002199"B.extend(iterable_of_ints) -> None\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002200\n\
2201Append all the elements from the iterator or sequence to the\n\
2202end of B.");
2203static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002204bytearray_extend(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002205{
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002206 PyObject *it, *item, *bytearray_obj;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002207 Py_ssize_t buf_size = 0, len = 0;
2208 int value;
2209 char *buf;
2210
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002211 /* bytearray_setslice code only accepts something supporting PEP 3118. */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002212 if (PyObject_CheckBuffer(arg)) {
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002213 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), arg) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002214 return NULL;
2215
2216 Py_RETURN_NONE;
2217 }
2218
2219 it = PyObject_GetIter(arg);
2220 if (it == NULL)
2221 return NULL;
2222
2223 /* Try to determine the length of the argument. 32 is abitrary. */
2224 buf_size = _PyObject_LengthHint(arg, 32);
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002225 if (buf_size == -1) {
2226 Py_DECREF(it);
2227 return NULL;
2228 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002229
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002230 bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
2231 if (bytearray_obj == NULL)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002232 return NULL;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002233 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002234
2235 while ((item = PyIter_Next(it)) != NULL) {
2236 if (! _getbytevalue(item, &value)) {
2237 Py_DECREF(item);
2238 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002239 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002240 return NULL;
2241 }
2242 buf[len++] = value;
2243 Py_DECREF(item);
2244
2245 if (len >= buf_size) {
2246 buf_size = len + (len >> 1) + 1;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002247 if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002248 Py_DECREF(it);
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002249 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002250 return NULL;
2251 }
2252 /* Recompute the `buf' pointer, since the resizing operation may
2253 have invalidated it. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002254 buf = PyByteArray_AS_STRING(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002255 }
2256 }
2257 Py_DECREF(it);
2258
2259 /* Resize down to exact size. */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002260 if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) {
2261 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002262 return NULL;
2263 }
2264
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002265 if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002266 return NULL;
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002267 Py_DECREF(bytearray_obj);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002268
2269 Py_RETURN_NONE;
2270}
2271
2272PyDoc_STRVAR(pop__doc__,
2273"B.pop([index]) -> int\n\
2274\n\
2275Remove and return a single item from B. If no index\n\
Benjamin Petersondcf97b92008-07-02 17:30:14 +00002276argument is given, will pop the last value.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002277static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002278bytearray_pop(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002279{
2280 int value;
2281 Py_ssize_t where = -1, n = Py_SIZE(self);
2282
2283 if (!PyArg_ParseTuple(args, "|n:pop", &where))
2284 return NULL;
2285
2286 if (n == 0) {
2287 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002288 "cannot pop an empty bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002289 return NULL;
2290 }
2291 if (where < 0)
2292 where += Py_SIZE(self);
2293 if (where < 0 || where >= Py_SIZE(self)) {
2294 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2295 return NULL;
2296 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002297 if (!_canresize(self))
2298 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002299
2300 value = self->ob_bytes[where];
2301 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2302 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2303 return NULL;
2304
Mark Dickinson54a3db92009-09-06 10:19:23 +00002305 return PyLong_FromLong((unsigned char)value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002306}
2307
2308PyDoc_STRVAR(remove__doc__,
2309"B.remove(int) -> None\n\
2310\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002311Remove the first occurrence of a value in B.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002312static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002313bytearray_remove(PyByteArrayObject *self, PyObject *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002314{
2315 int value;
2316 Py_ssize_t where, n = Py_SIZE(self);
2317
2318 if (! _getbytevalue(arg, &value))
2319 return NULL;
2320
2321 for (where = 0; where < n; where++) {
2322 if (self->ob_bytes[where] == value)
2323 break;
2324 }
2325 if (where == n) {
Mark Dickinson2b6705f2009-09-06 10:34:47 +00002326 PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002327 return NULL;
2328 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002329 if (!_canresize(self))
2330 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002331
2332 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2333 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2334 return NULL;
2335
2336 Py_RETURN_NONE;
2337}
2338
2339/* XXX These two helpers could be optimized if argsize == 1 */
2340
2341static Py_ssize_t
2342lstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2343 void *argptr, Py_ssize_t argsize)
2344{
2345 Py_ssize_t i = 0;
2346 while (i < mysize && memchr(argptr, myptr[i], argsize))
2347 i++;
2348 return i;
2349}
2350
2351static Py_ssize_t
2352rstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2353 void *argptr, Py_ssize_t argsize)
2354{
2355 Py_ssize_t i = mysize - 1;
2356 while (i >= 0 && memchr(argptr, myptr[i], argsize))
2357 i--;
2358 return i + 1;
2359}
2360
2361PyDoc_STRVAR(strip__doc__,
2362"B.strip([bytes]) -> bytearray\n\
2363\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002364Strip leading and trailing bytes contained in the argument\n\
2365and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002366If the argument is omitted, strip ASCII whitespace.");
2367static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002368bytearray_strip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002369{
2370 Py_ssize_t left, right, mysize, argsize;
2371 void *myptr, *argptr;
2372 PyObject *arg = Py_None;
2373 Py_buffer varg;
2374 if (!PyArg_ParseTuple(args, "|O:strip", &arg))
2375 return NULL;
2376 if (arg == Py_None) {
2377 argptr = "\t\n\r\f\v ";
2378 argsize = 6;
2379 }
2380 else {
2381 if (_getbuffer(arg, &varg) < 0)
2382 return NULL;
2383 argptr = varg.buf;
2384 argsize = varg.len;
2385 }
2386 myptr = self->ob_bytes;
2387 mysize = Py_SIZE(self);
2388 left = lstrip_helper(myptr, mysize, argptr, argsize);
2389 if (left == mysize)
2390 right = left;
2391 else
2392 right = rstrip_helper(myptr, mysize, argptr, argsize);
2393 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002394 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002395 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2396}
2397
2398PyDoc_STRVAR(lstrip__doc__,
2399"B.lstrip([bytes]) -> bytearray\n\
2400\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002401Strip leading bytes contained in the argument\n\
2402and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002403If the argument is omitted, strip leading ASCII whitespace.");
2404static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002405bytearray_lstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002406{
2407 Py_ssize_t left, right, mysize, argsize;
2408 void *myptr, *argptr;
2409 PyObject *arg = Py_None;
2410 Py_buffer varg;
2411 if (!PyArg_ParseTuple(args, "|O:lstrip", &arg))
2412 return NULL;
2413 if (arg == Py_None) {
2414 argptr = "\t\n\r\f\v ";
2415 argsize = 6;
2416 }
2417 else {
2418 if (_getbuffer(arg, &varg) < 0)
2419 return NULL;
2420 argptr = varg.buf;
2421 argsize = varg.len;
2422 }
2423 myptr = self->ob_bytes;
2424 mysize = Py_SIZE(self);
2425 left = lstrip_helper(myptr, mysize, argptr, argsize);
2426 right = mysize;
2427 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002428 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002429 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2430}
2431
2432PyDoc_STRVAR(rstrip__doc__,
2433"B.rstrip([bytes]) -> bytearray\n\
2434\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002435Strip trailing bytes contained in the argument\n\
2436and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002437If the argument is omitted, strip trailing ASCII whitespace.");
2438static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002439bytearray_rstrip(PyByteArrayObject *self, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002440{
2441 Py_ssize_t left, right, mysize, argsize;
2442 void *myptr, *argptr;
2443 PyObject *arg = Py_None;
2444 Py_buffer varg;
2445 if (!PyArg_ParseTuple(args, "|O:rstrip", &arg))
2446 return NULL;
2447 if (arg == Py_None) {
2448 argptr = "\t\n\r\f\v ";
2449 argsize = 6;
2450 }
2451 else {
2452 if (_getbuffer(arg, &varg) < 0)
2453 return NULL;
2454 argptr = varg.buf;
2455 argsize = varg.len;
2456 }
2457 myptr = self->ob_bytes;
2458 mysize = Py_SIZE(self);
2459 left = 0;
2460 right = rstrip_helper(myptr, mysize, argptr, argsize);
2461 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002462 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002463 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2464}
2465
2466PyDoc_STRVAR(decode_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002467"B.decode([encoding[, errors]]) -> str\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002468\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002469Decode B using the codec registered for encoding. encoding defaults\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002470to the default encoding. errors may be given to set a different error\n\
2471handling scheme. Default is 'strict' meaning that encoding errors raise\n\
2472a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
2473as well as any other name registered with codecs.register_error that is\n\
2474able to handle UnicodeDecodeErrors.");
2475
2476static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00002477bytearray_decode(PyObject *self, PyObject *args, PyObject *kwargs)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002478{
2479 const char *encoding = NULL;
2480 const char *errors = NULL;
Benjamin Peterson308d6372009-09-18 21:42:35 +00002481 static char *kwlist[] = {"encoding", "errors", 0};
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002482
Benjamin Peterson308d6372009-09-18 21:42:35 +00002483 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode", kwlist, &encoding, &errors))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002484 return NULL;
2485 if (encoding == NULL)
2486 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002487 return PyUnicode_FromEncodedObject(self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002488}
2489
2490PyDoc_STRVAR(alloc_doc,
2491"B.__alloc__() -> int\n\
2492\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002493Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002494
2495static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002496bytearray_alloc(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002497{
2498 return PyLong_FromSsize_t(self->ob_alloc);
2499}
2500
2501PyDoc_STRVAR(join_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002502"B.join(iterable_of_bytes) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002503\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002504Concatenate any number of bytes/bytearray objects, with B\n\
2505in between each pair, and return the result as a new bytearray.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002506
2507static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002508bytearray_join(PyByteArrayObject *self, PyObject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002509{
2510 PyObject *seq;
2511 Py_ssize_t mysize = Py_SIZE(self);
2512 Py_ssize_t i;
2513 Py_ssize_t n;
2514 PyObject **items;
2515 Py_ssize_t totalsize = 0;
2516 PyObject *result;
2517 char *dest;
2518
2519 seq = PySequence_Fast(it, "can only join an iterable");
2520 if (seq == NULL)
2521 return NULL;
2522 n = PySequence_Fast_GET_SIZE(seq);
2523 items = PySequence_Fast_ITEMS(seq);
2524
2525 /* Compute the total size, and check that they are all bytes */
2526 /* XXX Shouldn't we use _getbuffer() on these items instead? */
2527 for (i = 0; i < n; i++) {
2528 PyObject *obj = items[i];
2529 if (!PyByteArray_Check(obj) && !PyBytes_Check(obj)) {
2530 PyErr_Format(PyExc_TypeError,
2531 "can only join an iterable of bytes "
2532 "(item %ld has type '%.100s')",
2533 /* XXX %ld isn't right on Win64 */
2534 (long)i, Py_TYPE(obj)->tp_name);
2535 goto error;
2536 }
2537 if (i > 0)
2538 totalsize += mysize;
2539 totalsize += Py_SIZE(obj);
2540 if (totalsize < 0) {
2541 PyErr_NoMemory();
2542 goto error;
2543 }
2544 }
2545
2546 /* Allocate the result, and copy the bytes */
2547 result = PyByteArray_FromStringAndSize(NULL, totalsize);
2548 if (result == NULL)
2549 goto error;
2550 dest = PyByteArray_AS_STRING(result);
2551 for (i = 0; i < n; i++) {
2552 PyObject *obj = items[i];
2553 Py_ssize_t size = Py_SIZE(obj);
2554 char *buf;
2555 if (PyByteArray_Check(obj))
2556 buf = PyByteArray_AS_STRING(obj);
2557 else
2558 buf = PyBytes_AS_STRING(obj);
2559 if (i) {
2560 memcpy(dest, self->ob_bytes, mysize);
2561 dest += mysize;
2562 }
2563 memcpy(dest, buf, size);
2564 dest += size;
2565 }
2566
2567 /* Done */
2568 Py_DECREF(seq);
2569 return result;
2570
2571 /* Error handling */
2572 error:
2573 Py_DECREF(seq);
2574 return NULL;
2575}
2576
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002577PyDoc_STRVAR(splitlines__doc__,
2578"B.splitlines([keepends]) -> list of lines\n\
2579\n\
2580Return a list of the lines in B, breaking at line boundaries.\n\
2581Line breaks are not included in the resulting list unless keepends\n\
2582is given and true.");
2583
2584static PyObject*
2585bytearray_splitlines(PyObject *self, PyObject *args)
2586{
2587 int keepends = 0;
2588
2589 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
2590 return NULL;
2591
2592 return stringlib_splitlines(
2593 (PyObject*) self, PyByteArray_AS_STRING(self),
2594 PyByteArray_GET_SIZE(self), keepends
2595 );
2596}
2597
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002598PyDoc_STRVAR(fromhex_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002599"bytearray.fromhex(string) -> bytearray (static method)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002600\n\
2601Create a bytearray object from a string of hexadecimal numbers.\n\
2602Spaces between two numbers are accepted.\n\
2603Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef').");
2604
2605static int
2606hex_digit_to_int(Py_UNICODE c)
2607{
2608 if (c >= 128)
2609 return -1;
Eric Smith6dc46f52009-04-27 20:39:49 +00002610 if (Py_ISDIGIT(c))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002611 return c - '0';
2612 else {
Eric Smith6dc46f52009-04-27 20:39:49 +00002613 if (Py_ISUPPER(c))
2614 c = Py_TOLOWER(c);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002615 if (c >= 'a' && c <= 'f')
2616 return c - 'a' + 10;
2617 }
2618 return -1;
2619}
2620
2621static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002622bytearray_fromhex(PyObject *cls, PyObject *args)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002623{
2624 PyObject *newbytes, *hexobj;
2625 char *buf;
2626 Py_UNICODE *hex;
2627 Py_ssize_t hexlen, byteslen, i, j;
2628 int top, bot;
2629
2630 if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj))
2631 return NULL;
2632 assert(PyUnicode_Check(hexobj));
2633 hexlen = PyUnicode_GET_SIZE(hexobj);
2634 hex = PyUnicode_AS_UNICODE(hexobj);
2635 byteslen = hexlen/2; /* This overestimates if there are spaces */
2636 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
2637 if (!newbytes)
2638 return NULL;
2639 buf = PyByteArray_AS_STRING(newbytes);
2640 for (i = j = 0; i < hexlen; i += 2) {
2641 /* skip over spaces in the input */
2642 while (hex[i] == ' ')
2643 i++;
2644 if (i >= hexlen)
2645 break;
2646 top = hex_digit_to_int(hex[i]);
2647 bot = hex_digit_to_int(hex[i+1]);
2648 if (top == -1 || bot == -1) {
2649 PyErr_Format(PyExc_ValueError,
2650 "non-hexadecimal number found in "
2651 "fromhex() arg at position %zd", i);
2652 goto error;
2653 }
2654 buf[j++] = (top << 4) + bot;
2655 }
2656 if (PyByteArray_Resize(newbytes, j) < 0)
2657 goto error;
2658 return newbytes;
2659
2660 error:
2661 Py_DECREF(newbytes);
2662 return NULL;
2663}
2664
2665PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2666
2667static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002668bytearray_reduce(PyByteArrayObject *self)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002669{
2670 PyObject *latin1, *dict;
2671 if (self->ob_bytes)
2672 latin1 = PyUnicode_DecodeLatin1(self->ob_bytes,
2673 Py_SIZE(self), NULL);
2674 else
2675 latin1 = PyUnicode_FromString("");
2676
2677 dict = PyObject_GetAttrString((PyObject *)self, "__dict__");
2678 if (dict == NULL) {
2679 PyErr_Clear();
2680 dict = Py_None;
2681 Py_INCREF(dict);
2682 }
2683
2684 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
2685}
2686
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002687PyDoc_STRVAR(sizeof_doc,
2688"B.__sizeof__() -> int\n\
2689 \n\
2690Returns the size of B in memory, in bytes");
2691static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002692bytearray_sizeof(PyByteArrayObject *self)
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002693{
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002694 Py_ssize_t res;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002695
Benjamin Petersonef3e4c22009-04-11 19:48:14 +00002696 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
2697 return PyLong_FromSsize_t(res);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00002698}
2699
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002700static PySequenceMethods bytearray_as_sequence = {
2701 (lenfunc)bytearray_length, /* sq_length */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002702 (binaryfunc)PyByteArray_Concat, /* sq_concat */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002703 (ssizeargfunc)bytearray_repeat, /* sq_repeat */
2704 (ssizeargfunc)bytearray_getitem, /* sq_item */
2705 0, /* sq_slice */
2706 (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */
2707 0, /* sq_ass_slice */
2708 (objobjproc)bytearray_contains, /* sq_contains */
2709 (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */
2710 (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002711};
2712
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002713static PyMappingMethods bytearray_as_mapping = {
2714 (lenfunc)bytearray_length,
2715 (binaryfunc)bytearray_subscript,
2716 (objobjargproc)bytearray_ass_subscript,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002717};
2718
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002719static PyBufferProcs bytearray_as_buffer = {
2720 (getbufferproc)bytearray_getbuffer,
2721 (releasebufferproc)bytearray_releasebuffer,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002722};
2723
2724static PyMethodDef
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002725bytearray_methods[] = {
2726 {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc},
2727 {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, reduce_doc},
2728 {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, sizeof_doc},
2729 {"append", (PyCFunction)bytearray_append, METH_O, append__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002730 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
2731 _Py_capitalize__doc__},
2732 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002733 {"count", (PyCFunction)bytearray_count, METH_VARARGS, count__doc__},
Benjamin Peterson308d6372009-09-18 21:42:35 +00002734 {"decode", (PyCFunction)bytearray_decode, METH_VARARGS | METH_KEYWORDS, decode_doc},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002735 {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, endswith__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002736 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS,
2737 expandtabs__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002738 {"extend", (PyCFunction)bytearray_extend, METH_O, extend__doc__},
2739 {"find", (PyCFunction)bytearray_find, METH_VARARGS, find__doc__},
2740 {"fromhex", (PyCFunction)bytearray_fromhex, METH_VARARGS|METH_CLASS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002741 fromhex_doc},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002742 {"index", (PyCFunction)bytearray_index, METH_VARARGS, index__doc__},
2743 {"insert", (PyCFunction)bytearray_insert, METH_VARARGS, insert__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002744 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
2745 _Py_isalnum__doc__},
2746 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
2747 _Py_isalpha__doc__},
2748 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
2749 _Py_isdigit__doc__},
2750 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
2751 _Py_islower__doc__},
2752 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
2753 _Py_isspace__doc__},
2754 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
2755 _Py_istitle__doc__},
2756 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
2757 _Py_isupper__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002758 {"join", (PyCFunction)bytearray_join, METH_O, join_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002759 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
2760 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002761 {"lstrip", (PyCFunction)bytearray_lstrip, METH_VARARGS, lstrip__doc__},
2762 {"maketrans", (PyCFunction)bytearray_maketrans, METH_VARARGS|METH_STATIC,
Georg Brandlabc38772009-04-12 15:51:51 +00002763 _Py_maketrans__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002764 {"partition", (PyCFunction)bytearray_partition, METH_O, partition__doc__},
2765 {"pop", (PyCFunction)bytearray_pop, METH_VARARGS, pop__doc__},
2766 {"remove", (PyCFunction)bytearray_remove, METH_O, remove__doc__},
2767 {"replace", (PyCFunction)bytearray_replace, METH_VARARGS, replace__doc__},
2768 {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, reverse__doc__},
2769 {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, rfind__doc__},
2770 {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, rindex__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002771 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002772 {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, rpartition__doc__},
2773 {"rsplit", (PyCFunction)bytearray_rsplit, METH_VARARGS, rsplit__doc__},
2774 {"rstrip", (PyCFunction)bytearray_rstrip, METH_VARARGS, rstrip__doc__},
2775 {"split", (PyCFunction)bytearray_split, METH_VARARGS, split__doc__},
Antoine Pitrouf2c54842010-01-13 08:07:53 +00002776 {"splitlines", (PyCFunction)bytearray_splitlines, METH_VARARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002777 splitlines__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002778 {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS ,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002779 startswith__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002780 {"strip", (PyCFunction)bytearray_strip, METH_VARARGS, strip__doc__},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002781 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
2782 _Py_swapcase__doc__},
2783 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002784 {"translate", (PyCFunction)bytearray_translate, METH_VARARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002785 translate__doc__},
2786 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
2787 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
2788 {NULL}
2789};
2790
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002791PyDoc_STRVAR(bytearray_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002792"bytearray(iterable_of_ints) -> bytearray\n\
2793bytearray(string, encoding[, errors]) -> bytearray\n\
2794bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray\n\
2795bytearray(memory_view) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002796\n\
2797Construct an mutable bytearray object from:\n\
2798 - an iterable yielding integers in range(256)\n\
2799 - a text string encoded using the specified encoding\n\
2800 - a bytes or a bytearray object\n\
2801 - any object implementing the buffer API.\n\
2802\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002803bytearray(int) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002804\n\
2805Construct a zero-initialized bytearray of the given length.");
2806
2807
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002808static PyObject *bytearray_iter(PyObject *seq);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002809
2810PyTypeObject PyByteArray_Type = {
2811 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2812 "bytearray",
2813 sizeof(PyByteArrayObject),
2814 0,
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002815 (destructor)bytearray_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002816 0, /* tp_print */
2817 0, /* tp_getattr */
2818 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002819 0, /* tp_reserved */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002820 (reprfunc)bytearray_repr, /* tp_repr */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002821 0, /* tp_as_number */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002822 &bytearray_as_sequence, /* tp_as_sequence */
2823 &bytearray_as_mapping, /* tp_as_mapping */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002824 0, /* tp_hash */
2825 0, /* tp_call */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002826 bytearray_str, /* tp_str */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002827 PyObject_GenericGetAttr, /* tp_getattro */
2828 0, /* tp_setattro */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002829 &bytearray_as_buffer, /* tp_as_buffer */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002830 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002831 bytearray_doc, /* tp_doc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002832 0, /* tp_traverse */
2833 0, /* tp_clear */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002834 (richcmpfunc)bytearray_richcompare, /* tp_richcompare */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002835 0, /* tp_weaklistoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002836 bytearray_iter, /* tp_iter */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002837 0, /* tp_iternext */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002838 bytearray_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002839 0, /* tp_members */
2840 0, /* tp_getset */
2841 0, /* tp_base */
2842 0, /* tp_dict */
2843 0, /* tp_descr_get */
2844 0, /* tp_descr_set */
2845 0, /* tp_dictoffset */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002846 (initproc)bytearray_init, /* tp_init */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002847 PyType_GenericAlloc, /* tp_alloc */
2848 PyType_GenericNew, /* tp_new */
2849 PyObject_Del, /* tp_free */
2850};
2851
2852/*********************** Bytes Iterator ****************************/
2853
2854typedef struct {
2855 PyObject_HEAD
2856 Py_ssize_t it_index;
2857 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
2858} bytesiterobject;
2859
2860static void
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002861bytearrayiter_dealloc(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002862{
2863 _PyObject_GC_UNTRACK(it);
2864 Py_XDECREF(it->it_seq);
2865 PyObject_GC_Del(it);
2866}
2867
2868static int
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002869bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002870{
2871 Py_VISIT(it->it_seq);
2872 return 0;
2873}
2874
2875static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002876bytearrayiter_next(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002877{
2878 PyByteArrayObject *seq;
2879 PyObject *item;
2880
2881 assert(it != NULL);
2882 seq = it->it_seq;
2883 if (seq == NULL)
2884 return NULL;
2885 assert(PyByteArray_Check(seq));
2886
2887 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
2888 item = PyLong_FromLong(
2889 (unsigned char)seq->ob_bytes[it->it_index]);
2890 if (item != NULL)
2891 ++it->it_index;
2892 return item;
2893 }
2894
2895 Py_DECREF(seq);
2896 it->it_seq = NULL;
2897 return NULL;
2898}
2899
2900static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002901bytesarrayiter_length_hint(bytesiterobject *it)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002902{
2903 Py_ssize_t len = 0;
2904 if (it->it_seq)
2905 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
2906 return PyLong_FromSsize_t(len);
2907}
2908
2909PyDoc_STRVAR(length_hint_doc,
2910 "Private method returning an estimate of len(list(it)).");
2911
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002912static PyMethodDef bytearrayiter_methods[] = {
2913 {"__length_hint__", (PyCFunction)bytesarrayiter_length_hint, METH_NOARGS,
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002914 length_hint_doc},
2915 {NULL, NULL} /* sentinel */
2916};
2917
2918PyTypeObject PyByteArrayIter_Type = {
2919 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2920 "bytearray_iterator", /* tp_name */
2921 sizeof(bytesiterobject), /* tp_basicsize */
2922 0, /* tp_itemsize */
2923 /* methods */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002924 (destructor)bytearrayiter_dealloc, /* tp_dealloc */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002925 0, /* tp_print */
2926 0, /* tp_getattr */
2927 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002928 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002929 0, /* tp_repr */
2930 0, /* tp_as_number */
2931 0, /* tp_as_sequence */
2932 0, /* tp_as_mapping */
2933 0, /* tp_hash */
2934 0, /* tp_call */
2935 0, /* tp_str */
2936 PyObject_GenericGetAttr, /* tp_getattro */
2937 0, /* tp_setattro */
2938 0, /* tp_as_buffer */
2939 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2940 0, /* tp_doc */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002941 (traverseproc)bytearrayiter_traverse, /* tp_traverse */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002942 0, /* tp_clear */
2943 0, /* tp_richcompare */
2944 0, /* tp_weaklistoffset */
2945 PyObject_SelfIter, /* tp_iter */
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002946 (iternextfunc)bytearrayiter_next, /* tp_iternext */
2947 bytearrayiter_methods, /* tp_methods */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002948 0,
2949};
2950
2951static PyObject *
Benjamin Peterson153c70f2009-04-18 15:42:12 +00002952bytearray_iter(PyObject *seq)
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002953{
2954 bytesiterobject *it;
2955
2956 if (!PyByteArray_Check(seq)) {
2957 PyErr_BadInternalCall();
2958 return NULL;
2959 }
2960 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
2961 if (it == NULL)
2962 return NULL;
2963 it->it_index = 0;
2964 Py_INCREF(seq);
2965 it->it_seq = (PyByteArrayObject *)seq;
2966 _PyObject_GC_TRACK(it);
2967 return (PyObject *)it;
2968}