blob: fc1245208f2efbf40f2ebf7e5570b4a83601fe93 [file] [log] [blame]
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001/* PyByteArray (bytearray) implementation */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
5#include "structmember.h"
6#include "bytes_methods.h"
7
8static PyByteArrayObject *nullbytes = NULL;
9
10void
11PyByteArray_Fini(void)
12{
13 Py_CLEAR(nullbytes);
14}
15
16int
17PyByteArray_Init(void)
18{
19 nullbytes = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
20 if (nullbytes == NULL)
21 return 0;
22 nullbytes->ob_bytes = NULL;
23 Py_SIZE(nullbytes) = nullbytes->ob_alloc = 0;
24 nullbytes->ob_exports = 0;
25 return 1;
26}
27
28/* end nullbytes support */
29
30/* Helpers */
31
32static int
33_getbytevalue(PyObject* arg, int *value)
34{
35 long face_value;
36
37 if (PyLong_Check(arg)) {
38 face_value = PyLong_AsLong(arg);
Georg Brandl9a54d7c2008-07-16 23:15:30 +000039 } else {
40 PyObject *index = PyNumber_Index(arg);
41 if (index == NULL) {
42 PyErr_Format(PyExc_TypeError, "an integer is required");
Christian Heimes2c9c7a52008-05-26 13:42:13 +000043 return 0;
44 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +000045 face_value = PyLong_AsLong(index);
46 Py_DECREF(index);
47 }
48
49 if (face_value < 0 || face_value >= 256) {
50 /* this includes the OverflowError in case the long is too large */
51 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
Christian Heimes2c9c7a52008-05-26 13:42:13 +000052 return 0;
53 }
54
55 *value = face_value;
56 return 1;
57}
58
59static int
60bytes_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
61{
62 int ret;
63 void *ptr;
64 if (view == NULL) {
65 obj->ob_exports++;
66 return 0;
67 }
68 if (obj->ob_bytes == NULL)
69 ptr = "";
70 else
71 ptr = obj->ob_bytes;
Martin v. Löwis423be952008-08-13 15:53:07 +000072 ret = PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
Christian Heimes2c9c7a52008-05-26 13:42:13 +000073 if (ret >= 0) {
74 obj->ob_exports++;
75 }
76 return ret;
77}
78
79static void
80bytes_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
81{
82 obj->ob_exports--;
83}
84
85static Py_ssize_t
86_getbuffer(PyObject *obj, Py_buffer *view)
87{
88 PyBufferProcs *buffer = Py_TYPE(obj)->tp_as_buffer;
89
90 if (buffer == NULL || buffer->bf_getbuffer == NULL)
91 {
92 PyErr_Format(PyExc_TypeError,
93 "Type %.100s doesn't support the buffer API",
94 Py_TYPE(obj)->tp_name);
95 return -1;
96 }
97
98 if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0)
99 return -1;
100 return view->len;
101}
102
Antoine Pitrou5504e892008-12-06 21:27:53 +0000103static int
104_canresize(PyByteArrayObject *self)
105{
106 if (self->ob_exports > 0) {
107 PyErr_SetString(PyExc_BufferError,
108 "Existing exports of data: object cannot be re-sized");
109 return 0;
110 }
111 return 1;
112}
113
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000114/* Direct API functions */
115
116PyObject *
117PyByteArray_FromObject(PyObject *input)
118{
119 return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type,
120 input, NULL);
121}
122
123PyObject *
124PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
125{
126 PyByteArrayObject *new;
127 Py_ssize_t alloc;
128
129 if (size < 0) {
130 PyErr_SetString(PyExc_SystemError,
131 "Negative size passed to PyByteArray_FromStringAndSize");
132 return NULL;
133 }
134
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000135 /* Prevent buffer overflow when setting alloc to size+1. */
136 if (size == PY_SSIZE_T_MAX) {
137 return PyErr_NoMemory();
138 }
139
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000140 new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
141 if (new == NULL)
142 return NULL;
143
144 if (size == 0) {
145 new->ob_bytes = NULL;
146 alloc = 0;
147 }
148 else {
149 alloc = size + 1;
150 new->ob_bytes = PyMem_Malloc(alloc);
151 if (new->ob_bytes == NULL) {
152 Py_DECREF(new);
153 return PyErr_NoMemory();
154 }
155 if (bytes != NULL)
156 memcpy(new->ob_bytes, bytes, size);
157 new->ob_bytes[size] = '\0'; /* Trailing null byte */
158 }
159 Py_SIZE(new) = size;
160 new->ob_alloc = alloc;
161 new->ob_exports = 0;
162
163 return (PyObject *)new;
164}
165
166Py_ssize_t
167PyByteArray_Size(PyObject *self)
168{
169 assert(self != NULL);
170 assert(PyByteArray_Check(self));
171
172 return PyByteArray_GET_SIZE(self);
173}
174
175char *
176PyByteArray_AsString(PyObject *self)
177{
178 assert(self != NULL);
179 assert(PyByteArray_Check(self));
180
181 return PyByteArray_AS_STRING(self);
182}
183
184int
185PyByteArray_Resize(PyObject *self, Py_ssize_t size)
186{
187 void *sval;
188 Py_ssize_t alloc = ((PyByteArrayObject *)self)->ob_alloc;
189
190 assert(self != NULL);
191 assert(PyByteArray_Check(self));
192 assert(size >= 0);
193
Antoine Pitrou5504e892008-12-06 21:27:53 +0000194 if (size == Py_SIZE(self)) {
195 return 0;
196 }
197 if (!_canresize((PyByteArrayObject *)self)) {
198 return -1;
199 }
200
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000201 if (size < alloc / 2) {
202 /* Major downsize; resize down to exact size */
203 alloc = size + 1;
204 }
205 else if (size < alloc) {
206 /* Within allocated size; quick exit */
207 Py_SIZE(self) = size;
208 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null */
209 return 0;
210 }
211 else if (size <= alloc * 1.125) {
212 /* Moderate upsize; overallocate similar to list_resize() */
213 alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
214 }
215 else {
216 /* Major upsize; resize up to exact size */
217 alloc = size + 1;
218 }
219
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000220 sval = PyMem_Realloc(((PyByteArrayObject *)self)->ob_bytes, alloc);
221 if (sval == NULL) {
222 PyErr_NoMemory();
223 return -1;
224 }
225
226 ((PyByteArrayObject *)self)->ob_bytes = sval;
227 Py_SIZE(self) = size;
228 ((PyByteArrayObject *)self)->ob_alloc = alloc;
229 ((PyByteArrayObject *)self)->ob_bytes[size] = '\0'; /* Trailing null byte */
230
231 return 0;
232}
233
234PyObject *
235PyByteArray_Concat(PyObject *a, PyObject *b)
236{
237 Py_ssize_t size;
238 Py_buffer va, vb;
239 PyByteArrayObject *result = NULL;
240
241 va.len = -1;
242 vb.len = -1;
243 if (_getbuffer(a, &va) < 0 ||
244 _getbuffer(b, &vb) < 0) {
245 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
246 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
247 goto done;
248 }
249
250 size = va.len + vb.len;
251 if (size < 0) {
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000252 PyErr_NoMemory();
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000253 goto done;
254 }
255
256 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
257 if (result != NULL) {
258 memcpy(result->ob_bytes, va.buf, va.len);
259 memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
260 }
261
262 done:
263 if (va.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000264 PyBuffer_Release(&va);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000265 if (vb.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000266 PyBuffer_Release(&vb);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000267 return (PyObject *)result;
268}
269
270/* Functions stuffed into the type object */
271
272static Py_ssize_t
273bytes_length(PyByteArrayObject *self)
274{
275 return Py_SIZE(self);
276}
277
278static PyObject *
279bytes_iconcat(PyByteArrayObject *self, PyObject *other)
280{
281 Py_ssize_t mysize;
282 Py_ssize_t size;
283 Py_buffer vo;
284
285 if (_getbuffer(other, &vo) < 0) {
286 PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
287 Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
288 return NULL;
289 }
290
291 mysize = Py_SIZE(self);
292 size = mysize + vo.len;
293 if (size < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000294 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000295 return PyErr_NoMemory();
296 }
297 if (size < self->ob_alloc) {
298 Py_SIZE(self) = size;
299 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
300 }
301 else if (PyByteArray_Resize((PyObject *)self, size) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +0000302 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000303 return NULL;
304 }
305 memcpy(self->ob_bytes + mysize, vo.buf, vo.len);
Martin v. Löwis423be952008-08-13 15:53:07 +0000306 PyBuffer_Release(&vo);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000307 Py_INCREF(self);
308 return (PyObject *)self;
309}
310
311static PyObject *
312bytes_repeat(PyByteArrayObject *self, Py_ssize_t count)
313{
314 PyByteArrayObject *result;
315 Py_ssize_t mysize;
316 Py_ssize_t size;
317
318 if (count < 0)
319 count = 0;
320 mysize = Py_SIZE(self);
321 size = mysize * count;
322 if (count != 0 && size / count != mysize)
323 return PyErr_NoMemory();
324 result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
325 if (result != NULL && size != 0) {
326 if (mysize == 1)
327 memset(result->ob_bytes, self->ob_bytes[0], size);
328 else {
329 Py_ssize_t i;
330 for (i = 0; i < count; i++)
331 memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
332 }
333 }
334 return (PyObject *)result;
335}
336
337static PyObject *
338bytes_irepeat(PyByteArrayObject *self, Py_ssize_t count)
339{
340 Py_ssize_t mysize;
341 Py_ssize_t size;
342
343 if (count < 0)
344 count = 0;
345 mysize = Py_SIZE(self);
346 size = mysize * count;
347 if (count != 0 && size / count != mysize)
348 return PyErr_NoMemory();
349 if (size < self->ob_alloc) {
350 Py_SIZE(self) = size;
351 self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
352 }
353 else if (PyByteArray_Resize((PyObject *)self, size) < 0)
354 return NULL;
355
356 if (mysize == 1)
357 memset(self->ob_bytes, self->ob_bytes[0], size);
358 else {
359 Py_ssize_t i;
360 for (i = 1; i < count; i++)
361 memcpy(self->ob_bytes + i*mysize, self->ob_bytes, mysize);
362 }
363
364 Py_INCREF(self);
365 return (PyObject *)self;
366}
367
368static PyObject *
369bytes_getitem(PyByteArrayObject *self, Py_ssize_t i)
370{
371 if (i < 0)
372 i += Py_SIZE(self);
373 if (i < 0 || i >= Py_SIZE(self)) {
374 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
375 return NULL;
376 }
377 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
378}
379
380static PyObject *
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000381bytes_subscript(PyByteArrayObject *self, PyObject *index)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000382{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000383 if (PyIndex_Check(index)) {
384 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000385
386 if (i == -1 && PyErr_Occurred())
387 return NULL;
388
389 if (i < 0)
390 i += PyByteArray_GET_SIZE(self);
391
392 if (i < 0 || i >= Py_SIZE(self)) {
393 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
394 return NULL;
395 }
396 return PyLong_FromLong((unsigned char)(self->ob_bytes[i]));
397 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000398 else if (PySlice_Check(index)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000399 Py_ssize_t start, stop, step, slicelength, cur, i;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000400 if (PySlice_GetIndicesEx((PySliceObject *)index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000401 PyByteArray_GET_SIZE(self),
402 &start, &stop, &step, &slicelength) < 0) {
403 return NULL;
404 }
405
406 if (slicelength <= 0)
407 return PyByteArray_FromStringAndSize("", 0);
408 else if (step == 1) {
409 return PyByteArray_FromStringAndSize(self->ob_bytes + start,
410 slicelength);
411 }
412 else {
413 char *source_buf = PyByteArray_AS_STRING(self);
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000414 char *result_buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000415 PyObject *result;
416
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000417 result = PyByteArray_FromStringAndSize(NULL, slicelength);
418 if (result == NULL)
419 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000420
Alexandre Vassalottie2641f42009-04-03 06:38:02 +0000421 result_buf = PyByteArray_AS_STRING(result);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000422 for (cur = start, i = 0; i < slicelength;
423 cur += step, i++) {
424 result_buf[i] = source_buf[cur];
425 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000426 return result;
427 }
428 }
429 else {
430 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integers");
431 return NULL;
432 }
433}
434
435static int
436bytes_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
437 PyObject *values)
438{
439 Py_ssize_t avail, needed;
440 void *bytes;
441 Py_buffer vbytes;
442 int res = 0;
443
444 vbytes.len = -1;
445 if (values == (PyObject *)self) {
446 /* Make a copy and call this function recursively */
447 int err;
448 values = PyByteArray_FromObject(values);
449 if (values == NULL)
450 return -1;
451 err = bytes_setslice(self, lo, hi, values);
452 Py_DECREF(values);
453 return err;
454 }
455 if (values == NULL) {
456 /* del b[lo:hi] */
457 bytes = NULL;
458 needed = 0;
459 }
460 else {
461 if (_getbuffer(values, &vbytes) < 0) {
462 PyErr_Format(PyExc_TypeError,
Georg Brandl3dbca812008-07-23 16:10:53 +0000463 "can't set bytearray slice from %.100s",
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000464 Py_TYPE(values)->tp_name);
465 return -1;
466 }
467 needed = vbytes.len;
468 bytes = vbytes.buf;
469 }
470
471 if (lo < 0)
472 lo = 0;
473 if (hi < lo)
474 hi = lo;
475 if (hi > Py_SIZE(self))
476 hi = Py_SIZE(self);
477
478 avail = hi - lo;
479 if (avail < 0)
480 lo = hi = avail = 0;
481
482 if (avail != needed) {
483 if (avail > needed) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000484 if (!_canresize(self)) {
485 res = -1;
486 goto finish;
487 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000488 /*
489 0 lo hi old_size
490 | |<----avail----->|<-----tomove------>|
491 | |<-needed->|<-----tomove------>|
492 0 lo new_hi new_size
493 */
494 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
495 Py_SIZE(self) - hi);
496 }
497 /* XXX(nnorwitz): need to verify this can't overflow! */
498 if (PyByteArray_Resize((PyObject *)self,
499 Py_SIZE(self) + needed - avail) < 0) {
500 res = -1;
501 goto finish;
502 }
503 if (avail < needed) {
504 /*
505 0 lo hi old_size
506 | |<-avail->|<-----tomove------>|
507 | |<----needed---->|<-----tomove------>|
508 0 lo new_hi new_size
509 */
510 memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi,
511 Py_SIZE(self) - lo - needed);
512 }
513 }
514
515 if (needed > 0)
516 memcpy(self->ob_bytes + lo, bytes, needed);
517
518
519 finish:
520 if (vbytes.len != -1)
Martin v. Löwis423be952008-08-13 15:53:07 +0000521 PyBuffer_Release(&vbytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000522 return res;
523}
524
525static int
526bytes_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
527{
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000528 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000529
530 if (i < 0)
531 i += Py_SIZE(self);
532
533 if (i < 0 || i >= Py_SIZE(self)) {
534 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
535 return -1;
536 }
537
538 if (value == NULL)
539 return bytes_setslice(self, i, i+1, NULL);
540
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000541 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000542 return -1;
543
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000544 self->ob_bytes[i] = ival;
545 return 0;
546}
547
548static int
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000549bytes_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000550{
551 Py_ssize_t start, stop, step, slicelen, needed;
552 char *bytes;
553
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000554 if (PyIndex_Check(index)) {
555 Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000556
557 if (i == -1 && PyErr_Occurred())
558 return -1;
559
560 if (i < 0)
561 i += PyByteArray_GET_SIZE(self);
562
563 if (i < 0 || i >= Py_SIZE(self)) {
564 PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
565 return -1;
566 }
567
568 if (values == NULL) {
569 /* Fall through to slice assignment */
570 start = i;
571 stop = i + 1;
572 step = 1;
573 slicelen = 1;
574 }
575 else {
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000576 int ival;
577 if (!_getbytevalue(values, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000578 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000579 self->ob_bytes[i] = (char)ival;
580 return 0;
581 }
582 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000583 else if (PySlice_Check(index)) {
584 if (PySlice_GetIndicesEx((PySliceObject *)index,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000585 PyByteArray_GET_SIZE(self),
586 &start, &stop, &step, &slicelen) < 0) {
587 return -1;
588 }
589 }
590 else {
591 PyErr_SetString(PyExc_TypeError, "bytearray indices must be integer");
592 return -1;
593 }
594
595 if (values == NULL) {
596 bytes = NULL;
597 needed = 0;
598 }
599 else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
600 /* Make a copy an call this function recursively */
601 int err;
602 values = PyByteArray_FromObject(values);
603 if (values == NULL)
604 return -1;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000605 err = bytes_ass_subscript(self, index, values);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000606 Py_DECREF(values);
607 return err;
608 }
609 else {
610 assert(PyByteArray_Check(values));
611 bytes = ((PyByteArrayObject *)values)->ob_bytes;
612 needed = Py_SIZE(values);
613 }
614 /* Make sure b[5:2] = ... inserts before 5, not before 2. */
615 if ((step < 0 && start < stop) ||
616 (step > 0 && start > stop))
617 stop = start;
618 if (step == 1) {
619 if (slicelen != needed) {
Antoine Pitrou5504e892008-12-06 21:27:53 +0000620 if (!_canresize(self))
621 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000622 if (slicelen > needed) {
623 /*
624 0 start stop old_size
625 | |<---slicelen--->|<-----tomove------>|
626 | |<-needed->|<-----tomove------>|
627 0 lo new_hi new_size
628 */
629 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
630 Py_SIZE(self) - stop);
631 }
632 if (PyByteArray_Resize((PyObject *)self,
633 Py_SIZE(self) + needed - slicelen) < 0)
634 return -1;
635 if (slicelen < needed) {
636 /*
637 0 lo hi old_size
638 | |<-avail->|<-----tomove------>|
639 | |<----needed---->|<-----tomove------>|
640 0 lo new_hi new_size
641 */
642 memmove(self->ob_bytes + start + needed, self->ob_bytes + stop,
643 Py_SIZE(self) - start - needed);
644 }
645 }
646
647 if (needed > 0)
648 memcpy(self->ob_bytes + start, bytes, needed);
649
650 return 0;
651 }
652 else {
653 if (needed == 0) {
654 /* Delete slice */
655 Py_ssize_t cur, i;
656
Antoine Pitrou5504e892008-12-06 21:27:53 +0000657 if (!_canresize(self))
658 return -1;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000659 if (step < 0) {
660 stop = start + 1;
661 start = stop + step * (slicelen - 1) - 1;
662 step = -step;
663 }
664 for (cur = start, i = 0;
665 i < slicelen; cur += step, i++) {
666 Py_ssize_t lim = step - 1;
667
668 if (cur + step >= PyByteArray_GET_SIZE(self))
669 lim = PyByteArray_GET_SIZE(self) - cur - 1;
670
671 memmove(self->ob_bytes + cur - i,
672 self->ob_bytes + cur + 1, lim);
673 }
674 /* Move the tail of the bytes, in one chunk */
675 cur = start + slicelen*step;
676 if (cur < PyByteArray_GET_SIZE(self)) {
677 memmove(self->ob_bytes + cur - slicelen,
678 self->ob_bytes + cur,
679 PyByteArray_GET_SIZE(self) - cur);
680 }
681 if (PyByteArray_Resize((PyObject *)self,
682 PyByteArray_GET_SIZE(self) - slicelen) < 0)
683 return -1;
684
685 return 0;
686 }
687 else {
688 /* Assign slice */
689 Py_ssize_t cur, i;
690
691 if (needed != slicelen) {
692 PyErr_Format(PyExc_ValueError,
693 "attempt to assign bytes of size %zd "
694 "to extended slice of size %zd",
695 needed, slicelen);
696 return -1;
697 }
698 for (cur = start, i = 0; i < slicelen; cur += step, i++)
699 self->ob_bytes[cur] = bytes[i];
700 return 0;
701 }
702 }
703}
704
705static int
706bytes_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
707{
708 static char *kwlist[] = {"source", "encoding", "errors", 0};
709 PyObject *arg = NULL;
710 const char *encoding = NULL;
711 const char *errors = NULL;
712 Py_ssize_t count;
713 PyObject *it;
714 PyObject *(*iternext)(PyObject *);
715
716 if (Py_SIZE(self) != 0) {
717 /* Empty previous contents (yes, do this first of all!) */
718 if (PyByteArray_Resize((PyObject *)self, 0) < 0)
719 return -1;
720 }
721
722 /* Parse arguments */
Georg Brandl3dbca812008-07-23 16:10:53 +0000723 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist,
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000724 &arg, &encoding, &errors))
725 return -1;
726
727 /* Make a quick exit if no first argument */
728 if (arg == NULL) {
729 if (encoding != NULL || errors != NULL) {
730 PyErr_SetString(PyExc_TypeError,
731 "encoding or errors without sequence argument");
732 return -1;
733 }
734 return 0;
735 }
736
737 if (PyUnicode_Check(arg)) {
738 /* Encode via the codec registry */
739 PyObject *encoded, *new;
740 if (encoding == NULL) {
741 PyErr_SetString(PyExc_TypeError,
742 "string argument without an encoding");
743 return -1;
744 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000745 encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000746 if (encoded == NULL)
747 return -1;
748 assert(PyBytes_Check(encoded));
749 new = bytes_iconcat(self, encoded);
750 Py_DECREF(encoded);
751 if (new == NULL)
752 return -1;
753 Py_DECREF(new);
754 return 0;
755 }
756
757 /* If it's not unicode, there can't be encoding or errors */
758 if (encoding != NULL || errors != NULL) {
759 PyErr_SetString(PyExc_TypeError,
760 "encoding or errors without a string argument");
761 return -1;
762 }
763
764 /* Is it an int? */
765 count = PyNumber_AsSsize_t(arg, PyExc_ValueError);
766 if (count == -1 && PyErr_Occurred())
767 PyErr_Clear();
768 else {
769 if (count < 0) {
770 PyErr_SetString(PyExc_ValueError, "negative count");
771 return -1;
772 }
773 if (count > 0) {
774 if (PyByteArray_Resize((PyObject *)self, count))
775 return -1;
776 memset(self->ob_bytes, 0, count);
777 }
778 return 0;
779 }
780
781 /* Use the buffer API */
782 if (PyObject_CheckBuffer(arg)) {
783 Py_ssize_t size;
784 Py_buffer view;
785 if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
786 return -1;
787 size = view.len;
788 if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
789 if (PyBuffer_ToContiguous(self->ob_bytes, &view, size, 'C') < 0)
790 goto fail;
Martin v. Löwis423be952008-08-13 15:53:07 +0000791 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000792 return 0;
793 fail:
Martin v. Löwis423be952008-08-13 15:53:07 +0000794 PyBuffer_Release(&view);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000795 return -1;
796 }
797
798 /* XXX Optimize this if the arguments is a list, tuple */
799
800 /* Get the iterator */
801 it = PyObject_GetIter(arg);
802 if (it == NULL)
803 return -1;
804 iternext = *Py_TYPE(it)->tp_iternext;
805
806 /* Run the iterator to exhaustion */
807 for (;;) {
808 PyObject *item;
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000809 int rc, value;
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000810
811 /* Get the next item */
812 item = iternext(it);
813 if (item == NULL) {
814 if (PyErr_Occurred()) {
815 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
816 goto error;
817 PyErr_Clear();
818 }
819 break;
820 }
821
822 /* Interpret it as an int (__index__) */
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000823 rc = _getbytevalue(item, &value);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000824 Py_DECREF(item);
Georg Brandl9a54d7c2008-07-16 23:15:30 +0000825 if (!rc)
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000826 goto error;
827
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000828 /* Append the byte */
829 if (Py_SIZE(self) < self->ob_alloc)
830 Py_SIZE(self)++;
831 else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
832 goto error;
833 self->ob_bytes[Py_SIZE(self)-1] = value;
834 }
835
836 /* Clean up and return success */
837 Py_DECREF(it);
838 return 0;
839
840 error:
841 /* Error handling when it != NULL */
842 Py_DECREF(it);
843 return -1;
844}
845
846/* Mostly copied from string_repr, but without the
847 "smart quote" functionality. */
848static PyObject *
849bytes_repr(PyByteArrayObject *self)
850{
851 static const char *hexdigits = "0123456789abcdef";
852 const char *quote_prefix = "bytearray(b";
853 const char *quote_postfix = ")";
854 Py_ssize_t length = Py_SIZE(self);
855 /* 14 == strlen(quote_prefix) + 2 + strlen(quote_postfix) */
856 size_t newsize = 14 + 4 * length;
857 PyObject *v;
858 if (newsize > PY_SSIZE_T_MAX || newsize / 4 - 3 != length) {
859 PyErr_SetString(PyExc_OverflowError,
860 "bytearray object is too large to make repr");
861 return NULL;
862 }
863 v = PyUnicode_FromUnicode(NULL, newsize);
864 if (v == NULL) {
865 return NULL;
866 }
867 else {
868 register Py_ssize_t i;
869 register Py_UNICODE c;
870 register Py_UNICODE *p;
871 int quote;
872
873 /* Figure out which quote to use; single is preferred */
874 quote = '\'';
875 {
876 char *test, *start;
877 start = PyByteArray_AS_STRING(self);
878 for (test = start; test < start+length; ++test) {
879 if (*test == '"') {
880 quote = '\''; /* back to single */
881 goto decided;
882 }
883 else if (*test == '\'')
884 quote = '"';
885 }
886 decided:
887 ;
888 }
889
890 p = PyUnicode_AS_UNICODE(v);
891 while (*quote_prefix)
892 *p++ = *quote_prefix++;
893 *p++ = quote;
894
895 for (i = 0; i < length; i++) {
896 /* There's at least enough room for a hex escape
897 and a closing quote. */
898 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5);
899 c = self->ob_bytes[i];
900 if (c == '\'' || c == '\\')
901 *p++ = '\\', *p++ = c;
902 else if (c == '\t')
903 *p++ = '\\', *p++ = 't';
904 else if (c == '\n')
905 *p++ = '\\', *p++ = 'n';
906 else if (c == '\r')
907 *p++ = '\\', *p++ = 'r';
908 else if (c == 0)
909 *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
910 else if (c < ' ' || c >= 0x7f) {
911 *p++ = '\\';
912 *p++ = 'x';
913 *p++ = hexdigits[(c & 0xf0) >> 4];
914 *p++ = hexdigits[c & 0xf];
915 }
916 else
917 *p++ = c;
918 }
919 assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1);
920 *p++ = quote;
921 while (*quote_postfix) {
922 *p++ = *quote_postfix++;
923 }
924 *p = '\0';
925 if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) {
926 Py_DECREF(v);
927 return NULL;
928 }
929 return v;
930 }
931}
932
933static PyObject *
934bytes_str(PyObject *op)
935{
936 if (Py_BytesWarningFlag) {
937 if (PyErr_WarnEx(PyExc_BytesWarning,
938 "str() on a bytearray instance", 1))
939 return NULL;
940 }
941 return bytes_repr((PyByteArrayObject*)op);
942}
943
944static PyObject *
945bytes_richcompare(PyObject *self, PyObject *other, int op)
946{
947 Py_ssize_t self_size, other_size;
948 Py_buffer self_bytes, other_bytes;
949 PyObject *res;
950 Py_ssize_t minsize;
951 int cmp;
952
953 /* Bytes can be compared to anything that supports the (binary)
954 buffer API. Except that a comparison with Unicode is always an
955 error, even if the comparison is for equality. */
956 if (PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type) ||
957 PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
Barry Warsaw9e9dcd62008-10-17 01:50:37 +0000958 if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000959 if (PyErr_WarnEx(PyExc_BytesWarning,
Georg Brandle5d68ac2008-06-04 11:30:26 +0000960 "Comparison between bytearray and string", 1))
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000961 return NULL;
962 }
963
964 Py_INCREF(Py_NotImplemented);
965 return Py_NotImplemented;
966 }
967
968 self_size = _getbuffer(self, &self_bytes);
969 if (self_size < 0) {
970 PyErr_Clear();
971 Py_INCREF(Py_NotImplemented);
972 return Py_NotImplemented;
973 }
974
975 other_size = _getbuffer(other, &other_bytes);
976 if (other_size < 0) {
977 PyErr_Clear();
Martin v. Löwis423be952008-08-13 15:53:07 +0000978 PyBuffer_Release(&self_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +0000979 Py_INCREF(Py_NotImplemented);
980 return Py_NotImplemented;
981 }
982
983 if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
984 /* Shortcut: if the lengths differ, the objects differ */
985 cmp = (op == Py_NE);
986 }
987 else {
988 minsize = self_size;
989 if (other_size < minsize)
990 minsize = other_size;
991
992 cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize);
993 /* In ISO C, memcmp() guarantees to use unsigned bytes! */
994
995 if (cmp == 0) {
996 if (self_size < other_size)
997 cmp = -1;
998 else if (self_size > other_size)
999 cmp = 1;
1000 }
1001
1002 switch (op) {
1003 case Py_LT: cmp = cmp < 0; break;
1004 case Py_LE: cmp = cmp <= 0; break;
1005 case Py_EQ: cmp = cmp == 0; break;
1006 case Py_NE: cmp = cmp != 0; break;
1007 case Py_GT: cmp = cmp > 0; break;
1008 case Py_GE: cmp = cmp >= 0; break;
1009 }
1010 }
1011
1012 res = cmp ? Py_True : Py_False;
Martin v. Löwis423be952008-08-13 15:53:07 +00001013 PyBuffer_Release(&self_bytes);
1014 PyBuffer_Release(&other_bytes);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001015 Py_INCREF(res);
1016 return res;
1017}
1018
1019static void
1020bytes_dealloc(PyByteArrayObject *self)
1021{
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001022 if (self->ob_exports > 0) {
1023 PyErr_SetString(PyExc_SystemError,
Martin v. Löwis423be952008-08-13 15:53:07 +00001024 "deallocated bytearray object has exported buffers");
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001025 PyErr_Print();
1026 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001027 if (self->ob_bytes != 0) {
1028 PyMem_Free(self->ob_bytes);
1029 }
1030 Py_TYPE(self)->tp_free((PyObject *)self);
1031}
1032
1033
1034/* -------------------------------------------------------------------- */
1035/* Methods */
1036
1037#define STRINGLIB_CHAR char
1038#define STRINGLIB_CMP memcmp
1039#define STRINGLIB_LEN PyByteArray_GET_SIZE
1040#define STRINGLIB_STR PyByteArray_AS_STRING
1041#define STRINGLIB_NEW PyByteArray_FromStringAndSize
1042#define STRINGLIB_EMPTY nullbytes
1043#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1044#define STRINGLIB_MUTABLE 1
Benjamin Petersona786b022008-08-25 21:05:21 +00001045#define FROM_BYTEARRAY 1
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001046
1047#include "stringlib/fastsearch.h"
1048#include "stringlib/count.h"
1049#include "stringlib/find.h"
1050#include "stringlib/partition.h"
1051#include "stringlib/ctype.h"
1052#include "stringlib/transmogrify.h"
1053
1054
1055/* The following Py_LOCAL_INLINE and Py_LOCAL functions
1056were copied from the old char* style string object. */
1057
1058Py_LOCAL_INLINE(void)
1059_adjust_indices(Py_ssize_t *start, Py_ssize_t *end, Py_ssize_t len)
1060{
1061 if (*end > len)
1062 *end = len;
1063 else if (*end < 0)
1064 *end += len;
1065 if (*end < 0)
1066 *end = 0;
1067 if (*start < 0)
1068 *start += len;
1069 if (*start < 0)
1070 *start = 0;
1071}
1072
1073
1074Py_LOCAL_INLINE(Py_ssize_t)
1075bytes_find_internal(PyByteArrayObject *self, PyObject *args, int dir)
1076{
1077 PyObject *subobj;
1078 Py_buffer subbuf;
1079 Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
1080 Py_ssize_t res;
1081
1082 if (!PyArg_ParseTuple(args, "O|O&O&:find/rfind/index/rindex", &subobj,
1083 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1084 return -2;
1085 if (_getbuffer(subobj, &subbuf) < 0)
1086 return -2;
1087 if (dir > 0)
1088 res = stringlib_find_slice(
1089 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1090 subbuf.buf, subbuf.len, start, end);
1091 else
1092 res = stringlib_rfind_slice(
1093 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1094 subbuf.buf, subbuf.len, start, end);
Martin v. Löwis423be952008-08-13 15:53:07 +00001095 PyBuffer_Release(&subbuf);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001096 return res;
1097}
1098
1099PyDoc_STRVAR(find__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001100"B.find(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001101\n\
1102Return the lowest index in B where subsection sub is found,\n\
1103such that sub is contained within s[start,end]. Optional\n\
1104arguments start and end are interpreted as in slice notation.\n\
1105\n\
1106Return -1 on failure.");
1107
1108static PyObject *
1109bytes_find(PyByteArrayObject *self, PyObject *args)
1110{
1111 Py_ssize_t result = bytes_find_internal(self, args, +1);
1112 if (result == -2)
1113 return NULL;
1114 return PyLong_FromSsize_t(result);
1115}
1116
1117PyDoc_STRVAR(count__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001118"B.count(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001119\n\
1120Return the number of non-overlapping occurrences of subsection sub in\n\
1121bytes B[start:end]. Optional arguments start and end are interpreted\n\
1122as in slice notation.");
1123
1124static PyObject *
1125bytes_count(PyByteArrayObject *self, PyObject *args)
1126{
1127 PyObject *sub_obj;
1128 const char *str = PyByteArray_AS_STRING(self);
1129 Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
1130 Py_buffer vsub;
1131 PyObject *count_obj;
1132
1133 if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj,
1134 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1135 return NULL;
1136
1137 if (_getbuffer(sub_obj, &vsub) < 0)
1138 return NULL;
1139
1140 _adjust_indices(&start, &end, PyByteArray_GET_SIZE(self));
1141
1142 count_obj = PyLong_FromSsize_t(
1143 stringlib_count(str + start, end - start, vsub.buf, vsub.len)
1144 );
Martin v. Löwis423be952008-08-13 15:53:07 +00001145 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001146 return count_obj;
1147}
1148
1149
1150PyDoc_STRVAR(index__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001151"B.index(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001152\n\
1153Like B.find() but raise ValueError when the subsection is not found.");
1154
1155static PyObject *
1156bytes_index(PyByteArrayObject *self, PyObject *args)
1157{
1158 Py_ssize_t result = bytes_find_internal(self, args, +1);
1159 if (result == -2)
1160 return NULL;
1161 if (result == -1) {
1162 PyErr_SetString(PyExc_ValueError,
1163 "subsection not found");
1164 return NULL;
1165 }
1166 return PyLong_FromSsize_t(result);
1167}
1168
1169
1170PyDoc_STRVAR(rfind__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001171"B.rfind(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001172\n\
1173Return the highest index in B where subsection sub is found,\n\
1174such that sub is contained within s[start,end]. Optional\n\
1175arguments start and end are interpreted as in slice notation.\n\
1176\n\
1177Return -1 on failure.");
1178
1179static PyObject *
1180bytes_rfind(PyByteArrayObject *self, PyObject *args)
1181{
1182 Py_ssize_t result = bytes_find_internal(self, args, -1);
1183 if (result == -2)
1184 return NULL;
1185 return PyLong_FromSsize_t(result);
1186}
1187
1188
1189PyDoc_STRVAR(rindex__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001190"B.rindex(sub[, start[, end]]) -> int\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001191\n\
1192Like B.rfind() but raise ValueError when the subsection is not found.");
1193
1194static PyObject *
1195bytes_rindex(PyByteArrayObject *self, PyObject *args)
1196{
1197 Py_ssize_t result = bytes_find_internal(self, args, -1);
1198 if (result == -2)
1199 return NULL;
1200 if (result == -1) {
1201 PyErr_SetString(PyExc_ValueError,
1202 "subsection not found");
1203 return NULL;
1204 }
1205 return PyLong_FromSsize_t(result);
1206}
1207
1208
1209static int
1210bytes_contains(PyObject *self, PyObject *arg)
1211{
1212 Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1213 if (ival == -1 && PyErr_Occurred()) {
1214 Py_buffer varg;
1215 int pos;
1216 PyErr_Clear();
1217 if (_getbuffer(arg, &varg) < 0)
1218 return -1;
1219 pos = stringlib_find(PyByteArray_AS_STRING(self), Py_SIZE(self),
1220 varg.buf, varg.len, 0);
Martin v. Löwis423be952008-08-13 15:53:07 +00001221 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001222 return pos >= 0;
1223 }
1224 if (ival < 0 || ival >= 256) {
1225 PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
1226 return -1;
1227 }
1228
1229 return memchr(PyByteArray_AS_STRING(self), ival, Py_SIZE(self)) != NULL;
1230}
1231
1232
1233/* Matches the end (direction >= 0) or start (direction < 0) of self
1234 * against substr, using the start and end arguments. Returns
1235 * -1 on error, 0 if not found and 1 if found.
1236 */
1237Py_LOCAL(int)
1238_bytes_tailmatch(PyByteArrayObject *self, PyObject *substr, Py_ssize_t start,
1239 Py_ssize_t end, int direction)
1240{
1241 Py_ssize_t len = PyByteArray_GET_SIZE(self);
1242 const char* str;
1243 Py_buffer vsubstr;
1244 int rv = 0;
1245
1246 str = PyByteArray_AS_STRING(self);
1247
1248 if (_getbuffer(substr, &vsubstr) < 0)
1249 return -1;
1250
1251 _adjust_indices(&start, &end, len);
1252
1253 if (direction < 0) {
1254 /* startswith */
1255 if (start+vsubstr.len > len) {
1256 goto done;
1257 }
1258 } else {
1259 /* endswith */
1260 if (end-start < vsubstr.len || start > len) {
1261 goto done;
1262 }
1263
1264 if (end-vsubstr.len > start)
1265 start = end - vsubstr.len;
1266 }
1267 if (end-start >= vsubstr.len)
1268 rv = ! memcmp(str+start, vsubstr.buf, vsubstr.len);
1269
1270done:
Martin v. Löwis423be952008-08-13 15:53:07 +00001271 PyBuffer_Release(&vsubstr);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001272 return rv;
1273}
1274
1275
1276PyDoc_STRVAR(startswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001277"B.startswith(prefix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001278\n\
1279Return True if B starts with the specified prefix, False otherwise.\n\
1280With optional start, test B beginning at that position.\n\
1281With optional end, stop comparing B at that position.\n\
1282prefix can also be a tuple of strings to try.");
1283
1284static PyObject *
1285bytes_startswith(PyByteArrayObject *self, PyObject *args)
1286{
1287 Py_ssize_t start = 0;
1288 Py_ssize_t end = PY_SSIZE_T_MAX;
1289 PyObject *subobj;
1290 int result;
1291
1292 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
1293 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1294 return NULL;
1295 if (PyTuple_Check(subobj)) {
1296 Py_ssize_t i;
1297 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
1298 result = _bytes_tailmatch(self,
1299 PyTuple_GET_ITEM(subobj, i),
1300 start, end, -1);
1301 if (result == -1)
1302 return NULL;
1303 else if (result) {
1304 Py_RETURN_TRUE;
1305 }
1306 }
1307 Py_RETURN_FALSE;
1308 }
1309 result = _bytes_tailmatch(self, subobj, start, end, -1);
1310 if (result == -1)
1311 return NULL;
1312 else
1313 return PyBool_FromLong(result);
1314}
1315
1316PyDoc_STRVAR(endswith__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00001317"B.endswith(suffix[, start[, end]]) -> bool\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001318\n\
1319Return True if B ends with the specified suffix, False otherwise.\n\
1320With optional start, test B beginning at that position.\n\
1321With optional end, stop comparing B at that position.\n\
1322suffix can also be a tuple of strings to try.");
1323
1324static PyObject *
1325bytes_endswith(PyByteArrayObject *self, PyObject *args)
1326{
1327 Py_ssize_t start = 0;
1328 Py_ssize_t end = PY_SSIZE_T_MAX;
1329 PyObject *subobj;
1330 int result;
1331
1332 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
1333 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
1334 return NULL;
1335 if (PyTuple_Check(subobj)) {
1336 Py_ssize_t i;
1337 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
1338 result = _bytes_tailmatch(self,
1339 PyTuple_GET_ITEM(subobj, i),
1340 start, end, +1);
1341 if (result == -1)
1342 return NULL;
1343 else if (result) {
1344 Py_RETURN_TRUE;
1345 }
1346 }
1347 Py_RETURN_FALSE;
1348 }
1349 result = _bytes_tailmatch(self, subobj, start, end, +1);
1350 if (result == -1)
1351 return NULL;
1352 else
1353 return PyBool_FromLong(result);
1354}
1355
1356
1357PyDoc_STRVAR(translate__doc__,
1358"B.translate(table[, deletechars]) -> bytearray\n\
1359\n\
1360Return a copy of B, where all characters occurring in the\n\
1361optional argument deletechars are removed, and the remaining\n\
1362characters have been mapped through the given translation\n\
1363table, which must be a bytes object of length 256.");
1364
1365static PyObject *
1366bytes_translate(PyByteArrayObject *self, PyObject *args)
1367{
1368 register char *input, *output;
1369 register const char *table;
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001370 register Py_ssize_t i, c;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001371 PyObject *input_obj = (PyObject*)self;
1372 const char *output_start;
1373 Py_ssize_t inlen;
Georg Brandlccc47b62008-12-28 11:44:14 +00001374 PyObject *result = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001375 int trans_table[256];
Georg Brandlccc47b62008-12-28 11:44:14 +00001376 PyObject *tableobj = NULL, *delobj = NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001377 Py_buffer vtable, vdel;
1378
1379 if (!PyArg_UnpackTuple(args, "translate", 1, 2,
1380 &tableobj, &delobj))
1381 return NULL;
1382
Georg Brandlccc47b62008-12-28 11:44:14 +00001383 if (tableobj == Py_None) {
1384 table = NULL;
1385 tableobj = NULL;
1386 } else if (_getbuffer(tableobj, &vtable) < 0) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001387 return NULL;
Georg Brandlccc47b62008-12-28 11:44:14 +00001388 } else {
1389 if (vtable.len != 256) {
1390 PyErr_SetString(PyExc_ValueError,
1391 "translation table must be 256 characters long");
1392 goto done;
1393 }
1394 table = (const char*)vtable.buf;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001395 }
1396
1397 if (delobj != NULL) {
1398 if (_getbuffer(delobj, &vdel) < 0) {
Georg Brandlccc47b62008-12-28 11:44:14 +00001399 delobj = NULL; /* don't try to release vdel buffer on exit */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001400 goto done;
1401 }
1402 }
1403 else {
1404 vdel.buf = NULL;
1405 vdel.len = 0;
1406 }
1407
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001408 inlen = PyByteArray_GET_SIZE(input_obj);
1409 result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1410 if (result == NULL)
1411 goto done;
1412 output_start = output = PyByteArray_AsString(result);
1413 input = PyByteArray_AS_STRING(input_obj);
1414
Georg Brandlccc47b62008-12-28 11:44:14 +00001415 if (vdel.len == 0 && table != NULL) {
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001416 /* If no deletions are required, use faster code */
1417 for (i = inlen; --i >= 0; ) {
1418 c = Py_CHARMASK(*input++);
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001419 *output++ = table[c];
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001420 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001421 goto done;
1422 }
Georg Brandlccc47b62008-12-28 11:44:14 +00001423
1424 if (table == NULL) {
1425 for (i = 0; i < 256; i++)
1426 trans_table[i] = Py_CHARMASK(i);
1427 } else {
1428 for (i = 0; i < 256; i++)
1429 trans_table[i] = Py_CHARMASK(table[i]);
1430 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001431
1432 for (i = 0; i < vdel.len; i++)
1433 trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1434
1435 for (i = inlen; --i >= 0; ) {
1436 c = Py_CHARMASK(*input++);
1437 if (trans_table[c] != -1)
1438 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
1439 continue;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001440 }
1441 /* Fix the size of the resulting string */
1442 if (inlen > 0)
1443 PyByteArray_Resize(result, output - output_start);
1444
1445done:
Georg Brandlccc47b62008-12-28 11:44:14 +00001446 if (tableobj != NULL)
1447 PyBuffer_Release(&vtable);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001448 if (delobj != NULL)
Martin v. Löwis423be952008-08-13 15:53:07 +00001449 PyBuffer_Release(&vdel);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001450 return result;
1451}
1452
1453
1454#define FORWARD 1
1455#define REVERSE -1
1456
1457/* find and count characters and substrings */
1458
1459#define findchar(target, target_len, c) \
1460 ((char *)memchr((const void *)(target), c, target_len))
1461
1462/* Don't call if length < 2 */
1463#define Py_STRING_MATCH(target, offset, pattern, length) \
1464 (target[offset] == pattern[0] && \
1465 target[offset+length-1] == pattern[length-1] && \
1466 !memcmp(target+offset+1, pattern+1, length-2) )
1467
1468
Benjamin Peterson0f3641c2008-11-19 22:05:52 +00001469/* Bytes ops must return a string, create a copy */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001470Py_LOCAL(PyByteArrayObject *)
1471return_self(PyByteArrayObject *self)
1472{
Georg Brandl1e7217d2008-05-30 12:02:38 +00001473 /* always return a new bytearray */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00001474 return (PyByteArrayObject *)PyByteArray_FromStringAndSize(
1475 PyByteArray_AS_STRING(self),
1476 PyByteArray_GET_SIZE(self));
1477}
1478
1479Py_LOCAL_INLINE(Py_ssize_t)
1480countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
1481{
1482 Py_ssize_t count=0;
1483 const char *start=target;
1484 const char *end=target+target_len;
1485
1486 while ( (start=findchar(start, end-start, c)) != NULL ) {
1487 count++;
1488 if (count >= maxcount)
1489 break;
1490 start += 1;
1491 }
1492 return count;
1493}
1494
1495Py_LOCAL(Py_ssize_t)
1496findstring(const char *target, Py_ssize_t target_len,
1497 const char *pattern, Py_ssize_t pattern_len,
1498 Py_ssize_t start,
1499 Py_ssize_t end,
1500 int direction)
1501{
1502 if (start < 0) {
1503 start += target_len;
1504 if (start < 0)
1505 start = 0;
1506 }
1507 if (end > target_len) {
1508 end = target_len;
1509 } else if (end < 0) {
1510 end += target_len;
1511 if (end < 0)
1512 end = 0;
1513 }
1514
1515 /* zero-length substrings always match at the first attempt */
1516 if (pattern_len == 0)
1517 return (direction > 0) ? start : end;
1518
1519 end -= pattern_len;
1520
1521 if (direction < 0) {
1522 for (; end >= start; end--)
1523 if (Py_STRING_MATCH(target, end, pattern, pattern_len))
1524 return end;
1525 } else {
1526 for (; start <= end; start++)
1527 if (Py_STRING_MATCH(target, start, pattern, pattern_len))
1528 return start;
1529 }
1530 return -1;
1531}
1532
1533Py_LOCAL_INLINE(Py_ssize_t)
1534countstring(const char *target, Py_ssize_t target_len,
1535 const char *pattern, Py_ssize_t pattern_len,
1536 Py_ssize_t start,
1537 Py_ssize_t end,
1538 int direction, Py_ssize_t maxcount)
1539{
1540 Py_ssize_t count=0;
1541
1542 if (start < 0) {
1543 start += target_len;
1544 if (start < 0)
1545 start = 0;
1546 }
1547 if (end > target_len) {
1548 end = target_len;
1549 } else if (end < 0) {
1550 end += target_len;
1551 if (end < 0)
1552 end = 0;
1553 }
1554
1555 /* zero-length substrings match everywhere */
1556 if (pattern_len == 0 || maxcount == 0) {
1557 if (target_len+1 < maxcount)
1558 return target_len+1;
1559 return maxcount;
1560 }
1561
1562 end -= pattern_len;
1563 if (direction < 0) {
1564 for (; (end >= start); end--)
1565 if (Py_STRING_MATCH(target, end, pattern, pattern_len)) {
1566 count++;
1567 if (--maxcount <= 0) break;
1568 end -= pattern_len-1;
1569 }
1570 } else {
1571 for (; (start <= end); start++)
1572 if (Py_STRING_MATCH(target, start, pattern, pattern_len)) {
1573 count++;
1574 if (--maxcount <= 0)
1575 break;
1576 start += pattern_len-1;
1577 }
1578 }
1579 return count;
1580}
1581
1582
1583/* Algorithms for different cases of string replacement */
1584
1585/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
1586Py_LOCAL(PyByteArrayObject *)
1587replace_interleave(PyByteArrayObject *self,
1588 const char *to_s, Py_ssize_t to_len,
1589 Py_ssize_t maxcount)
1590{
1591 char *self_s, *result_s;
1592 Py_ssize_t self_len, result_len;
1593 Py_ssize_t count, i, product;
1594 PyByteArrayObject *result;
1595
1596 self_len = PyByteArray_GET_SIZE(self);
1597
1598 /* 1 at the end plus 1 after every character */
1599 count = self_len+1;
1600 if (maxcount < count)
1601 count = maxcount;
1602
1603 /* Check for overflow */
1604 /* result_len = count * to_len + self_len; */
1605 product = count * to_len;
1606 if (product / to_len != count) {
1607 PyErr_SetString(PyExc_OverflowError,
1608 "replace string is too long");
1609 return NULL;
1610 }
1611 result_len = product + self_len;
1612 if (result_len < 0) {
1613 PyErr_SetString(PyExc_OverflowError,
1614 "replace string is too long");
1615 return NULL;
1616 }
1617
1618 if (! (result = (PyByteArrayObject *)
1619 PyByteArray_FromStringAndSize(NULL, result_len)) )
1620 return NULL;
1621
1622 self_s = PyByteArray_AS_STRING(self);
1623 result_s = PyByteArray_AS_STRING(result);
1624
1625 /* TODO: special case single character, which doesn't need memcpy */
1626
1627 /* Lay the first one down (guaranteed this will occur) */
1628 Py_MEMCPY(result_s, to_s, to_len);
1629 result_s += to_len;
1630 count -= 1;
1631
1632 for (i=0; i<count; i++) {
1633 *result_s++ = *self_s++;
1634 Py_MEMCPY(result_s, to_s, to_len);
1635 result_s += to_len;
1636 }
1637
1638 /* Copy the rest of the original string */
1639 Py_MEMCPY(result_s, self_s, self_len-i);
1640
1641 return result;
1642}
1643
1644/* Special case for deleting a single character */
1645/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
1646Py_LOCAL(PyByteArrayObject *)
1647replace_delete_single_character(PyByteArrayObject *self,
1648 char from_c, Py_ssize_t maxcount)
1649{
1650 char *self_s, *result_s;
1651 char *start, *next, *end;
1652 Py_ssize_t self_len, result_len;
1653 Py_ssize_t count;
1654 PyByteArrayObject *result;
1655
1656 self_len = PyByteArray_GET_SIZE(self);
1657 self_s = PyByteArray_AS_STRING(self);
1658
1659 count = countchar(self_s, self_len, from_c, maxcount);
1660 if (count == 0) {
1661 return return_self(self);
1662 }
1663
1664 result_len = self_len - count; /* from_len == 1 */
1665 assert(result_len>=0);
1666
1667 if ( (result = (PyByteArrayObject *)
1668 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1669 return NULL;
1670 result_s = PyByteArray_AS_STRING(result);
1671
1672 start = self_s;
1673 end = self_s + self_len;
1674 while (count-- > 0) {
1675 next = findchar(start, end-start, from_c);
1676 if (next == NULL)
1677 break;
1678 Py_MEMCPY(result_s, start, next-start);
1679 result_s += (next-start);
1680 start = next+1;
1681 }
1682 Py_MEMCPY(result_s, start, end-start);
1683
1684 return result;
1685}
1686
1687/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
1688
1689Py_LOCAL(PyByteArrayObject *)
1690replace_delete_substring(PyByteArrayObject *self,
1691 const char *from_s, Py_ssize_t from_len,
1692 Py_ssize_t maxcount)
1693{
1694 char *self_s, *result_s;
1695 char *start, *next, *end;
1696 Py_ssize_t self_len, result_len;
1697 Py_ssize_t count, offset;
1698 PyByteArrayObject *result;
1699
1700 self_len = PyByteArray_GET_SIZE(self);
1701 self_s = PyByteArray_AS_STRING(self);
1702
1703 count = countstring(self_s, self_len,
1704 from_s, from_len,
1705 0, self_len, 1,
1706 maxcount);
1707
1708 if (count == 0) {
1709 /* no matches */
1710 return return_self(self);
1711 }
1712
1713 result_len = self_len - (count * from_len);
1714 assert (result_len>=0);
1715
1716 if ( (result = (PyByteArrayObject *)
1717 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL )
1718 return NULL;
1719
1720 result_s = PyByteArray_AS_STRING(result);
1721
1722 start = self_s;
1723 end = self_s + self_len;
1724 while (count-- > 0) {
1725 offset = findstring(start, end-start,
1726 from_s, from_len,
1727 0, end-start, FORWARD);
1728 if (offset == -1)
1729 break;
1730 next = start + offset;
1731
1732 Py_MEMCPY(result_s, start, next-start);
1733
1734 result_s += (next-start);
1735 start = next+from_len;
1736 }
1737 Py_MEMCPY(result_s, start, end-start);
1738 return result;
1739}
1740
1741/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
1742Py_LOCAL(PyByteArrayObject *)
1743replace_single_character_in_place(PyByteArrayObject *self,
1744 char from_c, char to_c,
1745 Py_ssize_t maxcount)
1746{
1747 char *self_s, *result_s, *start, *end, *next;
1748 Py_ssize_t self_len;
1749 PyByteArrayObject *result;
1750
1751 /* The result string will be the same size */
1752 self_s = PyByteArray_AS_STRING(self);
1753 self_len = PyByteArray_GET_SIZE(self);
1754
1755 next = findchar(self_s, self_len, from_c);
1756
1757 if (next == NULL) {
1758 /* No matches; return the original bytes */
1759 return return_self(self);
1760 }
1761
1762 /* Need to make a new bytes */
1763 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1764 if (result == NULL)
1765 return NULL;
1766 result_s = PyByteArray_AS_STRING(result);
1767 Py_MEMCPY(result_s, self_s, self_len);
1768
1769 /* change everything in-place, starting with this one */
1770 start = result_s + (next-self_s);
1771 *start = to_c;
1772 start++;
1773 end = result_s + self_len;
1774
1775 while (--maxcount > 0) {
1776 next = findchar(start, end-start, from_c);
1777 if (next == NULL)
1778 break;
1779 *next = to_c;
1780 start = next+1;
1781 }
1782
1783 return result;
1784}
1785
1786/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
1787Py_LOCAL(PyByteArrayObject *)
1788replace_substring_in_place(PyByteArrayObject *self,
1789 const char *from_s, Py_ssize_t from_len,
1790 const char *to_s, Py_ssize_t to_len,
1791 Py_ssize_t maxcount)
1792{
1793 char *result_s, *start, *end;
1794 char *self_s;
1795 Py_ssize_t self_len, offset;
1796 PyByteArrayObject *result;
1797
1798 /* The result bytes will be the same size */
1799
1800 self_s = PyByteArray_AS_STRING(self);
1801 self_len = PyByteArray_GET_SIZE(self);
1802
1803 offset = findstring(self_s, self_len,
1804 from_s, from_len,
1805 0, self_len, FORWARD);
1806 if (offset == -1) {
1807 /* No matches; return the original bytes */
1808 return return_self(self);
1809 }
1810
1811 /* Need to make a new bytes */
1812 result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, self_len);
1813 if (result == NULL)
1814 return NULL;
1815 result_s = PyByteArray_AS_STRING(result);
1816 Py_MEMCPY(result_s, self_s, self_len);
1817
1818 /* change everything in-place, starting with this one */
1819 start = result_s + offset;
1820 Py_MEMCPY(start, to_s, from_len);
1821 start += from_len;
1822 end = result_s + self_len;
1823
1824 while ( --maxcount > 0) {
1825 offset = findstring(start, end-start,
1826 from_s, from_len,
1827 0, end-start, FORWARD);
1828 if (offset==-1)
1829 break;
1830 Py_MEMCPY(start+offset, to_s, from_len);
1831 start += offset+from_len;
1832 }
1833
1834 return result;
1835}
1836
1837/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
1838Py_LOCAL(PyByteArrayObject *)
1839replace_single_character(PyByteArrayObject *self,
1840 char from_c,
1841 const char *to_s, Py_ssize_t to_len,
1842 Py_ssize_t maxcount)
1843{
1844 char *self_s, *result_s;
1845 char *start, *next, *end;
1846 Py_ssize_t self_len, result_len;
1847 Py_ssize_t count, product;
1848 PyByteArrayObject *result;
1849
1850 self_s = PyByteArray_AS_STRING(self);
1851 self_len = PyByteArray_GET_SIZE(self);
1852
1853 count = countchar(self_s, self_len, from_c, maxcount);
1854 if (count == 0) {
1855 /* no matches, return unchanged */
1856 return return_self(self);
1857 }
1858
1859 /* use the difference between current and new, hence the "-1" */
1860 /* result_len = self_len + count * (to_len-1) */
1861 product = count * (to_len-1);
1862 if (product / (to_len-1) != count) {
1863 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1864 return NULL;
1865 }
1866 result_len = self_len + product;
1867 if (result_len < 0) {
1868 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1869 return NULL;
1870 }
1871
1872 if ( (result = (PyByteArrayObject *)
1873 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1874 return NULL;
1875 result_s = PyByteArray_AS_STRING(result);
1876
1877 start = self_s;
1878 end = self_s + self_len;
1879 while (count-- > 0) {
1880 next = findchar(start, end-start, from_c);
1881 if (next == NULL)
1882 break;
1883
1884 if (next == start) {
1885 /* replace with the 'to' */
1886 Py_MEMCPY(result_s, to_s, to_len);
1887 result_s += to_len;
1888 start += 1;
1889 } else {
1890 /* copy the unchanged old then the 'to' */
1891 Py_MEMCPY(result_s, start, next-start);
1892 result_s += (next-start);
1893 Py_MEMCPY(result_s, to_s, to_len);
1894 result_s += to_len;
1895 start = next+1;
1896 }
1897 }
1898 /* Copy the remainder of the remaining bytes */
1899 Py_MEMCPY(result_s, start, end-start);
1900
1901 return result;
1902}
1903
1904/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
1905Py_LOCAL(PyByteArrayObject *)
1906replace_substring(PyByteArrayObject *self,
1907 const char *from_s, Py_ssize_t from_len,
1908 const char *to_s, Py_ssize_t to_len,
1909 Py_ssize_t maxcount)
1910{
1911 char *self_s, *result_s;
1912 char *start, *next, *end;
1913 Py_ssize_t self_len, result_len;
1914 Py_ssize_t count, offset, product;
1915 PyByteArrayObject *result;
1916
1917 self_s = PyByteArray_AS_STRING(self);
1918 self_len = PyByteArray_GET_SIZE(self);
1919
1920 count = countstring(self_s, self_len,
1921 from_s, from_len,
1922 0, self_len, FORWARD, maxcount);
1923 if (count == 0) {
1924 /* no matches, return unchanged */
1925 return return_self(self);
1926 }
1927
1928 /* Check for overflow */
1929 /* result_len = self_len + count * (to_len-from_len) */
1930 product = count * (to_len-from_len);
1931 if (product / (to_len-from_len) != count) {
1932 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1933 return NULL;
1934 }
1935 result_len = self_len + product;
1936 if (result_len < 0) {
1937 PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
1938 return NULL;
1939 }
1940
1941 if ( (result = (PyByteArrayObject *)
1942 PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
1943 return NULL;
1944 result_s = PyByteArray_AS_STRING(result);
1945
1946 start = self_s;
1947 end = self_s + self_len;
1948 while (count-- > 0) {
1949 offset = findstring(start, end-start,
1950 from_s, from_len,
1951 0, end-start, FORWARD);
1952 if (offset == -1)
1953 break;
1954 next = start+offset;
1955 if (next == start) {
1956 /* replace with the 'to' */
1957 Py_MEMCPY(result_s, to_s, to_len);
1958 result_s += to_len;
1959 start += from_len;
1960 } else {
1961 /* copy the unchanged old then the 'to' */
1962 Py_MEMCPY(result_s, start, next-start);
1963 result_s += (next-start);
1964 Py_MEMCPY(result_s, to_s, to_len);
1965 result_s += to_len;
1966 start = next+from_len;
1967 }
1968 }
1969 /* Copy the remainder of the remaining bytes */
1970 Py_MEMCPY(result_s, start, end-start);
1971
1972 return result;
1973}
1974
1975
1976Py_LOCAL(PyByteArrayObject *)
1977replace(PyByteArrayObject *self,
1978 const char *from_s, Py_ssize_t from_len,
1979 const char *to_s, Py_ssize_t to_len,
1980 Py_ssize_t maxcount)
1981{
1982 if (maxcount < 0) {
1983 maxcount = PY_SSIZE_T_MAX;
1984 } else if (maxcount == 0 || PyByteArray_GET_SIZE(self) == 0) {
1985 /* nothing to do; return the original bytes */
1986 return return_self(self);
1987 }
1988
1989 if (maxcount == 0 ||
1990 (from_len == 0 && to_len == 0)) {
1991 /* nothing to do; return the original bytes */
1992 return return_self(self);
1993 }
1994
1995 /* Handle zero-length special cases */
1996
1997 if (from_len == 0) {
1998 /* insert the 'to' bytes everywhere. */
1999 /* >>> "Python".replace("", ".") */
2000 /* '.P.y.t.h.o.n.' */
2001 return replace_interleave(self, to_s, to_len, maxcount);
2002 }
2003
2004 /* Except for "".replace("", "A") == "A" there is no way beyond this */
2005 /* point for an empty self bytes to generate a non-empty bytes */
2006 /* Special case so the remaining code always gets a non-empty bytes */
2007 if (PyByteArray_GET_SIZE(self) == 0) {
2008 return return_self(self);
2009 }
2010
2011 if (to_len == 0) {
Georg Brandl17cb8a82008-05-30 08:20:09 +00002012 /* delete all occurrences of 'from' bytes */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002013 if (from_len == 1) {
2014 return replace_delete_single_character(
2015 self, from_s[0], maxcount);
2016 } else {
2017 return replace_delete_substring(self, from_s, from_len, maxcount);
2018 }
2019 }
2020
2021 /* Handle special case where both bytes have the same length */
2022
2023 if (from_len == to_len) {
2024 if (from_len == 1) {
2025 return replace_single_character_in_place(
2026 self,
2027 from_s[0],
2028 to_s[0],
2029 maxcount);
2030 } else {
2031 return replace_substring_in_place(
2032 self, from_s, from_len, to_s, to_len, maxcount);
2033 }
2034 }
2035
2036 /* Otherwise use the more generic algorithms */
2037 if (from_len == 1) {
2038 return replace_single_character(self, from_s[0],
2039 to_s, to_len, maxcount);
2040 } else {
2041 /* len('from')>=2, len('to')>=1 */
2042 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
2043 }
2044}
2045
2046
2047PyDoc_STRVAR(replace__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002048"B.replace(old, new[, count]) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002049\n\
2050Return a copy of B with all occurrences of subsection\n\
2051old replaced by new. If the optional argument count is\n\
2052given, only the first count occurrences are replaced.");
2053
2054static PyObject *
2055bytes_replace(PyByteArrayObject *self, PyObject *args)
2056{
2057 Py_ssize_t count = -1;
2058 PyObject *from, *to, *res;
2059 Py_buffer vfrom, vto;
2060
2061 if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
2062 return NULL;
2063
2064 if (_getbuffer(from, &vfrom) < 0)
2065 return NULL;
2066 if (_getbuffer(to, &vto) < 0) {
Martin v. Löwis423be952008-08-13 15:53:07 +00002067 PyBuffer_Release(&vfrom);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002068 return NULL;
2069 }
2070
2071 res = (PyObject *)replace((PyByteArrayObject *) self,
2072 vfrom.buf, vfrom.len,
2073 vto.buf, vto.len, count);
2074
Martin v. Löwis423be952008-08-13 15:53:07 +00002075 PyBuffer_Release(&vfrom);
2076 PyBuffer_Release(&vto);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002077 return res;
2078}
2079
2080
2081/* Overallocate the initial list to reduce the number of reallocs for small
2082 split sizes. Eg, "A A A A A A A A A A".split() (10 elements) has three
2083 resizes, to sizes 4, 8, then 16. Most observed string splits are for human
2084 text (roughly 11 words per line) and field delimited data (usually 1-10
2085 fields). For large strings the split algorithms are bandwidth limited
2086 so increasing the preallocation likely will not improve things.*/
2087
2088#define MAX_PREALLOC 12
2089
2090/* 5 splits gives 6 elements */
2091#define PREALLOC_SIZE(maxsplit) \
2092 (maxsplit >= MAX_PREALLOC ? MAX_PREALLOC : maxsplit+1)
2093
2094#define SPLIT_APPEND(data, left, right) \
2095 str = PyByteArray_FromStringAndSize((data) + (left), \
2096 (right) - (left)); \
2097 if (str == NULL) \
2098 goto onError; \
2099 if (PyList_Append(list, str)) { \
2100 Py_DECREF(str); \
2101 goto onError; \
2102 } \
2103 else \
2104 Py_DECREF(str);
2105
2106#define SPLIT_ADD(data, left, right) { \
2107 str = PyByteArray_FromStringAndSize((data) + (left), \
2108 (right) - (left)); \
2109 if (str == NULL) \
2110 goto onError; \
2111 if (count < MAX_PREALLOC) { \
2112 PyList_SET_ITEM(list, count, str); \
2113 } else { \
2114 if (PyList_Append(list, str)) { \
2115 Py_DECREF(str); \
2116 goto onError; \
2117 } \
2118 else \
2119 Py_DECREF(str); \
2120 } \
2121 count++; }
2122
2123/* Always force the list to the expected size. */
2124#define FIX_PREALLOC_SIZE(list) Py_SIZE(list) = count
2125
2126
2127Py_LOCAL_INLINE(PyObject *)
2128split_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount)
2129{
2130 register Py_ssize_t i, j, count = 0;
2131 PyObject *str;
2132 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2133
2134 if (list == NULL)
2135 return NULL;
2136
2137 i = j = 0;
2138 while ((j < len) && (maxcount-- > 0)) {
2139 for(; j < len; j++) {
2140 /* I found that using memchr makes no difference */
2141 if (s[j] == ch) {
2142 SPLIT_ADD(s, i, j);
2143 i = j = j + 1;
2144 break;
2145 }
2146 }
2147 }
2148 if (i <= len) {
2149 SPLIT_ADD(s, i, len);
2150 }
2151 FIX_PREALLOC_SIZE(list);
2152 return list;
2153
2154 onError:
2155 Py_DECREF(list);
2156 return NULL;
2157}
2158
2159
2160Py_LOCAL_INLINE(PyObject *)
2161split_whitespace(const char *s, Py_ssize_t len, Py_ssize_t maxcount)
2162{
2163 register Py_ssize_t i, j, count = 0;
2164 PyObject *str;
2165 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2166
2167 if (list == NULL)
2168 return NULL;
2169
2170 for (i = j = 0; i < len; ) {
2171 /* find a token */
2172 while (i < len && ISSPACE(s[i]))
2173 i++;
2174 j = i;
2175 while (i < len && !ISSPACE(s[i]))
2176 i++;
2177 if (j < i) {
2178 if (maxcount-- <= 0)
2179 break;
2180 SPLIT_ADD(s, j, i);
2181 while (i < len && ISSPACE(s[i]))
2182 i++;
2183 j = i;
2184 }
2185 }
2186 if (j < len) {
2187 SPLIT_ADD(s, j, len);
2188 }
2189 FIX_PREALLOC_SIZE(list);
2190 return list;
2191
2192 onError:
2193 Py_DECREF(list);
2194 return NULL;
2195}
2196
2197PyDoc_STRVAR(split__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002198"B.split([sep[, maxsplit]]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002199\n\
2200Return a list of the sections in B, using sep as the delimiter.\n\
2201If sep is not given, B is split on ASCII whitespace characters\n\
2202(space, tab, return, newline, formfeed, vertical tab).\n\
2203If maxsplit is given, at most maxsplit splits are done.");
2204
2205static PyObject *
2206bytes_split(PyByteArrayObject *self, PyObject *args)
2207{
2208 Py_ssize_t len = PyByteArray_GET_SIZE(self), n, i, j;
2209 Py_ssize_t maxsplit = -1, count = 0;
2210 const char *s = PyByteArray_AS_STRING(self), *sub;
2211 PyObject *list, *str, *subobj = Py_None;
2212 Py_buffer vsub;
2213#ifdef USE_FAST
2214 Py_ssize_t pos;
2215#endif
2216
2217 if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
2218 return NULL;
2219 if (maxsplit < 0)
2220 maxsplit = PY_SSIZE_T_MAX;
2221
2222 if (subobj == Py_None)
2223 return split_whitespace(s, len, maxsplit);
2224
2225 if (_getbuffer(subobj, &vsub) < 0)
2226 return NULL;
2227 sub = vsub.buf;
2228 n = vsub.len;
2229
2230 if (n == 0) {
2231 PyErr_SetString(PyExc_ValueError, "empty separator");
Martin v. Löwis423be952008-08-13 15:53:07 +00002232 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002233 return NULL;
2234 }
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +00002235 if (n == 1) {
2236 list = split_char(s, len, sub[0], maxsplit);
2237 PyBuffer_Release(&vsub);
2238 return list;
2239 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002240
2241 list = PyList_New(PREALLOC_SIZE(maxsplit));
2242 if (list == NULL) {
Martin v. Löwis423be952008-08-13 15:53:07 +00002243 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002244 return NULL;
2245 }
2246
2247#ifdef USE_FAST
2248 i = j = 0;
2249 while (maxsplit-- > 0) {
2250 pos = fastsearch(s+i, len-i, sub, n, FAST_SEARCH);
2251 if (pos < 0)
2252 break;
2253 j = i+pos;
2254 SPLIT_ADD(s, i, j);
2255 i = j + n;
2256 }
2257#else
2258 i = j = 0;
2259 while ((j+n <= len) && (maxsplit-- > 0)) {
2260 for (; j+n <= len; j++) {
2261 if (Py_STRING_MATCH(s, j, sub, n)) {
2262 SPLIT_ADD(s, i, j);
2263 i = j = j + n;
2264 break;
2265 }
2266 }
2267 }
2268#endif
2269 SPLIT_ADD(s, i, len);
2270 FIX_PREALLOC_SIZE(list);
Martin v. Löwis423be952008-08-13 15:53:07 +00002271 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002272 return list;
2273
2274 onError:
2275 Py_DECREF(list);
Martin v. Löwis423be952008-08-13 15:53:07 +00002276 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002277 return NULL;
2278}
2279
2280/* stringlib's partition shares nullbytes in some cases.
2281 undo this, we don't want the nullbytes to be shared. */
2282static PyObject *
2283make_nullbytes_unique(PyObject *result)
2284{
2285 if (result != NULL) {
2286 int i;
2287 assert(PyTuple_Check(result));
2288 assert(PyTuple_GET_SIZE(result) == 3);
2289 for (i = 0; i < 3; i++) {
2290 if (PyTuple_GET_ITEM(result, i) == (PyObject *)nullbytes) {
2291 PyObject *new = PyByteArray_FromStringAndSize(NULL, 0);
2292 if (new == NULL) {
2293 Py_DECREF(result);
2294 result = NULL;
2295 break;
2296 }
2297 Py_DECREF(nullbytes);
2298 PyTuple_SET_ITEM(result, i, new);
2299 }
2300 }
2301 }
2302 return result;
2303}
2304
2305PyDoc_STRVAR(partition__doc__,
2306"B.partition(sep) -> (head, sep, tail)\n\
2307\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002308Search for the separator sep in B, and return the part before it,\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002309the separator itself, and the part after it. If the separator is not\n\
2310found, returns B and two empty bytearray objects.");
2311
2312static PyObject *
2313bytes_partition(PyByteArrayObject *self, PyObject *sep_obj)
2314{
2315 PyObject *bytesep, *result;
2316
2317 bytesep = PyByteArray_FromObject(sep_obj);
2318 if (! bytesep)
2319 return NULL;
2320
2321 result = stringlib_partition(
2322 (PyObject*) self,
2323 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2324 bytesep,
2325 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2326 );
2327
2328 Py_DECREF(bytesep);
2329 return make_nullbytes_unique(result);
2330}
2331
2332PyDoc_STRVAR(rpartition__doc__,
2333"B.rpartition(sep) -> (tail, sep, head)\n\
2334\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002335Search for the separator sep in B, starting at the end of B,\n\
2336and return the part before it, the separator itself, and the\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002337part after it. If the separator is not found, returns two empty\n\
2338bytearray objects and B.");
2339
2340static PyObject *
2341bytes_rpartition(PyByteArrayObject *self, PyObject *sep_obj)
2342{
2343 PyObject *bytesep, *result;
2344
2345 bytesep = PyByteArray_FromObject(sep_obj);
2346 if (! bytesep)
2347 return NULL;
2348
2349 result = stringlib_rpartition(
2350 (PyObject*) self,
2351 PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2352 bytesep,
2353 PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2354 );
2355
2356 Py_DECREF(bytesep);
2357 return make_nullbytes_unique(result);
2358}
2359
2360Py_LOCAL_INLINE(PyObject *)
2361rsplit_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount)
2362{
2363 register Py_ssize_t i, j, count=0;
2364 PyObject *str;
2365 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2366
2367 if (list == NULL)
2368 return NULL;
2369
2370 i = j = len - 1;
2371 while ((i >= 0) && (maxcount-- > 0)) {
2372 for (; i >= 0; i--) {
2373 if (s[i] == ch) {
2374 SPLIT_ADD(s, i + 1, j + 1);
2375 j = i = i - 1;
2376 break;
2377 }
2378 }
2379 }
2380 if (j >= -1) {
2381 SPLIT_ADD(s, 0, j + 1);
2382 }
2383 FIX_PREALLOC_SIZE(list);
2384 if (PyList_Reverse(list) < 0)
2385 goto onError;
2386
2387 return list;
2388
2389 onError:
2390 Py_DECREF(list);
2391 return NULL;
2392}
2393
2394Py_LOCAL_INLINE(PyObject *)
2395rsplit_whitespace(const char *s, Py_ssize_t len, Py_ssize_t maxcount)
2396{
2397 register Py_ssize_t i, j, count = 0;
2398 PyObject *str;
2399 PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
2400
2401 if (list == NULL)
2402 return NULL;
2403
2404 for (i = j = len - 1; i >= 0; ) {
2405 /* find a token */
2406 while (i >= 0 && ISSPACE(s[i]))
2407 i--;
2408 j = i;
2409 while (i >= 0 && !ISSPACE(s[i]))
2410 i--;
2411 if (j > i) {
2412 if (maxcount-- <= 0)
2413 break;
2414 SPLIT_ADD(s, i + 1, j + 1);
2415 while (i >= 0 && ISSPACE(s[i]))
2416 i--;
2417 j = i;
2418 }
2419 }
2420 if (j >= 0) {
2421 SPLIT_ADD(s, 0, j + 1);
2422 }
2423 FIX_PREALLOC_SIZE(list);
2424 if (PyList_Reverse(list) < 0)
2425 goto onError;
2426
2427 return list;
2428
2429 onError:
2430 Py_DECREF(list);
2431 return NULL;
2432}
2433
2434PyDoc_STRVAR(rsplit__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002435"B.rsplit(sep[, maxsplit]) -> list of bytearrays\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002436\n\
2437Return a list of the sections in B, using sep as the delimiter,\n\
2438starting at the end of B and working to the front.\n\
2439If sep is not given, B is split on ASCII whitespace characters\n\
2440(space, tab, return, newline, formfeed, vertical tab).\n\
2441If maxsplit is given, at most maxsplit splits are done.");
2442
2443static PyObject *
2444bytes_rsplit(PyByteArrayObject *self, PyObject *args)
2445{
2446 Py_ssize_t len = PyByteArray_GET_SIZE(self), n, i, j;
2447 Py_ssize_t maxsplit = -1, count = 0;
2448 const char *s = PyByteArray_AS_STRING(self), *sub;
2449 PyObject *list, *str, *subobj = Py_None;
2450 Py_buffer vsub;
2451
2452 if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
2453 return NULL;
2454 if (maxsplit < 0)
2455 maxsplit = PY_SSIZE_T_MAX;
2456
2457 if (subobj == Py_None)
2458 return rsplit_whitespace(s, len, maxsplit);
2459
2460 if (_getbuffer(subobj, &vsub) < 0)
2461 return NULL;
2462 sub = vsub.buf;
2463 n = vsub.len;
2464
2465 if (n == 0) {
2466 PyErr_SetString(PyExc_ValueError, "empty separator");
Martin v. Löwis423be952008-08-13 15:53:07 +00002467 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002468 return NULL;
2469 }
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +00002470 else if (n == 1) {
2471 list = rsplit_char(s, len, sub[0], maxsplit);
2472 PyBuffer_Release(&vsub);
2473 return list;
2474 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002475
2476 list = PyList_New(PREALLOC_SIZE(maxsplit));
2477 if (list == NULL) {
Martin v. Löwis423be952008-08-13 15:53:07 +00002478 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002479 return NULL;
2480 }
2481
2482 j = len;
2483 i = j - n;
2484
2485 while ( (i >= 0) && (maxsplit-- > 0) ) {
2486 for (; i>=0; i--) {
2487 if (Py_STRING_MATCH(s, i, sub, n)) {
2488 SPLIT_ADD(s, i + n, j);
2489 j = i;
2490 i -= n;
2491 break;
2492 }
2493 }
2494 }
2495 SPLIT_ADD(s, 0, j);
2496 FIX_PREALLOC_SIZE(list);
2497 if (PyList_Reverse(list) < 0)
2498 goto onError;
Martin v. Löwis423be952008-08-13 15:53:07 +00002499 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002500 return list;
2501
2502onError:
2503 Py_DECREF(list);
Martin v. Löwis423be952008-08-13 15:53:07 +00002504 PyBuffer_Release(&vsub);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002505 return NULL;
2506}
2507
2508PyDoc_STRVAR(reverse__doc__,
2509"B.reverse() -> None\n\
2510\n\
2511Reverse the order of the values in B in place.");
2512static PyObject *
2513bytes_reverse(PyByteArrayObject *self, PyObject *unused)
2514{
2515 char swap, *head, *tail;
2516 Py_ssize_t i, j, n = Py_SIZE(self);
2517
2518 j = n / 2;
2519 head = self->ob_bytes;
2520 tail = head + n - 1;
2521 for (i = 0; i < j; i++) {
2522 swap = *head;
2523 *head++ = *tail;
2524 *tail-- = swap;
2525 }
2526
2527 Py_RETURN_NONE;
2528}
2529
2530PyDoc_STRVAR(insert__doc__,
2531"B.insert(index, int) -> None\n\
2532\n\
2533Insert a single item into the bytearray before the given index.");
2534static PyObject *
2535bytes_insert(PyByteArrayObject *self, PyObject *args)
2536{
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002537 PyObject *value;
2538 int ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002539 Py_ssize_t where, n = Py_SIZE(self);
2540
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002541 if (!PyArg_ParseTuple(args, "nO:insert", &where, &value))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002542 return NULL;
2543
2544 if (n == PY_SSIZE_T_MAX) {
2545 PyErr_SetString(PyExc_OverflowError,
2546 "cannot add more objects to bytes");
2547 return NULL;
2548 }
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002549 if (!_getbytevalue(value, &ival))
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002550 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002551 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2552 return NULL;
2553
2554 if (where < 0) {
2555 where += n;
2556 if (where < 0)
2557 where = 0;
2558 }
2559 if (where > n)
2560 where = n;
2561 memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where);
Georg Brandl9a54d7c2008-07-16 23:15:30 +00002562 self->ob_bytes[where] = ival;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002563
2564 Py_RETURN_NONE;
2565}
2566
2567PyDoc_STRVAR(append__doc__,
2568"B.append(int) -> None\n\
2569\n\
2570Append a single item to the end of B.");
2571static PyObject *
2572bytes_append(PyByteArrayObject *self, PyObject *arg)
2573{
2574 int value;
2575 Py_ssize_t n = Py_SIZE(self);
2576
2577 if (! _getbytevalue(arg, &value))
2578 return NULL;
2579 if (n == PY_SSIZE_T_MAX) {
2580 PyErr_SetString(PyExc_OverflowError,
2581 "cannot add more objects to bytes");
2582 return NULL;
2583 }
2584 if (PyByteArray_Resize((PyObject *)self, n + 1) < 0)
2585 return NULL;
2586
2587 self->ob_bytes[n] = value;
2588
2589 Py_RETURN_NONE;
2590}
2591
2592PyDoc_STRVAR(extend__doc__,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002593"B.extend(iterable_of_ints) -> None\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002594\n\
2595Append all the elements from the iterator or sequence to the\n\
2596end of B.");
2597static PyObject *
2598bytes_extend(PyByteArrayObject *self, PyObject *arg)
2599{
2600 PyObject *it, *item, *bytes_obj;
2601 Py_ssize_t buf_size = 0, len = 0;
2602 int value;
2603 char *buf;
2604
2605 /* bytes_setslice code only accepts something supporting PEP 3118. */
2606 if (PyObject_CheckBuffer(arg)) {
2607 if (bytes_setslice(self, Py_SIZE(self), Py_SIZE(self), arg) == -1)
2608 return NULL;
2609
2610 Py_RETURN_NONE;
2611 }
2612
2613 it = PyObject_GetIter(arg);
2614 if (it == NULL)
2615 return NULL;
2616
2617 /* Try to determine the length of the argument. 32 is abitrary. */
2618 buf_size = _PyObject_LengthHint(arg, 32);
Raymond Hettingere8364232009-02-02 22:55:09 +00002619 if (buf_size == -1) {
2620 Py_DECREF(it);
2621 return NULL;
2622 }
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002623
2624 bytes_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
2625 if (bytes_obj == NULL)
2626 return NULL;
2627 buf = PyByteArray_AS_STRING(bytes_obj);
2628
2629 while ((item = PyIter_Next(it)) != NULL) {
2630 if (! _getbytevalue(item, &value)) {
2631 Py_DECREF(item);
2632 Py_DECREF(it);
2633 Py_DECREF(bytes_obj);
2634 return NULL;
2635 }
2636 buf[len++] = value;
2637 Py_DECREF(item);
2638
2639 if (len >= buf_size) {
2640 buf_size = len + (len >> 1) + 1;
2641 if (PyByteArray_Resize((PyObject *)bytes_obj, buf_size) < 0) {
2642 Py_DECREF(it);
2643 Py_DECREF(bytes_obj);
2644 return NULL;
2645 }
2646 /* Recompute the `buf' pointer, since the resizing operation may
2647 have invalidated it. */
2648 buf = PyByteArray_AS_STRING(bytes_obj);
2649 }
2650 }
2651 Py_DECREF(it);
2652
2653 /* Resize down to exact size. */
2654 if (PyByteArray_Resize((PyObject *)bytes_obj, len) < 0) {
2655 Py_DECREF(bytes_obj);
2656 return NULL;
2657 }
2658
2659 if (bytes_setslice(self, Py_SIZE(self), Py_SIZE(self), bytes_obj) == -1)
2660 return NULL;
2661 Py_DECREF(bytes_obj);
2662
2663 Py_RETURN_NONE;
2664}
2665
2666PyDoc_STRVAR(pop__doc__,
2667"B.pop([index]) -> int\n\
2668\n\
2669Remove and return a single item from B. If no index\n\
Benjamin Petersondcf97b92008-07-02 17:30:14 +00002670argument is given, will pop the last value.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002671static PyObject *
2672bytes_pop(PyByteArrayObject *self, PyObject *args)
2673{
2674 int value;
2675 Py_ssize_t where = -1, n = Py_SIZE(self);
2676
2677 if (!PyArg_ParseTuple(args, "|n:pop", &where))
2678 return NULL;
2679
2680 if (n == 0) {
2681 PyErr_SetString(PyExc_OverflowError,
2682 "cannot pop an empty bytes");
2683 return NULL;
2684 }
2685 if (where < 0)
2686 where += Py_SIZE(self);
2687 if (where < 0 || where >= Py_SIZE(self)) {
2688 PyErr_SetString(PyExc_IndexError, "pop index out of range");
2689 return NULL;
2690 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002691 if (!_canresize(self))
2692 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002693
2694 value = self->ob_bytes[where];
2695 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2696 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2697 return NULL;
2698
2699 return PyLong_FromLong(value);
2700}
2701
2702PyDoc_STRVAR(remove__doc__,
2703"B.remove(int) -> None\n\
2704\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002705Remove the first occurrence of a value in B.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002706static PyObject *
2707bytes_remove(PyByteArrayObject *self, PyObject *arg)
2708{
2709 int value;
2710 Py_ssize_t where, n = Py_SIZE(self);
2711
2712 if (! _getbytevalue(arg, &value))
2713 return NULL;
2714
2715 for (where = 0; where < n; where++) {
2716 if (self->ob_bytes[where] == value)
2717 break;
2718 }
2719 if (where == n) {
2720 PyErr_SetString(PyExc_ValueError, "value not found in bytes");
2721 return NULL;
2722 }
Antoine Pitrou5504e892008-12-06 21:27:53 +00002723 if (!_canresize(self))
2724 return NULL;
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002725
2726 memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
2727 if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
2728 return NULL;
2729
2730 Py_RETURN_NONE;
2731}
2732
2733/* XXX These two helpers could be optimized if argsize == 1 */
2734
2735static Py_ssize_t
2736lstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2737 void *argptr, Py_ssize_t argsize)
2738{
2739 Py_ssize_t i = 0;
2740 while (i < mysize && memchr(argptr, myptr[i], argsize))
2741 i++;
2742 return i;
2743}
2744
2745static Py_ssize_t
2746rstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
2747 void *argptr, Py_ssize_t argsize)
2748{
2749 Py_ssize_t i = mysize - 1;
2750 while (i >= 0 && memchr(argptr, myptr[i], argsize))
2751 i--;
2752 return i + 1;
2753}
2754
2755PyDoc_STRVAR(strip__doc__,
2756"B.strip([bytes]) -> bytearray\n\
2757\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002758Strip leading and trailing bytes contained in the argument\n\
2759and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002760If the argument is omitted, strip ASCII whitespace.");
2761static PyObject *
2762bytes_strip(PyByteArrayObject *self, PyObject *args)
2763{
2764 Py_ssize_t left, right, mysize, argsize;
2765 void *myptr, *argptr;
2766 PyObject *arg = Py_None;
2767 Py_buffer varg;
2768 if (!PyArg_ParseTuple(args, "|O:strip", &arg))
2769 return NULL;
2770 if (arg == Py_None) {
2771 argptr = "\t\n\r\f\v ";
2772 argsize = 6;
2773 }
2774 else {
2775 if (_getbuffer(arg, &varg) < 0)
2776 return NULL;
2777 argptr = varg.buf;
2778 argsize = varg.len;
2779 }
2780 myptr = self->ob_bytes;
2781 mysize = Py_SIZE(self);
2782 left = lstrip_helper(myptr, mysize, argptr, argsize);
2783 if (left == mysize)
2784 right = left;
2785 else
2786 right = rstrip_helper(myptr, mysize, argptr, argsize);
2787 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002788 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002789 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2790}
2791
2792PyDoc_STRVAR(lstrip__doc__,
2793"B.lstrip([bytes]) -> bytearray\n\
2794\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002795Strip leading bytes contained in the argument\n\
2796and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002797If the argument is omitted, strip leading ASCII whitespace.");
2798static PyObject *
2799bytes_lstrip(PyByteArrayObject *self, PyObject *args)
2800{
2801 Py_ssize_t left, right, mysize, argsize;
2802 void *myptr, *argptr;
2803 PyObject *arg = Py_None;
2804 Py_buffer varg;
2805 if (!PyArg_ParseTuple(args, "|O:lstrip", &arg))
2806 return NULL;
2807 if (arg == Py_None) {
2808 argptr = "\t\n\r\f\v ";
2809 argsize = 6;
2810 }
2811 else {
2812 if (_getbuffer(arg, &varg) < 0)
2813 return NULL;
2814 argptr = varg.buf;
2815 argsize = varg.len;
2816 }
2817 myptr = self->ob_bytes;
2818 mysize = Py_SIZE(self);
2819 left = lstrip_helper(myptr, mysize, argptr, argsize);
2820 right = mysize;
2821 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002822 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002823 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2824}
2825
2826PyDoc_STRVAR(rstrip__doc__,
2827"B.rstrip([bytes]) -> bytearray\n\
2828\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002829Strip trailing bytes contained in the argument\n\
2830and return the result as a new bytearray.\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002831If the argument is omitted, strip trailing ASCII whitespace.");
2832static PyObject *
2833bytes_rstrip(PyByteArrayObject *self, PyObject *args)
2834{
2835 Py_ssize_t left, right, mysize, argsize;
2836 void *myptr, *argptr;
2837 PyObject *arg = Py_None;
2838 Py_buffer varg;
2839 if (!PyArg_ParseTuple(args, "|O:rstrip", &arg))
2840 return NULL;
2841 if (arg == Py_None) {
2842 argptr = "\t\n\r\f\v ";
2843 argsize = 6;
2844 }
2845 else {
2846 if (_getbuffer(arg, &varg) < 0)
2847 return NULL;
2848 argptr = varg.buf;
2849 argsize = varg.len;
2850 }
2851 myptr = self->ob_bytes;
2852 mysize = Py_SIZE(self);
2853 left = 0;
2854 right = rstrip_helper(myptr, mysize, argptr, argsize);
2855 if (arg != Py_None)
Martin v. Löwis423be952008-08-13 15:53:07 +00002856 PyBuffer_Release(&varg);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002857 return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
2858}
2859
2860PyDoc_STRVAR(decode_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002861"B.decode([encoding[, errors]]) -> str\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002862\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002863Decode B using the codec registered for encoding. encoding defaults\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002864to the default encoding. errors may be given to set a different error\n\
2865handling scheme. Default is 'strict' meaning that encoding errors raise\n\
2866a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
2867as well as any other name registered with codecs.register_error that is\n\
2868able to handle UnicodeDecodeErrors.");
2869
2870static PyObject *
2871bytes_decode(PyObject *self, PyObject *args)
2872{
2873 const char *encoding = NULL;
2874 const char *errors = NULL;
2875
2876 if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
2877 return NULL;
2878 if (encoding == NULL)
2879 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002880 return PyUnicode_FromEncodedObject(self, encoding, errors);
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002881}
2882
2883PyDoc_STRVAR(alloc_doc,
2884"B.__alloc__() -> int\n\
2885\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002886Return the number of bytes actually allocated.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002887
2888static PyObject *
2889bytes_alloc(PyByteArrayObject *self)
2890{
2891 return PyLong_FromSsize_t(self->ob_alloc);
2892}
2893
2894PyDoc_STRVAR(join_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002895"B.join(iterable_of_bytes) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002896\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00002897Concatenate any number of bytes/bytearray objects, with B\n\
2898in between each pair, and return the result as a new bytearray.");
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002899
2900static PyObject *
2901bytes_join(PyByteArrayObject *self, PyObject *it)
2902{
2903 PyObject *seq;
2904 Py_ssize_t mysize = Py_SIZE(self);
2905 Py_ssize_t i;
2906 Py_ssize_t n;
2907 PyObject **items;
2908 Py_ssize_t totalsize = 0;
2909 PyObject *result;
2910 char *dest;
2911
2912 seq = PySequence_Fast(it, "can only join an iterable");
2913 if (seq == NULL)
2914 return NULL;
2915 n = PySequence_Fast_GET_SIZE(seq);
2916 items = PySequence_Fast_ITEMS(seq);
2917
2918 /* Compute the total size, and check that they are all bytes */
2919 /* XXX Shouldn't we use _getbuffer() on these items instead? */
2920 for (i = 0; i < n; i++) {
2921 PyObject *obj = items[i];
2922 if (!PyByteArray_Check(obj) && !PyBytes_Check(obj)) {
2923 PyErr_Format(PyExc_TypeError,
2924 "can only join an iterable of bytes "
2925 "(item %ld has type '%.100s')",
2926 /* XXX %ld isn't right on Win64 */
2927 (long)i, Py_TYPE(obj)->tp_name);
2928 goto error;
2929 }
2930 if (i > 0)
2931 totalsize += mysize;
2932 totalsize += Py_SIZE(obj);
2933 if (totalsize < 0) {
2934 PyErr_NoMemory();
2935 goto error;
2936 }
2937 }
2938
2939 /* Allocate the result, and copy the bytes */
2940 result = PyByteArray_FromStringAndSize(NULL, totalsize);
2941 if (result == NULL)
2942 goto error;
2943 dest = PyByteArray_AS_STRING(result);
2944 for (i = 0; i < n; i++) {
2945 PyObject *obj = items[i];
2946 Py_ssize_t size = Py_SIZE(obj);
2947 char *buf;
2948 if (PyByteArray_Check(obj))
2949 buf = PyByteArray_AS_STRING(obj);
2950 else
2951 buf = PyBytes_AS_STRING(obj);
2952 if (i) {
2953 memcpy(dest, self->ob_bytes, mysize);
2954 dest += mysize;
2955 }
2956 memcpy(dest, buf, size);
2957 dest += size;
2958 }
2959
2960 /* Done */
2961 Py_DECREF(seq);
2962 return result;
2963
2964 /* Error handling */
2965 error:
2966 Py_DECREF(seq);
2967 return NULL;
2968}
2969
2970PyDoc_STRVAR(fromhex_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00002971"bytearray.fromhex(string) -> bytearray (static method)\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00002972\n\
2973Create a bytearray object from a string of hexadecimal numbers.\n\
2974Spaces between two numbers are accepted.\n\
2975Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef').");
2976
2977static int
2978hex_digit_to_int(Py_UNICODE c)
2979{
2980 if (c >= 128)
2981 return -1;
2982 if (ISDIGIT(c))
2983 return c - '0';
2984 else {
2985 if (ISUPPER(c))
2986 c = TOLOWER(c);
2987 if (c >= 'a' && c <= 'f')
2988 return c - 'a' + 10;
2989 }
2990 return -1;
2991}
2992
2993static PyObject *
2994bytes_fromhex(PyObject *cls, PyObject *args)
2995{
2996 PyObject *newbytes, *hexobj;
2997 char *buf;
2998 Py_UNICODE *hex;
2999 Py_ssize_t hexlen, byteslen, i, j;
3000 int top, bot;
3001
3002 if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj))
3003 return NULL;
3004 assert(PyUnicode_Check(hexobj));
3005 hexlen = PyUnicode_GET_SIZE(hexobj);
3006 hex = PyUnicode_AS_UNICODE(hexobj);
3007 byteslen = hexlen/2; /* This overestimates if there are spaces */
3008 newbytes = PyByteArray_FromStringAndSize(NULL, byteslen);
3009 if (!newbytes)
3010 return NULL;
3011 buf = PyByteArray_AS_STRING(newbytes);
3012 for (i = j = 0; i < hexlen; i += 2) {
3013 /* skip over spaces in the input */
3014 while (hex[i] == ' ')
3015 i++;
3016 if (i >= hexlen)
3017 break;
3018 top = hex_digit_to_int(hex[i]);
3019 bot = hex_digit_to_int(hex[i+1]);
3020 if (top == -1 || bot == -1) {
3021 PyErr_Format(PyExc_ValueError,
3022 "non-hexadecimal number found in "
3023 "fromhex() arg at position %zd", i);
3024 goto error;
3025 }
3026 buf[j++] = (top << 4) + bot;
3027 }
3028 if (PyByteArray_Resize(newbytes, j) < 0)
3029 goto error;
3030 return newbytes;
3031
3032 error:
3033 Py_DECREF(newbytes);
3034 return NULL;
3035}
3036
3037PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3038
3039static PyObject *
3040bytes_reduce(PyByteArrayObject *self)
3041{
3042 PyObject *latin1, *dict;
3043 if (self->ob_bytes)
3044 latin1 = PyUnicode_DecodeLatin1(self->ob_bytes,
3045 Py_SIZE(self), NULL);
3046 else
3047 latin1 = PyUnicode_FromString("");
3048
3049 dict = PyObject_GetAttrString((PyObject *)self, "__dict__");
3050 if (dict == NULL) {
3051 PyErr_Clear();
3052 dict = Py_None;
3053 Py_INCREF(dict);
3054 }
3055
3056 return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
3057}
3058
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003059PyDoc_STRVAR(sizeof_doc,
3060"B.__sizeof__() -> int\n\
3061 \n\
3062Returns the size of B in memory, in bytes");
3063static PyObject *
3064bytes_sizeof(PyByteArrayObject *self)
3065{
3066 Py_ssize_t res;
3067
3068 res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
3069 return PyLong_FromSsize_t(res);
3070}
3071
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003072static PySequenceMethods bytes_as_sequence = {
3073 (lenfunc)bytes_length, /* sq_length */
3074 (binaryfunc)PyByteArray_Concat, /* sq_concat */
3075 (ssizeargfunc)bytes_repeat, /* sq_repeat */
3076 (ssizeargfunc)bytes_getitem, /* sq_item */
3077 0, /* sq_slice */
3078 (ssizeobjargproc)bytes_setitem, /* sq_ass_item */
3079 0, /* sq_ass_slice */
3080 (objobjproc)bytes_contains, /* sq_contains */
3081 (binaryfunc)bytes_iconcat, /* sq_inplace_concat */
3082 (ssizeargfunc)bytes_irepeat, /* sq_inplace_repeat */
3083};
3084
3085static PyMappingMethods bytes_as_mapping = {
3086 (lenfunc)bytes_length,
3087 (binaryfunc)bytes_subscript,
3088 (objobjargproc)bytes_ass_subscript,
3089};
3090
3091static PyBufferProcs bytes_as_buffer = {
3092 (getbufferproc)bytes_getbuffer,
3093 (releasebufferproc)bytes_releasebuffer,
3094};
3095
3096static PyMethodDef
3097bytes_methods[] = {
3098 {"__alloc__", (PyCFunction)bytes_alloc, METH_NOARGS, alloc_doc},
3099 {"__reduce__", (PyCFunction)bytes_reduce, METH_NOARGS, reduce_doc},
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003100 {"__sizeof__", (PyCFunction)bytes_sizeof, METH_NOARGS, sizeof_doc},
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003101 {"append", (PyCFunction)bytes_append, METH_O, append__doc__},
3102 {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
3103 _Py_capitalize__doc__},
3104 {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
3105 {"count", (PyCFunction)bytes_count, METH_VARARGS, count__doc__},
3106 {"decode", (PyCFunction)bytes_decode, METH_VARARGS, decode_doc},
3107 {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS, endswith__doc__},
3108 {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS,
3109 expandtabs__doc__},
3110 {"extend", (PyCFunction)bytes_extend, METH_O, extend__doc__},
3111 {"find", (PyCFunction)bytes_find, METH_VARARGS, find__doc__},
3112 {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS,
3113 fromhex_doc},
3114 {"index", (PyCFunction)bytes_index, METH_VARARGS, index__doc__},
3115 {"insert", (PyCFunction)bytes_insert, METH_VARARGS, insert__doc__},
3116 {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
3117 _Py_isalnum__doc__},
3118 {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
3119 _Py_isalpha__doc__},
3120 {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
3121 _Py_isdigit__doc__},
3122 {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
3123 _Py_islower__doc__},
3124 {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
3125 _Py_isspace__doc__},
3126 {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
3127 _Py_istitle__doc__},
3128 {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
3129 _Py_isupper__doc__},
3130 {"join", (PyCFunction)bytes_join, METH_O, join_doc},
3131 {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
3132 {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
3133 {"lstrip", (PyCFunction)bytes_lstrip, METH_VARARGS, lstrip__doc__},
3134 {"partition", (PyCFunction)bytes_partition, METH_O, partition__doc__},
3135 {"pop", (PyCFunction)bytes_pop, METH_VARARGS, pop__doc__},
3136 {"remove", (PyCFunction)bytes_remove, METH_O, remove__doc__},
3137 {"replace", (PyCFunction)bytes_replace, METH_VARARGS, replace__doc__},
3138 {"reverse", (PyCFunction)bytes_reverse, METH_NOARGS, reverse__doc__},
3139 {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, rfind__doc__},
3140 {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, rindex__doc__},
3141 {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
3142 {"rpartition", (PyCFunction)bytes_rpartition, METH_O, rpartition__doc__},
3143 {"rsplit", (PyCFunction)bytes_rsplit, METH_VARARGS, rsplit__doc__},
3144 {"rstrip", (PyCFunction)bytes_rstrip, METH_VARARGS, rstrip__doc__},
3145 {"split", (PyCFunction)bytes_split, METH_VARARGS, split__doc__},
3146 {"splitlines", (PyCFunction)stringlib_splitlines, METH_VARARGS,
3147 splitlines__doc__},
3148 {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS ,
3149 startswith__doc__},
3150 {"strip", (PyCFunction)bytes_strip, METH_VARARGS, strip__doc__},
3151 {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
3152 _Py_swapcase__doc__},
3153 {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
3154 {"translate", (PyCFunction)bytes_translate, METH_VARARGS,
3155 translate__doc__},
3156 {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
3157 {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
3158 {NULL}
3159};
3160
3161PyDoc_STRVAR(bytes_doc,
Georg Brandl17cb8a82008-05-30 08:20:09 +00003162"bytearray(iterable_of_ints) -> bytearray\n\
3163bytearray(string, encoding[, errors]) -> bytearray\n\
3164bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray\n\
3165bytearray(memory_view) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003166\n\
3167Construct an mutable bytearray object from:\n\
3168 - an iterable yielding integers in range(256)\n\
3169 - a text string encoded using the specified encoding\n\
3170 - a bytes or a bytearray object\n\
3171 - any object implementing the buffer API.\n\
3172\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00003173bytearray(int) -> bytearray\n\
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003174\n\
3175Construct a zero-initialized bytearray of the given length.");
3176
3177
3178static PyObject *bytes_iter(PyObject *seq);
3179
3180PyTypeObject PyByteArray_Type = {
3181 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3182 "bytearray",
3183 sizeof(PyByteArrayObject),
3184 0,
3185 (destructor)bytes_dealloc, /* tp_dealloc */
3186 0, /* tp_print */
3187 0, /* tp_getattr */
3188 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003189 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003190 (reprfunc)bytes_repr, /* tp_repr */
3191 0, /* tp_as_number */
3192 &bytes_as_sequence, /* tp_as_sequence */
3193 &bytes_as_mapping, /* tp_as_mapping */
3194 0, /* tp_hash */
3195 0, /* tp_call */
3196 bytes_str, /* tp_str */
3197 PyObject_GenericGetAttr, /* tp_getattro */
3198 0, /* tp_setattro */
3199 &bytes_as_buffer, /* tp_as_buffer */
3200 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3201 bytes_doc, /* tp_doc */
3202 0, /* tp_traverse */
3203 0, /* tp_clear */
3204 (richcmpfunc)bytes_richcompare, /* tp_richcompare */
3205 0, /* tp_weaklistoffset */
3206 bytes_iter, /* tp_iter */
3207 0, /* tp_iternext */
3208 bytes_methods, /* tp_methods */
3209 0, /* tp_members */
3210 0, /* tp_getset */
3211 0, /* tp_base */
3212 0, /* tp_dict */
3213 0, /* tp_descr_get */
3214 0, /* tp_descr_set */
3215 0, /* tp_dictoffset */
3216 (initproc)bytes_init, /* tp_init */
3217 PyType_GenericAlloc, /* tp_alloc */
3218 PyType_GenericNew, /* tp_new */
3219 PyObject_Del, /* tp_free */
3220};
3221
3222/*********************** Bytes Iterator ****************************/
3223
3224typedef struct {
3225 PyObject_HEAD
3226 Py_ssize_t it_index;
3227 PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
3228} bytesiterobject;
3229
3230static void
3231bytesiter_dealloc(bytesiterobject *it)
3232{
3233 _PyObject_GC_UNTRACK(it);
3234 Py_XDECREF(it->it_seq);
3235 PyObject_GC_Del(it);
3236}
3237
3238static int
3239bytesiter_traverse(bytesiterobject *it, visitproc visit, void *arg)
3240{
3241 Py_VISIT(it->it_seq);
3242 return 0;
3243}
3244
3245static PyObject *
3246bytesiter_next(bytesiterobject *it)
3247{
3248 PyByteArrayObject *seq;
3249 PyObject *item;
3250
3251 assert(it != NULL);
3252 seq = it->it_seq;
3253 if (seq == NULL)
3254 return NULL;
3255 assert(PyByteArray_Check(seq));
3256
3257 if (it->it_index < PyByteArray_GET_SIZE(seq)) {
3258 item = PyLong_FromLong(
3259 (unsigned char)seq->ob_bytes[it->it_index]);
3260 if (item != NULL)
3261 ++it->it_index;
3262 return item;
3263 }
3264
3265 Py_DECREF(seq);
3266 it->it_seq = NULL;
3267 return NULL;
3268}
3269
3270static PyObject *
3271bytesiter_length_hint(bytesiterobject *it)
3272{
3273 Py_ssize_t len = 0;
3274 if (it->it_seq)
3275 len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
3276 return PyLong_FromSsize_t(len);
3277}
3278
3279PyDoc_STRVAR(length_hint_doc,
3280 "Private method returning an estimate of len(list(it)).");
3281
3282static PyMethodDef bytesiter_methods[] = {
3283 {"__length_hint__", (PyCFunction)bytesiter_length_hint, METH_NOARGS,
3284 length_hint_doc},
3285 {NULL, NULL} /* sentinel */
3286};
3287
3288PyTypeObject PyByteArrayIter_Type = {
3289 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3290 "bytearray_iterator", /* tp_name */
3291 sizeof(bytesiterobject), /* tp_basicsize */
3292 0, /* tp_itemsize */
3293 /* methods */
3294 (destructor)bytesiter_dealloc, /* tp_dealloc */
3295 0, /* tp_print */
3296 0, /* tp_getattr */
3297 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003298 0, /* tp_reserved */
Christian Heimes2c9c7a52008-05-26 13:42:13 +00003299 0, /* tp_repr */
3300 0, /* tp_as_number */
3301 0, /* tp_as_sequence */
3302 0, /* tp_as_mapping */
3303 0, /* tp_hash */
3304 0, /* tp_call */
3305 0, /* tp_str */
3306 PyObject_GenericGetAttr, /* tp_getattro */
3307 0, /* tp_setattro */
3308 0, /* tp_as_buffer */
3309 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
3310 0, /* tp_doc */
3311 (traverseproc)bytesiter_traverse, /* tp_traverse */
3312 0, /* tp_clear */
3313 0, /* tp_richcompare */
3314 0, /* tp_weaklistoffset */
3315 PyObject_SelfIter, /* tp_iter */
3316 (iternextfunc)bytesiter_next, /* tp_iternext */
3317 bytesiter_methods, /* tp_methods */
3318 0,
3319};
3320
3321static PyObject *
3322bytes_iter(PyObject *seq)
3323{
3324 bytesiterobject *it;
3325
3326 if (!PyByteArray_Check(seq)) {
3327 PyErr_BadInternalCall();
3328 return NULL;
3329 }
3330 it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
3331 if (it == NULL)
3332 return NULL;
3333 it->it_index = 0;
3334 Py_INCREF(seq);
3335 it->it_seq = (PyByteArrayObject *)seq;
3336 _PyObject_GC_TRACK(it);
3337 return (PyObject *)it;
3338}