Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/bytearrayobject.c
Line
Count
Source
1
/* PyByteArray (bytearray) implementation */
2
3
#include "Python.h"
4
#include "pycore_abstract.h"      // _PyIndex_Check()
5
#include "pycore_bytes_methods.h"
6
#include "pycore_bytesobject.h"
7
#include "pycore_ceval.h"         // _PyEval_GetBuiltin()
8
#include "pycore_critical_section.h"
9
#include "pycore_object.h"        // _PyObject_GC_UNTRACK()
10
#include "pycore_strhex.h"        // _Py_strhex_with_sep()
11
#include "pycore_long.h"          // _PyLong_FromUnsignedChar()
12
#include "pycore_pyatomic_ft_wrappers.h"
13
#include "bytesobject.h"
14
15
/*[clinic input]
16
class bytearray "PyByteArrayObject *" "&PyByteArray_Type"
17
[clinic start generated code]*/
18
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5535b77c37a119e0]*/
19
20
/* Max number of bytes a bytearray can contain */
21
62.9M
#define PyByteArray_SIZE_MAX ((Py_ssize_t)(PY_SSIZE_T_MAX - _PyBytesObject_SIZE))
22
23
/* Helpers */
24
25
static int
26
_getbytevalue(PyObject* arg, int *value)
27
113M
{
28
113M
    int overflow;
29
113M
    long face_value = PyLong_AsLongAndOverflow(arg, &overflow);
30
31
113M
    if (face_value == -1 && PyErr_Occurred()) {
32
0
        *value = -1;
33
0
        return 0;
34
0
    }
35
113M
    if (face_value < 0 || face_value >= 256) {
36
        /* this includes an overflow in converting to C long */
37
0
        PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
38
0
        *value = -1;
39
0
        return 0;
40
0
    }
41
42
113M
    *value = face_value;
43
113M
    return 1;
44
113M
}
45
46
static inline void
47
bytearray_write_trailing_null_byte(PyByteArrayObject *self)
48
24.7M
{
49
24.7M
    char *data = PyByteArray_AS_STRING(self);
50
24.7M
    Py_ssize_t size = PyByteArray_GET_SIZE(self);
51
24.7M
    data[size] = '\0';
52
24.7M
}
53
54
55
static void
56
bytearray_reinit_from_bytes(PyByteArrayObject *self, Py_ssize_t size)
57
68.8M
{
58
68.8M
    Py_ssize_t alloc = PyBytes_GET_SIZE(self->ob_bytes_object);
59
68.8M
    assert(0 <= size && size <= alloc);
60
61
68.8M
    if (alloc != 0) {
62
36.1M
        assert(_PyBytes_IsMutable(self->ob_bytes_object));
63
36.1M
    }
64
32.7M
    else {
65
        // Use the empty bytes string singleton for an empty bytearray
66
32.7M
        assert(_Py_IsImmortal(self->ob_bytes_object));
67
32.7M
    }
68
69
68.8M
    self->ob_bytes = self->ob_start = PyBytes_AS_STRING(self->ob_bytes_object);
70
68.8M
    Py_SET_SIZE(self, size);
71
68.8M
    FT_ATOMIC_STORE_SSIZE_RELAXED(self->ob_alloc, alloc);
72
68.8M
}
73
74
static int
75
bytearray_getbuffer_lock_held(PyObject *self, Py_buffer *view, int flags)
76
20.3M
{
77
20.3M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
78
20.3M
    PyByteArrayObject *obj = _PyByteArray_CAST(self);
79
20.3M
    if (view == NULL) {
80
0
        PyErr_SetString(PyExc_BufferError,
81
0
            "bytearray_getbuffer: view==NULL argument is obsolete");
82
0
        return -1;
83
0
    }
84
85
20.3M
    void *ptr = (void *) PyByteArray_AS_STRING(obj);
86
20.3M
    if (PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags) < 0) {
87
0
        return -1;
88
0
    }
89
20.3M
    obj->ob_exports++;
90
20.3M
    return 0;
91
20.3M
}
92
93
static int
94
bytearray_getbuffer(PyObject *self, Py_buffer *view, int flags)
95
20.3M
{
96
20.3M
    int ret;
97
20.3M
    Py_BEGIN_CRITICAL_SECTION(self);
98
20.3M
    ret = bytearray_getbuffer_lock_held(self, view, flags);
99
20.3M
    Py_END_CRITICAL_SECTION();
100
20.3M
    return ret;
101
20.3M
}
102
103
static void
104
bytearray_releasebuffer(PyObject *self, Py_buffer *view)
105
20.3M
{
106
20.3M
    Py_BEGIN_CRITICAL_SECTION(self);
107
20.3M
    PyByteArrayObject *obj = _PyByteArray_CAST(self);
108
20.3M
    obj->ob_exports--;
109
20.3M
    assert(obj->ob_exports >= 0);
110
20.3M
    Py_END_CRITICAL_SECTION();
111
20.3M
}
112
113
typedef PyObject* (*_ba_bytes_op)(const char *buf, Py_ssize_t len,
114
                                  PyObject *sub, Py_ssize_t start,
115
                                  Py_ssize_t end);
116
117
static PyObject *
118
_bytearray_with_buffer(PyByteArrayObject *self, _ba_bytes_op op, PyObject *sub,
119
                       Py_ssize_t start, Py_ssize_t end)
120
323k
{
121
323k
    PyObject *res;
122
123
323k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
124
125
    /* Increase exports to prevent bytearray storage from changing during op. */
126
323k
    self->ob_exports++;
127
323k
    res = op(PyByteArray_AS_STRING(self), Py_SIZE(self), sub, start, end);
128
323k
    self->ob_exports--;
129
323k
    return res;
130
323k
}
131
132
static int
133
_canresize(PyByteArrayObject *self)
134
92.2M
{
135
92.2M
    if (self->ob_exports > 0) {
136
0
        PyErr_SetString(PyExc_BufferError,
137
0
                "Existing exports of data: object cannot be re-sized");
138
0
        return 0;
139
0
    }
140
92.2M
    return 1;
141
92.2M
}
142
143
#include "clinic/bytearrayobject.c.h"
144
145
/* Direct API functions */
146
147
PyObject *
148
PyByteArray_FromObject(PyObject *input)
149
0
{
150
0
    return PyObject_CallOneArg((PyObject *)&PyByteArray_Type, input);
151
0
}
152
153
static PyObject *
154
_PyByteArray_FromBufferObject(PyObject *obj)
155
0
{
156
0
    PyObject *result;
157
0
    Py_buffer view;
158
159
0
    if (PyObject_GetBuffer(obj, &view, PyBUF_FULL_RO) < 0) {
160
0
        return NULL;
161
0
    }
162
0
    result = PyByteArray_FromStringAndSize(NULL, view.len);
163
0
    if (result != NULL &&
164
0
        PyBuffer_ToContiguous(PyByteArray_AS_STRING(result),
165
0
                              &view, view.len, 'C') < 0)
166
0
    {
167
0
        Py_CLEAR(result);
168
0
    }
169
0
    PyBuffer_Release(&view);
170
0
    return result;
171
0
}
172
173
PyObject *
174
PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
175
1.75M
{
176
1.75M
    PyByteArrayObject *new;
177
178
1.75M
    if (size < 0) {
179
0
        PyErr_SetString(PyExc_SystemError,
180
0
            "Negative size passed to PyByteArray_FromStringAndSize");
181
0
        return NULL;
182
0
    }
183
184
1.75M
    new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
185
1.75M
    if (new == NULL) {
186
0
        return NULL;
187
0
    }
188
189
    /* Fill values used in bytearray_dealloc.
190
191
       In an optimized build the memory isn't zeroed and ob_exports would be
192
       uninitialized when when PyBytes_FromStringAndSize errored leading to
193
       intermittent test failures. */
194
1.75M
    new->ob_exports = 0;
195
196
    /* Optimization: size=0 bytearray should not allocate space
197
198
       PyBytes_FromStringAndSize returns the empty bytes global when size=0 so
199
       no allocation occurs. */
200
1.75M
    new->ob_bytes_object = PyBytes_FromStringAndSize(NULL, size);
201
1.75M
    if (new->ob_bytes_object == NULL) {
202
0
        Py_DECREF(new);
203
0
        return NULL;
204
0
    }
205
1.75M
    bytearray_reinit_from_bytes(new, size);
206
1.75M
    if (bytes != NULL && size > 0) {
207
1.62M
        memcpy(new->ob_bytes, bytes, size);
208
1.62M
    }
209
210
1.75M
    return (PyObject *)new;
211
1.75M
}
212
213
Py_ssize_t
214
PyByteArray_Size(PyObject *self)
215
0
{
216
0
    assert(self != NULL);
217
0
    assert(PyByteArray_Check(self));
218
219
0
    return PyByteArray_GET_SIZE(self);
220
0
}
221
222
char  *
223
PyByteArray_AsString(PyObject *self)
224
0
{
225
0
    assert(self != NULL);
226
0
    assert(PyByteArray_Check(self));
227
228
0
    return PyByteArray_AS_STRING(self);
229
0
}
230
231
232
static int
233
bytearray_resize_storage(PyByteArrayObject *self,
234
                         Py_ssize_t new_size, Py_ssize_t alloc)
235
39.8M
{
236
39.8M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
237
39.8M
    assert(1 <= new_size && new_size <= alloc);
238
239
39.8M
    Py_ssize_t size = Py_SIZE(self);
240
241
    /* Re-align data to the start of the allocation. */
242
39.8M
    char *old_start = self->ob_start;
243
39.8M
    if (self->ob_start != self->ob_bytes) {
244
        /* optimization tradeoff: This is faster than a new allocation when
245
           the number of bytes being removed in a resize is small; for
246
           large size changes it may be better to just make a new bytes
247
           object as _PyBytes_Resize will do a malloc + memcpy internally.
248
           */
249
0
        Py_ssize_t move = Py_MIN(new_size, size);
250
0
        memmove(self->ob_bytes, self->ob_start, move);
251
0
        self->ob_start = self->ob_bytes;
252
0
    }
253
254
39.8M
    if (_PyBytes_ResizeKeepOnError(&self->ob_bytes_object, alloc) < 0) {
255
0
        if (old_start != self->ob_bytes && new_size < size) {
256
            // Move remaining bytes
257
0
            Py_ssize_t moved = new_size;
258
0
            Py_ssize_t remaining = size - moved;
259
0
            memmove(self->ob_bytes + moved, old_start + moved, remaining);
260
0
        }
261
0
        bytearray_write_trailing_null_byte(self);
262
0
        return -1;
263
0
    }
264
39.8M
    assert(_PyBytes_IsMutable(self->ob_bytes_object));
265
39.8M
    return 0;
266
39.8M
}
267
268
269
/* Resize without the checks of bytearray_resize_lock_held(): the caller must
270
   have checked that the bytearray can be resized.
271
272
   Unlike bytearray_resize_lock_held(), this does not return early if
273
   requested_size is already the size of the bytearray.  A caller which
274
   removed bytes by advancing ob_start and reducing the size uses that to
275
   release the memory. */
276
static int
277
bytearray_resize_unchecked(PyByteArrayObject *obj, Py_ssize_t requested_size)
278
58.7M
{
279
58.7M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(obj);
280
58.7M
    PyObject *self = (PyObject *)obj;
281
282
58.7M
    assert(obj->ob_bytes_object != NULL);
283
58.7M
    assert(requested_size >= 0);
284
58.7M
    assert(obj->ob_exports == 0);
285
286
    /* All computations are done unsigned to avoid integer overflows
287
       (see issue #22335). */
288
58.7M
    size_t alloc = (size_t) obj->ob_alloc;
289
58.7M
    size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes);
290
58.7M
    size_t size = (size_t) requested_size;
291
292
58.7M
    assert(logical_offset <= alloc);
293
294
    /* Resize to 0 resets to empty bytes (see issue #153419). */
295
58.7M
    if (requested_size == 0) {
296
0
        Py_SETREF(obj->ob_bytes_object,
297
0
                   Py_GetConstant(Py_CONSTANT_EMPTY_BYTES));
298
0
        bytearray_reinit_from_bytes(obj, 0);
299
0
        return 0;
300
0
    }
301
302
58.7M
    if (size + logical_offset <= alloc) {
303
        /* Current buffer is large enough to host the requested size,
304
           decide on a strategy. */
305
24.3M
        if (size < alloc / 2) {
306
            /* Major downsize; resize down to exact size */
307
0
            alloc = size;
308
0
        }
309
24.3M
        else {
310
            /* Minor downsize; quick exit */
311
24.3M
            Py_SET_SIZE(self, size);
312
            /* Add mid-buffer null; end provided by bytes. */
313
24.3M
            bytearray_write_trailing_null_byte(_PyByteArray_CAST(self));
314
24.3M
            return 0;
315
24.3M
        }
316
24.3M
    }
317
34.3M
    else {
318
        /* Need growing, decide on a strategy */
319
34.3M
        if (size <= alloc * 1.125) {
320
            /* Moderate upsize; overallocate similar to list_resize() */
321
412k
            alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
322
412k
        }
323
33.9M
        else {
324
            /* Major upsize; resize up to exact size */
325
33.9M
            alloc = size;
326
33.9M
        }
327
34.3M
    }
328
34.3M
    if (alloc > PyByteArray_SIZE_MAX) {
329
0
        PyErr_NoMemory();
330
0
        return -1;
331
0
    }
332
333
34.3M
    if (bytearray_resize_storage(obj, requested_size, (Py_ssize_t)alloc) < 0) {
334
0
        return -1;
335
0
    }
336
337
34.3M
    bytearray_reinit_from_bytes(obj, size);
338
34.3M
    if (alloc != size) {
339
        /* Add mid-buffer null; end provided by bytes. */
340
412k
        bytearray_write_trailing_null_byte(obj);
341
412k
    }
342
34.3M
    return 0;
343
34.3M
}
344
345
static int
346
bytearray_resize_lock_held(PyObject *self, Py_ssize_t requested_size)
347
86.0M
{
348
86.0M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
349
86.0M
    PyByteArrayObject *obj = ((PyByteArrayObject *)self);
350
351
86.0M
    assert(self != NULL);
352
86.0M
    assert(PyByteArray_Check(self));
353
354
86.0M
    if (requested_size < 0) {
355
0
        PyErr_Format(PyExc_ValueError,
356
0
            "Can only resize to positive sizes, got %zd", requested_size);
357
0
        return -1;
358
0
    }
359
360
86.0M
    if (requested_size == Py_SIZE(self)) {
361
27.2M
        return 0;
362
27.2M
    }
363
58.7M
    if (!_canresize(obj)) {
364
0
        return -1;
365
0
    }
366
58.7M
    return bytearray_resize_unchecked(obj, requested_size);
367
58.7M
}
368
369
int
370
PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
371
48.1M
{
372
48.1M
    int ret;
373
48.1M
    Py_BEGIN_CRITICAL_SECTION(self);
374
48.1M
    ret = bytearray_resize_lock_held(self, requested_size);
375
48.1M
    Py_END_CRITICAL_SECTION();
376
48.1M
    return ret;
377
48.1M
}
378
379
PyObject *
380
PyByteArray_Concat(PyObject *a, PyObject *b)
381
0
{
382
0
    Py_buffer va, vb;
383
0
    PyByteArrayObject *result = NULL;
384
385
0
    va.len = -1;
386
0
    vb.len = -1;
387
0
    if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 ||
388
0
        PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) {
389
0
            PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
390
0
                         Py_TYPE(b)->tp_name, Py_TYPE(a)->tp_name);
391
0
            goto done;
392
0
    }
393
394
0
    if (va.len > PyByteArray_SIZE_MAX - vb.len) {
395
0
        PyErr_NoMemory();
396
0
        goto done;
397
0
    }
398
399
0
    result = (PyByteArrayObject *) \
400
0
        PyByteArray_FromStringAndSize(NULL, va.len + vb.len);
401
    // result->ob_bytes is NULL if result is an empty bytearray:
402
    // if va.len + vb.len equals zero.
403
0
    if (result != NULL && result->ob_bytes != NULL) {
404
0
        memcpy(result->ob_bytes, va.buf, va.len);
405
0
        memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
406
0
    }
407
408
0
  done:
409
0
    if (va.len != -1)
410
0
        PyBuffer_Release(&va);
411
0
    if (vb.len != -1)
412
0
        PyBuffer_Release(&vb);
413
0
    return (PyObject *)result;
414
0
}
415
416
/* Functions stuffed into the type object */
417
418
static Py_ssize_t
419
bytearray_length(PyObject *op)
420
245k
{
421
245k
    return PyByteArray_GET_SIZE(op);
422
245k
}
423
424
/*[clinic input]
425
@critical_section
426
bytearray.__iadd__ as bytearray_iconcat
427
428
    other: object
429
    /
430
[clinic start generated code]*/
431
432
static PyObject *
433
bytearray_iconcat_impl(PyByteArrayObject *self, PyObject *other)
434
/*[clinic end generated code: output=ba172f2db8f7a8dd input=5b6fb07ab387084d]*/
435
20.4M
{
436
20.4M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
437
438
20.4M
    Py_buffer vo;
439
20.4M
    if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) {
440
0
        PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
441
0
                     Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
442
0
        return NULL;
443
0
    }
444
445
20.4M
    Py_ssize_t size = Py_SIZE(self);
446
20.4M
    if (size > PyByteArray_SIZE_MAX - vo.len) {
447
0
        PyBuffer_Release(&vo);
448
0
        return PyErr_NoMemory();
449
0
    }
450
451
20.4M
    if (bytearray_resize_lock_held((PyObject *)self, size + vo.len) < 0) {
452
0
        PyBuffer_Release(&vo);
453
0
        return NULL;
454
0
    }
455
456
20.4M
    memcpy(PyByteArray_AS_STRING(self) + size, vo.buf, vo.len);
457
20.4M
    PyBuffer_Release(&vo);
458
20.4M
    return Py_NewRef(self);
459
20.4M
}
460
461
/*[clinic input]
462
@critical_section
463
bytearray.__mul__ as bytearray_repeat
464
465
    count: Py_ssize_t
466
    /
467
[clinic start generated code]*/
468
469
static PyObject *
470
bytearray_repeat_impl(PyByteArrayObject *self, Py_ssize_t count)
471
/*[clinic end generated code: output=0889e9ebbe61890a input=3363528e6db1f39b]*/
472
0
{
473
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
474
0
    if (count < 0) {
475
0
        count = 0;
476
0
    }
477
0
    const Py_ssize_t mysize = Py_SIZE(self);
478
0
    if (count > 0 && mysize > PyByteArray_SIZE_MAX / count) {
479
0
        return PyErr_NoMemory();
480
0
    }
481
0
    Py_ssize_t size = mysize * count;
482
483
0
    PyByteArrayObject* result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
484
0
    const char* buf = PyByteArray_AS_STRING(self);
485
0
    if (result != NULL && size != 0) {
486
0
        _PyBytes_RepeatBuffer(result->ob_bytes, size, buf, mysize);
487
0
    }
488
0
    return (PyObject *)result;
489
0
}
490
491
/*[clinic input]
492
@critical_section
493
bytearray.__imul__ as bytearray_irepeat
494
495
    count: Py_ssize_t
496
    /
497
[clinic start generated code]*/
498
499
static PyObject *
500
bytearray_irepeat_impl(PyByteArrayObject *self, Py_ssize_t count)
501
/*[clinic end generated code: output=4cfee919b3489219 input=e12991c89153490b]*/
502
0
{
503
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
504
0
    if (count < 0) {
505
0
        count = 0;
506
0
    }
507
0
    else if (count == 1) {
508
0
        return Py_NewRef(self);
509
0
    }
510
511
0
    const Py_ssize_t mysize = Py_SIZE(self);
512
0
    if (count > 0 && mysize > PyByteArray_SIZE_MAX / count) {
513
0
        return PyErr_NoMemory();
514
0
    }
515
0
    const Py_ssize_t size = mysize * count;
516
0
    if (bytearray_resize_lock_held((PyObject *)self, size) < 0) {
517
0
        return NULL;
518
0
    }
519
520
0
    char* buf = PyByteArray_AS_STRING(self);
521
0
    _PyBytes_RepeatBuffer(buf, size, buf, mysize);
522
523
0
    return Py_NewRef(self);
524
0
}
525
526
/*[clinic input]
527
@critical_section
528
bytearray.__getitem__ as bytearray_getitem
529
    i: Py_ssize_t
530
    /
531
[clinic start generated code]*/
532
533
static PyObject *
534
bytearray_getitem_impl(PyByteArrayObject *self, Py_ssize_t i)
535
/*[clinic end generated code: output=743cb7a5f892f7ed input=f90e2c70f80e2917]*/
536
0
{
537
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
538
0
    if (i < 0 || i >= Py_SIZE(self)) {
539
0
        PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
540
0
        return NULL;
541
0
    }
542
0
    return _PyLong_FromUnsignedChar((unsigned char)(self->ob_start[i]));
543
0
}
544
545
static PyObject *
546
bytearray_subscript_lock_held(PyObject *op, PyObject *index)
547
21.8M
{
548
21.8M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
549
21.8M
    PyByteArrayObject *self = _PyByteArray_CAST(op);
550
21.8M
    if (_PyIndex_Check(index)) {
551
20.2M
        Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
552
553
20.2M
        if (i == -1 && PyErr_Occurred())
554
0
            return NULL;
555
556
20.2M
        if (i < 0)
557
0
            i += PyByteArray_GET_SIZE(self);
558
559
20.2M
        if (i < 0 || i >= Py_SIZE(self)) {
560
0
            PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
561
0
            return NULL;
562
0
        }
563
20.2M
        return _PyLong_FromUnsignedChar((unsigned char)(self->ob_start[i]));
564
20.2M
    }
565
1.69M
    else if (PySlice_Check(index)) {
566
1.69M
        Py_ssize_t start, stop, step, slicelength, i;
567
1.69M
        size_t cur;
568
1.69M
        if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
569
0
            return NULL;
570
0
        }
571
1.69M
        slicelength = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self),
572
1.69M
                                            &start, &stop, step);
573
574
1.69M
        if (slicelength <= 0)
575
0
            return PyByteArray_FromStringAndSize("", 0);
576
1.69M
        else if (step == 1) {
577
1.62M
            return PyByteArray_FromStringAndSize(
578
1.62M
                PyByteArray_AS_STRING(self) + start, slicelength);
579
1.62M
        }
580
61.0k
        else {
581
61.0k
            char *source_buf = PyByteArray_AS_STRING(self);
582
61.0k
            char *result_buf;
583
61.0k
            PyObject *result;
584
585
61.0k
            result = PyByteArray_FromStringAndSize(NULL, slicelength);
586
61.0k
            if (result == NULL)
587
0
                return NULL;
588
589
61.0k
            result_buf = PyByteArray_AS_STRING(result);
590
52.2M
            for (cur = start, i = 0; i < slicelength;
591
52.1M
                 cur += step, i++) {
592
52.1M
                     result_buf[i] = source_buf[cur];
593
52.1M
            }
594
61.0k
            return result;
595
61.0k
        }
596
1.69M
    }
597
0
    else {
598
0
        PyErr_Format(PyExc_TypeError,
599
0
                     "bytearray indices must be integers or slices, not %.200s",
600
0
                     Py_TYPE(index)->tp_name);
601
0
        return NULL;
602
0
    }
603
21.8M
}
604
605
static PyObject *
606
bytearray_subscript(PyObject *op, PyObject *index)
607
21.8M
{
608
21.8M
    PyObject *ret;
609
21.8M
    Py_BEGIN_CRITICAL_SECTION(op);
610
21.8M
    ret = bytearray_subscript_lock_held(op, index);
611
21.8M
    Py_END_CRITICAL_SECTION();
612
21.8M
    return ret;
613
614
21.8M
}
615
616
static int
617
bytearray_setslice_linear(PyByteArrayObject *self,
618
                          Py_ssize_t lo, Py_ssize_t hi,
619
                          char *bytes, Py_ssize_t bytes_len)
620
12.3M
{
621
12.3M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
622
12.3M
    Py_ssize_t avail = hi - lo;
623
12.3M
    char *buf = PyByteArray_AS_STRING(self);
624
12.3M
    Py_ssize_t growth = bytes_len - avail;
625
12.3M
    int res = 0;
626
12.3M
    assert(avail >= 0);
627
628
12.3M
    if (growth < 0) {
629
0
        if (!_canresize(self))
630
0
            return -1;
631
632
0
        if (lo == 0) {
633
            /* Shrink the buffer by advancing its logical start.  The bytes
634
               are removed at this point; the resize below only releases
635
               memory. */
636
0
            self->ob_start -= growth;
637
0
            Py_SET_SIZE(self, Py_SIZE(self) + growth);
638
            /*
639
              0   lo               hi             old_size
640
              |   |<----avail----->|<-----tail------>|
641
              |      |<-bytes_len->|<-----tail------>|
642
              0    new_lo         new_hi          new_size
643
            */
644
0
            if (bytearray_resize_unchecked(self, Py_SIZE(self)) < 0) {
645
                /* The operation is completed, but a MemoryError is still
646
                   raised and the memory block is not shrunk. */
647
0
                res = -1;
648
0
            }
649
0
        }
650
0
        else {
651
            /*
652
              0   lo               hi               old_size
653
              |   |<----avail----->|<-----tomove------>|
654
              |   |<-bytes_len->|<-----tomove------>|
655
              0   lo         new_hi              new_size
656
            */
657
0
            memmove(buf + lo + bytes_len, buf + hi,
658
0
                    Py_SIZE(self) - hi);
659
0
            if (bytearray_resize_lock_held((PyObject *)self,
660
0
                                           Py_SIZE(self) + growth) < 0) {
661
                /* Issue #19578: memmove() removed bytes, the bytearray
662
                   object cannot be restored in its previous state.
663
664
                   The operation is completed, but a MemoryError is still
665
                   raised and the memory block is not shrunk. */
666
0
                Py_SET_SIZE(self, Py_SIZE(self) + growth);
667
0
                bytearray_write_trailing_null_byte(self);
668
0
                res = -1;
669
0
            }
670
0
        }
671
0
        buf = PyByteArray_AS_STRING(self);
672
0
    }
673
12.3M
    else if (growth > 0) {
674
8.13M
        if (Py_SIZE(self) > PyByteArray_SIZE_MAX - growth) {
675
0
            PyErr_NoMemory();
676
0
            return -1;
677
0
        }
678
679
8.13M
        if (bytearray_resize_lock_held((PyObject *)self,
680
8.13M
                               Py_SIZE(self) + growth) < 0) {
681
0
            return -1;
682
0
        }
683
8.13M
        buf = PyByteArray_AS_STRING(self);
684
        /* Make the place for the additional bytes */
685
        /*
686
          0   lo        hi               old_size
687
          |   |<-avail->|<-----tomove------>|
688
          |   |<---bytes_len-->|<-----tomove------>|
689
          0   lo            new_hi              new_size
690
         */
691
8.13M
        memmove(buf + lo + bytes_len, buf + hi,
692
8.13M
                Py_SIZE(self) - lo - bytes_len);
693
8.13M
    }
694
695
12.3M
    if (bytes_len > 0)
696
8.13M
        memcpy(buf + lo, bytes, bytes_len);
697
12.3M
    return res;
698
12.3M
}
699
700
static int
701
bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
702
               PyObject *values)
703
12.3M
{
704
12.3M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
705
12.3M
    Py_ssize_t needed;
706
12.3M
    void *bytes;
707
12.3M
    Py_buffer vbytes;
708
12.3M
    int res = 0;
709
710
12.3M
    vbytes.len = -1;
711
12.3M
    if (values == (PyObject *)self) {
712
        /* Make a copy and call this function recursively */
713
0
        int err;
714
0
        values = PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(values),
715
0
                                               PyByteArray_GET_SIZE(values));
716
0
        if (values == NULL)
717
0
            return -1;
718
0
        err = bytearray_setslice(self, lo, hi, values);
719
0
        Py_DECREF(values);
720
0
        return err;
721
0
    }
722
12.3M
    if (values == NULL) {
723
        /* del b[lo:hi] */
724
0
        bytes = NULL;
725
0
        needed = 0;
726
0
    }
727
12.3M
    else {
728
12.3M
        if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) {
729
0
            PyErr_Format(PyExc_TypeError,
730
0
                         "can't set bytearray slice from %.100s",
731
0
                         Py_TYPE(values)->tp_name);
732
0
            return -1;
733
0
        }
734
12.3M
        needed = vbytes.len;
735
12.3M
        bytes = vbytes.buf;
736
12.3M
    }
737
738
    // gh-153578: __buffer__() may have resized self; re-clamp both bounds.
739
12.3M
    if (lo < 0)
740
0
        lo = 0;
741
12.3M
    else if (lo > Py_SIZE(self))
742
0
        lo = Py_SIZE(self);
743
12.3M
    if (hi < lo)
744
0
        hi = lo;
745
12.3M
    if (hi > Py_SIZE(self))
746
0
        hi = Py_SIZE(self);
747
748
12.3M
    res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
749
12.3M
    if (vbytes.len != -1)
750
12.3M
        PyBuffer_Release(&vbytes);
751
12.3M
    return res;
752
12.3M
}
753
754
/*[clinic input]
755
@critical_section
756
bytearray.__setitem__ as bytearray_setitem
757
758
    i: Py_ssize_t
759
    value: object
760
    /
761
[clinic start generated code]*/
762
763
static int
764
bytearray_setitem_impl(PyByteArrayObject *self, Py_ssize_t i,
765
                       PyObject *value)
766
/*[clinic end generated code: output=c8e973819dd58098 input=460a77c3d8b7268f]*/
767
0
{
768
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
769
770
    // GH-91153: We need to do this *before* the size check, in case value has a
771
    // nasty __index__ method that changes the size of the bytearray:
772
0
    int ival = -1;
773
0
    if (value && !_getbytevalue(value, &ival)) {
774
0
        return -1;
775
0
    }
776
777
0
    if (i < 0) {
778
0
        i += Py_SIZE(self);
779
0
    }
780
781
0
    if (i < 0 || i >= Py_SIZE(self)) {
782
0
        PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
783
0
        return -1;
784
0
    }
785
786
0
    if (value == NULL) {
787
0
        return bytearray_setslice(self, i, i+1, NULL);
788
0
    }
789
790
0
    assert(0 <= ival && ival < 256);
791
0
    PyByteArray_AS_STRING(self)[i] = ival;
792
0
    return 0;
793
0
}
794
795
static int
796
bytearray_ass_subscript_lock_held(PyObject *op, PyObject *index, PyObject *values)
797
104M
{
798
104M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
799
104M
    PyByteArrayObject *self = _PyByteArray_CAST(op);
800
104M
    Py_ssize_t start, stop, step, slicelen;
801
    // Do not store a reference to the internal buffer since
802
    // index.__index__() or _getbytevalue() may alter 'self'.
803
    // See https://github.com/python/cpython/issues/91153.
804
805
104M
    if (_PyIndex_Check(index)) {
806
104M
        Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
807
808
104M
        if (i == -1 && PyErr_Occurred()) {
809
0
            return -1;
810
0
        }
811
812
104M
        int ival = -1;
813
814
        // GH-91153: We need to do this *before* the size check, in case values
815
        // has a nasty __index__ method that changes the size of the bytearray:
816
104M
        if (values && !_getbytevalue(values, &ival)) {
817
0
            return -1;
818
0
        }
819
820
104M
        if (i < 0) {
821
0
            i += PyByteArray_GET_SIZE(self);
822
0
        }
823
824
104M
        if (i < 0 || i >= Py_SIZE(self)) {
825
63.4k
            PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
826
63.4k
            return -1;
827
63.4k
        }
828
829
104M
        if (values == NULL) {
830
            /* Fall through to slice assignment */
831
0
            start = i;
832
0
            stop = i + 1;
833
0
            step = 1;
834
0
            slicelen = 1;
835
0
        }
836
104M
        else {
837
104M
            assert(0 <= ival && ival < 256);
838
104M
            PyByteArray_AS_STRING(self)[i] = (char)ival;
839
104M
            return 0;
840
104M
        }
841
104M
    }
842
0
    else if (PySlice_Check(index)) {
843
0
        if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
844
0
            return -1;
845
0
        }
846
0
        slicelen = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self), &start,
847
0
                                         &stop, step);
848
0
    }
849
0
    else {
850
0
        PyErr_Format(PyExc_TypeError,
851
0
                     "bytearray indices must be integers or slices, not %.200s",
852
0
                      Py_TYPE(index)->tp_name);
853
0
        return -1;
854
0
    }
855
856
0
    char *bytes;
857
0
    Py_ssize_t needed;
858
0
    if (values == NULL) {
859
0
        bytes = NULL;
860
0
        needed = 0;
861
0
    }
862
0
    else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
863
0
        int err;
864
0
        if (PyNumber_Check(values) || PyUnicode_Check(values)) {
865
0
            PyErr_SetString(PyExc_TypeError,
866
0
                            "can assign only bytes, buffers, or iterables "
867
0
                            "of ints in range(0, 256)");
868
0
            return -1;
869
0
        }
870
        /* Make a copy and call this function recursively */
871
0
        values = PyByteArray_FromObject(values);
872
0
        if (values == NULL)
873
0
            return -1;
874
0
        err = bytearray_ass_subscript_lock_held((PyObject*)self, index, values);
875
0
        Py_DECREF(values);
876
0
        return err;
877
0
    }
878
0
    else {
879
0
        assert(PyByteArray_Check(values));
880
0
        bytes = PyByteArray_AS_STRING(values);
881
0
        needed = Py_SIZE(values);
882
0
    }
883
884
    /* Make sure b[5:2] = ... inserts before 5, not before 2. */
885
0
    if ((step < 0 && start < stop) ||
886
0
        (step > 0 && start > stop))
887
0
    {
888
0
        stop = start;
889
0
    }
890
891
0
    if (step == 1) {
892
0
        return bytearray_setslice_linear(self, start, stop, bytes, needed);
893
0
    }
894
0
    else {
895
0
        if (needed == 0) {
896
            /* Delete slice */
897
0
            size_t cur;
898
0
            Py_ssize_t i;
899
0
            char *buf = PyByteArray_AS_STRING(self);
900
901
0
            if (!_canresize(self))
902
0
                return -1;
903
904
0
            if (slicelen == 0)
905
                /* Nothing to do here. */
906
0
                return 0;
907
908
0
            if (step < 0) {
909
0
                stop = start + 1;
910
0
                start = stop + step * (slicelen - 1) - 1;
911
0
                step = -step;
912
0
            }
913
0
            for (cur = start, i = 0;
914
0
                 i < slicelen; cur += step, i++) {
915
0
                Py_ssize_t lim = step - 1;
916
917
0
                if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
918
0
                    lim = PyByteArray_GET_SIZE(self) - cur - 1;
919
920
0
                memmove(buf + cur - i,
921
0
                        buf + cur + 1, lim);
922
0
            }
923
            /* Move the tail of the bytes, in one chunk */
924
0
            cur = start + (size_t)slicelen*step;
925
0
            if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
926
0
                memmove(buf + cur - slicelen,
927
0
                        buf + cur,
928
0
                        PyByteArray_GET_SIZE(self) - cur);
929
0
            }
930
0
            if (bytearray_resize_lock_held((PyObject *)self,
931
0
                               PyByteArray_GET_SIZE(self) - slicelen) < 0)
932
0
                return -1;
933
934
0
            return 0;
935
0
        }
936
0
        else {
937
            /* Assign slice */
938
0
            Py_ssize_t i;
939
0
            size_t cur;
940
0
            char *buf = PyByteArray_AS_STRING(self);
941
942
0
            if (needed != slicelen) {
943
0
                PyErr_Format(PyExc_ValueError,
944
0
                             "attempt to assign bytes of size %zd "
945
0
                             "to extended slice of size %zd",
946
0
                             needed, slicelen);
947
0
                return -1;
948
0
            }
949
0
            for (cur = start, i = 0; i < slicelen; cur += step, i++)
950
0
                buf[cur] = bytes[i];
951
0
            return 0;
952
0
        }
953
0
    }
954
0
}
955
956
static int
957
bytearray_ass_subscript(PyObject *op, PyObject *index, PyObject *values)
958
104M
{
959
104M
    int ret;
960
104M
    if (values != NULL && PyByteArray_Check(values)) {
961
0
        Py_BEGIN_CRITICAL_SECTION2(op, values);
962
0
        ret = bytearray_ass_subscript_lock_held(op, index, values);
963
0
        Py_END_CRITICAL_SECTION2();
964
0
    }
965
104M
    else {
966
104M
        Py_BEGIN_CRITICAL_SECTION(op);
967
104M
        ret = bytearray_ass_subscript_lock_held(op, index, values);
968
104M
        Py_END_CRITICAL_SECTION();
969
104M
    }
970
104M
    return ret;
971
104M
}
972
973
static PyObject *
974
bytearray_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
975
27.2M
{
976
27.2M
    PyObject *op = PyType_GenericNew(type, args, kwds);
977
27.2M
    if (op == NULL) {
978
0
        return NULL;
979
0
    }
980
27.2M
    PyByteArrayObject *self = _PyByteArray_CAST(op);
981
27.2M
    self->ob_bytes_object = Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
982
27.2M
    bytearray_reinit_from_bytes(self, 0);
983
27.2M
    self->ob_exports = 0;
984
27.2M
    return op;
985
27.2M
}
986
987
/*[clinic input]
988
@vectorcall
989
bytearray.__init__
990
991
    source as arg: object = NULL
992
    encoding: str = NULL
993
    errors: str = NULL
994
995
[clinic start generated code]*/
996
997
static int
998
bytearray___init___impl(PyByteArrayObject *self, PyObject *arg,
999
                        const char *encoding, const char *errors)
1000
/*[clinic end generated code: output=4ce1304649c2f8b3 input=24ddb84055f432dd]*/
1001
27.2M
{
1002
27.2M
    Py_ssize_t count;
1003
27.2M
    PyObject *it;
1004
27.2M
    PyObject *(*iternext)(PyObject *);
1005
1006
    /* Disallow any __init__ call if the object is not resizable (has exports)
1007
       to make the handling of non-null `source` init values simpler. */
1008
27.2M
    if (!_canresize(self)) {
1009
0
        return -1;
1010
0
    }
1011
1012
    /* Empty any previous contents (do this first of all!). */
1013
27.2M
    if (PyByteArray_Resize((PyObject *)self, 0) < 0) {
1014
0
        return -1;
1015
0
    }
1016
27.2M
    assert(self->ob_bytes_object == Py_GetConstantBorrowed(Py_CONSTANT_EMPTY_BYTES));
1017
27.2M
    assert(self->ob_exports == 0);
1018
1019
    /* Make a quick exit if no first argument */
1020
27.2M
    if (arg == NULL) {
1021
6.31M
        if (encoding != NULL || errors != NULL) {
1022
0
            PyErr_SetString(PyExc_TypeError,
1023
0
                            encoding != NULL ?
1024
0
                            "encoding without a string argument" :
1025
0
                            "errors without a string argument");
1026
0
            return -1;
1027
0
        }
1028
6.31M
        return 0;
1029
6.31M
    }
1030
1031
20.9M
    if (PyUnicode_Check(arg)) {
1032
        /* Encode via the codec registry */
1033
0
        PyObject *encoded, *new;
1034
0
        if (encoding == NULL) {
1035
0
            PyErr_SetString(PyExc_TypeError,
1036
0
                            "string argument without an encoding");
1037
0
            return -1;
1038
0
        }
1039
0
        encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
1040
0
        if (encoded == NULL) {
1041
0
            return -1;
1042
0
        }
1043
0
        assert(PyBytes_Check(encoded));
1044
1045
        /* Most encodes return a new unique bytes, just use it as buffer. */
1046
0
        if (_PyObject_IsUniquelyReferenced(encoded)
1047
0
            && PyBytes_CheckExact(encoded)
1048
0
            && _PyBytes_GET_CACHED_HASH((PyBytesObject*)encoded) == -1)
1049
0
        {
1050
0
            Py_ssize_t size = PyBytes_GET_SIZE(encoded);
1051
0
            self->ob_bytes_object = encoded;
1052
0
            bytearray_reinit_from_bytes(self, size);
1053
0
            return 0;
1054
0
        }
1055
0
        new = bytearray_iconcat((PyObject*)self, encoded);
1056
0
        Py_DECREF(encoded);
1057
0
        if (new == NULL)
1058
0
            return -1;
1059
0
        Py_DECREF(new);
1060
0
        return 0;
1061
0
    }
1062
1063
    /* If it's not unicode, there can't be encoding or errors */
1064
20.9M
    if (encoding != NULL || errors != NULL) {
1065
0
        PyErr_SetString(PyExc_TypeError,
1066
0
                        encoding != NULL ?
1067
0
                        "encoding without a string argument" :
1068
0
                        "errors without a string argument");
1069
0
        return -1;
1070
0
    }
1071
1072
    /* Is it an int? */
1073
20.9M
    if (_PyIndex_Check(arg)) {
1074
126k
        count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
1075
126k
        if (count == -1 && PyErr_Occurred()) {
1076
0
            if (!PyErr_ExceptionMatches(PyExc_TypeError))
1077
0
                return -1;
1078
0
            PyErr_Clear();  /* fall through */
1079
0
        }
1080
126k
        else {
1081
126k
            if (count < 0) {
1082
0
                PyErr_SetString(PyExc_ValueError, "negative count");
1083
0
                return -1;
1084
0
            }
1085
126k
            if (count > 0) {
1086
126k
                if (PyByteArray_Resize((PyObject *)self, count))
1087
0
                    return -1;
1088
126k
                memset(PyByteArray_AS_STRING(self), 0, count);
1089
126k
            }
1090
126k
            return 0;
1091
126k
        }
1092
126k
    }
1093
1094
    /* Use the buffer API */
1095
20.7M
    if (PyObject_CheckBuffer(arg)) {
1096
20.7M
        Py_ssize_t size;
1097
20.7M
        Py_buffer view;
1098
20.7M
        if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
1099
0
            return -1;
1100
20.7M
        size = view.len;
1101
20.7M
        if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
1102
20.7M
        if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
1103
20.7M
            &view, size, 'C') < 0)
1104
0
        {
1105
            /* Don't expose the uninitialized bytes: reset to empty */
1106
0
            (void)PyByteArray_Resize((PyObject *)self, 0);
1107
0
            goto fail;
1108
0
        }
1109
20.7M
        PyBuffer_Release(&view);
1110
20.7M
        return 0;
1111
0
    fail:
1112
0
        PyBuffer_Release(&view);
1113
0
        return -1;
1114
20.7M
    }
1115
1116
2.04k
    if (PyList_CheckExact(arg) || PyTuple_CheckExact(arg)) {
1117
2.03k
        Py_ssize_t size = PySequence_Fast_GET_SIZE(arg);
1118
2.03k
        if (PyByteArray_Resize((PyObject *)self, size) < 0) {
1119
0
            return -1;
1120
0
        }
1121
2.03k
        PyObject **items = PySequence_Fast_ITEMS(arg);
1122
2.03k
        char *s = PyByteArray_AS_STRING(self);
1123
4.07k
        for (Py_ssize_t i = 0; i < size; i++) {
1124
2.03k
            int value;
1125
2.03k
            if (!PyLong_CheckExact(items[i])) {
1126
                /* Resize to 0 and go through slowpath */
1127
0
                if (Py_SIZE(self) != 0) {
1128
0
                   if (PyByteArray_Resize((PyObject *)self, 0) < 0) {
1129
0
                       return -1;
1130
0
                   }
1131
0
                }
1132
0
                goto slowpath;
1133
0
            }
1134
2.03k
            int rc = _getbytevalue(items[i], &value);
1135
2.03k
            if (!rc) {
1136
                /* Don't expose the uninitialized bytes: reset to empty */
1137
0
                (void)PyByteArray_Resize((PyObject *)self, 0);
1138
0
                return -1;
1139
0
            }
1140
2.03k
            s[i] = value;
1141
2.03k
        }
1142
2.03k
        return 0;
1143
2.03k
    }
1144
4
slowpath:
1145
    /* Get the iterator */
1146
4
    it = PyObject_GetIter(arg);
1147
4
    if (it == NULL) {
1148
0
        if (PyErr_ExceptionMatches(PyExc_TypeError)) {
1149
0
            PyErr_Format(PyExc_TypeError,
1150
0
                         "cannot convert '%.200s' object to bytearray",
1151
0
                         Py_TYPE(arg)->tp_name);
1152
0
        }
1153
0
        return -1;
1154
0
    }
1155
4
    iternext = *Py_TYPE(it)->tp_iternext;
1156
1157
    /* Run the iterator to exhaustion */
1158
1.02k
    for (;;) {
1159
1.02k
        PyObject *item;
1160
1.02k
        int rc, value;
1161
1162
        /* Get the next item */
1163
1.02k
        item = iternext(it);
1164
1.02k
        if (item == NULL) {
1165
4
            if (PyErr_Occurred()) {
1166
0
                if (!PyErr_ExceptionMatches(PyExc_StopIteration))
1167
0
                    goto error;
1168
0
                PyErr_Clear();
1169
0
            }
1170
4
            break;
1171
4
        }
1172
1173
        /* Interpret it as an int (__index__) */
1174
1.02k
        rc = _getbytevalue(item, &value);
1175
1.02k
        Py_DECREF(item);
1176
1.02k
        if (!rc) {
1177
0
            goto error;
1178
0
        }
1179
1180
        /* Append the byte.
1181
1182
           gh-158928: Iterators are arbitrary code which could modify the
1183
           bytearray so this must re-calculate if there is enough space(). */
1184
1.02k
        Py_ssize_t needed =
1185
1.02k
            self->ob_start - self->ob_bytes + Py_SIZE(self) + 1;
1186
1.02k
        if (needed < self->ob_alloc) {
1187
884
            Py_SET_SIZE(self, Py_SIZE(self) + 1);
1188
884
            bytearray_write_trailing_null_byte(self);
1189
884
        }
1190
140
        else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0) {
1191
0
            goto error;
1192
0
        }
1193
1.02k
        PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
1194
1.02k
        assert(self->ob_start - self->ob_bytes + Py_SIZE(self) <=
1195
1.02k
               self->ob_alloc);
1196
1.02k
    }
1197
1198
    /* Clean up and return success */
1199
4
    Py_DECREF(it);
1200
4
    return 0;
1201
1202
0
 error:
1203
    /* Error handling when it != NULL */
1204
0
    Py_DECREF(it);
1205
0
    return -1;
1206
4
}
1207
1208
/*[clinic input]
1209
@critical_section
1210
bytearray.__repr__
1211
1212
    op: self(type="PyObject *")
1213
[clinic start generated code]*/
1214
1215
static PyObject *
1216
bytearray_repr_impl(PyObject *op)
1217
/*[clinic end generated code: output=4086ab6928ebab1d input=d46ad3c1f3071b27]*/
1218
0
{
1219
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
1220
0
    const char *className = _PyType_Name(Py_TYPE(op));
1221
0
    PyObject *bytes_repr = _Py_bytes_repr(PyByteArray_AS_STRING(op),
1222
0
                                          PyByteArray_GET_SIZE(op), 1,
1223
0
                                          "bytearray");
1224
0
    if (bytes_repr == NULL) {
1225
0
        return NULL;
1226
0
    }
1227
0
    PyObject *res = PyUnicode_FromFormat("%s(%U)", className, bytes_repr);
1228
0
    Py_DECREF(bytes_repr);
1229
0
    return res;
1230
0
}
1231
1232
static PyObject *
1233
bytearray_str(PyObject *op)
1234
0
{
1235
0
    if (_Py_GetConfig()->bytes_warning) {
1236
0
        if (PyErr_WarnEx(PyExc_BytesWarning,
1237
0
                         "str() on a bytearray instance", 1)) {
1238
0
                return NULL;
1239
0
        }
1240
0
    }
1241
0
    return bytearray_repr(op);
1242
0
}
1243
1244
static PyObject *
1245
bytearray_richcompare(PyObject *self, PyObject *other, int op)
1246
0
{
1247
0
    Py_ssize_t self_size, other_size;
1248
0
    Py_buffer self_bytes, other_bytes;
1249
0
    int cmp;
1250
1251
0
    if (!PyObject_CheckBuffer(self) || !PyObject_CheckBuffer(other)) {
1252
0
        if (PyUnicode_Check(self) || PyUnicode_Check(other)) {
1253
0
            if (_Py_GetConfig()->bytes_warning && (op == Py_EQ || op == Py_NE)) {
1254
0
                if (PyErr_WarnEx(PyExc_BytesWarning,
1255
0
                                "Comparison between bytearray and string", 1))
1256
0
                    return NULL;
1257
0
            }
1258
0
        }
1259
0
        Py_RETURN_NOTIMPLEMENTED;
1260
0
    }
1261
1262
    /* Bytearrays can be compared to anything that supports the buffer API. */
1263
0
    if (PyObject_GetBuffer(self, &self_bytes, PyBUF_SIMPLE) != 0) {
1264
0
        PyErr_Clear();
1265
0
        Py_RETURN_NOTIMPLEMENTED;
1266
0
    }
1267
0
    self_size = self_bytes.len;
1268
1269
0
    if (PyObject_GetBuffer(other, &other_bytes, PyBUF_SIMPLE) != 0) {
1270
0
        PyErr_Clear();
1271
0
        PyBuffer_Release(&self_bytes);
1272
0
        Py_RETURN_NOTIMPLEMENTED;
1273
0
    }
1274
0
    other_size = other_bytes.len;
1275
1276
0
    if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
1277
        /* Shortcut: if the lengths differ, the objects differ */
1278
0
        PyBuffer_Release(&self_bytes);
1279
0
        PyBuffer_Release(&other_bytes);
1280
0
        return PyBool_FromLong((op == Py_NE));
1281
0
    }
1282
0
    else {
1283
0
        cmp = memcmp(self_bytes.buf, other_bytes.buf,
1284
0
                     Py_MIN(self_size, other_size));
1285
        /* In ISO C, memcmp() guarantees to use unsigned bytes! */
1286
1287
0
        PyBuffer_Release(&self_bytes);
1288
0
        PyBuffer_Release(&other_bytes);
1289
1290
0
        if (cmp != 0) {
1291
0
            Py_RETURN_RICHCOMPARE(cmp, 0, op);
1292
0
        }
1293
1294
0
        Py_RETURN_RICHCOMPARE(self_size, other_size, op);
1295
0
    }
1296
1297
0
}
1298
1299
static void
1300
bytearray_dealloc(PyObject *op)
1301
28.9M
{
1302
28.9M
    PyByteArrayObject *self = _PyByteArray_CAST(op);
1303
#ifdef Py_DEBUG
1304
    if (self->ob_bytes_object != NULL) {
1305
        _PyBytes_CheckOverflow(self->ob_bytes_object, op, "bytearray");
1306
    }
1307
#endif
1308
1309
28.9M
    if (self->ob_exports > 0) {
1310
0
        PyErr_SetString(PyExc_SystemError,
1311
0
                        "deallocated bytearray object has exported buffers");
1312
0
        PyErr_Print();
1313
0
    }
1314
28.9M
    Py_XDECREF(self->ob_bytes_object);
1315
28.9M
    Py_TYPE(self)->tp_free((PyObject *)self);
1316
28.9M
}
1317
1318
1319
/* -------------------------------------------------------------------- */
1320
/* Methods */
1321
1322
#define STRINGLIB_IS_UNICODE 0
1323
0
#define FASTSEARCH fastsearch
1324
0
#define STRINGLIB(F) stringlib_##F
1325
0
#define STRINGLIB_CHAR char
1326
0
#define STRINGLIB_SIZEOF_CHAR 1
1327
0
#define STRINGLIB_LEN PyByteArray_GET_SIZE
1328
0
#define STRINGLIB_STR PyByteArray_AS_STRING
1329
0
#define STRINGLIB_NEW PyByteArray_FromStringAndSize
1330
0
#define STRINGLIB_ISSPACE Py_ISSPACE
1331
0
#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
1332
#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
1333
0
#define STRINGLIB_FAST_MEMCHR memchr
1334
#define STRINGLIB_MUTABLE 1
1335
1336
#include "stringlib/fastsearch.h"
1337
#include "stringlib/count.h"
1338
#include "stringlib/find.h"
1339
#include "stringlib/join.h"
1340
#include "stringlib/partition.h"
1341
#include "stringlib/split.h"
1342
#include "stringlib/ctype.h"
1343
#include "stringlib/transmogrify.h"
1344
1345
1346
/*[clinic input]
1347
@permit_long_summary
1348
@critical_section
1349
@text_signature "($self, sub[, start[, end]], /)"
1350
bytearray.find
1351
1352
    sub: object
1353
    start: slice_index(accept={int, NoneType}, c_default='0') = None
1354
         Optional start position. Default: start of the bytes.
1355
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
1356
         Optional stop position. Default: end of the bytes.
1357
    /
1358
1359
Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end].
1360
1361
Return -1 on failure.
1362
[clinic start generated code]*/
1363
1364
static PyObject *
1365
bytearray_find_impl(PyByteArrayObject *self, PyObject *sub, Py_ssize_t start,
1366
                    Py_ssize_t end)
1367
/*[clinic end generated code: output=413e1cab2ae87da0 input=df3aa94840d893a7]*/
1368
323k
{
1369
323k
    return _bytearray_with_buffer(self, _Py_bytes_find, sub, start, end);
1370
323k
}
1371
1372
/*[clinic input]
1373
@permit_long_summary
1374
@critical_section
1375
bytearray.count = bytearray.find
1376
1377
Return the number of non-overlapping occurrences of subsection 'sub' in bytes B[start:end].
1378
[clinic start generated code]*/
1379
1380
static PyObject *
1381
bytearray_count_impl(PyByteArrayObject *self, PyObject *sub,
1382
                     Py_ssize_t start, Py_ssize_t end)
1383
/*[clinic end generated code: output=a21ee2692e4f1233 input=e8fcdca8272857e0]*/
1384
0
{
1385
0
    return _bytearray_with_buffer(self, _Py_bytes_count, sub, start, end);
1386
0
}
1387
1388
/*[clinic input]
1389
bytearray.clear
1390
1391
Remove all items from the bytearray.
1392
[clinic start generated code]*/
1393
1394
static PyObject *
1395
bytearray_clear_impl(PyByteArrayObject *self)
1396
/*[clinic end generated code: output=85c2fe6aede0956c input=ed6edae9de447ac4]*/
1397
0
{
1398
0
    if (PyByteArray_Resize((PyObject *)self, 0) < 0)
1399
0
        return NULL;
1400
0
    Py_RETURN_NONE;
1401
0
}
1402
1403
/*[clinic input]
1404
@critical_section
1405
bytearray.copy
1406
1407
Return a copy of B.
1408
[clinic start generated code]*/
1409
1410
static PyObject *
1411
bytearray_copy_impl(PyByteArrayObject *self)
1412
/*[clinic end generated code: output=68cfbcfed484c132 input=b96f8b01f73851ad]*/
1413
0
{
1414
0
    return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
1415
0
                                         PyByteArray_GET_SIZE(self));
1416
0
}
1417
1418
/*[clinic input]
1419
@permit_long_summary
1420
@critical_section
1421
bytearray.index = bytearray.find
1422
1423
Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end].
1424
1425
Raise ValueError if the subsection is not found.
1426
[clinic start generated code]*/
1427
1428
static PyObject *
1429
bytearray_index_impl(PyByteArrayObject *self, PyObject *sub,
1430
                     Py_ssize_t start, Py_ssize_t end)
1431
/*[clinic end generated code: output=067a1e78efc672a7 input=c37f177cfee19fe4]*/
1432
0
{
1433
0
    return _bytearray_with_buffer(self, _Py_bytes_index, sub, start, end);
1434
0
}
1435
1436
/*[clinic input]
1437
@permit_long_summary
1438
@critical_section
1439
bytearray.rfind = bytearray.find
1440
1441
Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end].
1442
1443
Return -1 on failure.
1444
[clinic start generated code]*/
1445
1446
static PyObject *
1447
bytearray_rfind_impl(PyByteArrayObject *self, PyObject *sub,
1448
                     Py_ssize_t start, Py_ssize_t end)
1449
/*[clinic end generated code: output=51bf886f932b283c input=1265b11c437d2750]*/
1450
0
{
1451
0
    return _bytearray_with_buffer(self, _Py_bytes_rfind, sub, start, end);
1452
0
}
1453
1454
/*[clinic input]
1455
@permit_long_summary
1456
@critical_section
1457
bytearray.rindex = bytearray.find
1458
1459
Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end].
1460
1461
Raise ValueError if the subsection is not found.
1462
[clinic start generated code]*/
1463
1464
static PyObject *
1465
bytearray_rindex_impl(PyByteArrayObject *self, PyObject *sub,
1466
                      Py_ssize_t start, Py_ssize_t end)
1467
/*[clinic end generated code: output=38e1cf66bafb08b9 input=7d198b3d6b0a62ce]*/
1468
0
{
1469
0
    return _bytearray_with_buffer(self, _Py_bytes_rindex, sub, start, end);
1470
0
}
1471
1472
static int
1473
bytearray_contains(PyObject *self, PyObject *arg)
1474
0
{
1475
0
    int ret = -1;
1476
0
    Py_BEGIN_CRITICAL_SECTION(self);
1477
0
    PyByteArrayObject *ba = _PyByteArray_CAST(self);
1478
1479
    /* Increase exports to prevent bytearray storage from changing during _Py_bytes_contains(). */
1480
0
    ba->ob_exports++;
1481
0
    ret = _Py_bytes_contains(PyByteArray_AS_STRING(ba),
1482
0
                             PyByteArray_GET_SIZE(self),
1483
0
                             arg);
1484
0
    ba->ob_exports--;
1485
0
    Py_END_CRITICAL_SECTION();
1486
0
    return ret;
1487
0
}
1488
1489
/*[clinic input]
1490
@permit_long_summary
1491
@critical_section
1492
@text_signature "($self, prefix[, start[, end]], /)"
1493
bytearray.startswith
1494
1495
    prefix as subobj: object
1496
        A bytes or a tuple of bytes to try.
1497
    start: slice_index(accept={int, NoneType}, c_default='0') = None
1498
        Optional start position. Default: start of the bytearray.
1499
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
1500
        Optional stop position. Default: end of the bytearray.
1501
    /
1502
1503
Return True if the bytearray starts with the specified prefix, False otherwise.
1504
[clinic start generated code]*/
1505
1506
static PyObject *
1507
bytearray_startswith_impl(PyByteArrayObject *self, PyObject *subobj,
1508
                          Py_ssize_t start, Py_ssize_t end)
1509
/*[clinic end generated code: output=a3d9b6d44d3662a6 input=93f9ffee684f109a]*/
1510
0
{
1511
0
    return _bytearray_with_buffer(self, _Py_bytes_startswith, subobj, start, end);
1512
0
}
1513
1514
/*[clinic input]
1515
@permit_long_summary
1516
@critical_section
1517
@text_signature "($self, suffix[, start[, end]], /)"
1518
bytearray.endswith
1519
1520
    suffix as subobj: object
1521
        A bytes or a tuple of bytes to try.
1522
    start: slice_index(accept={int, NoneType}, c_default='0') = None
1523
         Optional start position. Default: start of the bytearray.
1524
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
1525
         Optional stop position. Default: end of the bytearray.
1526
    /
1527
1528
Return True if the bytearray ends with the specified suffix, False otherwise.
1529
[clinic start generated code]*/
1530
1531
static PyObject *
1532
bytearray_endswith_impl(PyByteArrayObject *self, PyObject *subobj,
1533
                        Py_ssize_t start, Py_ssize_t end)
1534
/*[clinic end generated code: output=e75ea8c227954caa input=d158b030a11d0b06]*/
1535
0
{
1536
0
    return _bytearray_with_buffer(self, _Py_bytes_endswith, subobj, start, end);
1537
0
}
1538
1539
/*[clinic input]
1540
@critical_section
1541
bytearray.removeprefix as bytearray_removeprefix
1542
1543
    prefix: Py_buffer
1544
    /
1545
1546
Return a bytearray with the given prefix string removed if present.
1547
1548
If the bytearray starts with the prefix string, return
1549
bytearray[len(prefix):].  Otherwise, return a copy of the original
1550
bytearray.
1551
[clinic start generated code]*/
1552
1553
static PyObject *
1554
bytearray_removeprefix_impl(PyByteArrayObject *self, Py_buffer *prefix)
1555
/*[clinic end generated code: output=6cabc585e7f502e0 input=4323ba6d275fe7a8]*/
1556
0
{
1557
0
    const char *self_start = PyByteArray_AS_STRING(self);
1558
0
    Py_ssize_t self_len = PyByteArray_GET_SIZE(self);
1559
0
    const char *prefix_start = prefix->buf;
1560
0
    Py_ssize_t prefix_len = prefix->len;
1561
1562
0
    if (self_len >= prefix_len
1563
0
        && memcmp(self_start, prefix_start, prefix_len) == 0)
1564
0
    {
1565
0
        return PyByteArray_FromStringAndSize(self_start + prefix_len,
1566
0
                                             self_len - prefix_len);
1567
0
    }
1568
1569
0
    return PyByteArray_FromStringAndSize(self_start, self_len);
1570
0
}
1571
1572
/*[clinic input]
1573
@critical_section
1574
bytearray.removesuffix as bytearray_removesuffix
1575
1576
    suffix: Py_buffer
1577
    /
1578
1579
Return a bytearray with the given suffix string removed if present.
1580
1581
If the bytearray ends with the suffix string and that suffix is not
1582
empty, return bytearray[:-len(suffix)].  Otherwise, return a copy of
1583
the original bytearray.
1584
[clinic start generated code]*/
1585
1586
static PyObject *
1587
bytearray_removesuffix_impl(PyByteArrayObject *self, Py_buffer *suffix)
1588
/*[clinic end generated code: output=2bc8cfb79de793d3 input=f71ba2e1a40c47dd]*/
1589
0
{
1590
0
    const char *self_start = PyByteArray_AS_STRING(self);
1591
0
    Py_ssize_t self_len = PyByteArray_GET_SIZE(self);
1592
0
    const char *suffix_start = suffix->buf;
1593
0
    Py_ssize_t suffix_len = suffix->len;
1594
1595
0
    if (self_len >= suffix_len
1596
0
        && memcmp(self_start + self_len - suffix_len,
1597
0
                  suffix_start, suffix_len) == 0)
1598
0
    {
1599
0
        return PyByteArray_FromStringAndSize(self_start,
1600
0
                                             self_len - suffix_len);
1601
0
    }
1602
1603
0
    return PyByteArray_FromStringAndSize(self_start, self_len);
1604
0
}
1605
1606
1607
/*[clinic input]
1608
@critical_section
1609
bytearray.resize
1610
    size: Py_ssize_t
1611
        New size to resize to.
1612
    /
1613
Resize the internal buffer of bytearray to len.
1614
[clinic start generated code]*/
1615
1616
static PyObject *
1617
bytearray_resize_impl(PyByteArrayObject *self, Py_ssize_t size)
1618
/*[clinic end generated code: output=f73524922990b2d9 input=116046316a2b5cfc]*/
1619
0
{
1620
0
    Py_ssize_t start_size = PyByteArray_GET_SIZE(self);
1621
0
    int result = bytearray_resize_lock_held((PyObject *)self, size);
1622
0
    if (result < 0) {
1623
0
        return NULL;
1624
0
    }
1625
    // Set new bytes to null bytes
1626
0
    if (size > start_size) {
1627
0
        memset(PyByteArray_AS_STRING(self) + start_size, 0, size - start_size);
1628
0
    }
1629
0
    Py_RETURN_NONE;
1630
0
}
1631
1632
1633
/*[clinic input]
1634
@critical_section
1635
bytearray.take_bytes
1636
    n: object = None
1637
        Bytes to take, negative indexes from end. None indicates all bytes.
1638
    /
1639
Take *n* bytes from the bytearray and return them as a bytes object.
1640
[clinic start generated code]*/
1641
1642
static PyObject *
1643
bytearray_take_bytes_impl(PyByteArrayObject *self, PyObject *n)
1644
/*[clinic end generated code: output=3147fbc0bbbe8d94 input=b15b5172cdc6deda]*/
1645
6.31M
{
1646
6.31M
    Py_ssize_t to_take;
1647
6.31M
    Py_ssize_t size = Py_SIZE(self);
1648
6.31M
    if (Py_IsNone(n)) {
1649
6.31M
        to_take = size;
1650
6.31M
    }
1651
    // Integer index, from start (zero, positive) or end (negative).
1652
0
    else if (_PyIndex_Check(n)) {
1653
0
        to_take = PyNumber_AsSsize_t(n, PyExc_IndexError);
1654
0
        if (to_take == -1 && PyErr_Occurred()) {
1655
0
            return NULL;
1656
0
        }
1657
        // n.__index__() may have resized self; use the current size.
1658
0
        size = Py_SIZE(self);
1659
0
        if (to_take < 0) {
1660
0
            to_take += size;
1661
0
        }
1662
0
    }
1663
0
    else {
1664
0
        PyErr_SetString(PyExc_TypeError, "n must be an integer or None");
1665
0
        return NULL;
1666
0
    }
1667
1668
6.31M
    if (to_take < 0 || to_take > size) {
1669
0
        PyErr_Format(PyExc_IndexError,
1670
0
            "can't take %zd bytes outside size %zd",
1671
0
            to_take, size);
1672
0
        return NULL;
1673
0
    }
1674
1675
    // Exports may change the contents. No mutable bytes allowed.
1676
6.31M
    if (!_canresize(self)) {
1677
0
        return NULL;
1678
0
    }
1679
1680
6.31M
    if (to_take == 0 || size == 0) {
1681
803k
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
1682
803k
    }
1683
1684
5.50M
    Py_ssize_t remaining_length = size - to_take;
1685
1686
    // optimization: If taking less than leaving, just copy the small to_take
1687
    // portion out and move ob_start.
1688
5.50M
    if (to_take < remaining_length) {
1689
0
        PyObject *ret = PyBytes_FromStringAndSize(self->ob_start, to_take);
1690
0
        if (ret == NULL) {
1691
0
            return NULL;
1692
0
        }
1693
0
        self->ob_start += to_take;
1694
0
        Py_SET_SIZE(self, remaining_length);
1695
0
        return ret;
1696
0
    }
1697
1698
    // Copy remaining bytes to a new bytes. Allocate and then copy
1699
    // so we don't get a shared immortal one-character singleton!
1700
5.50M
    PyObject *remaining = PyBytes_FromStringAndSize(NULL, remaining_length);
1701
5.50M
    if (remaining == NULL) {
1702
0
        return NULL;
1703
0
    }
1704
5.50M
    memcpy(PyBytes_AS_STRING(remaining), self->ob_start + to_take,
1705
5.50M
           remaining_length);
1706
1707
5.50M
    if (bytearray_resize_storage(self, to_take, to_take) < 0) {
1708
0
        Py_DECREF(remaining);
1709
0
        return NULL;
1710
0
    }
1711
1712
    // Point the bytearray towards the buffer with the remaining data.
1713
5.50M
    PyObject *result = self->ob_bytes_object;
1714
5.50M
    self->ob_bytes_object = remaining;
1715
5.50M
    bytearray_reinit_from_bytes(self, remaining_length);
1716
5.50M
    return result;
1717
5.50M
}
1718
1719
1720
/*[clinic input]
1721
@permit_long_summary
1722
@critical_section
1723
bytearray.translate
1724
1725
    table: object
1726
        Translation table, which must be a bytes object of length 256.
1727
    /
1728
    delete as deletechars: object(c_default="NULL") = b''
1729
1730
Return a copy with each character mapped by the given translation table.
1731
1732
All characters occurring in the optional argument delete are
1733
removed.  The remaining characters are mapped through the given
1734
translation table.
1735
[clinic start generated code]*/
1736
1737
static PyObject *
1738
bytearray_translate_impl(PyByteArrayObject *self, PyObject *table,
1739
                         PyObject *deletechars)
1740
/*[clinic end generated code: output=b6a8f01c2a74e446 input=e30d2ae004365ed9]*/
1741
61.0k
{
1742
61.0k
    char *input, *output;
1743
61.0k
    const char *table_chars;
1744
61.0k
    Py_ssize_t i, c;
1745
61.0k
    PyObject *input_obj = (PyObject*)self;
1746
61.0k
    const char *output_start;
1747
61.0k
    Py_ssize_t inlen;
1748
61.0k
    PyObject *result = NULL;
1749
61.0k
    int trans_table[256];
1750
61.0k
    Py_buffer vtable, vdel;
1751
1752
61.0k
    if (table == Py_None) {
1753
0
        table_chars = NULL;
1754
0
        table = NULL;
1755
61.0k
    } else if (PyObject_GetBuffer(table, &vtable, PyBUF_SIMPLE) != 0) {
1756
0
        return NULL;
1757
61.0k
    } else {
1758
61.0k
        if (vtable.len != 256) {
1759
0
            PyErr_SetString(PyExc_ValueError,
1760
0
                            "translation table must be 256 characters long");
1761
0
            PyBuffer_Release(&vtable);
1762
0
            return NULL;
1763
0
        }
1764
61.0k
        table_chars = (const char*)vtable.buf;
1765
61.0k
    }
1766
1767
61.0k
    if (deletechars != NULL) {
1768
0
        if (PyObject_GetBuffer(deletechars, &vdel, PyBUF_SIMPLE) != 0) {
1769
0
            if (table != NULL)
1770
0
                PyBuffer_Release(&vtable);
1771
0
            return NULL;
1772
0
        }
1773
0
    }
1774
61.0k
    else {
1775
61.0k
        vdel.buf = NULL;
1776
61.0k
        vdel.len = 0;
1777
61.0k
    }
1778
1779
61.0k
    inlen = PyByteArray_GET_SIZE(input_obj);
1780
61.0k
    result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
1781
61.0k
    if (result == NULL)
1782
0
        goto done;
1783
61.0k
    output_start = output = PyByteArray_AS_STRING(result);
1784
61.0k
    input = PyByteArray_AS_STRING(input_obj);
1785
1786
61.0k
    if (vdel.len == 0 && table_chars != NULL) {
1787
        /* If no deletions are required, use faster code */
1788
52.2M
        for (i = inlen; --i >= 0; ) {
1789
52.1M
            c = Py_CHARMASK(*input++);
1790
52.1M
            *output++ = table_chars[c];
1791
52.1M
        }
1792
61.0k
        goto done;
1793
61.0k
    }
1794
1795
0
    if (table_chars == NULL) {
1796
0
        for (i = 0; i < 256; i++)
1797
0
            trans_table[i] = Py_CHARMASK(i);
1798
0
    } else {
1799
0
        for (i = 0; i < 256; i++)
1800
0
            trans_table[i] = Py_CHARMASK(table_chars[i]);
1801
0
    }
1802
1803
0
    for (i = 0; i < vdel.len; i++)
1804
0
        trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
1805
1806
0
    for (i = inlen; --i >= 0; ) {
1807
0
        c = Py_CHARMASK(*input++);
1808
0
        if (trans_table[c] != -1)
1809
0
            *output++ = (char)trans_table[c];
1810
0
    }
1811
    /* Fix the size of the resulting bytearray */
1812
0
    if (inlen > 0)
1813
0
        if (PyByteArray_Resize(result, output - output_start) < 0) {
1814
0
            Py_CLEAR(result);
1815
0
            goto done;
1816
0
        }
1817
1818
61.0k
done:
1819
61.0k
    if (table != NULL)
1820
61.0k
        PyBuffer_Release(&vtable);
1821
61.0k
    if (deletechars != NULL)
1822
0
        PyBuffer_Release(&vdel);
1823
61.0k
    return result;
1824
0
}
1825
1826
1827
/*[clinic input]
1828
1829
@permit_long_summary
1830
@staticmethod
1831
bytearray.maketrans
1832
1833
    frm: Py_buffer
1834
    to: Py_buffer
1835
    /
1836
1837
Return a translation table usable for the bytes or bytearray translate method.
1838
1839
The returned table will be one where each byte in frm is mapped to
1840
the byte at the same position in to.
1841
1842
The bytes objects frm and to must be of the same length.
1843
[clinic start generated code]*/
1844
1845
static PyObject *
1846
bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to)
1847
/*[clinic end generated code: output=1df267d99f56b15e input=c2f5f6e7e6b0221d]*/
1848
0
{
1849
0
    return _Py_bytes_maketrans(frm, to);
1850
0
}
1851
1852
1853
/*[clinic input]
1854
@critical_section
1855
bytearray.replace
1856
1857
    old: Py_buffer
1858
    new: Py_buffer
1859
    /
1860
    count: Py_ssize_t = -1
1861
        Maximum number of occurrences to replace.
1862
        -1 (the default value) means replace all occurrences.
1863
1864
Return a copy with all occurrences of substring old replaced by new.
1865
1866
If count is given, only the first count occurrences are replaced.
1867
If count is not specified or -1, then all occurrences are replaced.
1868
[clinic start generated code]*/
1869
1870
static PyObject *
1871
bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old,
1872
                       Py_buffer *new, Py_ssize_t count)
1873
/*[clinic end generated code: output=d39884c4dc59412a input=e2591806f954aec3]*/
1874
0
{
1875
0
    return stringlib_replace((PyObject *)self,
1876
0
                             (const char *)old->buf, old->len,
1877
0
                             (const char *)new->buf, new->len, count);
1878
0
}
1879
1880
/*[clinic input]
1881
@permit_long_summary
1882
@critical_section
1883
bytearray.split
1884
1885
    sep: object = None
1886
        The delimiter according which to split the bytearray.
1887
        None (the default value) means split on ASCII whitespace
1888
        characters (space, tab, return, newline, formfeed, vertical tab).
1889
    maxsplit: Py_ssize_t = -1
1890
        Maximum number of splits to do.
1891
        -1 (the default value) means no limit.
1892
1893
Return a list of the sections in the bytearray, using sep as the delimiter.
1894
[clinic start generated code]*/
1895
1896
static PyObject *
1897
bytearray_split_impl(PyByteArrayObject *self, PyObject *sep,
1898
                     Py_ssize_t maxsplit)
1899
/*[clinic end generated code: output=833e2cf385d9a04d input=45605178023b52ac]*/
1900
0
{
1901
0
    PyObject *list = NULL;
1902
1903
    /* Increase exports to prevent bytearray storage from changing during _Py_bytes_contains(). */
1904
0
    self->ob_exports++;
1905
0
    const char *sbuf = PyByteArray_AS_STRING(self);
1906
0
    Py_ssize_t slen = PyByteArray_GET_SIZE((PyObject *)self);
1907
1908
0
    if (maxsplit < 0)
1909
0
        maxsplit = PY_SSIZE_T_MAX;
1910
1911
0
    if (sep == Py_None) {
1912
0
        list = stringlib_split_whitespace((PyObject*)self, sbuf, slen, maxsplit);
1913
0
        goto done;
1914
0
    }
1915
1916
0
    Py_buffer vsub;
1917
0
    if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0) {
1918
0
        goto done;
1919
0
    }
1920
1921
0
    list = stringlib_split((PyObject*)self, sbuf, slen,
1922
0
                           (const char *)vsub.buf, vsub.len, maxsplit);
1923
0
    PyBuffer_Release(&vsub);
1924
1925
0
done:
1926
0
    self->ob_exports--;
1927
0
    return list;
1928
0
}
1929
1930
/*[clinic input]
1931
@critical_section
1932
bytearray.partition
1933
1934
    sep: object
1935
    /
1936
1937
Partition the bytearray into three parts using the given separator.
1938
1939
This will search for the separator sep in the bytearray.  If the
1940
separator is found, returns a 3-tuple containing the part before the
1941
separator, the separator itself, and the part after it as new
1942
bytearray objects.
1943
1944
If the separator is not found, returns a 3-tuple containing the copy
1945
of the original bytearray object and two empty bytearray objects.
1946
[clinic start generated code]*/
1947
1948
static PyObject *
1949
bytearray_partition_impl(PyByteArrayObject *self, PyObject *sep)
1950
/*[clinic end generated code: output=b5fa1e03f10cfccb input=d76673ed03acf5dd]*/
1951
0
{
1952
0
    PyObject *bytesep, *result;
1953
1954
0
    bytesep = _PyByteArray_FromBufferObject(sep);
1955
0
    if (! bytesep)
1956
0
        return NULL;
1957
1958
0
    result = stringlib_partition(
1959
0
            (PyObject*) self,
1960
0
            PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
1961
0
            bytesep,
1962
0
            PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
1963
0
            );
1964
1965
0
    Py_DECREF(bytesep);
1966
0
    return result;
1967
0
}
1968
1969
/*[clinic input]
1970
@critical_section
1971
bytearray.rpartition
1972
1973
    sep: object
1974
    /
1975
1976
Partition the bytearray into three parts using the given separator.
1977
1978
This will search for the separator sep in the bytearray, starting at
1979
the end.  If the separator is found, returns a 3-tuple containing
1980
the part before the separator, the separator itself, and the part
1981
after it as new bytearray objects.
1982
1983
If the separator is not found, returns a 3-tuple containing two
1984
empty bytearray objects and the copy of the original bytearray
1985
object.
1986
[clinic start generated code]*/
1987
1988
static PyObject *
1989
bytearray_rpartition_impl(PyByteArrayObject *self, PyObject *sep)
1990
/*[clinic end generated code: output=0186ce7b1ef61289 input=b9216a2074174a36]*/
1991
0
{
1992
0
    PyObject *bytesep, *result;
1993
1994
0
    bytesep = _PyByteArray_FromBufferObject(sep);
1995
0
    if (! bytesep)
1996
0
        return NULL;
1997
1998
0
    result = stringlib_rpartition(
1999
0
            (PyObject*) self,
2000
0
            PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
2001
0
            bytesep,
2002
0
            PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
2003
0
            );
2004
2005
0
    Py_DECREF(bytesep);
2006
0
    return result;
2007
0
}
2008
2009
/*[clinic input]
2010
@permit_long_summary
2011
@critical_section
2012
bytearray.rsplit = bytearray.split
2013
2014
Return a list of the sections in the bytearray, using sep as the delimiter.
2015
2016
Splitting is done starting at the end of the bytearray and working
2017
to the front.
2018
[clinic start generated code]*/
2019
2020
static PyObject *
2021
bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep,
2022
                      Py_ssize_t maxsplit)
2023
/*[clinic end generated code: output=a55e0b5a03cb6190 input=e201671c9a0c19ee]*/
2024
0
{
2025
0
    PyObject *list = NULL;
2026
2027
    /* Increase exports to prevent bytearray storage from changing during _Py_bytes_contains(). */
2028
0
    self->ob_exports++;
2029
0
    const char *sbuf = PyByteArray_AS_STRING(self);
2030
0
    Py_ssize_t slen = PyByteArray_GET_SIZE((PyObject *)self);
2031
2032
0
    if (maxsplit < 0)
2033
0
        maxsplit = PY_SSIZE_T_MAX;
2034
2035
0
    if (sep == Py_None) {
2036
0
        list = stringlib_rsplit_whitespace((PyObject*)self, sbuf, slen, maxsplit);
2037
0
        goto done;
2038
0
    }
2039
2040
0
    Py_buffer vsub;
2041
0
    if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0) {
2042
0
        goto done;
2043
0
    }
2044
2045
0
    list = stringlib_rsplit((PyObject*)self, sbuf, slen,
2046
0
                            (const char *)vsub.buf, vsub.len, maxsplit);
2047
0
    PyBuffer_Release(&vsub);
2048
2049
0
done:
2050
0
    self->ob_exports--;
2051
0
    return list;
2052
0
}
2053
2054
/*[clinic input]
2055
@critical_section
2056
bytearray.reverse
2057
2058
Reverse the order of the values in B in place.
2059
[clinic start generated code]*/
2060
2061
static PyObject *
2062
bytearray_reverse_impl(PyByteArrayObject *self)
2063
/*[clinic end generated code: output=9f7616f29ab309d3 input=2f3d5ce3180ffc53]*/
2064
0
{
2065
0
    char swap, *head, *tail;
2066
0
    Py_ssize_t i, j, n = Py_SIZE(self);
2067
2068
0
    j = n / 2;
2069
0
    head = PyByteArray_AS_STRING(self);
2070
0
    tail = head + n - 1;
2071
0
    for (i = 0; i < j; i++) {
2072
0
        swap = *head;
2073
0
        *head++ = *tail;
2074
0
        *tail-- = swap;
2075
0
    }
2076
2077
0
    Py_RETURN_NONE;
2078
0
}
2079
2080
2081
/*[python input]
2082
class bytesvalue_converter(CConverter):
2083
    type = 'int'
2084
    converter = '_getbytevalue'
2085
[python start generated code]*/
2086
/*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/
2087
2088
2089
/*[clinic input]
2090
@critical_section
2091
bytearray.insert
2092
2093
    index: Py_ssize_t
2094
        The index where the value is to be inserted.
2095
    item: bytesvalue
2096
        The item to be inserted.
2097
    /
2098
2099
Insert a single item into the bytearray before the given index.
2100
[clinic start generated code]*/
2101
2102
static PyObject *
2103
bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
2104
/*[clinic end generated code: output=76c775a70e7b07b7 input=b3e14ede546dd8cc]*/
2105
17.0k
{
2106
17.0k
    Py_ssize_t n = Py_SIZE(self);
2107
17.0k
    char *buf;
2108
2109
17.0k
    if (bytearray_resize_lock_held((PyObject *)self, n + 1) < 0)
2110
0
        return NULL;
2111
17.0k
    buf = PyByteArray_AS_STRING(self);
2112
2113
17.0k
    if (index < 0) {
2114
0
        index += n;
2115
0
        if (index < 0)
2116
0
            index = 0;
2117
0
    }
2118
17.0k
    if (index > n)
2119
0
        index = n;
2120
17.0k
    memmove(buf + index + 1, buf + index, n - index);
2121
17.0k
    buf[index] = item;
2122
2123
17.0k
    Py_RETURN_NONE;
2124
17.0k
}
2125
2126
static PyObject *
2127
bytearray_isalnum(PyObject *self, PyObject *Py_UNUSED(ignored))
2128
0
{
2129
0
    PyObject *ret;
2130
0
    Py_BEGIN_CRITICAL_SECTION(self);
2131
0
    ret = stringlib_isalnum(self, NULL);
2132
0
    Py_END_CRITICAL_SECTION();
2133
0
    return ret;
2134
0
}
2135
2136
static PyObject *
2137
bytearray_isalpha(PyObject *self, PyObject *Py_UNUSED(ignored))
2138
0
{
2139
0
    PyObject *ret;
2140
0
    Py_BEGIN_CRITICAL_SECTION(self);
2141
0
    ret = stringlib_isalpha(self, NULL);
2142
0
    Py_END_CRITICAL_SECTION();
2143
0
    return ret;
2144
0
}
2145
2146
static PyObject *
2147
bytearray_isascii(PyObject *self, PyObject *Py_UNUSED(ignored))
2148
0
{
2149
0
    PyObject *ret;
2150
0
    Py_BEGIN_CRITICAL_SECTION(self);
2151
0
    ret = stringlib_isascii(self, NULL);
2152
0
    Py_END_CRITICAL_SECTION();
2153
0
    return ret;
2154
0
}
2155
2156
static PyObject *
2157
bytearray_isdigit(PyObject *self, PyObject *Py_UNUSED(ignored))
2158
0
{
2159
0
    PyObject *ret;
2160
0
    Py_BEGIN_CRITICAL_SECTION(self);
2161
0
    ret = stringlib_isdigit(self, NULL);
2162
0
    Py_END_CRITICAL_SECTION();
2163
0
    return ret;
2164
0
}
2165
2166
static PyObject *
2167
bytearray_islower(PyObject *self, PyObject *Py_UNUSED(ignored))
2168
0
{
2169
0
    PyObject *ret;
2170
0
    Py_BEGIN_CRITICAL_SECTION(self);
2171
0
    ret = stringlib_islower(self, NULL);
2172
0
    Py_END_CRITICAL_SECTION();
2173
0
    return ret;
2174
0
}
2175
2176
static PyObject *
2177
bytearray_isspace(PyObject *self, PyObject *Py_UNUSED(ignored))
2178
0
{
2179
0
    PyObject *ret;
2180
0
    Py_BEGIN_CRITICAL_SECTION(self);
2181
0
    ret = stringlib_isspace(self, NULL);
2182
0
    Py_END_CRITICAL_SECTION();
2183
0
    return ret;
2184
0
}
2185
2186
static PyObject *
2187
bytearray_istitle(PyObject *self, PyObject *Py_UNUSED(ignored))
2188
0
{
2189
0
    PyObject *ret;
2190
0
    Py_BEGIN_CRITICAL_SECTION(self);
2191
0
    ret = stringlib_istitle(self, NULL);
2192
0
    Py_END_CRITICAL_SECTION();
2193
0
    return ret;
2194
0
}
2195
2196
static PyObject *
2197
bytearray_isupper(PyObject *self, PyObject *Py_UNUSED(ignored))
2198
0
{
2199
0
    PyObject *ret;
2200
0
    Py_BEGIN_CRITICAL_SECTION(self);
2201
0
    ret = stringlib_isupper(self, NULL);
2202
0
    Py_END_CRITICAL_SECTION();
2203
0
    return ret;
2204
0
}
2205
2206
/*[clinic input]
2207
@critical_section
2208
bytearray.append
2209
2210
    item: bytesvalue
2211
        The item to be appended.
2212
    /
2213
2214
Append a single item to the end of the bytearray.
2215
[clinic start generated code]*/
2216
2217
static PyObject *
2218
bytearray_append_impl(PyByteArrayObject *self, int item)
2219
/*[clinic end generated code: output=a154e19ed1886cb6 input=a874689bac8bd352]*/
2220
9.22M
{
2221
9.22M
    Py_ssize_t n = Py_SIZE(self);
2222
2223
9.22M
    if (bytearray_resize_lock_held((PyObject *)self, n + 1) < 0)
2224
0
        return NULL;
2225
2226
9.22M
    PyByteArray_AS_STRING(self)[n] = item;
2227
2228
9.22M
    Py_RETURN_NONE;
2229
9.22M
}
2230
2231
static PyObject *
2232
bytearray_capitalize(PyObject *self, PyObject *Py_UNUSED(ignored))
2233
0
{
2234
0
    PyObject *ret;
2235
0
    Py_BEGIN_CRITICAL_SECTION(self);
2236
0
    ret = stringlib_capitalize(self, NULL);
2237
0
    Py_END_CRITICAL_SECTION();
2238
0
    return ret;
2239
0
}
2240
2241
static PyObject *
2242
bytearray_center(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
2243
0
{
2244
0
    PyObject *ret;
2245
0
    Py_BEGIN_CRITICAL_SECTION(self);
2246
0
    ret = stringlib_center(self, args, nargs);
2247
0
    Py_END_CRITICAL_SECTION();
2248
0
    return ret;
2249
0
}
2250
2251
static PyObject *
2252
bytearray_expandtabs(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
2253
0
{
2254
0
    PyObject *ret;
2255
0
    Py_BEGIN_CRITICAL_SECTION(self);
2256
0
    ret = stringlib_expandtabs(self, args, nargs, kwnames);
2257
0
    Py_END_CRITICAL_SECTION();
2258
0
    return ret;
2259
0
}
2260
2261
/*[clinic input]
2262
@permit_long_summary
2263
@critical_section
2264
bytearray.extend
2265
2266
    iterable_of_ints: object
2267
        The iterable of items to append.
2268
    /
2269
2270
Append all the items from the iterator or sequence to the end of the bytearray.
2271
[clinic start generated code]*/
2272
2273
static PyObject *
2274
bytearray_extend_impl(PyByteArrayObject *self, PyObject *iterable_of_ints)
2275
/*[clinic end generated code: output=2f25e0ce72b98748 input=aeed44b025146632]*/
2276
12.3M
{
2277
12.3M
    PyObject *it, *item, *bytearray_obj;
2278
12.3M
    Py_ssize_t buf_size = 0, len = 0;
2279
12.3M
    int value;
2280
12.3M
    char *buf;
2281
2282
    /* bytearray_setslice code only accepts something supporting PEP 3118. */
2283
12.3M
    if (PyObject_CheckBuffer(iterable_of_ints)) {
2284
12.3M
        if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1)
2285
0
            return NULL;
2286
2287
12.3M
        Py_RETURN_NONE;
2288
12.3M
    }
2289
2290
0
    it = PyObject_GetIter(iterable_of_ints);
2291
0
    if (it == NULL) {
2292
0
        if (PyErr_ExceptionMatches(PyExc_TypeError)) {
2293
0
            PyErr_Format(PyExc_TypeError,
2294
0
                         "can't extend bytearray with %.100s",
2295
0
                         Py_TYPE(iterable_of_ints)->tp_name);
2296
0
        }
2297
0
        return NULL;
2298
0
    }
2299
2300
    /* Try to determine the length of the argument. 32 is arbitrary. */
2301
0
    buf_size = PyObject_LengthHint(iterable_of_ints, 32);
2302
0
    if (buf_size == -1) {
2303
0
        Py_DECREF(it);
2304
0
        return NULL;
2305
0
    }
2306
2307
0
    bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
2308
0
    if (bytearray_obj == NULL) {
2309
0
        Py_DECREF(it);
2310
0
        return NULL;
2311
0
    }
2312
0
    buf = PyByteArray_AS_STRING(bytearray_obj);
2313
2314
0
    while ((item = PyIter_Next(it)) != NULL) {
2315
0
        if (! _getbytevalue(item, &value)) {
2316
0
            if (PyErr_ExceptionMatches(PyExc_TypeError) && PyUnicode_Check(iterable_of_ints)) {
2317
0
                PyErr_Format(PyExc_TypeError,
2318
0
                             "expected iterable of integers; got: 'str'");
2319
0
            }
2320
0
            Py_DECREF(item);
2321
0
            Py_DECREF(it);
2322
0
            Py_DECREF(bytearray_obj);
2323
0
            return NULL;
2324
0
        }
2325
0
        Py_DECREF(item);
2326
2327
0
        if (len >= buf_size) {
2328
0
            Py_ssize_t addition;
2329
0
            if (len == PyByteArray_SIZE_MAX) {
2330
0
                Py_DECREF(it);
2331
0
                Py_DECREF(bytearray_obj);
2332
0
                return PyErr_NoMemory();
2333
0
            }
2334
0
            addition = len ? len >> 1 : 1;
2335
0
            if (addition > PyByteArray_SIZE_MAX - len)
2336
0
                buf_size = PyByteArray_SIZE_MAX;
2337
0
            else
2338
0
                buf_size = len + addition;
2339
0
            if (bytearray_resize_lock_held((PyObject *)bytearray_obj, buf_size) < 0) {
2340
0
                Py_DECREF(it);
2341
0
                Py_DECREF(bytearray_obj);
2342
0
                return NULL;
2343
0
            }
2344
            /* Recompute the `buf' pointer, since the resizing operation may
2345
               have invalidated it. */
2346
0
            buf = PyByteArray_AS_STRING(bytearray_obj);
2347
0
        }
2348
0
        buf[len++] = value;
2349
0
    }
2350
0
    Py_DECREF(it);
2351
2352
0
    if (PyErr_Occurred()) {
2353
0
        Py_DECREF(bytearray_obj);
2354
0
        return NULL;
2355
0
    }
2356
2357
    /* Resize down to exact size. */
2358
0
    if (bytearray_resize_lock_held((PyObject *)bytearray_obj, len) < 0) {
2359
0
        Py_DECREF(bytearray_obj);
2360
0
        return NULL;
2361
0
    }
2362
2363
0
    if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
2364
0
        Py_DECREF(bytearray_obj);
2365
0
        return NULL;
2366
0
    }
2367
0
    Py_DECREF(bytearray_obj);
2368
2369
0
    assert(!PyErr_Occurred());
2370
0
    Py_RETURN_NONE;
2371
0
}
2372
2373
/*[clinic input]
2374
@critical_section
2375
bytearray.pop
2376
2377
    index: Py_ssize_t = -1
2378
        The index from where to remove the item.
2379
        -1 (the default value) means remove the last item.
2380
    /
2381
2382
Remove and return a single item from B.
2383
2384
If no index argument is given, will pop the last item.
2385
[clinic start generated code]*/
2386
2387
static PyObject *
2388
bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
2389
/*[clinic end generated code: output=e0ccd401f8021da8 input=fc0fd8de4f97661c]*/
2390
0
{
2391
0
    int value;
2392
0
    Py_ssize_t n = Py_SIZE(self);
2393
0
    char *buf;
2394
2395
0
    if (n == 0) {
2396
0
        PyErr_SetString(PyExc_IndexError,
2397
0
                        "pop from empty bytearray");
2398
0
        return NULL;
2399
0
    }
2400
0
    if (index < 0)
2401
0
        index += Py_SIZE(self);
2402
0
    if (index < 0 || index >= Py_SIZE(self)) {
2403
0
        PyErr_SetString(PyExc_IndexError, "pop index out of range");
2404
0
        return NULL;
2405
0
    }
2406
0
    if (!_canresize(self))
2407
0
        return NULL;
2408
2409
0
    buf = PyByteArray_AS_STRING(self);
2410
0
    value = buf[index];
2411
0
    memmove(buf + index, buf + index + 1, n - index);
2412
0
    if (bytearray_resize_lock_held((PyObject *)self, n - 1) < 0)
2413
0
        return NULL;
2414
2415
0
    return _PyLong_FromUnsignedChar((unsigned char)value);
2416
0
}
2417
2418
/*[clinic input]
2419
@critical_section
2420
bytearray.remove
2421
2422
    value: bytesvalue
2423
        The value to remove.
2424
    /
2425
2426
Remove the first occurrence of a value in the bytearray.
2427
[clinic start generated code]*/
2428
2429
static PyObject *
2430
bytearray_remove_impl(PyByteArrayObject *self, int value)
2431
/*[clinic end generated code: output=d659e37866709c13 input=797588bc77f86afb]*/
2432
0
{
2433
0
    Py_ssize_t where, n = Py_SIZE(self);
2434
0
    char *buf = PyByteArray_AS_STRING(self);
2435
2436
0
    where = stringlib_find_char(buf, n, value);
2437
0
    if (where < 0) {
2438
0
        PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
2439
0
        return NULL;
2440
0
    }
2441
0
    if (!_canresize(self))
2442
0
        return NULL;
2443
2444
0
    memmove(buf + where, buf + where + 1, n - where);
2445
0
    if (bytearray_resize_lock_held((PyObject *)self, n - 1) < 0)
2446
0
        return NULL;
2447
2448
0
    Py_RETURN_NONE;
2449
0
}
2450
2451
0
#define LEFTSTRIP 0
2452
0
#define RIGHTSTRIP 1
2453
0
#define BOTHSTRIP 2
2454
2455
static PyObject*
2456
bytearray_strip_impl_helper(PyByteArrayObject* self, PyObject* bytes, int striptype)
2457
0
{
2458
0
    Py_ssize_t mysize, byteslen;
2459
0
    const char* myptr;
2460
0
    const char* bytesptr;
2461
0
    Py_buffer vbytes;
2462
2463
0
    if (bytes == Py_None) {
2464
0
        bytesptr = "\t\n\r\f\v ";
2465
0
        byteslen = 6;
2466
0
    }
2467
0
    else {
2468
0
        if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
2469
0
            return NULL;
2470
0
        bytesptr = (const char*)vbytes.buf;
2471
0
        byteslen = vbytes.len;
2472
0
    }
2473
0
    myptr = PyByteArray_AS_STRING(self);
2474
0
    mysize = Py_SIZE(self);
2475
2476
0
    Py_ssize_t left = 0;
2477
0
    if (striptype != RIGHTSTRIP) {
2478
0
        while (left < mysize && memchr(bytesptr, (unsigned char)myptr[left], byteslen))
2479
0
            left++;
2480
0
    }
2481
0
    Py_ssize_t right = mysize;
2482
0
    if (striptype != LEFTSTRIP) {
2483
0
        do {
2484
0
            right--;
2485
0
        } while (right >= left && memchr(bytesptr, (unsigned char)myptr[right], byteslen));
2486
0
        right++;
2487
0
    }
2488
0
    if (bytes != Py_None)
2489
0
        PyBuffer_Release(&vbytes);
2490
0
    return PyByteArray_FromStringAndSize(myptr + left, right - left);
2491
0
}
2492
2493
/*[clinic input]
2494
@critical_section
2495
bytearray.strip
2496
2497
    bytes: object = None
2498
    /
2499
2500
Strip leading and trailing bytes contained in the argument.
2501
2502
If the argument is omitted or None, strip leading and trailing ASCII
2503
whitespace.
2504
[clinic start generated code]*/
2505
2506
static PyObject *
2507
bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
2508
/*[clinic end generated code: output=760412661a34ad5a input=f4ec5fa609df7d14]*/
2509
0
{
2510
0
    return bytearray_strip_impl_helper(self, bytes, BOTHSTRIP);
2511
0
}
2512
2513
static PyObject *
2514
bytearray_swapcase(PyObject *self, PyObject *Py_UNUSED(ignored))
2515
0
{
2516
0
    PyObject *ret;
2517
0
    Py_BEGIN_CRITICAL_SECTION(self);
2518
0
    ret = stringlib_swapcase(self, NULL);
2519
0
    Py_END_CRITICAL_SECTION();
2520
0
    return ret;
2521
0
}
2522
2523
static PyObject *
2524
bytearray_title(PyObject *self, PyObject *Py_UNUSED(ignored))
2525
0
{
2526
0
    PyObject *ret;
2527
0
    Py_BEGIN_CRITICAL_SECTION(self);
2528
0
    ret = stringlib_title(self, NULL);
2529
0
    Py_END_CRITICAL_SECTION();
2530
0
    return ret;
2531
0
}
2532
2533
static PyObject *
2534
bytearray_upper(PyObject *self, PyObject *Py_UNUSED(ignored))
2535
0
{
2536
0
    PyObject *ret;
2537
0
    Py_BEGIN_CRITICAL_SECTION(self);
2538
0
    ret = stringlib_upper(self, NULL);
2539
0
    Py_END_CRITICAL_SECTION();
2540
0
    return ret;
2541
0
}
2542
2543
static PyObject *
2544
bytearray_lower(PyObject *self, PyObject *Py_UNUSED(ignored))
2545
0
{
2546
0
    PyObject *ret;
2547
0
    Py_BEGIN_CRITICAL_SECTION(self);
2548
0
    ret = stringlib_lower(self, NULL);
2549
0
    Py_END_CRITICAL_SECTION();
2550
0
    return ret;
2551
0
}
2552
2553
static PyObject *
2554
bytearray_zfill(PyObject *self, PyObject *arg)
2555
0
{
2556
0
    PyObject *ret;
2557
0
    Py_BEGIN_CRITICAL_SECTION(self);
2558
0
    ret = stringlib_zfill(self, arg);
2559
0
    Py_END_CRITICAL_SECTION();
2560
0
    return ret;
2561
0
}
2562
2563
/*[clinic input]
2564
@critical_section
2565
bytearray.lstrip
2566
2567
    bytes: object = None
2568
    /
2569
2570
Strip leading bytes contained in the argument.
2571
2572
If the argument is omitted or None, strip leading ASCII whitespace.
2573
[clinic start generated code]*/
2574
2575
static PyObject *
2576
bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
2577
/*[clinic end generated code: output=d005c9d0ab909e66 input=ed86e00eb2023625]*/
2578
0
{
2579
0
    return bytearray_strip_impl_helper(self, bytes, LEFTSTRIP);
2580
0
}
2581
2582
/*[clinic input]
2583
@critical_section
2584
bytearray.rstrip
2585
2586
    bytes: object = None
2587
    /
2588
2589
Strip trailing bytes contained in the argument.
2590
2591
If the argument is omitted or None, strip trailing ASCII whitespace.
2592
[clinic start generated code]*/
2593
2594
static PyObject *
2595
bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
2596
/*[clinic end generated code: output=030e2fbd2f7276bd input=d9ca66cf20fe7649]*/
2597
0
{
2598
0
    return bytearray_strip_impl_helper(self, bytes, RIGHTSTRIP);
2599
0
}
2600
2601
/*[clinic input]
2602
@critical_section
2603
bytearray.decode
2604
2605
    encoding: str(c_default="NULL") = 'utf-8'
2606
        The encoding with which to decode the bytearray.
2607
    errors: str(c_default="NULL") = 'strict'
2608
        The error handling scheme to use for the handling of decoding
2609
        errors.  The default is 'strict' meaning that decoding errors
2610
        raise a UnicodeDecodeError.  Other possible values are 'ignore'
2611
        and 'replace' as well as any other name registered with
2612
        codecs.register_error that can handle UnicodeDecodeErrors.
2613
2614
Decode the bytearray using the codec registered for encoding.
2615
[clinic start generated code]*/
2616
2617
static PyObject *
2618
bytearray_decode_impl(PyByteArrayObject *self, const char *encoding,
2619
                      const char *errors)
2620
/*[clinic end generated code: output=f57d43f4a00b42c5 input=e51ce9b82b51e2ca]*/
2621
542k
{
2622
542k
    if (encoding == NULL)
2623
0
        encoding = PyUnicode_GetDefaultEncoding();
2624
542k
    if (Py_TYPE(self)->tp_as_buffer->bf_getbuffer != bytearray_getbuffer) {
2625
        /* A subclass may export a different buffer. */
2626
0
        return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
2627
0
    }
2628
2629
    /* Decode the storage directly instead of exporting a buffer, which
2630
       would re-acquire the critical section we already hold.  Increase
2631
       exports to prevent the storage from changing during the decode. */
2632
542k
    self->ob_exports++;
2633
542k
    PyObject *res = PyUnicode_Decode(PyByteArray_AS_STRING(self),
2634
542k
                                     Py_SIZE(self), encoding, errors);
2635
542k
    self->ob_exports--;
2636
542k
    return res;
2637
542k
}
2638
2639
PyDoc_STRVAR(alloc_doc,
2640
"B.__alloc__() -> int\n\
2641
\n\
2642
Return the number of bytes actually allocated.");
2643
2644
static PyObject *
2645
bytearray_alloc(PyObject *op, PyObject *Py_UNUSED(ignored))
2646
0
{
2647
0
    PyByteArrayObject *self = _PyByteArray_CAST(op);
2648
0
    Py_ssize_t alloc = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->ob_alloc);
2649
0
    if (alloc > 0) {
2650
0
        alloc += _PyBytesObject_SIZE;
2651
0
    }
2652
0
    return PyLong_FromSsize_t(alloc);
2653
0
}
2654
2655
/*[clinic input]
2656
@critical_section
2657
bytearray.join
2658
2659
    iterable_of_bytes: object
2660
    /
2661
2662
Concatenate any number of bytes/bytearray objects.
2663
2664
The bytearray whose method is called is inserted in between each
2665
pair.
2666
2667
The result is returned as a new bytearray object.
2668
[clinic start generated code]*/
2669
2670
static PyObject *
2671
bytearray_join_impl(PyByteArrayObject *self, PyObject *iterable_of_bytes)
2672
/*[clinic end generated code: output=0ced382b5846a7ee input=0a31db349efcd7fa]*/
2673
0
{
2674
0
    PyObject *ret;
2675
0
    self->ob_exports++; // this protects `self` from being cleared/resized if `iterable_of_bytes` is a custom iterator
2676
0
    ret = stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
2677
0
    self->ob_exports--; // unexport `self`
2678
0
    return ret;
2679
0
}
2680
2681
static PyObject *
2682
bytearray_ljust(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
2683
0
{
2684
0
    PyObject *ret;
2685
0
    Py_BEGIN_CRITICAL_SECTION(self);
2686
0
    ret = stringlib_ljust(self, args, nargs);
2687
0
    Py_END_CRITICAL_SECTION();
2688
0
    return ret;
2689
0
}
2690
2691
static PyObject *
2692
bytearray_rjust(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
2693
0
{
2694
0
    PyObject *ret;
2695
0
    Py_BEGIN_CRITICAL_SECTION(self);
2696
0
    ret = stringlib_rjust(self, args, nargs);
2697
0
    Py_END_CRITICAL_SECTION();
2698
0
    return ret;
2699
0
}
2700
2701
/*[clinic input]
2702
@permit_long_summary
2703
@critical_section
2704
bytearray.splitlines
2705
2706
    keepends: bool = False
2707
2708
Return a list of the lines in the bytearray, breaking at line boundaries.
2709
2710
Line breaks are not included in the resulting list unless keepends
2711
is given and true.
2712
[clinic start generated code]*/
2713
2714
static PyObject *
2715
bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
2716
/*[clinic end generated code: output=4223c94b895f6ad9 input=cc2bb740eed19f27]*/
2717
0
{
2718
0
    return stringlib_splitlines(
2719
0
        (PyObject*) self, PyByteArray_AS_STRING(self),
2720
0
        PyByteArray_GET_SIZE(self), keepends
2721
0
        );
2722
0
}
2723
2724
/*[clinic input]
2725
@classmethod
2726
bytearray.fromhex
2727
2728
    string: object
2729
    /
2730
2731
Create a bytearray object from a string of hexadecimal numbers.
2732
2733
Spaces between two numbers are accepted.
2734
Example:
2735
    bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
2736
[clinic start generated code]*/
2737
2738
static PyObject *
2739
bytearray_fromhex_impl(PyTypeObject *type, PyObject *string)
2740
/*[clinic end generated code: output=8f0f0b6d30fb3ba0 input=2243a8b0b9e66cd5]*/
2741
0
{
2742
0
    PyObject *result = _PyBytes_FromHex(string, type == &PyByteArray_Type);
2743
0
    if (type != &PyByteArray_Type && result != NULL) {
2744
0
        Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
2745
0
    }
2746
0
    return result;
2747
0
}
2748
2749
/*[clinic input]
2750
@critical_section
2751
bytearray.hex
2752
2753
    sep: object = NULL
2754
        An optional single character or byte to separate hex bytes.
2755
    bytes_per_sep: Py_ssize_t = 1
2756
        How many bytes between separators.  Positive values count from
2757
        the right, negative values count from the left.
2758
2759
Create a string of hexadecimal numbers from a bytearray object.
2760
2761
Example:
2762
>>> value = bytearray([0xb9, 0x01, 0xef])
2763
>>> value.hex()
2764
'b901ef'
2765
>>> value.hex(':')
2766
'b9:01:ef'
2767
>>> value.hex(':', 2)
2768
'b9:01ef'
2769
>>> value.hex(':', -2)
2770
'b901:ef'
2771
[clinic start generated code]*/
2772
2773
static PyObject *
2774
bytearray_hex_impl(PyByteArrayObject *self, PyObject *sep,
2775
                   Py_ssize_t bytes_per_sep)
2776
/*[clinic end generated code: output=c9563921aff1262b input=9ed746203691e894]*/
2777
0
{
2778
0
    char* argbuf = PyByteArray_AS_STRING(self);
2779
0
    Py_ssize_t arglen = PyByteArray_GET_SIZE(self);
2780
    // Prevent 'self' from being freed if computing len(sep) mutates 'self'
2781
    // in _Py_strhex_with_sep().
2782
    // See: https://github.com/python/cpython/issues/143195.
2783
0
    self->ob_exports++;
2784
0
    PyObject *res = _Py_strhex_with_sep(argbuf, arglen, sep, bytes_per_sep);
2785
0
    self->ob_exports--;
2786
0
    return res;
2787
0
}
2788
2789
static PyObject *
2790
_common_reduce(PyByteArrayObject *self, int proto)
2791
0
{
2792
0
    PyObject *state;
2793
0
    const char *buf;
2794
2795
0
    state = _PyObject_GetState((PyObject *)self);
2796
0
    if (state == NULL) {
2797
0
        return NULL;
2798
0
    }
2799
2800
0
    if (!Py_SIZE(self)) {
2801
0
        return Py_BuildValue("(O()N)", Py_TYPE(self), state);
2802
0
    }
2803
0
    buf = PyByteArray_AS_STRING(self);
2804
0
    if (proto < 3) {
2805
        /* use str based reduction for backwards compatibility with Python 2.x */
2806
0
        PyObject *latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL);
2807
0
        return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", state);
2808
0
    }
2809
0
    else {
2810
        /* use more efficient byte based reduction */
2811
0
        return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), state);
2812
0
    }
2813
0
}
2814
2815
/*[clinic input]
2816
@critical_section
2817
bytearray.__reduce__ as bytearray_reduce
2818
2819
Return state information for pickling.
2820
[clinic start generated code]*/
2821
2822
static PyObject *
2823
bytearray_reduce_impl(PyByteArrayObject *self)
2824
/*[clinic end generated code: output=52bf304086464cab input=0fac78e4b7d84dd2]*/
2825
0
{
2826
0
    return _common_reduce(self, 2);
2827
0
}
2828
2829
/*[clinic input]
2830
@critical_section
2831
bytearray.__reduce_ex__ as bytearray_reduce_ex
2832
2833
    proto: int = 0
2834
    /
2835
2836
Return state information for pickling.
2837
[clinic start generated code]*/
2838
2839
static PyObject *
2840
bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
2841
/*[clinic end generated code: output=52eac33377197520 input=751718f477033a29]*/
2842
0
{
2843
0
    return _common_reduce(self, proto);
2844
0
}
2845
2846
/*[clinic input]
2847
bytearray.__sizeof__ as bytearray_sizeof
2848
2849
Returns the size of the bytearray object in memory, in bytes.
2850
[clinic start generated code]*/
2851
2852
static PyObject *
2853
bytearray_sizeof_impl(PyByteArrayObject *self)
2854
/*[clinic end generated code: output=738abdd17951c427 input=e27320fd98a4bc5a]*/
2855
0
{
2856
0
    Py_ssize_t res = _PyObject_SIZE(Py_TYPE(self));
2857
0
    Py_ssize_t alloc = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->ob_alloc);
2858
0
    if (alloc > 0) {
2859
0
        res += _PyBytesObject_SIZE + alloc;
2860
0
    }
2861
2862
0
    return PyLong_FromSsize_t(res);
2863
0
}
2864
2865
static PySequenceMethods bytearray_as_sequence = {
2866
    bytearray_length,                       /* sq_length */
2867
    PyByteArray_Concat,                     /* sq_concat */
2868
    bytearray_repeat,                       /* sq_repeat */
2869
    bytearray_getitem,                      /* sq_item */
2870
    0,                                      /* sq_slice */
2871
    bytearray_setitem,                      /* sq_ass_item */
2872
    0,                                      /* sq_ass_slice */
2873
    bytearray_contains,                     /* sq_contains */
2874
    bytearray_iconcat,                      /* sq_inplace_concat */
2875
    bytearray_irepeat,                      /* sq_inplace_repeat */
2876
};
2877
2878
static PyMappingMethods bytearray_as_mapping = {
2879
    bytearray_length,
2880
    bytearray_subscript,
2881
    bytearray_ass_subscript,
2882
};
2883
2884
static PyBufferProcs bytearray_as_buffer = {
2885
    bytearray_getbuffer,
2886
    bytearray_releasebuffer,
2887
};
2888
2889
static PyMethodDef bytearray_methods[] = {
2890
    {"__alloc__", bytearray_alloc, METH_NOARGS, alloc_doc},
2891
    BYTEARRAY_REDUCE_METHODDEF
2892
    BYTEARRAY_REDUCE_EX_METHODDEF
2893
    BYTEARRAY_SIZEOF_METHODDEF
2894
    BYTEARRAY_APPEND_METHODDEF
2895
    {"capitalize", bytearray_capitalize, METH_NOARGS, _Py_capitalize__doc__},
2896
    {"center", _PyCFunction_CAST(bytearray_center), METH_FASTCALL,
2897
    stringlib_center__doc__},
2898
    BYTEARRAY_CLEAR_METHODDEF
2899
    BYTEARRAY_COPY_METHODDEF
2900
    BYTEARRAY_COUNT_METHODDEF
2901
    BYTEARRAY_DECODE_METHODDEF
2902
    BYTEARRAY_ENDSWITH_METHODDEF
2903
    {"expandtabs", _PyCFunction_CAST(bytearray_expandtabs),
2904
    METH_FASTCALL|METH_KEYWORDS, stringlib_expandtabs__doc__},
2905
    BYTEARRAY_EXTEND_METHODDEF
2906
    BYTEARRAY_FIND_METHODDEF
2907
    BYTEARRAY_FROMHEX_METHODDEF
2908
    BYTEARRAY_HEX_METHODDEF
2909
    BYTEARRAY_INDEX_METHODDEF
2910
    BYTEARRAY_INSERT_METHODDEF
2911
    {"isalnum", bytearray_isalnum, METH_NOARGS, _Py_isalnum__doc__},
2912
    {"isalpha", bytearray_isalpha, METH_NOARGS, _Py_isalpha__doc__},
2913
    {"isascii", bytearray_isascii, METH_NOARGS, _Py_isascii__doc__},
2914
    {"isdigit", bytearray_isdigit, METH_NOARGS, _Py_isdigit__doc__},
2915
    {"islower", bytearray_islower, METH_NOARGS, _Py_islower__doc__},
2916
    {"isspace", bytearray_isspace, METH_NOARGS, _Py_isspace__doc__},
2917
    {"istitle", bytearray_istitle, METH_NOARGS, _Py_istitle__doc__},
2918
    {"isupper", bytearray_isupper, METH_NOARGS, _Py_isupper__doc__},
2919
    BYTEARRAY_JOIN_METHODDEF
2920
    {"ljust", _PyCFunction_CAST(bytearray_ljust), METH_FASTCALL,
2921
    stringlib_ljust__doc__},
2922
    {"lower", bytearray_lower, METH_NOARGS, _Py_lower__doc__},
2923
    BYTEARRAY_LSTRIP_METHODDEF
2924
    BYTEARRAY_MAKETRANS_METHODDEF
2925
    BYTEARRAY_PARTITION_METHODDEF
2926
    BYTEARRAY_POP_METHODDEF
2927
    BYTEARRAY_REMOVE_METHODDEF
2928
    BYTEARRAY_REPLACE_METHODDEF
2929
    BYTEARRAY_REMOVEPREFIX_METHODDEF
2930
    BYTEARRAY_REMOVESUFFIX_METHODDEF
2931
    BYTEARRAY_RESIZE_METHODDEF
2932
    BYTEARRAY_REVERSE_METHODDEF
2933
    BYTEARRAY_RFIND_METHODDEF
2934
    BYTEARRAY_RINDEX_METHODDEF
2935
    {"rjust", _PyCFunction_CAST(bytearray_rjust), METH_FASTCALL,
2936
    stringlib_rjust__doc__},
2937
    BYTEARRAY_RPARTITION_METHODDEF
2938
    BYTEARRAY_RSPLIT_METHODDEF
2939
    BYTEARRAY_RSTRIP_METHODDEF
2940
    BYTEARRAY_SPLIT_METHODDEF
2941
    BYTEARRAY_SPLITLINES_METHODDEF
2942
    BYTEARRAY_STARTSWITH_METHODDEF
2943
    BYTEARRAY_STRIP_METHODDEF
2944
    {"swapcase", bytearray_swapcase, METH_NOARGS, _Py_swapcase__doc__},
2945
    BYTEARRAY_TAKE_BYTES_METHODDEF
2946
    {"title", bytearray_title, METH_NOARGS, _Py_title__doc__},
2947
    BYTEARRAY_TRANSLATE_METHODDEF
2948
    {"upper", bytearray_upper, METH_NOARGS, _Py_upper__doc__},
2949
    {"zfill", bytearray_zfill, METH_O, stringlib_zfill__doc__},
2950
    {NULL}
2951
};
2952
2953
static PyObject *
2954
bytearray_mod_lock_held(PyObject *v, PyObject *w)
2955
0
{
2956
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(v);
2957
0
    if (!PyByteArray_Check(v))
2958
0
        Py_RETURN_NOTIMPLEMENTED;
2959
2960
0
    PyByteArrayObject *self = _PyByteArray_CAST(v);
2961
    /* Increase exports to prevent bytearray storage from changing during op. */
2962
0
    self->ob_exports++;
2963
0
    PyObject *res = _PyBytes_FormatEx(
2964
0
        PyByteArray_AS_STRING(v), PyByteArray_GET_SIZE(v), w, 1
2965
0
    );
2966
0
    self->ob_exports--;
2967
0
    return res;
2968
0
}
2969
2970
static PyObject *
2971
bytearray_mod(PyObject *v, PyObject *w)
2972
0
{
2973
0
    PyObject *ret;
2974
0
    if (PyByteArray_Check(w)) {
2975
0
        Py_BEGIN_CRITICAL_SECTION2(v, w);
2976
0
        ret = bytearray_mod_lock_held(v, w);
2977
0
        Py_END_CRITICAL_SECTION2();
2978
0
    }
2979
0
    else {
2980
0
        Py_BEGIN_CRITICAL_SECTION(v);
2981
0
        ret = bytearray_mod_lock_held(v, w);
2982
0
        Py_END_CRITICAL_SECTION();
2983
0
    }
2984
0
    return ret;
2985
0
}
2986
2987
static PyNumberMethods bytearray_as_number = {
2988
    0,              /*nb_add*/
2989
    0,              /*nb_subtract*/
2990
    0,              /*nb_multiply*/
2991
    bytearray_mod,  /*nb_remainder*/
2992
};
2993
2994
PyDoc_STRVAR(bytearray_doc,
2995
"bytearray(iterable_of_ints) -> bytearray\n\
2996
bytearray(string, encoding[, errors]) -> bytearray\n\
2997
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
2998
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
2999
bytearray() -> empty bytes array\n\
3000
\n\
3001
Construct a mutable bytearray object from:\n\
3002
  - an iterable yielding integers in range(256)\n\
3003
  - a text string encoded using the specified encoding\n\
3004
  - a bytes or a buffer object\n\
3005
  - any object implementing the buffer API.\n\
3006
  - an integer");
3007
3008
3009
static PyObject *bytearray_iter(PyObject *seq);
3010
3011
PyTypeObject PyByteArray_Type = {
3012
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3013
    "bytearray",
3014
    sizeof(PyByteArrayObject),
3015
    0,
3016
    bytearray_dealloc,                  /* tp_dealloc */
3017
    0,                                  /* tp_vectorcall_offset */
3018
    0,                                  /* tp_getattr */
3019
    0,                                  /* tp_setattr */
3020
    0,                                  /* tp_as_async */
3021
    bytearray_repr,                     /* tp_repr */
3022
    &bytearray_as_number,               /* tp_as_number */
3023
    &bytearray_as_sequence,             /* tp_as_sequence */
3024
    &bytearray_as_mapping,              /* tp_as_mapping */
3025
    0,                                  /* tp_hash */
3026
    0,                                  /* tp_call */
3027
    bytearray_str,                      /* tp_str */
3028
    PyObject_GenericGetAttr,            /* tp_getattro */
3029
    0,                                  /* tp_setattro */
3030
    &bytearray_as_buffer,               /* tp_as_buffer */
3031
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3032
        _Py_TPFLAGS_MATCH_SELF,       /* tp_flags */
3033
    bytearray_doc,                      /* tp_doc */
3034
    0,                                  /* tp_traverse */
3035
    0,                                  /* tp_clear */
3036
    bytearray_richcompare,              /* tp_richcompare */
3037
    0,                                  /* tp_weaklistoffset */
3038
    bytearray_iter,                     /* tp_iter */
3039
    0,                                  /* tp_iternext */
3040
    bytearray_methods,                  /* tp_methods */
3041
    0,                                  /* tp_members */
3042
    0,                                  /* tp_getset */
3043
    0,                                  /* tp_base */
3044
    0,                                  /* tp_dict */
3045
    0,                                  /* tp_descr_get */
3046
    0,                                  /* tp_descr_set */
3047
    0,                                  /* tp_dictoffset */
3048
    bytearray___init__,                 /* tp_init */
3049
    PyType_GenericAlloc,                /* tp_alloc */
3050
    bytearray_new,                      /* tp_new */
3051
    PyObject_Free,                      /* tp_free */
3052
    .tp_vectorcall = bytearray_vectorcall,
3053
    .tp_version_tag = _Py_TYPE_VERSION_BYTEARRAY,
3054
};
3055
3056
/*********************** Bytearray Iterator ****************************/
3057
3058
typedef struct {
3059
    PyObject_HEAD
3060
    Py_ssize_t it_index;
3061
    PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
3062
} bytesiterobject;
3063
3064
37
#define _bytesiterobject_CAST(op)   ((bytesiterobject *)(op))
3065
3066
static void
3067
bytearrayiter_dealloc(PyObject *self)
3068
37
{
3069
37
    bytesiterobject *it = _bytesiterobject_CAST(self);
3070
37
    _PyObject_GC_UNTRACK(it);
3071
37
    Py_XDECREF(it->it_seq);
3072
37
    PyObject_GC_Del(it);
3073
37
}
3074
3075
static int
3076
bytearrayiter_traverse(PyObject *self, visitproc visit, void *arg)
3077
0
{
3078
0
    bytesiterobject *it = _bytesiterobject_CAST(self);
3079
0
    Py_VISIT(it->it_seq);
3080
0
    return 0;
3081
0
}
3082
3083
static PyObject *
3084
bytearrayiter_next(PyObject *self)
3085
0
{
3086
0
    bytesiterobject *it = _bytesiterobject_CAST(self);
3087
0
    int val;
3088
3089
0
    assert(it != NULL);
3090
0
    Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
3091
0
    if (index < 0) {
3092
0
        return NULL;
3093
0
    }
3094
0
    PyByteArrayObject *seq = it->it_seq;
3095
0
    assert(PyByteArray_Check(seq));
3096
3097
0
    Py_BEGIN_CRITICAL_SECTION(seq);
3098
0
    if (index < Py_SIZE(seq)) {
3099
0
        val = (unsigned char)PyByteArray_AS_STRING(seq)[index];
3100
0
    }
3101
0
    else {
3102
0
        val = -1;
3103
0
    }
3104
0
    Py_END_CRITICAL_SECTION();
3105
3106
0
    if (val == -1) {
3107
0
        FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, -1);
3108
0
#ifndef Py_GIL_DISABLED
3109
0
        Py_CLEAR(it->it_seq);
3110
0
#endif
3111
0
        return NULL;
3112
0
    }
3113
0
    FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index + 1);
3114
0
    return _PyLong_FromUnsignedChar((unsigned char)val);
3115
0
}
3116
3117
static PyObject *
3118
bytearrayiter_length_hint(PyObject *self, PyObject *Py_UNUSED(ignored))
3119
0
{
3120
0
    bytesiterobject *it = _bytesiterobject_CAST(self);
3121
0
    Py_ssize_t len = 0;
3122
0
    Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
3123
0
    if (index >= 0) {
3124
0
        len = PyByteArray_GET_SIZE(it->it_seq) - index;
3125
0
        if (len < 0) {
3126
0
            len = 0;
3127
0
        }
3128
0
    }
3129
0
    return PyLong_FromSsize_t(len);
3130
0
}
3131
3132
PyDoc_STRVAR(length_hint_doc,
3133
    "Private method returning an estimate of len(list(it)).");
3134
3135
static PyObject *
3136
bytearrayiter_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
3137
0
{
3138
0
    PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
3139
3140
    /* _PyEval_GetBuiltin can invoke arbitrary code,
3141
     * call must be before access of iterator pointers.
3142
     * see issue #101765 */
3143
0
    bytesiterobject *it = _bytesiterobject_CAST(self);
3144
0
    Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
3145
0
    if (index >= 0) {
3146
0
        return Py_BuildValue("N(O)n", iter, it->it_seq, index);
3147
0
    }
3148
0
    return Py_BuildValue("N(())", iter);
3149
0
}
3150
3151
static PyObject *
3152
bytearrayiter_setstate(PyObject *self, PyObject *state)
3153
0
{
3154
0
    Py_ssize_t index = PyLong_AsSsize_t(state);
3155
0
    if (index == -1 && PyErr_Occurred()) {
3156
0
        return NULL;
3157
0
    }
3158
3159
0
    bytesiterobject *it = _bytesiterobject_CAST(self);
3160
0
    if (FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index) >= 0) {
3161
0
        if (index < -1) {
3162
0
            index = -1;
3163
0
        }
3164
0
        else {
3165
0
            Py_ssize_t size = PyByteArray_GET_SIZE(it->it_seq);
3166
0
            if (index > size) {
3167
0
                index = size; /* iterator at end */
3168
0
            }
3169
0
        }
3170
0
        FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index);
3171
0
    }
3172
0
    Py_RETURN_NONE;
3173
0
}
3174
3175
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
3176
3177
static PyMethodDef bytearrayiter_methods[] = {
3178
    {"__length_hint__", bytearrayiter_length_hint, METH_NOARGS,
3179
     length_hint_doc},
3180
     {"__reduce__",     bytearrayiter_reduce, METH_NOARGS,
3181
     bytearray_reduce__doc__},
3182
    {"__setstate__",    bytearrayiter_setstate, METH_O,
3183
     setstate_doc},
3184
    {NULL, NULL} /* sentinel */
3185
};
3186
3187
PyTypeObject PyByteArrayIter_Type = {
3188
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3189
    "bytearray_iterator",              /* tp_name */
3190
    sizeof(bytesiterobject),           /* tp_basicsize */
3191
    0,                                 /* tp_itemsize */
3192
    /* methods */
3193
    bytearrayiter_dealloc,             /* tp_dealloc */
3194
    0,                                 /* tp_vectorcall_offset */
3195
    0,                                 /* tp_getattr */
3196
    0,                                 /* tp_setattr */
3197
    0,                                 /* tp_as_async */
3198
    0,                                 /* tp_repr */
3199
    0,                                 /* tp_as_number */
3200
    0,                                 /* tp_as_sequence */
3201
    0,                                 /* tp_as_mapping */
3202
    0,                                 /* tp_hash */
3203
    0,                                 /* tp_call */
3204
    0,                                 /* tp_str */
3205
    PyObject_GenericGetAttr,           /* tp_getattro */
3206
    0,                                 /* tp_setattro */
3207
    0,                                 /* tp_as_buffer */
3208
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
3209
    0,                                 /* tp_doc */
3210
    bytearrayiter_traverse,            /* tp_traverse */
3211
    0,                                 /* tp_clear */
3212
    0,                                 /* tp_richcompare */
3213
    0,                                 /* tp_weaklistoffset */
3214
    PyObject_SelfIter,                 /* tp_iter */
3215
    bytearrayiter_next,                /* tp_iternext */
3216
    bytearrayiter_methods,             /* tp_methods */
3217
    0,
3218
};
3219
3220
static PyObject *
3221
bytearray_iter(PyObject *seq)
3222
37
{
3223
37
    bytesiterobject *it;
3224
3225
37
    if (!PyByteArray_Check(seq)) {
3226
0
        PyErr_BadInternalCall();
3227
0
        return NULL;
3228
0
    }
3229
37
    it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
3230
37
    if (it == NULL)
3231
0
        return NULL;
3232
37
    it->it_index = 0;  // -1 indicates exhausted
3233
37
    it->it_seq = (PyByteArrayObject *)Py_NewRef(seq);
3234
37
    _PyObject_GC_TRACK(it);
3235
37
    return (PyObject *)it;
3236
37
}