-
-
Notifications
You must be signed in to change notification settings - Fork 30.4k
/
bytearrayobject.c
2485 lines (2128 loc) · 71.6 KB
/
bytearrayobject.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* PyByteArray (bytearray) implementation */
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#include "pycore_abstract.h" // _PyIndex_Check()
#include "pycore_bytes_methods.h"
#include "pycore_bytesobject.h"
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
#include "pycore_strhex.h" // _Py_strhex_with_sep()
#include "pycore_long.h" // _PyLong_FromUnsignedChar()
#include "bytesobject.h"
/*[clinic input]
class bytearray "PyByteArrayObject *" "&PyByteArray_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5535b77c37a119e0]*/
/* For PyByteArray_AS_STRING(). */
char _PyByteArray_empty_string[] = "";
/* Helpers */
static int
_getbytevalue(PyObject* arg, int *value)
{
int overflow;
long face_value = PyLong_AsLongAndOverflow(arg, &overflow);
if (face_value == -1 && PyErr_Occurred()) {
*value = -1;
return 0;
}
if (face_value < 0 || face_value >= 256) {
/* this includes an overflow in converting to C long */
PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
*value = -1;
return 0;
}
*value = face_value;
return 1;
}
static int
bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags)
{
void *ptr;
if (view == NULL) {
PyErr_SetString(PyExc_BufferError,
"bytearray_getbuffer: view==NULL argument is obsolete");
return -1;
}
ptr = (void *) PyByteArray_AS_STRING(obj);
/* cannot fail if view != NULL and readonly == 0 */
(void)PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
obj->ob_exports++;
return 0;
}
static void
bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view)
{
obj->ob_exports--;
assert(obj->ob_exports >= 0);
}
static int
_canresize(PyByteArrayObject *self)
{
if (self->ob_exports > 0) {
PyErr_SetString(PyExc_BufferError,
"Existing exports of data: object cannot be re-sized");
return 0;
}
return 1;
}
#include "clinic/bytearrayobject.c.h"
/* Direct API functions */
PyObject *
PyByteArray_FromObject(PyObject *input)
{
return PyObject_CallOneArg((PyObject *)&PyByteArray_Type, input);
}
static PyObject *
_PyByteArray_FromBufferObject(PyObject *obj)
{
PyObject *result;
Py_buffer view;
if (PyObject_GetBuffer(obj, &view, PyBUF_FULL_RO) < 0) {
return NULL;
}
result = PyByteArray_FromStringAndSize(NULL, view.len);
if (result != NULL &&
PyBuffer_ToContiguous(PyByteArray_AS_STRING(result),
&view, view.len, 'C') < 0)
{
Py_CLEAR(result);
}
PyBuffer_Release(&view);
return result;
}
PyObject *
PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
{
PyByteArrayObject *new;
Py_ssize_t alloc;
if (size < 0) {
PyErr_SetString(PyExc_SystemError,
"Negative size passed to PyByteArray_FromStringAndSize");
return NULL;
}
/* Prevent buffer overflow when setting alloc to size+1. */
if (size == PY_SSIZE_T_MAX) {
return PyErr_NoMemory();
}
new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
if (new == NULL)
return NULL;
if (size == 0) {
new->ob_bytes = NULL;
alloc = 0;
}
else {
alloc = size + 1;
new->ob_bytes = PyObject_Malloc(alloc);
if (new->ob_bytes == NULL) {
Py_DECREF(new);
return PyErr_NoMemory();
}
if (bytes != NULL && size > 0)
memcpy(new->ob_bytes, bytes, size);
new->ob_bytes[size] = '\0'; /* Trailing null byte */
}
Py_SET_SIZE(new, size);
new->ob_alloc = alloc;
new->ob_start = new->ob_bytes;
new->ob_exports = 0;
return (PyObject *)new;
}
Py_ssize_t
PyByteArray_Size(PyObject *self)
{
assert(self != NULL);
assert(PyByteArray_Check(self));
return PyByteArray_GET_SIZE(self);
}
char *
PyByteArray_AsString(PyObject *self)
{
assert(self != NULL);
assert(PyByteArray_Check(self));
return PyByteArray_AS_STRING(self);
}
int
PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
{
void *sval;
PyByteArrayObject *obj = ((PyByteArrayObject *)self);
/* All computations are done unsigned to avoid integer overflows
(see issue #22335). */
size_t alloc = (size_t) obj->ob_alloc;
size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes);
size_t size = (size_t) requested_size;
assert(self != NULL);
assert(PyByteArray_Check(self));
assert(logical_offset <= alloc);
assert(requested_size >= 0);
if (requested_size == Py_SIZE(self)) {
return 0;
}
if (!_canresize(obj)) {
return -1;
}
if (size + logical_offset + 1 <= alloc) {
/* Current buffer is large enough to host the requested size,
decide on a strategy. */
if (size < alloc / 2) {
/* Major downsize; resize down to exact size */
alloc = size + 1;
}
else {
/* Minor downsize; quick exit */
Py_SET_SIZE(self, size);
PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */
return 0;
}
}
else {
/* Need growing, decide on a strategy */
if (size <= alloc * 1.125) {
/* Moderate upsize; overallocate similar to list_resize() */
alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
}
else {
/* Major upsize; resize up to exact size */
alloc = size + 1;
}
}
if (alloc > PY_SSIZE_T_MAX) {
PyErr_NoMemory();
return -1;
}
if (logical_offset > 0) {
sval = PyObject_Malloc(alloc);
if (sval == NULL) {
PyErr_NoMemory();
return -1;
}
memcpy(sval, PyByteArray_AS_STRING(self),
Py_MIN((size_t)requested_size, (size_t)Py_SIZE(self)));
PyObject_Free(obj->ob_bytes);
}
else {
sval = PyObject_Realloc(obj->ob_bytes, alloc);
if (sval == NULL) {
PyErr_NoMemory();
return -1;
}
}
obj->ob_bytes = obj->ob_start = sval;
Py_SET_SIZE(self, size);
obj->ob_alloc = alloc;
obj->ob_bytes[size] = '\0'; /* Trailing null byte */
return 0;
}
PyObject *
PyByteArray_Concat(PyObject *a, PyObject *b)
{
Py_buffer va, vb;
PyByteArrayObject *result = NULL;
va.len = -1;
vb.len = -1;
if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 ||
PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) {
PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
Py_TYPE(b)->tp_name, Py_TYPE(a)->tp_name);
goto done;
}
if (va.len > PY_SSIZE_T_MAX - vb.len) {
PyErr_NoMemory();
goto done;
}
result = (PyByteArrayObject *) \
PyByteArray_FromStringAndSize(NULL, va.len + vb.len);
// result->ob_bytes is NULL if result is an empty bytearray:
// if va.len + vb.len equals zero.
if (result != NULL && result->ob_bytes != NULL) {
memcpy(result->ob_bytes, va.buf, va.len);
memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
}
done:
if (va.len != -1)
PyBuffer_Release(&va);
if (vb.len != -1)
PyBuffer_Release(&vb);
return (PyObject *)result;
}
/* Functions stuffed into the type object */
static Py_ssize_t
bytearray_length(PyByteArrayObject *self)
{
return Py_SIZE(self);
}
static PyObject *
bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
{
Py_ssize_t size;
Py_buffer vo;
if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) {
PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
return NULL;
}
size = Py_SIZE(self);
if (size > PY_SSIZE_T_MAX - vo.len) {
PyBuffer_Release(&vo);
return PyErr_NoMemory();
}
if (PyByteArray_Resize((PyObject *)self, size + vo.len) < 0) {
PyBuffer_Release(&vo);
return NULL;
}
memcpy(PyByteArray_AS_STRING(self) + size, vo.buf, vo.len);
PyBuffer_Release(&vo);
return Py_NewRef(self);
}
static PyObject *
bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
{
if (count < 0)
count = 0;
const Py_ssize_t mysize = Py_SIZE(self);
if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
return PyErr_NoMemory();
Py_ssize_t size = mysize * count;
PyByteArrayObject* result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
const char* buf = PyByteArray_AS_STRING(self);
if (result != NULL && size != 0) {
_PyBytes_Repeat(result->ob_bytes, size, buf, mysize);
}
return (PyObject *)result;
}
static PyObject *
bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
{
if (count < 0)
count = 0;
else if (count == 1) {
return Py_NewRef(self);
}
const Py_ssize_t mysize = Py_SIZE(self);
if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
return PyErr_NoMemory();
const Py_ssize_t size = mysize * count;
if (PyByteArray_Resize((PyObject *)self, size) < 0)
return NULL;
char* buf = PyByteArray_AS_STRING(self);
_PyBytes_Repeat(buf, size, buf, mysize);
return Py_NewRef(self);
}
static PyObject *
bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
{
if (i < 0 || i >= Py_SIZE(self)) {
PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
return NULL;
}
return _PyLong_FromUnsignedChar((unsigned char)(self->ob_start[i]));
}
static PyObject *
bytearray_subscript(PyByteArrayObject *self, PyObject *index)
{
if (_PyIndex_Check(index)) {
Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
if (i == -1 && PyErr_Occurred())
return NULL;
if (i < 0)
i += PyByteArray_GET_SIZE(self);
if (i < 0 || i >= Py_SIZE(self)) {
PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
return NULL;
}
return _PyLong_FromUnsignedChar((unsigned char)(self->ob_start[i]));
}
else if (PySlice_Check(index)) {
Py_ssize_t start, stop, step, slicelength, i;
size_t cur;
if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
return NULL;
}
slicelength = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self),
&start, &stop, step);
if (slicelength <= 0)
return PyByteArray_FromStringAndSize("", 0);
else if (step == 1) {
return PyByteArray_FromStringAndSize(
PyByteArray_AS_STRING(self) + start, slicelength);
}
else {
char *source_buf = PyByteArray_AS_STRING(self);
char *result_buf;
PyObject *result;
result = PyByteArray_FromStringAndSize(NULL, slicelength);
if (result == NULL)
return NULL;
result_buf = PyByteArray_AS_STRING(result);
for (cur = start, i = 0; i < slicelength;
cur += step, i++) {
result_buf[i] = source_buf[cur];
}
return result;
}
}
else {
PyErr_Format(PyExc_TypeError,
"bytearray indices must be integers or slices, not %.200s",
Py_TYPE(index)->tp_name);
return NULL;
}
}
static int
bytearray_setslice_linear(PyByteArrayObject *self,
Py_ssize_t lo, Py_ssize_t hi,
char *bytes, Py_ssize_t bytes_len)
{
Py_ssize_t avail = hi - lo;
char *buf = PyByteArray_AS_STRING(self);
Py_ssize_t growth = bytes_len - avail;
int res = 0;
assert(avail >= 0);
if (growth < 0) {
if (!_canresize(self))
return -1;
if (lo == 0) {
/* Shrink the buffer by advancing its logical start */
self->ob_start -= growth;
/*
0 lo hi old_size
| |<----avail----->|<-----tail------>|
| |<-bytes_len->|<-----tail------>|
0 new_lo new_hi new_size
*/
}
else {
/*
0 lo hi old_size
| |<----avail----->|<-----tomove------>|
| |<-bytes_len->|<-----tomove------>|
0 lo new_hi new_size
*/
memmove(buf + lo + bytes_len, buf + hi,
Py_SIZE(self) - hi);
}
if (PyByteArray_Resize((PyObject *)self,
Py_SIZE(self) + growth) < 0) {
/* Issue #19578: Handling the memory allocation failure here is
tricky here because the bytearray object has already been
modified. Depending on growth and lo, the behaviour is
different.
If growth < 0 and lo != 0, the operation is completed, but a
MemoryError is still raised and the memory block is not
shrunk. Otherwise, the bytearray is restored in its previous
state and a MemoryError is raised. */
if (lo == 0) {
self->ob_start += growth;
return -1;
}
/* memmove() removed bytes, the bytearray object cannot be
restored in its previous state. */
Py_SET_SIZE(self, Py_SIZE(self) + growth);
res = -1;
}
buf = PyByteArray_AS_STRING(self);
}
else if (growth > 0) {
if (Py_SIZE(self) > (Py_ssize_t)PY_SSIZE_T_MAX - growth) {
PyErr_NoMemory();
return -1;
}
if (PyByteArray_Resize((PyObject *)self,
Py_SIZE(self) + growth) < 0) {
return -1;
}
buf = PyByteArray_AS_STRING(self);
/* Make the place for the additional bytes */
/*
0 lo hi old_size
| |<-avail->|<-----tomove------>|
| |<---bytes_len-->|<-----tomove------>|
0 lo new_hi new_size
*/
memmove(buf + lo + bytes_len, buf + hi,
Py_SIZE(self) - lo - bytes_len);
}
if (bytes_len > 0)
memcpy(buf + lo, bytes, bytes_len);
return res;
}
static int
bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
PyObject *values)
{
Py_ssize_t needed;
void *bytes;
Py_buffer vbytes;
int res = 0;
vbytes.len = -1;
if (values == (PyObject *)self) {
/* Make a copy and call this function recursively */
int err;
values = PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(values),
PyByteArray_GET_SIZE(values));
if (values == NULL)
return -1;
err = bytearray_setslice(self, lo, hi, values);
Py_DECREF(values);
return err;
}
if (values == NULL) {
/* del b[lo:hi] */
bytes = NULL;
needed = 0;
}
else {
if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) {
PyErr_Format(PyExc_TypeError,
"can't set bytearray slice from %.100s",
Py_TYPE(values)->tp_name);
return -1;
}
needed = vbytes.len;
bytes = vbytes.buf;
}
if (lo < 0)
lo = 0;
if (hi < lo)
hi = lo;
if (hi > Py_SIZE(self))
hi = Py_SIZE(self);
res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
if (vbytes.len != -1)
PyBuffer_Release(&vbytes);
return res;
}
static int
bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value)
{
int ival = -1;
// GH-91153: We need to do this *before* the size check, in case value has a
// nasty __index__ method that changes the size of the bytearray:
if (value && !_getbytevalue(value, &ival)) {
return -1;
}
if (i < 0) {
i += Py_SIZE(self);
}
if (i < 0 || i >= Py_SIZE(self)) {
PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
return -1;
}
if (value == NULL) {
return bytearray_setslice(self, i, i+1, NULL);
}
assert(0 <= ival && ival < 256);
PyByteArray_AS_STRING(self)[i] = ival;
return 0;
}
static int
bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values)
{
Py_ssize_t start, stop, step, slicelen, needed;
char *buf, *bytes;
buf = PyByteArray_AS_STRING(self);
if (_PyIndex_Check(index)) {
Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
if (i == -1 && PyErr_Occurred()) {
return -1;
}
int ival = -1;
// GH-91153: We need to do this *before* the size check, in case values
// has a nasty __index__ method that changes the size of the bytearray:
if (values && !_getbytevalue(values, &ival)) {
return -1;
}
if (i < 0) {
i += PyByteArray_GET_SIZE(self);
}
if (i < 0 || i >= Py_SIZE(self)) {
PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
return -1;
}
if (values == NULL) {
/* Fall through to slice assignment */
start = i;
stop = i + 1;
step = 1;
slicelen = 1;
}
else {
assert(0 <= ival && ival < 256);
buf[i] = (char)ival;
return 0;
}
}
else if (PySlice_Check(index)) {
if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
return -1;
}
slicelen = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self), &start,
&stop, step);
}
else {
PyErr_Format(PyExc_TypeError,
"bytearray indices must be integers or slices, not %.200s",
Py_TYPE(index)->tp_name);
return -1;
}
if (values == NULL) {
bytes = NULL;
needed = 0;
}
else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
int err;
if (PyNumber_Check(values) || PyUnicode_Check(values)) {
PyErr_SetString(PyExc_TypeError,
"can assign only bytes, buffers, or iterables "
"of ints in range(0, 256)");
return -1;
}
/* Make a copy and call this function recursively */
values = PyByteArray_FromObject(values);
if (values == NULL)
return -1;
err = bytearray_ass_subscript(self, index, values);
Py_DECREF(values);
return err;
}
else {
assert(PyByteArray_Check(values));
bytes = PyByteArray_AS_STRING(values);
needed = Py_SIZE(values);
}
/* Make sure b[5:2] = ... inserts before 5, not before 2. */
if ((step < 0 && start < stop) ||
(step > 0 && start > stop))
stop = start;
if (step == 1) {
return bytearray_setslice_linear(self, start, stop, bytes, needed);
}
else {
if (needed == 0) {
/* Delete slice */
size_t cur;
Py_ssize_t i;
if (!_canresize(self))
return -1;
if (slicelen == 0)
/* Nothing to do here. */
return 0;
if (step < 0) {
stop = start + 1;
start = stop + step * (slicelen - 1) - 1;
step = -step;
}
for (cur = start, i = 0;
i < slicelen; cur += step, i++) {
Py_ssize_t lim = step - 1;
if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
lim = PyByteArray_GET_SIZE(self) - cur - 1;
memmove(buf + cur - i,
buf + cur + 1, lim);
}
/* Move the tail of the bytes, in one chunk */
cur = start + (size_t)slicelen*step;
if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
memmove(buf + cur - slicelen,
buf + cur,
PyByteArray_GET_SIZE(self) - cur);
}
if (PyByteArray_Resize((PyObject *)self,
PyByteArray_GET_SIZE(self) - slicelen) < 0)
return -1;
return 0;
}
else {
/* Assign slice */
Py_ssize_t i;
size_t cur;
if (needed != slicelen) {
PyErr_Format(PyExc_ValueError,
"attempt to assign bytes of size %zd "
"to extended slice of size %zd",
needed, slicelen);
return -1;
}
for (cur = start, i = 0; i < slicelen; cur += step, i++)
buf[cur] = bytes[i];
return 0;
}
}
}
/*[clinic input]
bytearray.__init__
source as arg: object = NULL
encoding: str = NULL
errors: str = NULL
[clinic start generated code]*/
static int
bytearray___init___impl(PyByteArrayObject *self, PyObject *arg,
const char *encoding, const char *errors)
/*[clinic end generated code: output=4ce1304649c2f8b3 input=1141a7122eefd7b9]*/
{
Py_ssize_t count;
PyObject *it;
PyObject *(*iternext)(PyObject *);
if (Py_SIZE(self) != 0) {
/* Empty previous contents (yes, do this first of all!) */
if (PyByteArray_Resize((PyObject *)self, 0) < 0)
return -1;
}
/* Make a quick exit if no first argument */
if (arg == NULL) {
if (encoding != NULL || errors != NULL) {
PyErr_SetString(PyExc_TypeError,
encoding != NULL ?
"encoding without a string argument" :
"errors without a string argument");
return -1;
}
return 0;
}
if (PyUnicode_Check(arg)) {
/* Encode via the codec registry */
PyObject *encoded, *new;
if (encoding == NULL) {
PyErr_SetString(PyExc_TypeError,
"string argument without an encoding");
return -1;
}
encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
if (encoded == NULL)
return -1;
assert(PyBytes_Check(encoded));
new = bytearray_iconcat(self, encoded);
Py_DECREF(encoded);
if (new == NULL)
return -1;
Py_DECREF(new);
return 0;
}
/* If it's not unicode, there can't be encoding or errors */
if (encoding != NULL || errors != NULL) {
PyErr_SetString(PyExc_TypeError,
encoding != NULL ?
"encoding without a string argument" :
"errors without a string argument");
return -1;
}
/* Is it an int? */
if (_PyIndex_Check(arg)) {
count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
if (count == -1 && PyErr_Occurred()) {
if (!PyErr_ExceptionMatches(PyExc_TypeError))
return -1;
PyErr_Clear(); /* fall through */
}
else {
if (count < 0) {
PyErr_SetString(PyExc_ValueError, "negative count");
return -1;
}
if (count > 0) {
if (PyByteArray_Resize((PyObject *)self, count))
return -1;
memset(PyByteArray_AS_STRING(self), 0, count);
}
return 0;
}
}
/* Use the buffer API */
if (PyObject_CheckBuffer(arg)) {
Py_ssize_t size;
Py_buffer view;
if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
return -1;
size = view.len;
if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
&view, size, 'C') < 0)
goto fail;
PyBuffer_Release(&view);
return 0;
fail:
PyBuffer_Release(&view);
return -1;
}
if (PyList_CheckExact(arg) || PyTuple_CheckExact(arg)) {
Py_ssize_t size = PySequence_Fast_GET_SIZE(arg);
if (PyByteArray_Resize((PyObject *)self, size) < 0) {
return -1;
}
PyObject **items = PySequence_Fast_ITEMS(arg);
char *s = PyByteArray_AS_STRING(self);
for (Py_ssize_t i = 0; i < size; i++) {
int value;
if (!PyLong_CheckExact(items[i])) {
/* Resize to 0 and go through slowpath */
if (Py_SIZE(self) != 0) {
if (PyByteArray_Resize((PyObject *)self, 0) < 0) {
return -1;
}
}
goto slowpath;
}
int rc = _getbytevalue(items[i], &value);
if (!rc) {
return -1;
}
s[i] = value;
}
return 0;
}
slowpath:
/* Get the iterator */
it = PyObject_GetIter(arg);
if (it == NULL) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_Format(PyExc_TypeError,
"cannot convert '%.200s' object to bytearray",
Py_TYPE(arg)->tp_name);
}
return -1;
}
iternext = *Py_TYPE(it)->tp_iternext;
/* Run the iterator to exhaustion */
for (;;) {
PyObject *item;
int rc, value;
/* Get the next item */
item = iternext(it);
if (item == NULL) {
if (PyErr_Occurred()) {
if (!PyErr_ExceptionMatches(PyExc_StopIteration))
goto error;
PyErr_Clear();
}
break;
}
/* Interpret it as an int (__index__) */
rc = _getbytevalue(item, &value);
Py_DECREF(item);
if (!rc)
goto error;
/* Append the byte */
if (Py_SIZE(self) + 1 < self->ob_alloc) {
Py_SET_SIZE(self, Py_SIZE(self) + 1);
PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0';
}
else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
goto error;
PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
}
/* Clean up and return success */
Py_DECREF(it);
return 0;
error:
/* Error handling when it != NULL */
Py_DECREF(it);
return -1;
}
/* Mostly copied from string_repr, but without the
"smart quote" functionality. */
static PyObject *
bytearray_repr(PyByteArrayObject *self)
{
const char *className = _PyType_Name(Py_TYPE(self));
const char *quote_prefix = "(b";
const char *quote_postfix = ")";
Py_ssize_t length = Py_SIZE(self);
/* 6 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */
Py_ssize_t newsize;
PyObject *v;
Py_ssize_t i;
char *bytes;
char c;
char *p;
int quote;
char *test, *start;
char *buffer;
newsize = strlen(className);
if (length > (PY_SSIZE_T_MAX - 6 - newsize) / 4) {
PyErr_SetString(PyExc_OverflowError,
"bytearray object is too large to make repr");
return NULL;
}
newsize += 6 + length * 4;
buffer = PyObject_Malloc(newsize);
if (buffer == NULL) {
PyErr_NoMemory();
return NULL;
}
/* Figure out which quote to use; single is preferred */
quote = '\'';
start = PyByteArray_AS_STRING(self);
for (test = start; test < start+length; ++test) {
if (*test == '"') {
quote = '\''; /* back to single */
break;
}
else if (*test == '\'')
quote = '"';
}
p = buffer;
while (*className)
*p++ = *className++;
while (*quote_prefix)
*p++ = *quote_prefix++;
*p++ = quote;
bytes = PyByteArray_AS_STRING(self);
for (i = 0; i < length; i++) {
/* There's at least enough room for a hex escape
and a closing quote. */
assert(newsize - (p - buffer) >= 5);
c = bytes[i];
if (c == '\'' || c == '\\')
*p++ = '\\', *p++ = c;
else if (c == '\t')
*p++ = '\\', *p++ = 't';
else if (c == '\n')
*p++ = '\\', *p++ = 'n';
else if (c == '\r')
*p++ = '\\', *p++ = 'r';
else if (c == 0)
*p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0';
else if (c < ' ' || c >= 0x7f) {
*p++ = '\\';
*p++ = 'x';
*p++ = Py_hexdigits[(c & 0xf0) >> 4];
*p++ = Py_hexdigits[c & 0xf];
}