Coverage Report

Created: 2026-10-31 06:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/bytesobject.c
Line
Count
Source
1
/* bytes object implementation */
2
3
#include "Python.h"
4
#include "pycore_abstract.h"      // _PyIndex_Check()
5
#include "pycore_bytes_methods.h" // _Py_bytes_startswith()
6
#include "pycore_bytesobject.h"   // _PyBytes_Find(), _PyBytes_RepeatBuffer()
7
#include "pycore_call.h"          // _PyObject_CallNoArgs()
8
#include "pycore_ceval.h"         // _PyEval_GetBuiltin()
9
#include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST()
10
#include "pycore_format.h"        // F_LJUST
11
#include "pycore_freelist.h"      // _Py_FREELIST_FREE()
12
#include "pycore_global_objects.h"// _Py_GET_GLOBAL_OBJECT()
13
#include "pycore_initconfig.h"    // _PyStatus_OK()
14
#include "pycore_long.h"          // _PyLong_DigitValue
15
#include "pycore_list.h"          // _PyList_GetItemRef
16
#include "pycore_object.h"        // _PyObject_GC_TRACK
17
#include "pycore_pymem.h"         // PYMEM_CLEANBYTE
18
#include "pycore_strhex.h"        // _Py_strhex_with_sep()
19
#include "pycore_unicodeobject.h" // _PyUnicode_FormatLong()
20
21
#include <stddef.h>
22
23
/*[clinic input]
24
class bytes "PyBytesObject *" "&PyBytes_Type"
25
[clinic start generated code]*/
26
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7a238f965d64892b]*/
27
28
#include "clinic/bytesobject.c.h"
29
30
336M
#define PyBytesObject_SIZE _PyBytesObject_SIZE
31
32
/* Forward declaration */
33
static void* _PyBytesWriter_ResizeAndUpdatePointer(PyBytesWriter *writer,
34
                                                   Py_ssize_t size, void *data);
35
static Py_ssize_t _PyBytesWriter_ResizeToAllocated(PyBytesWriter *writer);
36
37
38
26.9M
#define CHARACTERS _Py_SINGLETON(bytes_characters)
39
#define CHARACTER(ch) \
40
26.9M
     ((PyBytesObject *)&(CHARACTERS[ch]))
41
24.4M
#define EMPTY (&_Py_SINGLETON(bytes_empty))
42
43
44
// Return a reference to the immortal empty bytes string singleton.
45
static inline PyObject*
46
bytes_get_empty(void)
47
24.4M
{
48
24.4M
    PyObject *empty = &EMPTY->ob_base.ob_base;
49
24.4M
    assert(_Py_IsImmortal(empty));
50
24.4M
    return empty;
51
24.4M
}
52
53
54
// The function cannot fail
55
static inline PyObject*
56
bytes_get_char(uint8_t ch)
57
26.9M
{
58
26.9M
    PyObject *obj = (PyObject*)CHARACTER(ch);
59
26.9M
    assert(_Py_IsImmortal(obj));
60
26.9M
    return obj;
61
26.9M
}
62
63
64
static inline void
65
set_ob_shash(PyBytesObject *a, Py_hash_t hash)
66
43.0M
{
67
43.0M
_Py_COMP_DIAG_PUSH
68
43.0M
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
69
#ifdef Py_GIL_DISABLED
70
    _Py_atomic_store_ssize_relaxed(&a->ob_shash, hash);
71
#else
72
43.0M
    a->ob_shash = hash;
73
43.0M
#endif
74
43.0M
_Py_COMP_DIAG_POP
75
43.0M
}
76
77
// Similar to set_ob_shash() but don't use an atomic operation on Free
78
// Threading. This function must only be used on newly allocated bytes objects.
79
static inline void
80
set_ob_shash_unsafe(PyBytesObject *a, Py_hash_t hash)
81
158M
{
82
    // Don't test _PyObject_IsUniquelyReferenced(), so the function can be
83
    // called by bytes_resize_inplace().
84
158M
    assert(Py_REFCNT(a) == 1);
85
86
158M
_Py_COMP_DIAG_PUSH
87
158M
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
88
158M
    a->ob_shash = hash;
89
158M
_Py_COMP_DIAG_POP
90
158M
}
91
92
75.4M
#define get_ob_shash(op) _PyBytes_GET_CACHED_HASH(op)
93
94
95
/*
96
   For PyBytes_FromString(), the parameter 'str' points to a null-terminated
97
   string containing exactly 'size' bytes.
98
99
   For PyBytes_FromStringAndSize(), the parameter 'str' is
100
   either NULL or else points to a string containing at least 'size' bytes.
101
   For PyBytes_FromStringAndSize(), the string in the 'str' parameter does
102
   not have to be null-terminated.  (Therefore it is safe to construct a
103
   substring by calling 'PyBytes_FromStringAndSize(origstring, substrlen)'.)
104
   If 'str' is NULL then PyBytes_FromStringAndSize() will allocate 'size+1'
105
   bytes (setting the last byte to the null terminating character) and you can
106
   fill in the data yourself.  If 'str' is non-NULL then the resulting
107
   PyBytes object must be treated as immutable and you must not fill in nor
108
   alter the data yourself, since the strings may be shared.
109
110
   The PyObject member 'op->ob_size', which denotes the number of "extra
111
   items" in a variable-size object, will contain the number of bytes
112
   allocated for string data, not counting the null terminating character.
113
   It is therefore equal to the 'size' parameter (for
114
   PyBytes_FromStringAndSize()) or the length of the string in the 'str'
115
   parameter (for PyBytes_FromString()).
116
*/
117
118
// Allocate a new bytes object with contents left uninitialized. The caller is
119
// responsible to fill the contents. size must be greater than 0.
120
static PyObject *
121
bytes_alloc(Py_ssize_t size)
122
158M
{
123
158M
    assert(size >= 1);
124
125
158M
    if ((size_t)size > (size_t)PY_SSIZE_T_MAX - PyBytesObject_SIZE) {
126
0
        PyErr_SetString(PyExc_OverflowError,
127
0
                        "byte string is too large");
128
0
        return NULL;
129
0
    }
130
158M
    size_t alloc = PyBytesObject_SIZE + size;
131
132
    /* Inline PyObject_NewVar */
133
158M
    PyBytesObject *op = (PyBytesObject *)PyObject_Malloc(alloc);
134
158M
    if (op == NULL) {
135
0
        return PyErr_NoMemory();
136
0
    }
137
138
158M
    _PyObject_InitVar(_PyVarObject_CAST(op), &PyBytes_Type, size);
139
158M
    set_ob_shash_unsafe(op, -1);
140
158M
    op->ob_sval[size] = '\0';
141
158M
    return (PyObject *) op;
142
158M
}
143
144
// Create a new bytes object with contents initialized to zero. size can be 0.
145
static PyObject *
146
_PyBytes_FromSizeZero(Py_ssize_t size)
147
0
{
148
0
    PyBytesObject *op;
149
0
    assert(size >= 0);
150
151
0
    if (size == 0) {
152
0
        return bytes_get_empty();
153
0
    }
154
155
0
    if ((size_t)size > (size_t)PY_SSIZE_T_MAX - PyBytesObject_SIZE) {
156
0
        PyErr_SetString(PyExc_OverflowError,
157
0
                        "byte string is too large");
158
0
        return NULL;
159
0
    }
160
0
    size_t alloc = PyBytesObject_SIZE + size;
161
162
    /* Inline PyObject_NewVar */
163
0
    op = (PyBytesObject *)PyObject_Calloc(1, alloc);
164
0
    if (op == NULL) {
165
0
        return PyErr_NoMemory();
166
0
    }
167
0
    _PyObject_InitVar((PyVarObject*)op, &PyBytes_Type, size);
168
0
    set_ob_shash_unsafe(op, -1);
169
    // op->ob_sval[size] is equal to '\0'
170
0
    return (PyObject *) op;
171
0
}
172
173
// Similar to PyBytes_FromStringAndSize(), but str must not be NULL.
174
static PyObject *
175
_PyBytes_FromStringAndSize(const char *str, Py_ssize_t size)
176
138M
{
177
138M
    assert(str != NULL);
178
138M
    assert(size >= 0);
179
180
138M
    if (size == 0) {
181
12.5M
        return bytes_get_empty();
182
12.5M
    }
183
126M
    if (size == 1) {
184
19.1M
        return bytes_get_char((uint8_t)str[0]);
185
19.1M
    }
186
187
107M
    PyBytesObject *op = (PyBytesObject *)bytes_alloc(size);
188
107M
    if (op == NULL) {
189
0
        return NULL;
190
0
    }
191
107M
    memcpy(op->ob_sval, str, size);
192
107M
    return (PyObject *) op;
193
107M
}
194
195
PyObject *
196
PyBytes_FromStringAndSize(const char *str, Py_ssize_t size)
197
108M
{
198
108M
    if (size < 0) {
199
0
        PyErr_SetString(PyExc_SystemError,
200
0
            "Negative size passed to PyBytes_FromStringAndSize");
201
0
        return NULL;
202
0
    }
203
204
108M
    if (str != NULL) {
205
86.2M
        return _PyBytes_FromStringAndSize(str, size);
206
86.2M
    }
207
22.0M
    else {
208
22.0M
        if (size == 0) {
209
11.8M
            return bytes_get_empty();
210
11.8M
        }
211
10.2M
        return bytes_alloc(size);
212
22.0M
    }
213
108M
}
214
215
PyObject *
216
PyBytes_FromString(const char *str)
217
96
{
218
96
    assert(str != NULL);
219
96
    size_t size = strlen(str);
220
96
    if (size == 0) {
221
0
        return bytes_get_empty();
222
0
    }
223
96
    if (size == 1) {
224
0
        return bytes_get_char((uint8_t)str[0]);
225
0
    }
226
227
96
    PyBytesObject *op = (PyBytesObject *)bytes_alloc(size);
228
96
    if (op == NULL) {
229
0
        return PyErr_NoMemory();
230
0
    }
231
96
    memcpy(op->ob_sval, str, size+1);
232
96
    return (PyObject *) op;
233
96
}
234
235
236
static char*
237
bytes_fromformat(PyBytesWriter *writer, Py_ssize_t writer_pos,
238
                 const char *format, va_list vargs)
239
0
{
240
    /* Longest 64-bit formatted numbers:
241
       - "18446744073709551615\0" (21 bytes)
242
       - "-9223372036854775808\0" (21 bytes)
243
       Decimal takes the most space (it isn't enough for octal.)
244
245
       Longest 64-bit pointer representation:
246
       "0xffffffffffffffff\0" (19 bytes).
247
248
       Longest 64-bit "%p" with "0x" prefix: len(hex(2**64-1)+'\0') = 19.
249
    */
250
0
    char buffer[21];
251
252
0
    char *s = (char*)PyBytesWriter_GetData(writer) + writer_pos;
253
254
0
#define WRITE_BYTES(str, len_expr) \
255
0
    do { \
256
0
        size_t _len = (len_expr); \
257
0
        size_t _prealloc = (f - p + 1); \
258
0
        if (_len > _prealloc) { \
259
0
            s = PyBytesWriter_GrowAndUpdatePointer(writer, _len - _prealloc, s); \
260
0
            if (s == NULL) { \
261
0
                return NULL; \
262
0
            } \
263
0
        } \
264
0
        memcpy(s, (str), _len); \
265
0
        s += _len; \
266
0
    } while (0)
267
268
0
    for (const char *f = format; *f; f++) {
269
0
        if (*f != '%') {
270
0
            *s++ = *f;
271
0
            continue;
272
0
        }
273
274
0
        const char *p = f++;
275
276
        /* ignore the width (ex: 10 in "%10s") */
277
0
        while (Py_ISDIGIT(*f))
278
0
            f++;
279
280
        /* parse the precision (ex: 10 in "%.10s") */
281
0
        Py_ssize_t prec = 0;
282
0
        if (*f == '.') {
283
0
            f++;
284
0
            for (; Py_ISDIGIT(*f); f++) {
285
0
                prec = (prec * 10) + (*f - '0');
286
0
            }
287
0
        }
288
0
        assert(prec >= 0);
289
290
0
        while (*f && *f != '%' && !Py_ISALPHA(*f)) {
291
0
            f++;
292
0
        }
293
294
        /* handle the long flag ('l'), but only for %ld and %lu.
295
           others can be added when necessary. */
296
0
        int longflag = 0;
297
0
        if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
298
0
            longflag = 1;
299
0
            ++f;
300
0
        }
301
302
        /* handle the size_t flag ('z'). */
303
0
        int size_tflag = 0;
304
0
        if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
305
0
            size_tflag = 1;
306
0
            ++f;
307
0
        }
308
309
0
        Py_ssize_t len;
310
311
0
        switch (*f) {
312
0
        case 'c':
313
0
        {
314
0
            int c = va_arg(vargs, int);
315
0
            if (c < 0 || c > 255) {
316
0
                PyErr_SetString(PyExc_OverflowError,
317
0
                                "PyBytes_FromFormatV(): %c format "
318
0
                                "expects an integer in range [0; 255]");
319
0
                return NULL;
320
0
            }
321
0
            *s++ = (unsigned char)c;
322
0
            break;
323
0
        }
324
325
0
        case 'd':
326
0
            if (longflag) {
327
0
                len = sprintf(buffer, "%ld", va_arg(vargs, long));
328
0
            }
329
0
            else if (size_tflag) {
330
0
                len = sprintf(buffer, "%zd", va_arg(vargs, Py_ssize_t));
331
0
            }
332
0
            else {
333
0
                len = sprintf(buffer, "%d", va_arg(vargs, int));
334
0
            }
335
0
            assert(1 <= len && len < (Py_ssize_t)sizeof(buffer));
336
0
            WRITE_BYTES(buffer, len);
337
0
            break;
338
339
0
        case 'u':
340
0
            if (longflag) {
341
0
                len = sprintf(buffer, "%lu", va_arg(vargs, unsigned long));
342
0
            }
343
0
            else if (size_tflag) {
344
0
                len = sprintf(buffer, "%zu", va_arg(vargs, size_t));
345
0
            }
346
0
            else {
347
0
                len = sprintf(buffer, "%u", va_arg(vargs, unsigned int));
348
0
            }
349
0
            assert(1 <= len && len < (Py_ssize_t)sizeof(buffer));
350
0
            WRITE_BYTES(buffer, len);
351
0
            break;
352
353
0
        case 'i':
354
0
            len = sprintf(buffer, "%i", va_arg(vargs, int));
355
0
            assert(1 <= len && len < (Py_ssize_t)sizeof(buffer));
356
0
            WRITE_BYTES(buffer, len);
357
0
            break;
358
359
0
        case 'x':
360
0
            len = sprintf(buffer, "%x", va_arg(vargs, int));
361
0
            assert(1 <= len && len < (Py_ssize_t)sizeof(buffer));
362
0
            WRITE_BYTES(buffer, len);
363
0
            break;
364
365
0
        case 's':
366
0
        {
367
0
            const char *str = va_arg(vargs, const char*);
368
0
            if (prec == 0) {
369
0
                len = strlen(str);
370
0
            }
371
0
            else {
372
0
                const char *end = memchr(str, 0, prec);
373
0
                if (end != NULL) {
374
0
                    len = (end - str);
375
0
                }
376
0
                else {
377
0
                    len = (size_t)prec;
378
0
                }
379
0
            }
380
0
            WRITE_BYTES(str, len);
381
0
            break;
382
0
        }
383
384
0
        case 'p':
385
0
            len = sprintf(buffer, "%p", va_arg(vargs, void*));
386
0
            assert(1 <= len && len < (Py_ssize_t)sizeof(buffer));
387
            /* %p is ill-defined:  ensure leading 0x. */
388
0
            if (buffer[1] == 'X') {
389
0
                buffer[1] = 'x';
390
0
            }
391
0
            else if (buffer[1] != 'x') {
392
0
                memmove(buffer + 2, buffer, len + 1);
393
0
                buffer[0] = '0';
394
0
                buffer[1] = 'x';
395
0
                len += 2;
396
0
            }
397
0
            WRITE_BYTES(buffer, len);
398
0
            break;
399
400
0
        case '%':
401
0
            *s++ = '%';
402
0
            break;
403
404
0
        default:
405
            // Invalid format string: copy unformatted string and exit.
406
            // No need to grow the writer buffer, we already preallocated
407
            // enough bytes.
408
0
            len = strlen(p);
409
0
            memcpy(s, p, len);
410
0
            s += len;
411
0
            return s;
412
0
        }
413
0
    }
414
415
0
    return s;
416
417
0
#undef WRITE_BYTES
418
0
}
419
420
421
PyObject *
422
PyBytes_FromFormatV(const char *format, va_list vargs)
423
0
{
424
0
    Py_ssize_t alloc = strlen(format);
425
0
    PyBytesWriter *writer = PyBytesWriter_Create(alloc);
426
0
    if (writer == NULL) {
427
0
        return NULL;
428
0
    }
429
430
0
    char *s = bytes_fromformat(writer, 0, format, vargs);
431
0
    if (s == NULL) {
432
0
        PyBytesWriter_Discard(writer);
433
0
        return NULL;
434
0
    }
435
436
0
    return PyBytesWriter_FinishWithPointer(writer, s);
437
0
}
438
439
440
PyObject *
441
PyBytes_FromFormat(const char *format, ...)
442
0
{
443
0
    PyObject* ret;
444
0
    va_list vargs;
445
446
0
    va_start(vargs, format);
447
0
    ret = PyBytes_FromFormatV(format, vargs);
448
0
    va_end(vargs);
449
0
    return ret;
450
0
}
451
452
453
/* Helpers for formatstring */
454
455
0
#define FORMAT_ERROR(EXC, FMT, ...) do {                                    \
456
0
    if (key != NULL) {                                                      \
457
0
        PyErr_Format((EXC), "format argument %R: " FMT,                     \
458
0
                     key, __VA_ARGS__);                                     \
459
0
    }                                                                       \
460
0
    else if (argidx >= 0) {                                                 \
461
0
        PyErr_Format((EXC), "format argument %zd: " FMT,                    \
462
0
                     argidx, __VA_ARGS__);                                  \
463
0
    }                                                                       \
464
0
    else {                                                                  \
465
0
        PyErr_Format((EXC), "format argument: " FMT, __VA_ARGS__);          \
466
0
    }                                                                       \
467
0
} while (0)
468
469
Py_LOCAL_INLINE(PyObject *)
470
getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx, int allowone)
471
0
{
472
0
    Py_ssize_t argidx = *p_argidx;
473
0
    if (argidx < arglen) {
474
0
        (*p_argidx)++;
475
0
        if (arglen >= 0) {
476
0
            return PyTuple_GetItem(args, argidx);
477
0
        }
478
0
        else if (allowone) {
479
0
            return args;
480
0
        }
481
0
    }
482
0
    PyErr_Format(PyExc_TypeError,
483
0
                 "not enough arguments for format string (got %zd)",
484
0
                 arglen < 0 ? 1 : arglen);
485
0
    return NULL;
486
0
}
487
488
/* Returns a new reference to a PyBytes object, or NULL on failure. */
489
490
static char*
491
formatfloat(PyObject *v, Py_ssize_t argidx, PyObject *key,
492
            int flags, int prec, int type,
493
            PyObject **p_result, PyBytesWriter *writer, char *str)
494
0
{
495
0
    char *p;
496
0
    PyObject *result;
497
0
    double x;
498
0
    size_t len;
499
0
    int dtoa_flags = 0;
500
501
0
    x = PyFloat_AsDouble(v);
502
0
    if (x == -1.0 && PyErr_Occurred()) {
503
0
        if (PyErr_ExceptionMatches(PyExc_TypeError)) {
504
0
            FORMAT_ERROR(PyExc_TypeError,
505
0
                         "%%%c requires a real number, not %T",
506
0
                         type, v);
507
0
        }
508
0
        return NULL;
509
0
    }
510
511
0
    if (prec < 0)
512
0
        prec = 6;
513
514
0
    if (flags & F_ALT) {
515
0
        dtoa_flags |= Py_DTSF_ALT;
516
0
    }
517
0
    p = PyOS_double_to_string(x, type, prec, dtoa_flags, NULL);
518
519
0
    if (p == NULL)
520
0
        return NULL;
521
522
0
    len = strlen(p);
523
0
    if (writer != NULL) {
524
0
        str = PyBytesWriter_GrowAndUpdatePointer(writer, len, str);
525
0
        if (str == NULL) {
526
0
            PyMem_Free(p);
527
0
            return NULL;
528
0
        }
529
0
        memcpy(str, p, len);
530
0
        PyMem_Free(p);
531
0
        str += len;
532
0
        return str;
533
0
    }
534
535
0
    result = _PyBytes_FromStringAndSize(p, len);
536
0
    PyMem_Free(p);
537
0
    *p_result = result;
538
0
    return result != NULL ? str : NULL;
539
0
}
540
541
static PyObject *
542
formatlong(PyObject *v, Py_ssize_t argidx, PyObject *key,
543
           int flags, int prec, int type)
544
0
{
545
0
    PyObject *result, *iobj;
546
0
    if (PyLong_Check(v))
547
0
        return _PyUnicode_FormatLong(v, flags & F_ALT, prec, type);
548
0
    if (PyNumber_Check(v)) {
549
        /* make sure number is a type of integer for o, x, and X */
550
0
        if (type == 'o' || type == 'x' || type == 'X')
551
0
            iobj = _PyNumber_Index(v);
552
0
        else
553
0
            iobj = PyNumber_Long(v);
554
0
        if (iobj != NULL) {
555
0
            assert(PyLong_Check(iobj));
556
0
            result = _PyUnicode_FormatLong(iobj, flags & F_ALT, prec, type);
557
0
            Py_DECREF(iobj);
558
0
            return result;
559
0
        }
560
0
        if (!PyErr_ExceptionMatches(PyExc_TypeError))
561
0
            return NULL;
562
0
    }
563
0
    FORMAT_ERROR(PyExc_TypeError,
564
0
                 "%%%c requires %s, not %T",
565
0
                 type,
566
0
                 (type == 'o' || type == 'x' || type == 'X') ? "an integer"
567
0
                                                             : "a real number",
568
0
                 v);
569
0
    return NULL;
570
0
}
571
572
static int
573
byte_converter(PyObject *arg, Py_ssize_t argidx, PyObject *key, char *p)
574
0
{
575
0
    if (PyBytes_Check(arg)) {
576
0
        if (PyBytes_GET_SIZE(arg) != 1) {
577
0
            FORMAT_ERROR(PyExc_TypeError,
578
0
                         "%%c requires an integer in range(256) or "
579
0
                         "a single byte, not a bytes object of length %zd",
580
0
                         PyBytes_GET_SIZE(arg));
581
0
            return 0;
582
0
        }
583
0
        *p = PyBytes_AS_STRING(arg)[0];
584
0
        return 1;
585
0
    }
586
0
    else if (PyByteArray_Check(arg)) {
587
0
        if (PyByteArray_GET_SIZE(arg) != 1) {
588
0
            FORMAT_ERROR(PyExc_TypeError,
589
0
                         "%%c requires an integer in range(256) or "
590
0
                         "a single byte, not a bytearray object of length %zd",
591
0
                         PyByteArray_GET_SIZE(arg));
592
0
            return 0;
593
0
        }
594
0
        *p = PyByteArray_AS_STRING(arg)[0];
595
0
        return 1;
596
0
    }
597
0
    else if (PyIndex_Check(arg)) {
598
0
        int overflow;
599
0
        long ival = PyLong_AsLongAndOverflow(arg, &overflow);
600
0
        if (ival == -1 && PyErr_Occurred()) {
601
0
            return 0;
602
0
        }
603
0
        if (!(0 <= ival && ival <= 255)) {
604
            /* this includes an overflow in converting to C long */
605
0
            FORMAT_ERROR(PyExc_OverflowError,
606
0
                         "%%c argument not in range(256)%s", "");
607
0
            return 0;
608
0
        }
609
0
        *p = (char)ival;
610
0
        return 1;
611
0
    }
612
0
    FORMAT_ERROR(PyExc_TypeError,
613
0
                 "%%c requires an integer in range(256) or "
614
0
                 "a single byte, not %T",
615
0
                 arg);
616
0
    return 0;
617
0
}
618
619
static PyObject *_PyBytes_FromBuffer(PyObject *x);
620
621
static PyObject *
622
format_obj(PyObject *v, Py_ssize_t argidx, PyObject *key,
623
           const char **pbuf, Py_ssize_t *plen)
624
0
{
625
0
    PyObject *func, *result;
626
    /* is it a bytes object? */
627
0
    if (PyBytes_Check(v)) {
628
0
        *pbuf = PyBytes_AS_STRING(v);
629
0
        *plen = PyBytes_GET_SIZE(v);
630
0
        return Py_NewRef(v);
631
0
    }
632
0
    if (PyByteArray_Check(v)) {
633
0
        *pbuf = PyByteArray_AS_STRING(v);
634
0
        *plen = PyByteArray_GET_SIZE(v);
635
0
        return Py_NewRef(v);
636
0
    }
637
    /* does it support __bytes__? */
638
0
    func = _PyObject_LookupSpecial(v, &_Py_ID(__bytes__));
639
0
    if (func != NULL) {
640
0
        result = _PyObject_CallNoArgs(func);
641
0
        Py_DECREF(func);
642
0
        if (result == NULL)
643
0
            return NULL;
644
0
        if (!PyBytes_Check(result)) {
645
0
            PyErr_Format(PyExc_TypeError,
646
0
                         "%T.__bytes__() must return a bytes, not %T",
647
0
                         v, result);
648
0
            Py_DECREF(result);
649
0
            return NULL;
650
0
        }
651
0
        *pbuf = PyBytes_AS_STRING(result);
652
0
        *plen = PyBytes_GET_SIZE(result);
653
0
        return result;
654
0
    }
655
0
    else if (PyErr_Occurred()) {
656
0
        return NULL;
657
0
    }
658
    /* does it support buffer protocol? */
659
0
    if (PyObject_CheckBuffer(v)) {
660
        /* maybe we can avoid making a copy of the buffer object here? */
661
0
        result = _PyBytes_FromBuffer(v);
662
0
        if (result == NULL)
663
0
            return NULL;
664
0
        *pbuf = PyBytes_AS_STRING(result);
665
0
        *plen = PyBytes_GET_SIZE(result);
666
0
        return result;
667
0
    }
668
0
    FORMAT_ERROR(PyExc_TypeError,
669
0
                 "%%b requires a bytes-like object, "
670
0
                 "or an object that implements __bytes__, not %T",
671
0
                 v);
672
0
    return NULL;
673
0
}
674
675
/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...) */
676
677
PyObject *
678
_PyBytes_FormatEx(const char *format, Py_ssize_t format_len,
679
                  PyObject *args, int use_bytearray)
680
0
{
681
0
    const char *fmt;
682
0
    Py_ssize_t arglen, argidx;
683
0
    Py_ssize_t fmtcnt;
684
0
    int args_owned = 0;
685
0
    PyObject *dict = NULL;
686
0
    PyObject *key = NULL;
687
688
0
    if (args == NULL) {
689
0
        PyErr_BadInternalCall();
690
0
        return NULL;
691
0
    }
692
0
    fmt = format;
693
0
    fmtcnt = format_len;
694
695
0
    PyBytesWriter *writer;
696
0
    if (use_bytearray) {
697
0
        writer = _PyBytesWriter_CreateByteArray(fmtcnt);
698
0
    }
699
0
    else {
700
0
        writer = PyBytesWriter_Create(fmtcnt);
701
0
    }
702
0
    if (writer == NULL) {
703
0
        return NULL;
704
0
    }
705
0
    char *res = PyBytesWriter_GetData(writer);
706
707
0
    if (PyTuple_Check(args)) {
708
0
        arglen = PyTuple_GET_SIZE(args);
709
0
        argidx = 0;
710
0
    }
711
0
    else {
712
0
        arglen = -1;
713
0
        argidx = -2;
714
0
    }
715
0
    if (Py_TYPE(args)->tp_as_mapping && Py_TYPE(args)->tp_as_mapping->mp_subscript &&
716
0
        !PyTuple_Check(args) && !PyBytes_Check(args) && !PyUnicode_Check(args) &&
717
0
        !PyByteArray_Check(args)) {
718
0
            dict = args;
719
0
    }
720
721
0
    while (--fmtcnt >= 0) {
722
0
        if (*fmt != '%') {
723
0
            Py_ssize_t len;
724
0
            char *pos;
725
726
0
            pos = (char *)memchr(fmt + 1, '%', fmtcnt);
727
0
            if (pos != NULL)
728
0
                len = pos - fmt;
729
0
            else
730
0
                len = fmtcnt + 1;
731
0
            assert(len != 0);
732
733
0
            memcpy(res, fmt, len);
734
0
            res += len;
735
0
            fmt += len;
736
0
            fmtcnt -= (len - 1);
737
0
        }
738
0
        else {
739
            /* Got a format specifier */
740
0
            int flags = 0;
741
0
            Py_ssize_t width = -1;
742
0
            int prec = -1;
743
0
            int c = '\0';
744
0
            int fill;
745
0
            PyObject *v = NULL;
746
0
            PyObject *temp = NULL;
747
0
            const char *pbuf = NULL;
748
0
            int sign;
749
0
            Py_ssize_t len = 0;
750
0
            char onechar; /* For byte_converter() */
751
0
            Py_ssize_t alloc;
752
753
0
            const char *start = fmt;
754
0
            fmt++;
755
0
            if (*fmt == '%') {
756
0
                *res++ = '%';
757
0
                fmt++;
758
0
                fmtcnt--;
759
0
                continue;
760
0
            }
761
0
            Py_CLEAR(key);
762
0
            const char *fmtstart = fmt;
763
0
            if (*fmt == '(') {
764
0
                const char *keystart;
765
0
                Py_ssize_t keylen;
766
0
                int pcount = 1;
767
768
0
                if (dict == NULL) {
769
0
                    PyErr_Format(PyExc_TypeError,
770
0
                                 "format requires a mapping, not %T",
771
0
                                 args);
772
0
                    goto error;
773
0
                }
774
0
                ++fmt;
775
0
                --fmtcnt;
776
0
                keystart = fmt;
777
                /* Skip over balanced parentheses */
778
0
                while (pcount > 0 && --fmtcnt >= 0) {
779
0
                    if (*fmt == ')')
780
0
                        --pcount;
781
0
                    else if (*fmt == '(')
782
0
                        ++pcount;
783
0
                    fmt++;
784
0
                }
785
0
                keylen = fmt - keystart - 1;
786
0
                if (fmtcnt < 0 || pcount > 0) {
787
0
                    PyErr_Format(PyExc_ValueError,
788
0
                                 "stray %% or incomplete format key "
789
0
                                 "at position %zd",
790
0
                                 (Py_ssize_t)(fmtstart - format - 1));
791
0
                    goto error;
792
0
                }
793
0
                key = _PyBytes_FromStringAndSize(keystart, keylen);
794
0
                if (key == NULL)
795
0
                    goto error;
796
0
                if (args_owned) {
797
0
                    Py_DECREF(args);
798
0
                    args_owned = 0;
799
0
                }
800
0
                args = PyObject_GetItem(dict, key);
801
0
                if (args == NULL) {
802
0
                    goto error;
803
0
                }
804
0
                args_owned = 1;
805
0
                arglen = -3;
806
0
                argidx = -4;
807
0
            }
808
0
            else {
809
0
                if (arglen < -1) {
810
0
                    PyErr_Format(PyExc_ValueError,
811
0
                                 "format requires a parenthesised mapping key "
812
0
                                 "at position %zd",
813
0
                                 (Py_ssize_t)(fmtstart - format - 1));
814
0
                    goto error;
815
0
                }
816
0
            }
817
818
            /* Parse flags. Example: "%+i" => flags=F_SIGN. */
819
0
            while (--fmtcnt >= 0) {
820
0
                switch (c = *fmt++) {
821
0
                case '-': flags |= F_LJUST; continue;
822
0
                case '+': flags |= F_SIGN; continue;
823
0
                case ' ': flags |= F_BLANK; continue;
824
0
                case '#': flags |= F_ALT; continue;
825
0
                case '0': flags |= F_ZERO; continue;
826
0
                }
827
0
                break;
828
0
            }
829
830
            /* Parse width. Example: "%10s" => width=10 */
831
0
            if (c == '*') {
832
0
                if (arglen < -1) {
833
0
                    PyErr_Format(PyExc_ValueError,
834
0
                            "* cannot be used with a parenthesised mapping key "
835
0
                            "at position %zd",
836
0
                            (Py_ssize_t)(fmtstart - format - 1));
837
0
                    goto error;
838
0
                }
839
0
                v = getnextarg(args, arglen, &argidx, 0);
840
0
                if (v == NULL)
841
0
                    goto error;
842
0
                if (!PyLong_Check(v)) {
843
0
                    FORMAT_ERROR(PyExc_TypeError, "* requires int, not %T", v);
844
0
                    goto error;
845
0
                }
846
0
                width = PyLong_AsSsize_t(v);
847
0
                if (width == -1 && PyErr_Occurred()) {
848
0
                    if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
849
0
                        FORMAT_ERROR(PyExc_OverflowError,
850
0
                                     "too big for width%s", "");
851
0
                    }
852
0
                    goto error;
853
0
                }
854
0
                if (width < 0) {
855
0
                    if (width == PY_SSIZE_T_MIN) {
856
0
                        FORMAT_ERROR(PyExc_OverflowError, "too big for width%s", "");
857
0
                        goto error;
858
0
                    }
859
0
                    flags |= F_LJUST;
860
0
                    width = -width;
861
0
                }
862
0
                if (--fmtcnt >= 0)
863
0
                    c = *fmt++;
864
0
            }
865
0
            else if (c >= 0 && Py_ISDIGIT(c)) {
866
0
                width = c - '0';
867
0
                while (--fmtcnt >= 0) {
868
0
                    c = Py_CHARMASK(*fmt++);
869
0
                    if (!Py_ISDIGIT(c))
870
0
                        break;
871
0
                    if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
872
0
                        PyErr_Format(PyExc_ValueError,
873
0
                                     "width too big at position %zd",
874
0
                                     (Py_ssize_t)(fmtstart - format - 1));
875
0
                        goto error;
876
0
                    }
877
0
                    width = width*10 + (c - '0');
878
0
                }
879
0
            }
880
881
            /* Parse precision. Example: "%.3f" => prec=3 */
882
0
            if (c == '.') {
883
0
                prec = 0;
884
0
                if (--fmtcnt >= 0)
885
0
                    c = *fmt++;
886
0
                if (c == '*') {
887
0
                    if (arglen < -1) {
888
0
                        PyErr_Format(PyExc_ValueError,
889
0
                                "* cannot be used with a parenthesised mapping key "
890
0
                                "at position %zd",
891
0
                                (Py_ssize_t)(fmtstart - format - 1));
892
0
                        goto error;
893
0
                    }
894
0
                    v = getnextarg(args, arglen, &argidx, 0);
895
0
                    if (v == NULL)
896
0
                        goto error;
897
0
                    if (!PyLong_Check(v)) {
898
0
                        FORMAT_ERROR(PyExc_TypeError,
899
0
                                     "* requires int, not %T", v);
900
0
                        goto error;
901
0
                    }
902
0
                    prec = PyLong_AsInt(v);
903
0
                    if (prec == -1 && PyErr_Occurred()) {
904
0
                        if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
905
0
                            FORMAT_ERROR(PyExc_OverflowError,
906
0
                                         "too big for precision%s", "");
907
0
                        }
908
0
                        goto error;
909
0
                    }
910
0
                    if (prec < 0)
911
0
                        prec = 0;
912
0
                    if (--fmtcnt >= 0)
913
0
                        c = *fmt++;
914
0
                }
915
0
                else if (c >= 0 && Py_ISDIGIT(c)) {
916
0
                    prec = c - '0';
917
0
                    while (--fmtcnt >= 0) {
918
0
                        c = Py_CHARMASK(*fmt++);
919
0
                        if (!Py_ISDIGIT(c))
920
0
                            break;
921
0
                        if (prec > (INT_MAX - ((int)c - '0')) / 10) {
922
0
                            PyErr_Format(PyExc_ValueError,
923
0
                                "precision too big at position %zd",
924
0
                                (Py_ssize_t)(fmtstart - format - 1));
925
0
                            goto error;
926
0
                        }
927
0
                        prec = prec*10 + (c - '0');
928
0
                    }
929
0
                }
930
0
            } /* prec */
931
0
            if (fmtcnt >= 0) {
932
0
                if (c == 'h' || c == 'l' || c == 'L') {
933
0
                    if (--fmtcnt >= 0)
934
0
                        c = *fmt++;
935
0
                }
936
0
            }
937
0
            if (fmtcnt < 0) {
938
0
                PyErr_Format(PyExc_ValueError,
939
0
                             "stray %% at position %zd",
940
0
                             (Py_ssize_t)(fmtstart - format - 1));
941
0
                goto error;
942
0
            }
943
0
            v = getnextarg(args, arglen, &argidx, 1);
944
0
            if (v == NULL)
945
0
                goto error;
946
947
0
            if (fmtcnt == 0) {
948
                /* last write: disable writer overallocation */
949
0
                writer->overallocate = 0;
950
0
            }
951
952
0
            sign = 0;
953
0
            fill = ' ';
954
0
            switch (c) {
955
0
            case 'r':
956
                // %r is only for 2/3 code; 3 only code should use %a
957
0
            case 'a':
958
0
                temp = PyObject_ASCII(v);
959
0
                if (temp == NULL)
960
0
                    goto error;
961
0
                assert(PyUnicode_IS_ASCII(temp));
962
0
                pbuf = (const char *)PyUnicode_1BYTE_DATA(temp);
963
0
                len = PyUnicode_GET_LENGTH(temp);
964
0
                if (prec >= 0 && len > prec)
965
0
                    len = prec;
966
0
                break;
967
968
0
            case 's':
969
                // %s is only for 2/3 code; 3 only code should use %b
970
0
            case 'b':
971
0
                temp = format_obj(v, argidx, key, &pbuf, &len);
972
0
                if (temp == NULL)
973
0
                    goto error;
974
0
                if (prec >= 0 && len > prec)
975
0
                    len = prec;
976
0
                break;
977
978
0
            case 'i':
979
0
            case 'd':
980
0
            case 'u':
981
0
            case 'o':
982
0
            case 'x':
983
0
            case 'X':
984
0
                if (PyLong_CheckExact(v)
985
0
                    && width == -1 && prec == -1
986
0
                    && !(flags & (F_SIGN | F_BLANK))
987
0
                    && c != 'X')
988
0
                {
989
                    /* Fast path */
990
0
                    int alternate = flags & F_ALT;
991
0
                    int base;
992
993
0
                    switch(c)
994
0
                    {
995
0
                        default:
996
0
                            Py_UNREACHABLE();
997
0
                        case 'd':
998
0
                        case 'i':
999
0
                        case 'u':
1000
0
                            base = 10;
1001
0
                            break;
1002
0
                        case 'o':
1003
0
                            base = 8;
1004
0
                            break;
1005
0
                        case 'x':
1006
0
                        case 'X':
1007
0
                            base = 16;
1008
0
                            break;
1009
0
                    }
1010
1011
                    /* Fast path */
1012
0
                    res = _PyLong_FormatBytesWriter(writer, res,
1013
0
                                                    v, base, alternate);
1014
0
                    if (res == NULL)
1015
0
                        goto error;
1016
0
                    continue;
1017
0
                }
1018
1019
0
                temp = formatlong(v, argidx, key, flags, prec, c);
1020
0
                if (!temp)
1021
0
                    goto error;
1022
0
                assert(PyUnicode_IS_ASCII(temp));
1023
0
                pbuf = (const char *)PyUnicode_1BYTE_DATA(temp);
1024
0
                len = PyUnicode_GET_LENGTH(temp);
1025
0
                sign = 1;
1026
0
                if (flags & F_ZERO)
1027
0
                    fill = '0';
1028
0
                break;
1029
1030
0
            case 'e':
1031
0
            case 'E':
1032
0
            case 'f':
1033
0
            case 'F':
1034
0
            case 'g':
1035
0
            case 'G':
1036
0
                if (width == -1 && prec == -1
1037
0
                    && !(flags & (F_SIGN | F_BLANK)))
1038
0
                {
1039
                    /* Fast path */
1040
0
                    res = formatfloat(v, argidx, key, flags, prec, c, NULL, writer, res);
1041
0
                    if (res == NULL)
1042
0
                        goto error;
1043
0
                    continue;
1044
0
                }
1045
1046
0
                if (!formatfloat(v, argidx, key, flags, prec, c, &temp, NULL, res))
1047
0
                    goto error;
1048
0
                pbuf = PyBytes_AS_STRING(temp);
1049
0
                len = PyBytes_GET_SIZE(temp);
1050
0
                sign = 1;
1051
0
                if (flags & F_ZERO)
1052
0
                    fill = '0';
1053
0
                break;
1054
1055
0
            case 'c':
1056
0
                pbuf = &onechar;
1057
0
                len = byte_converter(v, argidx, key, &onechar);
1058
0
                if (!len)
1059
0
                    goto error;
1060
0
                if (width == -1) {
1061
                    /* Fast path */
1062
0
                    *res++ = onechar;
1063
0
                    continue;
1064
0
                }
1065
0
                break;
1066
1067
0
            default:
1068
0
                if (Py_ISALPHA(c)) {
1069
0
                    PyErr_Format(PyExc_ValueError,
1070
0
                                 "unsupported format %%%c at position %zd",
1071
0
                                 c, (Py_ssize_t)(fmtstart - format - 1));
1072
0
                }
1073
0
                else if (c == '\'') {
1074
0
                    PyErr_Format(PyExc_ValueError,
1075
0
                                 "stray %% at position %zd or unexpected "
1076
0
                                 "format character \"'\" "
1077
0
                                 "at position %zd",
1078
0
                                 (Py_ssize_t)(fmtstart - format - 1),
1079
0
                                 (Py_ssize_t)(fmt - format - 1));
1080
0
                }
1081
0
                else if (c >= 32 && c < 127 && c != '\'') {
1082
0
                    PyErr_Format(PyExc_ValueError,
1083
0
                                 "stray %% at position %zd or unexpected "
1084
0
                                 "format character '%c' "
1085
0
                                 "at position %zd",
1086
0
                                 (Py_ssize_t)(fmtstart - format - 1),
1087
0
                                 c, (Py_ssize_t)(fmt - format - 1));
1088
0
                }
1089
0
                else {
1090
0
                    PyErr_Format(PyExc_ValueError,
1091
0
                                 "stray %% at position %zd or unexpected "
1092
0
                                 "format character with code 0x%02x "
1093
0
                                 "at position %zd",
1094
0
                                 (Py_ssize_t)(fmtstart - format - 1),
1095
0
                                 Py_CHARMASK(c),
1096
0
                                 (Py_ssize_t)(fmt - format - 1));
1097
0
                }
1098
0
                goto error;
1099
0
            }
1100
1101
0
            if (sign) {
1102
0
                if (*pbuf == '-' || *pbuf == '+') {
1103
0
                    sign = *pbuf++;
1104
0
                    len--;
1105
0
                }
1106
0
                else if (flags & F_SIGN)
1107
0
                    sign = '+';
1108
0
                else if (flags & F_BLANK)
1109
0
                    sign = ' ';
1110
0
                else
1111
0
                    sign = 0;
1112
0
            }
1113
0
            if (width < len)
1114
0
                width = len;
1115
1116
0
            alloc = width;
1117
0
            if (sign != 0 && len == width)
1118
0
                alloc++;
1119
            /* size preallocated for the format */
1120
0
            Py_ssize_t prealloc = fmt - start;
1121
0
            if (alloc > prealloc) {
1122
0
                res = PyBytesWriter_GrowAndUpdatePointer(writer, alloc - prealloc, res);
1123
0
                if (res == NULL) {
1124
0
                    Py_XDECREF(temp);
1125
0
                    goto error;
1126
0
                }
1127
0
            }
1128
#ifndef NDEBUG
1129
            char *before = res;
1130
#endif
1131
1132
            /* Write the sign if needed */
1133
0
            if (sign) {
1134
0
                if (fill != ' ')
1135
0
                    *res++ = sign;
1136
0
                if (width > len)
1137
0
                    width--;
1138
0
            }
1139
1140
            /* Write the numeric prefix for "x", "X" and "o" formats
1141
               if the alternate form is used.
1142
               For example, write "0x" for the "%#x" format. */
1143
0
            if ((flags & F_ALT) && (c == 'o' || c == 'x' || c == 'X')) {
1144
0
                assert(pbuf[0] == '0');
1145
0
                assert(pbuf[1] == c);
1146
0
                if (fill != ' ') {
1147
0
                    *res++ = *pbuf++;
1148
0
                    *res++ = *pbuf++;
1149
0
                }
1150
0
                width -= 2;
1151
0
                if (width < 0)
1152
0
                    width = 0;
1153
0
                len -= 2;
1154
0
            }
1155
1156
            /* Pad left with the fill character if needed */
1157
0
            if (width > len && !(flags & F_LJUST)) {
1158
0
                memset(res, fill, width - len);
1159
0
                res += (width - len);
1160
0
                width = len;
1161
0
            }
1162
1163
            /* If padding with spaces: write sign if needed and/or numeric
1164
               prefix if the alternate form is used */
1165
0
            if (fill == ' ') {
1166
0
                if (sign)
1167
0
                    *res++ = sign;
1168
0
                if ((flags & F_ALT) && (c == 'o' || c == 'x' || c == 'X')) {
1169
0
                    assert(pbuf[0] == '0');
1170
0
                    assert(pbuf[1] == c);
1171
0
                    *res++ = *pbuf++;
1172
0
                    *res++ = *pbuf++;
1173
0
                }
1174
0
            }
1175
1176
            /* Copy bytes */
1177
0
            memcpy(res, pbuf, len);
1178
0
            res += len;
1179
1180
            /* Pad right with the fill character if needed */
1181
0
            if (width > len) {
1182
0
                memset(res, ' ', width - len);
1183
0
                res += (width - len);
1184
0
            }
1185
1186
0
            if (dict && (argidx < arglen)) {
1187
                // XXX: Never happens?
1188
0
                PyErr_SetString(PyExc_TypeError,
1189
0
                           "not all arguments converted during bytes formatting");
1190
0
                Py_XDECREF(temp);
1191
0
                goto error;
1192
0
            }
1193
0
            Py_XDECREF(temp);
1194
1195
#ifndef NDEBUG
1196
            /* check that we computed the exact size for this write */
1197
            assert((res - before) == alloc);
1198
#endif
1199
0
        } /* '%' */
1200
1201
        /* If overallocation was disabled, ensure that it was the last
1202
           write. Otherwise, we missed an optimization */
1203
0
        assert(writer->overallocate || fmtcnt == 0 || use_bytearray);
1204
0
    } /* until end */
1205
1206
0
    if (argidx < arglen && !dict) {
1207
0
        PyErr_Format(PyExc_TypeError,
1208
0
                     "not all arguments converted during bytes formatting "
1209
0
                     "(required %zd, got %zd)",
1210
0
                     arglen < 0 ? 0 : argidx,
1211
0
                     arglen < 0 ? 1 : arglen);
1212
0
        goto error;
1213
0
    }
1214
1215
0
    Py_XDECREF(key);
1216
0
    if (args_owned) {
1217
0
        Py_DECREF(args);
1218
0
    }
1219
0
    return PyBytesWriter_FinishWithPointer(writer, res);
1220
1221
0
 error:
1222
0
    Py_XDECREF(key);
1223
0
    PyBytesWriter_Discard(writer);
1224
0
    if (args_owned) {
1225
0
        Py_DECREF(args);
1226
0
    }
1227
0
    return NULL;
1228
0
}
1229
1230
/* Unescape a backslash-escaped string. */
1231
PyObject *_PyBytes_DecodeEscape2(const char *s,
1232
                                Py_ssize_t len,
1233
                                const char *errors,
1234
                                int *first_invalid_escape_char,
1235
                                const char **first_invalid_escape_ptr)
1236
2.82k
{
1237
2.82k
    PyBytesWriter *writer = PyBytesWriter_Create(len);
1238
2.82k
    if (writer == NULL) {
1239
0
        return NULL;
1240
0
    }
1241
2.82k
    char *p = PyBytesWriter_GetData(writer);
1242
1243
2.82k
    *first_invalid_escape_char = -1;
1244
2.82k
    *first_invalid_escape_ptr = NULL;
1245
1246
2.82k
    const char *end = s + len;
1247
74.6k
    while (s < end) {
1248
71.8k
        if (*s != '\\') {
1249
44.6k
            *p++ = *s++;
1250
44.6k
            continue;
1251
44.6k
        }
1252
1253
27.2k
        s++;
1254
27.2k
        if (s == end) {
1255
0
            PyErr_SetString(PyExc_ValueError,
1256
0
                            "Trailing \\ in string");
1257
0
            goto failed;
1258
0
        }
1259
1260
27.2k
        switch (*s++) {
1261
        /* XXX This assumes ASCII! */
1262
16.7k
        case '\n': break;
1263
474
        case '\\': *p++ = '\\'; break;
1264
385
        case '\'': *p++ = '\''; break;
1265
650
        case '\"': *p++ = '\"'; break;
1266
206
        case 'b': *p++ = '\b'; break;
1267
304
        case 'f': *p++ = '\014'; break; /* FF */
1268
286
        case 't': *p++ = '\t'; break;
1269
424
        case 'n': *p++ = '\n'; break;
1270
485
        case 'r': *p++ = '\r'; break;
1271
219
        case 'v': *p++ = '\013'; break; /* VT */
1272
234
        case 'a': *p++ = '\007'; break; /* BEL, not classic C */
1273
2.57k
        case '0': case '1': case '2': case '3':
1274
4.43k
        case '4': case '5': case '6': case '7':
1275
4.43k
        {
1276
4.43k
            int c = s[-1] - '0';
1277
4.43k
            if (s < end && '0' <= *s && *s <= '7') {
1278
1.73k
                c = (c<<3) + *s++ - '0';
1279
1.73k
                if (s < end && '0' <= *s && *s <= '7')
1280
630
                    c = (c<<3) + *s++ - '0';
1281
1.73k
            }
1282
4.43k
            if (c > 0377) {
1283
552
                if (*first_invalid_escape_char == -1) {
1284
275
                    *first_invalid_escape_char = c;
1285
                    /* Back up 3 chars, since we've already incremented s. */
1286
275
                    *first_invalid_escape_ptr = s - 3;
1287
275
                }
1288
552
            }
1289
4.43k
            *p++ = c;
1290
4.43k
            break;
1291
3.90k
        }
1292
422
        case 'x':
1293
422
            if (s+1 < end) {
1294
421
                int digit1, digit2;
1295
421
                digit1 = _PyLong_DigitValue[Py_CHARMASK(s[0])];
1296
421
                digit2 = _PyLong_DigitValue[Py_CHARMASK(s[1])];
1297
421
                if (digit1 < 16 && digit2 < 16) {
1298
418
                    *p++ = (unsigned char)((digit1 << 4) + digit2);
1299
418
                    s += 2;
1300
418
                    break;
1301
418
                }
1302
421
            }
1303
            /* invalid hexadecimal digits */
1304
1305
4
            if (!errors || strcmp(errors, "strict") == 0) {
1306
4
                PyErr_Format(PyExc_ValueError,
1307
4
                             "invalid \\x escape at position %zd",
1308
4
                             s - 2 - (end - len));
1309
4
                goto failed;
1310
4
            }
1311
0
            if (strcmp(errors, "replace") == 0) {
1312
0
                *p++ = '?';
1313
0
            } else if (strcmp(errors, "ignore") == 0)
1314
0
                /* do nothing */;
1315
0
            else {
1316
0
                PyErr_Format(PyExc_ValueError,
1317
0
                             "decoding error; unknown "
1318
0
                             "error handling code: %.400s",
1319
0
                             errors);
1320
0
                goto failed;
1321
0
            }
1322
            /* skip \x */
1323
0
            if (s < end && Py_ISXDIGIT(s[0]))
1324
0
                s++; /* and a hexdigit */
1325
0
            break;
1326
1327
2.00k
        default:
1328
2.00k
            if (*first_invalid_escape_char == -1) {
1329
873
                *first_invalid_escape_char = (unsigned char)s[-1];
1330
                /* Back up one char, since we've already incremented s. */
1331
873
                *first_invalid_escape_ptr = s - 1;
1332
873
            }
1333
2.00k
            *p++ = '\\';
1334
2.00k
            s--;
1335
27.2k
        }
1336
27.2k
    }
1337
1338
2.82k
    return PyBytesWriter_FinishWithPointer(writer, p);
1339
1340
4
  failed:
1341
4
    PyBytesWriter_Discard(writer);
1342
4
    return NULL;
1343
2.82k
}
1344
1345
PyObject *PyBytes_DecodeEscape(const char *s,
1346
                                Py_ssize_t len,
1347
                                const char *errors,
1348
                                Py_ssize_t Py_UNUSED(unicode),
1349
                                const char *Py_UNUSED(recode_encoding))
1350
0
{
1351
0
    int first_invalid_escape_char;
1352
0
    const char *first_invalid_escape_ptr;
1353
0
    PyObject *result = _PyBytes_DecodeEscape2(s, len, errors,
1354
0
                                             &first_invalid_escape_char,
1355
0
                                             &first_invalid_escape_ptr);
1356
0
    if (result == NULL)
1357
0
        return NULL;
1358
0
    if (first_invalid_escape_char != -1) {
1359
0
        if (first_invalid_escape_char > 0xff) {
1360
0
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1361
0
                                 "b\"\\%o\" is an invalid octal escape sequence. "
1362
0
                                 "Such sequences will not work in the future. ",
1363
0
                                 first_invalid_escape_char) < 0)
1364
0
            {
1365
0
                Py_DECREF(result);
1366
0
                return NULL;
1367
0
            }
1368
0
        }
1369
0
        else {
1370
0
            if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1371
0
                                 "b\"\\%c\" is an invalid escape sequence. "
1372
0
                                 "Such sequences will not work in the future. ",
1373
0
                                 first_invalid_escape_char) < 0)
1374
0
            {
1375
0
                Py_DECREF(result);
1376
0
                return NULL;
1377
0
            }
1378
0
        }
1379
0
    }
1380
0
    return result;
1381
0
}
1382
/* -------------------------------------------------------------------- */
1383
/* object api */
1384
1385
Py_ssize_t
1386
PyBytes_Size(PyObject *op)
1387
5.72k
{
1388
5.72k
    if (!PyBytes_Check(op)) {
1389
0
        PyErr_Format(PyExc_TypeError,
1390
0
             "expected bytes, %.200s found", Py_TYPE(op)->tp_name);
1391
0
        return -1;
1392
0
    }
1393
5.72k
    return Py_SIZE(op);
1394
5.72k
}
1395
1396
char *
1397
PyBytes_AsString(PyObject *op)
1398
1.07M
{
1399
1.07M
    if (!PyBytes_Check(op)) {
1400
0
        PyErr_Format(PyExc_TypeError,
1401
0
             "expected bytes, %.200s found", Py_TYPE(op)->tp_name);
1402
0
        return NULL;
1403
0
    }
1404
1.07M
    return ((PyBytesObject *)op)->ob_sval;
1405
1.07M
}
1406
1407
int
1408
PyBytes_AsStringAndSize(PyObject *obj,
1409
                         char **s,
1410
                         Py_ssize_t *len)
1411
78.7k
{
1412
78.7k
    if (s == NULL) {
1413
0
        PyErr_BadInternalCall();
1414
0
        return -1;
1415
0
    }
1416
1417
78.7k
    if (!PyBytes_Check(obj)) {
1418
0
        PyErr_Format(PyExc_TypeError,
1419
0
             "expected bytes, %.200s found", Py_TYPE(obj)->tp_name);
1420
0
        return -1;
1421
0
    }
1422
1423
78.7k
    *s = PyBytes_AS_STRING(obj);
1424
78.7k
    if (len != NULL)
1425
78.5k
        *len = PyBytes_GET_SIZE(obj);
1426
111
    else if (strlen(*s) != (size_t)PyBytes_GET_SIZE(obj)) {
1427
0
        PyErr_SetString(PyExc_ValueError,
1428
0
                        "embedded null byte");
1429
0
        return -1;
1430
0
    }
1431
78.7k
    return 0;
1432
78.7k
}
1433
1434
/* -------------------------------------------------------------------- */
1435
/* Methods */
1436
1437
3.26k
#define STRINGLIB_GET_EMPTY() bytes_get_empty()
1438
1439
#include "stringlib/stringdefs.h"
1440
#define STRINGLIB_MUTABLE 0
1441
1442
#include "stringlib/fastsearch.h"
1443
#include "stringlib/count.h"
1444
#include "stringlib/find.h"
1445
#include "stringlib/join.h"
1446
#include "stringlib/partition.h"
1447
#include "stringlib/split.h"
1448
#include "stringlib/ctype.h"
1449
1450
#include "stringlib/transmogrify.h"
1451
1452
#undef STRINGLIB_GET_EMPTY
1453
1454
Py_ssize_t
1455
_PyBytes_Find(const char *haystack, Py_ssize_t len_haystack,
1456
              const char *needle, Py_ssize_t len_needle,
1457
              Py_ssize_t offset)
1458
0
{
1459
0
    assert(len_haystack >= 0);
1460
0
    assert(len_needle >= 0);
1461
    // Extra checks because stringlib_find accesses haystack[len_haystack].
1462
0
    if (len_needle == 0) {
1463
0
        return offset;
1464
0
    }
1465
0
    if (len_needle > len_haystack) {
1466
0
        return -1;
1467
0
    }
1468
0
    assert(len_haystack >= 1);
1469
0
    Py_ssize_t res = stringlib_find(haystack, len_haystack - 1,
1470
0
                                    needle, len_needle, offset);
1471
0
    if (res == -1) {
1472
0
        Py_ssize_t last_align = len_haystack - len_needle;
1473
0
        if (memcmp(haystack + last_align, needle, len_needle) == 0) {
1474
0
            return offset + last_align;
1475
0
        }
1476
0
    }
1477
0
    return res;
1478
0
}
1479
1480
Py_ssize_t
1481
_PyBytes_ReverseFind(const char *haystack, Py_ssize_t len_haystack,
1482
                     const char *needle, Py_ssize_t len_needle,
1483
                     Py_ssize_t offset)
1484
0
{
1485
0
    return stringlib_rfind(haystack, len_haystack,
1486
0
                           needle, len_needle, offset);
1487
0
}
1488
1489
PyObject *
1490
PyBytes_Repr(PyObject *obj, int smartquotes)
1491
4.12k
{
1492
4.12k
    return _Py_bytes_repr(PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
1493
4.12k
                          smartquotes, "bytes");
1494
4.12k
}
1495
1496
PyObject *
1497
_Py_bytes_repr(const char *data, Py_ssize_t length, int smartquotes,
1498
               const char *classname)
1499
4.12k
{
1500
4.12k
    Py_ssize_t i;
1501
4.12k
    Py_ssize_t newsize, squotes, dquotes;
1502
4.12k
    PyObject *v;
1503
4.12k
    unsigned char quote;
1504
4.12k
    Py_UCS1 *p;
1505
1506
    /* Compute size of output string */
1507
4.12k
    squotes = dquotes = 0;
1508
4.12k
    newsize = 3; /* b'' */
1509
25.7M
    for (i = 0; i < length; i++) {
1510
25.7M
        unsigned char c = data[i];
1511
25.7M
        Py_ssize_t incr = 1;
1512
25.7M
        switch(c) {
1513
5.10k
        case '\'': squotes++; break;
1514
9.70k
        case '"':  dquotes++; break;
1515
20.2k
        case '\\': case '\t': case '\n': case '\r':
1516
20.2k
            incr = 2; break; /* \C */
1517
25.6M
        default:
1518
25.6M
            if (c < ' ' || c >= 0x7f)
1519
23.4M
                incr = 4; /* \xHH */
1520
25.7M
        }
1521
25.7M
        if (newsize > PY_SSIZE_T_MAX - incr)
1522
0
            goto overflow;
1523
25.7M
        newsize += incr;
1524
25.7M
    }
1525
4.12k
    quote = '\'';
1526
4.12k
    if (smartquotes && squotes && !dquotes)
1527
421
        quote = '"';
1528
4.12k
    if (squotes && quote == '\'') {
1529
295
        if (newsize > PY_SSIZE_T_MAX - squotes)
1530
0
            goto overflow;
1531
295
        newsize += squotes;
1532
295
    }
1533
1534
4.12k
    v = PyUnicode_New(newsize, 127);
1535
4.12k
    if (v == NULL) {
1536
0
        return NULL;
1537
0
    }
1538
4.12k
    p = PyUnicode_1BYTE_DATA(v);
1539
1540
4.12k
    *p++ = 'b', *p++ = quote;
1541
25.7M
    for (i = 0; i < length; i++) {
1542
25.7M
        unsigned char c = data[i];
1543
25.7M
        if (c == quote || c == '\\')
1544
5.92k
            *p++ = '\\', *p++ = c;
1545
25.7M
        else if (c == '\t')
1546
10.4k
            *p++ = '\\', *p++ = 't';
1547
25.6M
        else if (c == '\n')
1548
3.99k
            *p++ = '\\', *p++ = 'n';
1549
25.6M
        else if (c == '\r')
1550
4.13k
            *p++ = '\\', *p++ = 'r';
1551
25.6M
        else if (c < ' ' || c >= 0x7f) {
1552
23.4M
            *p++ = '\\';
1553
23.4M
            *p++ = 'x';
1554
23.4M
            *p++ = Py_hexdigits[(c & 0xf0) >> 4];
1555
23.4M
            *p++ = Py_hexdigits[c & 0xf];
1556
23.4M
        }
1557
2.20M
        else
1558
2.20M
            *p++ = c;
1559
25.7M
    }
1560
4.12k
    *p++ = quote;
1561
4.12k
    assert(_PyUnicode_CheckConsistency(v, 1));
1562
4.12k
    return v;
1563
1564
0
  overflow:
1565
0
    PyErr_Format(PyExc_OverflowError,
1566
0
                 "%s object is too large to make repr", classname);
1567
0
    return NULL;
1568
4.12k
}
1569
1570
static PyObject *
1571
bytes_repr(PyObject *op)
1572
4.12k
{
1573
4.12k
    return PyBytes_Repr(op, 1);
1574
4.12k
}
1575
1576
static PyObject *
1577
bytes_str(PyObject *op)
1578
0
{
1579
0
    if (_Py_GetConfig()->bytes_warning) {
1580
0
        if (PyErr_WarnEx(PyExc_BytesWarning,
1581
0
                         "str() on a bytes instance", 1)) {
1582
0
            return NULL;
1583
0
        }
1584
0
    }
1585
0
    return bytes_repr(op);
1586
0
}
1587
1588
static Py_ssize_t
1589
bytes_length(PyObject *self)
1590
50.5M
{
1591
50.5M
    PyBytesObject *a = _PyBytes_CAST(self);
1592
50.5M
    return Py_SIZE(a);
1593
50.5M
}
1594
1595
/* This is also used by PyBytes_Concat() and the specializing interpreter. */
1596
PyObject *
1597
_PyBytes_Concat(PyObject *a, PyObject *b)
1598
2.55M
{
1599
2.55M
    Py_buffer va, vb;
1600
2.55M
    PyObject *result = NULL;
1601
1602
2.55M
    va.len = -1;
1603
2.55M
    vb.len = -1;
1604
2.55M
    if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 ||
1605
2.55M
        PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) {
1606
0
        PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
1607
0
                     Py_TYPE(b)->tp_name, Py_TYPE(a)->tp_name);
1608
0
        goto done;
1609
0
    }
1610
1611
    /* Optimize end cases */
1612
2.55M
    if (va.len == 0 && PyBytes_CheckExact(b)) {
1613
88.1k
        result = Py_NewRef(b);
1614
88.1k
        goto done;
1615
88.1k
    }
1616
2.46M
    if (vb.len == 0 && PyBytes_CheckExact(a)) {
1617
49.0k
        result = Py_NewRef(a);
1618
49.0k
        goto done;
1619
49.0k
    }
1620
1621
2.41M
    if (va.len > PY_SSIZE_T_MAX - vb.len) {
1622
0
        PyErr_NoMemory();
1623
0
        goto done;
1624
0
    }
1625
1626
2.41M
    if ((va.len + vb.len) != 0) {
1627
2.41M
        result = bytes_alloc(va.len + vb.len);
1628
2.41M
        if (result != NULL) {
1629
2.41M
            memcpy(PyBytes_AS_STRING(result), va.buf, va.len);
1630
2.41M
            memcpy(PyBytes_AS_STRING(result) + va.len, vb.buf, vb.len);
1631
2.41M
        }
1632
2.41M
    }
1633
0
    else {
1634
0
        result = bytes_get_empty();
1635
0
    }
1636
1637
2.55M
  done:
1638
2.55M
    if (va.len != -1)
1639
2.55M
        PyBuffer_Release(&va);
1640
2.55M
    if (vb.len != -1)
1641
2.55M
        PyBuffer_Release(&vb);
1642
2.55M
    return result;
1643
2.41M
}
1644
1645
PyObject *
1646
_PyBytes_Repeat(PyObject *self, Py_ssize_t n)
1647
121k
{
1648
121k
    PyBytesObject *a = _PyBytes_CAST(self);
1649
121k
    if (n < 0)
1650
0
        n = 0;
1651
    /* watch out for overflows:  the size can overflow int,
1652
     * and the # of bytes needed can overflow size_t
1653
     */
1654
121k
    if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n) {
1655
0
        PyErr_SetString(PyExc_OverflowError,
1656
0
            "repeated bytes are too long");
1657
0
        return NULL;
1658
0
    }
1659
121k
    Py_ssize_t old_size = Py_SIZE(a);
1660
121k
    Py_ssize_t new_size = old_size * n;
1661
121k
    if (new_size == old_size && PyBytes_CheckExact(a)) {
1662
27
        return Py_NewRef(a);
1663
27
    }
1664
1665
121k
    if (new_size == 0) {
1666
1.08k
        return bytes_get_empty();
1667
1.08k
    }
1668
1669
120k
    PyBytesObject *op = (PyBytesObject *)bytes_alloc(new_size);
1670
120k
    if (op == NULL) {
1671
0
        return PyErr_NoMemory();
1672
0
    }
1673
1674
120k
    _PyBytes_RepeatBuffer(op->ob_sval, new_size, a->ob_sval, old_size);
1675
120k
    return (PyObject *) op;
1676
120k
}
1677
1678
static int
1679
bytes_contains(PyObject *self, PyObject *arg)
1680
2.77k
{
1681
2.77k
    return _Py_bytes_contains(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), arg);
1682
2.77k
}
1683
1684
static PyObject *
1685
bytes_item(PyObject *self, Py_ssize_t i)
1686
0
{
1687
0
    PyBytesObject *a = _PyBytes_CAST(self);
1688
0
    if (i < 0 || i >= Py_SIZE(a)) {
1689
0
        PyErr_SetString(PyExc_IndexError, "index out of range");
1690
0
        return NULL;
1691
0
    }
1692
0
    return _PyLong_FromUnsignedChar((unsigned char)a->ob_sval[i]);
1693
0
}
1694
1695
static int
1696
bytes_compare_eq(PyBytesObject *a, PyBytesObject *b)
1697
67.9M
{
1698
67.9M
    int cmp;
1699
67.9M
    Py_ssize_t len;
1700
1701
67.9M
    len = Py_SIZE(a);
1702
67.9M
    if (Py_SIZE(b) != len)
1703
723k
        return 0;
1704
1705
67.1M
    if (a->ob_sval[0] != b->ob_sval[0])
1706
8.16M
        return 0;
1707
1708
59.0M
    cmp = memcmp(a->ob_sval, b->ob_sval, len);
1709
59.0M
    return (cmp == 0);
1710
67.1M
}
1711
1712
static PyObject*
1713
bytes_richcompare(PyObject *aa, PyObject *bb, int op)
1714
68.4M
{
1715
    /* Make sure both arguments are strings. */
1716
68.4M
    if (!(PyBytes_Check(aa) && PyBytes_Check(bb))) {
1717
0
        if (_Py_GetConfig()->bytes_warning && (op == Py_EQ || op == Py_NE)) {
1718
0
            if (PyUnicode_Check(aa) || PyUnicode_Check(bb)) {
1719
0
                if (PyErr_WarnEx(PyExc_BytesWarning,
1720
0
                                 "Comparison between bytes and string", 1))
1721
0
                    return NULL;
1722
0
            }
1723
0
            if (PyLong_Check(aa) || PyLong_Check(bb)) {
1724
0
                if (PyErr_WarnEx(PyExc_BytesWarning,
1725
0
                                 "Comparison between bytes and int", 1))
1726
0
                    return NULL;
1727
0
            }
1728
0
        }
1729
0
        Py_RETURN_NOTIMPLEMENTED;
1730
0
    }
1731
1732
68.4M
    PyBytesObject *a = _PyBytes_CAST(aa);
1733
68.4M
    PyBytesObject *b = _PyBytes_CAST(bb);
1734
68.4M
    if (a == b) {
1735
549k
        switch (op) {
1736
246k
        case Py_EQ:
1737
246k
        case Py_LE:
1738
246k
        case Py_GE:
1739
            /* a byte string is equal to itself */
1740
246k
            Py_RETURN_TRUE;
1741
303k
        case Py_NE:
1742
303k
        case Py_LT:
1743
303k
        case Py_GT:
1744
303k
            Py_RETURN_FALSE;
1745
0
        default:
1746
0
            PyErr_BadArgument();
1747
0
            return NULL;
1748
549k
        }
1749
549k
    }
1750
67.9M
    else if (op == Py_EQ || op == Py_NE) {
1751
67.9M
        int eq = bytes_compare_eq(a, b);
1752
67.9M
        eq ^= (op == Py_NE);
1753
67.9M
        return PyBool_FromLong(eq);
1754
67.9M
    }
1755
87
    else {
1756
87
        Py_ssize_t len_a = Py_SIZE(a);
1757
87
        Py_ssize_t len_b = Py_SIZE(b);
1758
87
        Py_ssize_t min_len = Py_MIN(len_a, len_b);
1759
87
        int c;
1760
87
        if (min_len > 0) {
1761
87
            c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
1762
87
            if (c == 0)
1763
87
                c = memcmp(a->ob_sval, b->ob_sval, min_len);
1764
87
        }
1765
0
        else {
1766
0
            c = 0;
1767
0
        }
1768
87
        if (c != 0) {
1769
87
            Py_RETURN_RICHCOMPARE(c, 0, op);
1770
87
        }
1771
0
        Py_RETURN_RICHCOMPARE(len_a, len_b, op);
1772
0
    }
1773
68.4M
}
1774
1775
static Py_hash_t
1776
bytes_hash(PyObject *self)
1777
66.5M
{
1778
66.5M
    PyBytesObject *a = _PyBytes_CAST(self);
1779
66.5M
    Py_hash_t hash = get_ob_shash(a);
1780
66.5M
    if (hash == -1) {
1781
        /* Can't fail */
1782
43.0M
        hash = Py_HashBuffer(a->ob_sval, Py_SIZE(a));
1783
43.0M
        set_ob_shash(a, hash);
1784
43.0M
    }
1785
66.5M
    return hash;
1786
66.5M
}
1787
1788
static PyObject*
1789
bytes_subscript(PyObject *op, PyObject* item)
1790
94.0M
{
1791
94.0M
    PyBytesObject *self = _PyBytes_CAST(op);
1792
94.0M
    if (_PyIndex_Check(item)) {
1793
35.6M
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1794
35.6M
        if (i == -1 && PyErr_Occurred())
1795
0
            return NULL;
1796
35.6M
        if (i < 0)
1797
0
            i += PyBytes_GET_SIZE(self);
1798
35.6M
        if (i < 0 || i >= PyBytes_GET_SIZE(self)) {
1799
142
            PyErr_SetString(PyExc_IndexError,
1800
142
                            "index out of range");
1801
142
            return NULL;
1802
142
        }
1803
35.6M
        return _PyLong_FromUnsignedChar((unsigned char)self->ob_sval[i]);
1804
35.6M
    }
1805
58.3M
    else if (PySlice_Check(item)) {
1806
58.3M
        Py_ssize_t start, stop, step, slicelength, i;
1807
58.3M
        size_t cur;
1808
58.3M
        const char* source_buf;
1809
58.3M
        char* result_buf;
1810
1811
58.3M
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
1812
0
            return NULL;
1813
0
        }
1814
58.3M
        slicelength = PySlice_AdjustIndices(PyBytes_GET_SIZE(self), &start,
1815
58.3M
                                            &stop, step);
1816
1817
58.3M
        if (slicelength <= 0) {
1818
5.55M
            return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
1819
5.55M
        }
1820
52.8M
        else if (start == 0 && step == 1 &&
1821
7.31M
                 slicelength == PyBytes_GET_SIZE(self) &&
1822
147k
                 PyBytes_CheckExact(self)) {
1823
147k
            return Py_NewRef(self);
1824
147k
        }
1825
52.6M
        else if (step == 1) {
1826
52.6M
            return _PyBytes_FromStringAndSize(
1827
52.6M
                PyBytes_AS_STRING(self) + start,
1828
52.6M
                slicelength);
1829
52.6M
        }
1830
0
        else {
1831
0
            source_buf = PyBytes_AS_STRING(self);
1832
0
            PyObject* result = bytes_alloc(slicelength);
1833
0
            if (result == NULL) {
1834
0
                return NULL;
1835
0
            }
1836
1837
0
            result_buf = PyBytes_AS_STRING(result);
1838
0
            for (cur = start, i = 0; i < slicelength;
1839
0
                 cur += step, i++) {
1840
0
                result_buf[i] = source_buf[cur];
1841
0
            }
1842
0
            return result;
1843
0
        }
1844
58.3M
    }
1845
0
    else {
1846
0
        PyErr_Format(PyExc_TypeError,
1847
0
                     "byte indices must be integers or slices, not %.200s",
1848
0
                     Py_TYPE(item)->tp_name);
1849
0
        return NULL;
1850
0
    }
1851
94.0M
}
1852
1853
static int
1854
bytes_buffer_getbuffer(PyObject *op, Py_buffer *view, int flags)
1855
87.4M
{
1856
87.4M
    PyBytesObject *self = _PyBytes_CAST(op);
1857
87.4M
    return PyBuffer_FillInfo(view, (PyObject*)self, (void *)self->ob_sval, Py_SIZE(self),
1858
87.4M
                             1, flags);
1859
87.4M
}
1860
1861
static PySequenceMethods bytes_as_sequence = {
1862
    bytes_length,       /*sq_length*/
1863
    _PyBytes_Concat,       /*sq_concat*/
1864
    _PyBytes_Repeat,    /*sq_repeat*/
1865
    bytes_item,         /*sq_item*/
1866
    0,                  /*sq_slice*/
1867
    0,                  /*sq_ass_item*/
1868
    0,                  /*sq_ass_slice*/
1869
    bytes_contains      /*sq_contains*/
1870
};
1871
1872
static PyMappingMethods bytes_as_mapping = {
1873
    bytes_length,
1874
    bytes_subscript,
1875
    0,
1876
};
1877
1878
static PyBufferProcs bytes_as_buffer = {
1879
    bytes_buffer_getbuffer,
1880
    NULL,
1881
};
1882
1883
1884
/*[clinic input]
1885
bytes.__bytes__
1886
Convert this value to exact type bytes.
1887
[clinic start generated code]*/
1888
1889
static PyObject *
1890
bytes___bytes___impl(PyBytesObject *self)
1891
/*[clinic end generated code: output=63a306a9bc0caac5 input=34ec5ddba98bd6bb]*/
1892
45.1k
{
1893
45.1k
    if (PyBytes_CheckExact(self)) {
1894
45.1k
        return Py_NewRef(self);
1895
45.1k
    }
1896
0
    else {
1897
0
        return _PyBytes_FromStringAndSize(self->ob_sval, Py_SIZE(self));
1898
0
    }
1899
45.1k
}
1900
1901
1902
726
#define LEFTSTRIP 0
1903
1.45k
#define RIGHTSTRIP 1
1904
0
#define BOTHSTRIP 2
1905
1906
/*[clinic input]
1907
@permit_long_summary
1908
bytes.split
1909
1910
    sep: object = None
1911
        The delimiter according which to split the bytes.
1912
        None (the default value) means split on ASCII whitespace
1913
        characters (space, tab, return, newline, formfeed, vertical tab).
1914
    maxsplit: Py_ssize_t = -1
1915
        Maximum number of splits to do.
1916
        -1 (the default value) means no limit.
1917
1918
Return a list of the sections in the bytes, using sep as the delimiter.
1919
[clinic start generated code]*/
1920
1921
static PyObject *
1922
bytes_split_impl(PyBytesObject *self, PyObject *sep, Py_ssize_t maxsplit)
1923
/*[clinic end generated code: output=52126b5844c1d8ef input=330ff95d92544b05]*/
1924
3.51M
{
1925
3.51M
    Py_ssize_t len = PyBytes_GET_SIZE(self), n;
1926
3.51M
    const char *s = PyBytes_AS_STRING(self), *sub;
1927
3.51M
    Py_buffer vsub;
1928
3.51M
    PyObject *list;
1929
1930
3.51M
    if (maxsplit < 0)
1931
3.51M
        maxsplit = PY_SSIZE_T_MAX;
1932
3.51M
    if (sep == Py_None)
1933
0
        return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
1934
3.51M
    if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
1935
0
        return NULL;
1936
3.51M
    sub = vsub.buf;
1937
3.51M
    n = vsub.len;
1938
1939
3.51M
    list = stringlib_split((PyObject*) self, s, len, sub, n, maxsplit);
1940
3.51M
    PyBuffer_Release(&vsub);
1941
3.51M
    return list;
1942
3.51M
}
1943
1944
/*[clinic input]
1945
bytes.partition
1946
1947
    sep: Py_buffer
1948
    /
1949
1950
Partition the bytes into three parts using the given separator.
1951
1952
This will search for the separator sep in the bytes.  If the
1953
separator is found, returns a 3-tuple containing the part before the
1954
separator, the separator itself, and the part after it.
1955
1956
If the separator is not found, returns a 3-tuple containing the
1957
original bytes object and two empty bytes objects.
1958
[clinic start generated code]*/
1959
1960
static PyObject *
1961
bytes_partition_impl(PyBytesObject *self, Py_buffer *sep)
1962
/*[clinic end generated code: output=f532b392a17ff695 input=2e6e551ea4f8b95a]*/
1963
290k
{
1964
290k
    return stringlib_partition(
1965
290k
        (PyObject*) self,
1966
290k
        PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
1967
290k
        sep->obj, (const char *)sep->buf, sep->len
1968
290k
        );
1969
290k
}
1970
1971
/*[clinic input]
1972
bytes.rpartition
1973
1974
    sep: Py_buffer
1975
    /
1976
1977
Partition the bytes into three parts using the given separator.
1978
1979
This will search for the separator sep in the bytes, starting at the
1980
end.  If the separator is found, returns a 3-tuple containing the
1981
part before the separator, the separator itself, and the part after
1982
it.
1983
1984
If the separator is not found, returns a 3-tuple containing two
1985
empty bytes objects and the original bytes object.
1986
[clinic start generated code]*/
1987
1988
static PyObject *
1989
bytes_rpartition_impl(PyBytesObject *self, Py_buffer *sep)
1990
/*[clinic end generated code: output=191b114cbb028e50 input=f7d24f722a5470a4]*/
1991
0
{
1992
0
    return stringlib_rpartition(
1993
0
        (PyObject*) self,
1994
0
        PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
1995
0
        sep->obj, (const char *)sep->buf, sep->len
1996
0
        );
1997
0
}
1998
1999
/*[clinic input]
2000
@permit_long_summary
2001
bytes.rsplit = bytes.split
2002
2003
Return a list of the sections in the bytes, using sep as the delimiter.
2004
2005
Splitting is done starting at the end of the bytes and working to
2006
the front.
2007
[clinic start generated code]*/
2008
2009
static PyObject *
2010
bytes_rsplit_impl(PyBytesObject *self, PyObject *sep, Py_ssize_t maxsplit)
2011
/*[clinic end generated code: output=ba698d9ea01e1c8f input=ba9bee56285f43e4]*/
2012
0
{
2013
0
    Py_ssize_t len = PyBytes_GET_SIZE(self), n;
2014
0
    const char *s = PyBytes_AS_STRING(self), *sub;
2015
0
    Py_buffer vsub;
2016
0
    PyObject *list;
2017
2018
0
    if (maxsplit < 0)
2019
0
        maxsplit = PY_SSIZE_T_MAX;
2020
0
    if (sep == Py_None)
2021
0
        return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
2022
0
    if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
2023
0
        return NULL;
2024
0
    sub = vsub.buf;
2025
0
    n = vsub.len;
2026
2027
0
    list = stringlib_rsplit((PyObject*) self, s, len, sub, n, maxsplit);
2028
0
    PyBuffer_Release(&vsub);
2029
0
    return list;
2030
0
}
2031
2032
2033
/*[clinic input]
2034
bytes.join
2035
2036
    iterable_of_bytes: object
2037
    /
2038
2039
Concatenate any number of bytes objects.
2040
2041
The bytes whose method is called is inserted in between each pair.
2042
2043
The result is returned as a new bytes object.
2044
2045
Example: b'.'.join([b'ab', b'pq', b'rs']) -> b'ab.pq.rs'.
2046
[clinic start generated code]*/
2047
2048
static PyObject *
2049
bytes_join_impl(PyBytesObject *self, PyObject *iterable_of_bytes)
2050
/*[clinic end generated code: output=0687abb94d7d438e input=7fe377b95bd549d2]*/
2051
16.8k
{
2052
16.8k
    return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
2053
16.8k
}
2054
2055
PyObject *
2056
PyBytes_Join(PyObject *sep, PyObject *iterable)
2057
31.0k
{
2058
31.0k
    if (sep == NULL) {
2059
0
        PyErr_BadInternalCall();
2060
0
        return NULL;
2061
0
    }
2062
31.0k
    if (!PyBytes_Check(sep)) {
2063
0
        PyErr_Format(PyExc_TypeError,
2064
0
                     "sep: expected bytes, got %T", sep);
2065
0
        return NULL;
2066
0
    }
2067
2068
31.0k
    return stringlib_bytes_join(sep, iterable);
2069
31.0k
}
2070
2071
/*[clinic input]
2072
@permit_long_summary
2073
@text_signature "($self, sub[, start[, end]], /)"
2074
bytes.find
2075
2076
    sub: object
2077
    start: slice_index(accept={int, NoneType}, c_default='0') = None
2078
         Optional start position. Default: start of the bytes.
2079
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
2080
         Optional stop position. Default: end of the bytes.
2081
    /
2082
2083
Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end].
2084
2085
Return -1 on failure.
2086
[clinic start generated code]*/
2087
2088
static PyObject *
2089
bytes_find_impl(PyBytesObject *self, PyObject *sub, Py_ssize_t start,
2090
                Py_ssize_t end)
2091
/*[clinic end generated code: output=d5961a1c77b472a1 input=47d0929adafc6b0b]*/
2092
11.2M
{
2093
11.2M
    return _Py_bytes_find(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
2094
11.2M
                          sub, start, end);
2095
11.2M
}
2096
2097
/*[clinic input]
2098
@permit_long_summary
2099
bytes.index = bytes.find
2100
2101
Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end].
2102
2103
Raise ValueError if the subsection is not found.
2104
[clinic start generated code]*/
2105
2106
static PyObject *
2107
bytes_index_impl(PyBytesObject *self, PyObject *sub, Py_ssize_t start,
2108
                 Py_ssize_t end)
2109
/*[clinic end generated code: output=0da25cc74683ba42 input=1cb45ce71456a269]*/
2110
0
{
2111
0
    return _Py_bytes_index(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
2112
0
                           sub, start, end);
2113
0
}
2114
2115
/*[clinic input]
2116
@permit_long_summary
2117
bytes.rfind = bytes.find
2118
2119
Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end].
2120
2121
Return -1 on failure.
2122
[clinic start generated code]*/
2123
2124
static PyObject *
2125
bytes_rfind_impl(PyBytesObject *self, PyObject *sub, Py_ssize_t start,
2126
                 Py_ssize_t end)
2127
/*[clinic end generated code: output=51b60fa4ad011c09 input=c9473d714251f1ab]*/
2128
1.38M
{
2129
1.38M
    return _Py_bytes_rfind(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
2130
1.38M
                           sub, start, end);
2131
1.38M
}
2132
2133
/*[clinic input]
2134
@permit_long_summary
2135
bytes.rindex = bytes.find
2136
2137
Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end].
2138
2139
Raise ValueError if the subsection is not found.
2140
[clinic start generated code]*/
2141
2142
static PyObject *
2143
bytes_rindex_impl(PyBytesObject *self, PyObject *sub, Py_ssize_t start,
2144
                  Py_ssize_t end)
2145
/*[clinic end generated code: output=42bf674e0a0aabf6 input=bb5f473c64610c43]*/
2146
0
{
2147
0
    return _Py_bytes_rindex(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
2148
0
                            sub, start, end);
2149
0
}
2150
2151
2152
Py_LOCAL_INLINE(PyObject *)
2153
do_xstrip(PyBytesObject *self, int striptype, PyObject *sepobj)
2154
726
{
2155
726
    Py_buffer vsep;
2156
726
    const char *s = PyBytes_AS_STRING(self);
2157
726
    Py_ssize_t len = PyBytes_GET_SIZE(self);
2158
726
    char *sep;
2159
726
    Py_ssize_t seplen;
2160
726
    Py_ssize_t i, j;
2161
2162
726
    if (PyObject_GetBuffer(sepobj, &vsep, PyBUF_SIMPLE) != 0)
2163
0
        return NULL;
2164
726
    sep = vsep.buf;
2165
726
    seplen = vsep.len;
2166
2167
726
    i = 0;
2168
726
    if (striptype != RIGHTSTRIP) {
2169
0
        while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) {
2170
0
            i++;
2171
0
        }
2172
0
    }
2173
2174
726
    j = len;
2175
726
    if (striptype != LEFTSTRIP) {
2176
1.45k
        do {
2177
1.45k
            j--;
2178
1.45k
        } while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen));
2179
726
        j++;
2180
726
    }
2181
2182
726
    PyBuffer_Release(&vsep);
2183
2184
726
    if (i == 0 && j == len && PyBytes_CheckExact(self)) {
2185
0
        return Py_NewRef(self);
2186
0
    }
2187
726
    else
2188
726
        return _PyBytes_FromStringAndSize(s+i, j-i);
2189
726
}
2190
2191
2192
Py_LOCAL_INLINE(PyObject *)
2193
do_strip(PyBytesObject *self, int striptype)
2194
0
{
2195
0
    const char *s = PyBytes_AS_STRING(self);
2196
0
    Py_ssize_t len = PyBytes_GET_SIZE(self), i, j;
2197
2198
0
    i = 0;
2199
0
    if (striptype != RIGHTSTRIP) {
2200
0
        while (i < len && Py_ISSPACE(s[i])) {
2201
0
            i++;
2202
0
        }
2203
0
    }
2204
2205
0
    j = len;
2206
0
    if (striptype != LEFTSTRIP) {
2207
0
        do {
2208
0
            j--;
2209
0
        } while (j >= i && Py_ISSPACE(s[j]));
2210
0
        j++;
2211
0
    }
2212
2213
0
    if (i == 0 && j == len && PyBytes_CheckExact(self)) {
2214
0
        return Py_NewRef(self);
2215
0
    }
2216
0
    else
2217
0
        return _PyBytes_FromStringAndSize(s+i, j-i);
2218
0
}
2219
2220
2221
Py_LOCAL_INLINE(PyObject *)
2222
do_argstrip(PyBytesObject *self, int striptype, PyObject *bytes)
2223
726
{
2224
726
    if (bytes != Py_None) {
2225
726
        return do_xstrip(self, striptype, bytes);
2226
726
    }
2227
0
    return do_strip(self, striptype);
2228
726
}
2229
2230
/*[clinic input]
2231
bytes.strip
2232
2233
    bytes: object = None
2234
    /
2235
2236
Strip leading and trailing bytes contained in the argument.
2237
2238
If the argument is omitted or None, strip leading and trailing ASCII
2239
whitespace.
2240
[clinic start generated code]*/
2241
2242
static PyObject *
2243
bytes_strip_impl(PyBytesObject *self, PyObject *bytes)
2244
/*[clinic end generated code: output=c7c228d3bd104a1b input=9ffea5f752032bd0]*/
2245
0
{
2246
0
    return do_argstrip(self, BOTHSTRIP, bytes);
2247
0
}
2248
2249
/*[clinic input]
2250
bytes.lstrip
2251
2252
    bytes: object = None
2253
    /
2254
2255
Strip leading bytes contained in the argument.
2256
2257
If the argument is omitted or None, strip leading  ASCII whitespace.
2258
[clinic start generated code]*/
2259
2260
static PyObject *
2261
bytes_lstrip_impl(PyBytesObject *self, PyObject *bytes)
2262
/*[clinic end generated code: output=28602e586f524e82 input=9baff4398c3f6857]*/
2263
0
{
2264
0
    return do_argstrip(self, LEFTSTRIP, bytes);
2265
0
}
2266
2267
/*[clinic input]
2268
bytes.rstrip
2269
2270
    bytes: object = None
2271
    /
2272
2273
Strip trailing bytes contained in the argument.
2274
2275
If the argument is omitted or None, strip trailing ASCII whitespace.
2276
[clinic start generated code]*/
2277
2278
static PyObject *
2279
bytes_rstrip_impl(PyBytesObject *self, PyObject *bytes)
2280
/*[clinic end generated code: output=547e3815c95447da input=b78af445c727e32b]*/
2281
726
{
2282
726
    return do_argstrip(self, RIGHTSTRIP, bytes);
2283
726
}
2284
2285
2286
/*[clinic input]
2287
@permit_long_summary
2288
bytes.count = bytes.find
2289
2290
Return the number of non-overlapping occurrences of subsection 'sub' in bytes B[start:end].
2291
[clinic start generated code]*/
2292
2293
static PyObject *
2294
bytes_count_impl(PyBytesObject *self, PyObject *sub, Py_ssize_t start,
2295
                 Py_ssize_t end)
2296
/*[clinic end generated code: output=9848140b9be17d0f input=bb2f136f83f0d30e]*/
2297
5.18M
{
2298
5.18M
    return _Py_bytes_count(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
2299
5.18M
                           sub, start, end);
2300
5.18M
}
2301
2302
2303
/*[clinic input]
2304
@permit_long_summary
2305
bytes.translate
2306
2307
    table: object
2308
        Translation table, which must be a bytes object of length 256.
2309
    /
2310
    delete as deletechars: object(c_default="NULL") = b''
2311
2312
Return a copy with each character mapped by the given translation table.
2313
2314
All characters occurring in the optional argument delete are
2315
removed.  The remaining characters are mapped through the given
2316
translation table.
2317
[clinic start generated code]*/
2318
2319
static PyObject *
2320
bytes_translate_impl(PyBytesObject *self, PyObject *table,
2321
                     PyObject *deletechars)
2322
/*[clinic end generated code: output=43be3437f1956211 input=bddcdef0a87895d2]*/
2323
0
{
2324
0
    const char *input;
2325
0
    char *output;
2326
0
    Py_buffer table_view = {NULL, NULL};
2327
0
    Py_buffer del_table_view = {NULL, NULL};
2328
0
    const char *table_chars;
2329
0
    Py_ssize_t i, c, changed = 0;
2330
0
    PyObject *input_obj = (PyObject*)self;
2331
0
    const char *output_start, *del_table_chars=NULL;
2332
0
    Py_ssize_t inlen, tablen, dellen = 0;
2333
0
    int trans_table[256];
2334
2335
0
    if (PyBytes_Check(table)) {
2336
0
        table_chars = PyBytes_AS_STRING(table);
2337
0
        tablen = PyBytes_GET_SIZE(table);
2338
0
    }
2339
0
    else if (table == Py_None) {
2340
0
        table_chars = NULL;
2341
0
        tablen = 256;
2342
0
    }
2343
0
    else {
2344
0
        if (PyObject_GetBuffer(table, &table_view, PyBUF_SIMPLE) != 0)
2345
0
            return NULL;
2346
0
        table_chars = table_view.buf;
2347
0
        tablen = table_view.len;
2348
0
    }
2349
2350
0
    if (tablen != 256) {
2351
0
        PyErr_SetString(PyExc_ValueError,
2352
0
          "translation table must be 256 characters long");
2353
0
        PyBuffer_Release(&table_view);
2354
0
        return NULL;
2355
0
    }
2356
2357
0
    if (deletechars != NULL) {
2358
0
        if (PyBytes_Check(deletechars)) {
2359
0
            del_table_chars = PyBytes_AS_STRING(deletechars);
2360
0
            dellen = PyBytes_GET_SIZE(deletechars);
2361
0
        }
2362
0
        else {
2363
0
            if (PyObject_GetBuffer(deletechars, &del_table_view, PyBUF_SIMPLE) != 0) {
2364
0
                PyBuffer_Release(&table_view);
2365
0
                return NULL;
2366
0
            }
2367
0
            del_table_chars = del_table_view.buf;
2368
0
            dellen = del_table_view.len;
2369
0
        }
2370
0
    }
2371
0
    else {
2372
0
        del_table_chars = NULL;
2373
0
        dellen = 0;
2374
0
    }
2375
2376
0
    inlen = PyBytes_GET_SIZE(input_obj);
2377
0
    PyBytesWriter *writer = PyBytesWriter_Create(inlen);
2378
0
    if (writer == NULL) {
2379
0
        PyBuffer_Release(&del_table_view);
2380
0
        PyBuffer_Release(&table_view);
2381
0
        return NULL;
2382
0
    }
2383
0
    output_start = output = PyBytesWriter_GetData(writer);
2384
0
    input = PyBytes_AS_STRING(input_obj);
2385
2386
0
    if (dellen == 0 && table_chars != NULL) {
2387
        /* If no deletions are required, use faster code */
2388
0
        for (i = inlen; --i >= 0; ) {
2389
0
            c = Py_CHARMASK(*input++);
2390
0
            *output++ = table_chars[c];
2391
0
        }
2392
2393
        /* Check if anything changed (for returning original object) */
2394
        /* We save this check until the end so that the compiler will */
2395
        /* unroll the loop above leading to MUCH faster code. */
2396
0
        PyObject *result;
2397
0
        if (PyBytes_CheckExact(input_obj)
2398
0
            && memcmp(PyBytes_AS_STRING(input_obj), output_start, inlen) == 0)
2399
0
        {
2400
0
            PyBytesWriter_Discard(writer);
2401
0
            result = Py_NewRef(input_obj);
2402
0
        }
2403
0
        else {
2404
0
            result = PyBytesWriter_Finish(writer);
2405
0
        }
2406
2407
0
        PyBuffer_Release(&del_table_view);
2408
0
        PyBuffer_Release(&table_view);
2409
0
        return result;
2410
0
    }
2411
2412
0
    if (table_chars == NULL) {
2413
0
        for (i = 0; i < 256; i++)
2414
0
            trans_table[i] = Py_CHARMASK(i);
2415
0
    } else {
2416
0
        for (i = 0; i < 256; i++)
2417
0
            trans_table[i] = Py_CHARMASK(table_chars[i]);
2418
0
    }
2419
0
    PyBuffer_Release(&table_view);
2420
2421
0
    for (i = 0; i < dellen; i++)
2422
0
        trans_table[(int) Py_CHARMASK(del_table_chars[i])] = -1;
2423
0
    PyBuffer_Release(&del_table_view);
2424
2425
0
    for (i = inlen; --i >= 0; ) {
2426
0
        c = Py_CHARMASK(*input++);
2427
0
        if (trans_table[c] != -1)
2428
0
            if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
2429
0
                continue;
2430
0
        changed = 1;
2431
0
    }
2432
0
    if (!changed && PyBytes_CheckExact(input_obj)) {
2433
0
        PyBytesWriter_Discard(writer);
2434
0
        return Py_NewRef(input_obj);
2435
0
    }
2436
    /* Fix the size of the resulting byte string */
2437
0
    return PyBytesWriter_FinishWithPointer(writer, output);
2438
0
}
2439
2440
2441
/*[clinic input]
2442
2443
@permit_long_summary
2444
@staticmethod
2445
bytes.maketrans
2446
2447
    frm: Py_buffer
2448
    to: Py_buffer
2449
    /
2450
2451
Return a translation table usable for the bytes or bytearray translate method.
2452
2453
The returned table will be one where each byte in frm is mapped to
2454
the byte at the same position in to.
2455
2456
The bytes objects frm and to must be of the same length.
2457
[clinic start generated code]*/
2458
2459
static PyObject *
2460
bytes_maketrans_impl(Py_buffer *frm, Py_buffer *to)
2461
/*[clinic end generated code: output=a36f6399d4b77f6f input=3a577e5badfea8f7]*/
2462
9
{
2463
9
    return _Py_bytes_maketrans(frm, to);
2464
9
}
2465
2466
2467
/*[clinic input]
2468
bytes.replace
2469
2470
    old: Py_buffer
2471
    new: Py_buffer
2472
    /
2473
    count: Py_ssize_t = -1
2474
        Maximum number of occurrences to replace.
2475
        -1 (the default value) means replace all occurrences.
2476
2477
Return a copy with all occurrences of substring old replaced by new.
2478
2479
If count is given, only the first count occurrences are replaced.
2480
If count is not specified or -1, then all occurrences are replaced.
2481
[clinic start generated code]*/
2482
2483
static PyObject *
2484
bytes_replace_impl(PyBytesObject *self, Py_buffer *old, Py_buffer *new,
2485
                   Py_ssize_t count)
2486
/*[clinic end generated code: output=994fa588b6b9c104 input=cdf3cf8639297745]*/
2487
32.2k
{
2488
32.2k
    return stringlib_replace((PyObject *)self,
2489
32.2k
                             (const char *)old->buf, old->len,
2490
32.2k
                             (const char *)new->buf, new->len, count);
2491
32.2k
}
2492
2493
/** End DALKE **/
2494
2495
/*[clinic input]
2496
@permit_long_summary
2497
bytes.removeprefix as bytes_removeprefix
2498
2499
    prefix: Py_buffer
2500
    /
2501
2502
Return a bytes object with the given prefix string removed if present.
2503
2504
If the bytes starts with the prefix string, return
2505
bytes[len(prefix):].  Otherwise, return a copy of the original
2506
bytes.
2507
[clinic start generated code]*/
2508
2509
static PyObject *
2510
bytes_removeprefix_impl(PyBytesObject *self, Py_buffer *prefix)
2511
/*[clinic end generated code: output=f006865331a06ab6 input=3a2672bcee61d7a7]*/
2512
0
{
2513
0
    const char *self_start = PyBytes_AS_STRING(self);
2514
0
    Py_ssize_t self_len = PyBytes_GET_SIZE(self);
2515
0
    const char *prefix_start = prefix->buf;
2516
0
    Py_ssize_t prefix_len = prefix->len;
2517
2518
0
    if (self_len >= prefix_len
2519
0
        && prefix_len > 0
2520
0
        && memcmp(self_start, prefix_start, prefix_len) == 0)
2521
0
    {
2522
0
        return _PyBytes_FromStringAndSize(self_start + prefix_len,
2523
0
                                          self_len - prefix_len);
2524
0
    }
2525
2526
0
    if (PyBytes_CheckExact(self)) {
2527
0
        return Py_NewRef(self);
2528
0
    }
2529
2530
0
    return _PyBytes_FromStringAndSize(self_start, self_len);
2531
0
}
2532
2533
/*[clinic input]
2534
@permit_long_summary
2535
bytes.removesuffix as bytes_removesuffix
2536
2537
    suffix: Py_buffer
2538
    /
2539
2540
Return a bytes object with the given suffix string removed if present.
2541
2542
If the bytes ends with the suffix string and that suffix is not
2543
empty, return bytes[:-len(prefix)].  Otherwise, return a copy of the
2544
original bytes.
2545
[clinic start generated code]*/
2546
2547
static PyObject *
2548
bytes_removesuffix_impl(PyBytesObject *self, Py_buffer *suffix)
2549
/*[clinic end generated code: output=d887d308e3242eeb input=04df5f18a36f69d7]*/
2550
0
{
2551
0
    const char *self_start = PyBytes_AS_STRING(self);
2552
0
    Py_ssize_t self_len = PyBytes_GET_SIZE(self);
2553
0
    const char *suffix_start = suffix->buf;
2554
0
    Py_ssize_t suffix_len = suffix->len;
2555
2556
0
    if (self_len >= suffix_len
2557
0
        && suffix_len > 0
2558
0
        && memcmp(self_start + self_len - suffix_len,
2559
0
                  suffix_start, suffix_len) == 0)
2560
0
    {
2561
0
        return _PyBytes_FromStringAndSize(self_start,
2562
0
                                          self_len - suffix_len);
2563
0
    }
2564
2565
0
    if (PyBytes_CheckExact(self)) {
2566
0
        return Py_NewRef(self);
2567
0
    }
2568
2569
0
    return _PyBytes_FromStringAndSize(self_start, self_len);
2570
0
}
2571
2572
/*[clinic input]
2573
@permit_long_summary
2574
@text_signature "($self, prefix[, start[, end]], /)"
2575
bytes.startswith
2576
2577
    prefix as subobj: object
2578
        A bytes or a tuple of bytes to try.
2579
    start: slice_index(accept={int, NoneType}, c_default='0') = None
2580
        Optional start position. Default: start of the bytes.
2581
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
2582
        Optional stop position. Default: end of the bytes.
2583
    /
2584
2585
Return True if the bytes starts with the specified prefix, False otherwise.
2586
[clinic start generated code]*/
2587
2588
static PyObject *
2589
bytes_startswith_impl(PyBytesObject *self, PyObject *subobj,
2590
                      Py_ssize_t start, Py_ssize_t end)
2591
/*[clinic end generated code: output=b1e8da1cbd528e8c input=a14efd070f15be80]*/
2592
9.69M
{
2593
9.69M
    return _Py_bytes_startswith(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
2594
9.69M
                                subobj, start, end);
2595
9.69M
}
2596
2597
/*[clinic input]
2598
@permit_long_summary
2599
@text_signature "($self, suffix[, start[, end]], /)"
2600
bytes.endswith
2601
2602
    suffix as subobj: object
2603
        A bytes or a tuple of bytes to try.
2604
    start: slice_index(accept={int, NoneType}, c_default='0') = None
2605
         Optional start position. Default: start of the bytes.
2606
    end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
2607
         Optional stop position. Default: end of the bytes.
2608
    /
2609
2610
Return True if the bytes ends with the specified suffix, False otherwise.
2611
[clinic start generated code]*/
2612
2613
static PyObject *
2614
bytes_endswith_impl(PyBytesObject *self, PyObject *subobj, Py_ssize_t start,
2615
                    Py_ssize_t end)
2616
/*[clinic end generated code: output=038b633111f3629d input=49e383eaaf292713]*/
2617
756
{
2618
756
    return _Py_bytes_endswith(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
2619
756
                              subobj, start, end);
2620
756
}
2621
2622
2623
/*[clinic input]
2624
bytes.decode
2625
2626
    encoding: str(c_default="NULL") = 'utf-8'
2627
        The encoding with which to decode the bytes.
2628
    errors: str(c_default="NULL") = 'strict'
2629
        The error handling scheme to use for the handling of decoding
2630
        errors.  The default is 'strict' meaning that decoding errors
2631
        raise a UnicodeDecodeError.  Other possible values are 'ignore'
2632
        and 'replace' as well as any other name registered with
2633
        codecs.register_error that can handle UnicodeDecodeErrors.
2634
2635
Decode the bytes using the codec registered for encoding.
2636
[clinic start generated code]*/
2637
2638
static PyObject *
2639
bytes_decode_impl(PyBytesObject *self, const char *encoding,
2640
                  const char *errors)
2641
/*[clinic end generated code: output=5649a53dde27b314 input=94e9b8524f1d7f37]*/
2642
19.2M
{
2643
19.2M
    return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
2644
19.2M
}
2645
2646
2647
/*[clinic input]
2648
@permit_long_summary
2649
bytes.splitlines
2650
2651
    keepends: bool = False
2652
2653
Return a list of the lines in the bytes, breaking at line boundaries.
2654
2655
Line breaks are not included in the resulting list unless keepends
2656
is given and true.
2657
[clinic start generated code]*/
2658
2659
static PyObject *
2660
bytes_splitlines_impl(PyBytesObject *self, int keepends)
2661
/*[clinic end generated code: output=3484149a5d880ffb input=8734672f34430514]*/
2662
0
{
2663
0
    return stringlib_splitlines(
2664
0
        (PyObject*) self, PyBytes_AS_STRING(self),
2665
0
        PyBytes_GET_SIZE(self), keepends
2666
0
        );
2667
0
}
2668
2669
/*[clinic input]
2670
@classmethod
2671
bytes.fromhex
2672
2673
    string: object
2674
    /
2675
2676
Create a bytes object from a string of hexadecimal numbers.
2677
2678
Spaces between two numbers are accepted.
2679
Example: bytes.fromhex('B9 01EF') -> b'\\xb9\\x01\\xef'.
2680
[clinic start generated code]*/
2681
2682
static PyObject *
2683
bytes_fromhex_impl(PyTypeObject *type, PyObject *string)
2684
/*[clinic end generated code: output=0973acc63661bb2e input=f37d98ed51088a21]*/
2685
31.1k
{
2686
31.1k
    PyObject *result = _PyBytes_FromHex(string, 0);
2687
31.1k
    if (type != &PyBytes_Type && result != NULL) {
2688
0
        Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
2689
0
    }
2690
31.1k
    return result;
2691
31.1k
}
2692
2693
PyObject*
2694
_PyBytes_FromHex(PyObject *string, int use_bytearray)
2695
31.1k
{
2696
31.1k
    Py_ssize_t hexlen, invalid_char;
2697
31.1k
    unsigned int top, bot;
2698
31.1k
    const Py_UCS1 *str, *start, *end;
2699
31.1k
    PyBytesWriter *writer = NULL;
2700
31.1k
    Py_buffer view;
2701
31.1k
    view.obj = NULL;
2702
2703
31.1k
    if (PyUnicode_Check(string)) {
2704
31.1k
        hexlen = PyUnicode_GET_LENGTH(string);
2705
2706
31.1k
        if (!PyUnicode_IS_ASCII(string)) {
2707
0
            const void *data = PyUnicode_DATA(string);
2708
0
            int kind = PyUnicode_KIND(string);
2709
0
            Py_ssize_t i;
2710
2711
            /* search for the first non-ASCII character */
2712
0
            for (i = 0; i < hexlen; i++) {
2713
0
                if (PyUnicode_READ(kind, data, i) >= 128)
2714
0
                    break;
2715
0
            }
2716
0
            invalid_char = i;
2717
0
            goto error;
2718
0
        }
2719
2720
31.1k
        assert(PyUnicode_KIND(string) == PyUnicode_1BYTE_KIND);
2721
31.1k
        str = PyUnicode_1BYTE_DATA(string);
2722
31.1k
    }
2723
0
    else if (PyObject_CheckBuffer(string)) {
2724
0
        if (PyObject_GetBuffer(string, &view, PyBUF_SIMPLE) != 0) {
2725
0
            return NULL;
2726
0
        }
2727
0
        hexlen = view.len;
2728
0
        str = view.buf;
2729
0
    }
2730
0
    else {
2731
0
        PyErr_Format(PyExc_TypeError,
2732
0
                     "fromhex() argument must be str or bytes-like, not %T",
2733
0
                     string);
2734
0
        return NULL;
2735
0
    }
2736
2737
    /* This overestimates if there are spaces */
2738
31.1k
    if (use_bytearray) {
2739
0
        writer = _PyBytesWriter_CreateByteArray(hexlen / 2);
2740
0
    }
2741
31.1k
    else {
2742
31.1k
        writer = PyBytesWriter_Create(hexlen / 2);
2743
31.1k
    }
2744
31.1k
    if (writer == NULL) {
2745
0
        goto release_buffer;
2746
0
    }
2747
31.1k
    char *buf = PyBytesWriter_GetData(writer);
2748
2749
31.1k
    start = str;
2750
31.1k
    end = str + hexlen;
2751
62.2k
    while (str < end) {
2752
        /* skip over spaces in the input */
2753
31.1k
        if (Py_ISSPACE(*str)) {
2754
0
            do {
2755
0
                str++;
2756
0
                if (str >= end) {
2757
0
                    goto done;
2758
0
                }
2759
0
            } while (Py_ISSPACE(*str));
2760
0
        }
2761
2762
31.1k
        top = _PyLong_DigitValue[*str];
2763
31.1k
        if (top >= 16) {
2764
0
            invalid_char = str - start;
2765
0
            goto error;
2766
0
        }
2767
2768
31.1k
        str++;
2769
31.1k
        if (str >= end) {
2770
0
            invalid_char = -1;
2771
0
            goto error;
2772
0
        }
2773
2774
31.1k
        bot = _PyLong_DigitValue[*str];
2775
31.1k
        if (bot >= 16) {
2776
0
            invalid_char = str - start;
2777
0
            goto error;
2778
0
        }
2779
31.1k
        str++;
2780
2781
31.1k
        *buf++ = (unsigned char)((top << 4) + bot);
2782
31.1k
    }
2783
2784
31.1k
  done:
2785
31.1k
    if (view.obj != NULL) {
2786
0
       PyBuffer_Release(&view);
2787
0
    }
2788
31.1k
    return PyBytesWriter_FinishWithPointer(writer, buf);
2789
2790
0
  error:
2791
0
    if (invalid_char == -1) {
2792
0
        PyErr_SetString(PyExc_ValueError,
2793
0
                        "fromhex() arg must contain an even number of hexadecimal digits");
2794
0
    } else {
2795
0
        PyErr_Format(PyExc_ValueError,
2796
0
                     "non-hexadecimal number found in "
2797
0
                     "fromhex() arg at position %zd", invalid_char);
2798
0
    }
2799
0
    PyBytesWriter_Discard(writer);
2800
2801
0
  release_buffer:
2802
0
    if (view.obj != NULL) {
2803
0
        PyBuffer_Release(&view);
2804
0
    }
2805
0
    return NULL;
2806
0
}
2807
2808
/*[clinic input]
2809
bytes.hex
2810
2811
    sep: object = NULL
2812
        An optional single character or byte to separate hex bytes.
2813
    bytes_per_sep: Py_ssize_t = 1
2814
        How many bytes between separators.  Positive values count from
2815
        the right, negative values count from the left.
2816
2817
Create a string of hexadecimal numbers from a bytes object.
2818
2819
Example:
2820
>>> value = b'\xb9\x01\xef'
2821
>>> value.hex()
2822
'b901ef'
2823
>>> value.hex(':')
2824
'b9:01:ef'
2825
>>> value.hex(':', 2)
2826
'b9:01ef'
2827
>>> value.hex(':', -2)
2828
'b901:ef'
2829
[clinic start generated code]*/
2830
2831
static PyObject *
2832
bytes_hex_impl(PyBytesObject *self, PyObject *sep, Py_ssize_t bytes_per_sep)
2833
/*[clinic end generated code: output=588821f02cb9d8f5 input=b8d40cf203d172dc]*/
2834
0
{
2835
0
    const char *argbuf = PyBytes_AS_STRING(self);
2836
0
    Py_ssize_t arglen = PyBytes_GET_SIZE(self);
2837
0
    return _Py_strhex_with_sep(argbuf, arglen, sep, bytes_per_sep);
2838
0
}
2839
2840
static PyObject *
2841
bytes_getnewargs(PyObject *op, PyObject *Py_UNUSED(dummy))
2842
0
{
2843
0
    PyBytesObject *v = _PyBytes_CAST(op);
2844
0
    return Py_BuildValue("(y#)", v->ob_sval, Py_SIZE(v));
2845
0
}
2846
2847
2848
static PyMethodDef
2849
bytes_methods[] = {
2850
    {"__getnewargs__", bytes_getnewargs,  METH_NOARGS},
2851
    BYTES___BYTES___METHODDEF
2852
    {"capitalize", stringlib_capitalize, METH_NOARGS,
2853
     _Py_capitalize__doc__},
2854
    STRINGLIB_CENTER_METHODDEF
2855
    BYTES_COUNT_METHODDEF
2856
    BYTES_DECODE_METHODDEF
2857
    BYTES_ENDSWITH_METHODDEF
2858
    STRINGLIB_EXPANDTABS_METHODDEF
2859
    BYTES_FIND_METHODDEF
2860
    BYTES_FROMHEX_METHODDEF
2861
    BYTES_HEX_METHODDEF
2862
    BYTES_INDEX_METHODDEF
2863
    {"isalnum", stringlib_isalnum, METH_NOARGS,
2864
     _Py_isalnum__doc__},
2865
    {"isalpha", stringlib_isalpha, METH_NOARGS,
2866
     _Py_isalpha__doc__},
2867
    {"isascii", stringlib_isascii, METH_NOARGS,
2868
     _Py_isascii__doc__},
2869
    {"isdigit", stringlib_isdigit, METH_NOARGS,
2870
     _Py_isdigit__doc__},
2871
    {"islower", stringlib_islower, METH_NOARGS,
2872
     _Py_islower__doc__},
2873
    {"isspace", stringlib_isspace, METH_NOARGS,
2874
     _Py_isspace__doc__},
2875
    {"istitle", stringlib_istitle, METH_NOARGS,
2876
     _Py_istitle__doc__},
2877
    {"isupper", stringlib_isupper, METH_NOARGS,
2878
     _Py_isupper__doc__},
2879
    BYTES_JOIN_METHODDEF
2880
    STRINGLIB_LJUST_METHODDEF
2881
    {"lower", stringlib_lower, METH_NOARGS, _Py_lower__doc__},
2882
    BYTES_LSTRIP_METHODDEF
2883
    BYTES_MAKETRANS_METHODDEF
2884
    BYTES_PARTITION_METHODDEF
2885
    BYTES_REPLACE_METHODDEF
2886
    BYTES_REMOVEPREFIX_METHODDEF
2887
    BYTES_REMOVESUFFIX_METHODDEF
2888
    BYTES_RFIND_METHODDEF
2889
    BYTES_RINDEX_METHODDEF
2890
    STRINGLIB_RJUST_METHODDEF
2891
    BYTES_RPARTITION_METHODDEF
2892
    BYTES_RSPLIT_METHODDEF
2893
    BYTES_RSTRIP_METHODDEF
2894
    BYTES_SPLIT_METHODDEF
2895
    BYTES_SPLITLINES_METHODDEF
2896
    BYTES_STARTSWITH_METHODDEF
2897
    BYTES_STRIP_METHODDEF
2898
    {"swapcase", stringlib_swapcase, METH_NOARGS,
2899
     _Py_swapcase__doc__},
2900
    {"title", stringlib_title, METH_NOARGS, _Py_title__doc__},
2901
    BYTES_TRANSLATE_METHODDEF
2902
    {"upper", stringlib_upper, METH_NOARGS, _Py_upper__doc__},
2903
    STRINGLIB_ZFILL_METHODDEF
2904
    {NULL,     NULL}                         /* sentinel */
2905
};
2906
2907
static PyObject *
2908
bytes_mod(PyObject *self, PyObject *arg)
2909
0
{
2910
0
    if (!PyBytes_Check(self)) {
2911
0
        Py_RETURN_NOTIMPLEMENTED;
2912
0
    }
2913
0
    return _PyBytes_FormatEx(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
2914
0
                             arg, 0);
2915
0
}
2916
2917
static PyNumberMethods bytes_as_number = {
2918
    0,              /*nb_add*/
2919
    0,              /*nb_subtract*/
2920
    0,              /*nb_multiply*/
2921
    bytes_mod,      /*nb_remainder*/
2922
};
2923
2924
static PyObject *
2925
bytes_subtype_new(PyTypeObject *, PyObject *);
2926
2927
/*[clinic input]
2928
@vectorcall
2929
@classmethod
2930
bytes.__new__ as bytes_new
2931
2932
    source as x: object = NULL
2933
    encoding: str = NULL
2934
    errors: str = NULL
2935
2936
[clinic start generated code]*/
2937
2938
static PyObject *
2939
bytes_new_impl(PyTypeObject *type, PyObject *x, const char *encoding,
2940
               const char *errors)
2941
/*[clinic end generated code: output=1e0c471be311a425 input=b0248d22e221a095]*/
2942
16.3M
{
2943
16.3M
    PyObject *bytes;
2944
16.3M
    PyObject *func;
2945
16.3M
    Py_ssize_t size;
2946
2947
16.3M
    if (x == NULL) {
2948
0
        if (encoding != NULL || errors != NULL) {
2949
0
            PyErr_SetString(PyExc_TypeError,
2950
0
                            encoding != NULL ?
2951
0
                            "encoding without a string argument" :
2952
0
                            "errors without a string argument");
2953
0
            return NULL;
2954
0
        }
2955
0
        bytes = Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
2956
0
    }
2957
16.3M
    else if (encoding != NULL) {
2958
        /* Encode via the codec registry */
2959
323k
        if (!PyUnicode_Check(x)) {
2960
0
            PyErr_SetString(PyExc_TypeError,
2961
0
                            "encoding without a string argument");
2962
0
            return NULL;
2963
0
        }
2964
323k
        bytes = PyUnicode_AsEncodedString(x, encoding, errors);
2965
323k
    }
2966
15.9M
    else if (errors != NULL) {
2967
0
        PyErr_SetString(PyExc_TypeError,
2968
0
                        PyUnicode_Check(x) ?
2969
0
                        "string argument without an encoding" :
2970
0
                        "errors without a string argument");
2971
0
        return NULL;
2972
0
    }
2973
    /* We'd like to call PyObject_Bytes here, but we need to check for an
2974
       integer argument before deferring to PyBytes_FromObject, something
2975
       PyObject_Bytes doesn't do. */
2976
15.9M
    else if ((func = _PyObject_LookupSpecial(x, &_Py_ID(__bytes__))) != NULL) {
2977
45.1k
        bytes = _PyObject_CallNoArgs(func);
2978
45.1k
        Py_DECREF(func);
2979
45.1k
        if (bytes == NULL)
2980
0
            return NULL;
2981
45.1k
        if (!PyBytes_Check(bytes)) {
2982
0
            PyErr_Format(PyExc_TypeError,
2983
0
                         "%T.__bytes__() must return a bytes, not %T",
2984
0
                         x, bytes);
2985
0
            Py_DECREF(bytes);
2986
0
            return NULL;
2987
0
        }
2988
45.1k
    }
2989
15.9M
    else if (PyErr_Occurred())
2990
0
        return NULL;
2991
15.9M
    else if (PyUnicode_Check(x)) {
2992
0
        PyErr_SetString(PyExc_TypeError,
2993
0
                        "string argument without an encoding");
2994
0
        return NULL;
2995
0
    }
2996
    /* Is it an integer? */
2997
15.9M
    else if (_PyIndex_Check(x)) {
2998
0
        size = PyNumber_AsSsize_t(x, PyExc_OverflowError);
2999
0
        if (size == -1 && PyErr_Occurred()) {
3000
0
            if (!PyErr_ExceptionMatches(PyExc_TypeError))
3001
0
                return NULL;
3002
0
            PyErr_Clear();  /* fall through */
3003
0
            bytes = PyBytes_FromObject(x);
3004
0
        }
3005
0
        else {
3006
0
            if (size < 0) {
3007
0
                PyErr_SetString(PyExc_ValueError, "negative count");
3008
0
                return NULL;
3009
0
            }
3010
0
            bytes = _PyBytes_FromSizeZero(size);
3011
0
        }
3012
0
    }
3013
15.9M
    else {
3014
15.9M
        bytes = PyBytes_FromObject(x);
3015
15.9M
    }
3016
3017
16.3M
    if (bytes != NULL && type != &PyBytes_Type) {
3018
0
        Py_SETREF(bytes, bytes_subtype_new(type, bytes));
3019
0
    }
3020
3021
16.3M
    return bytes;
3022
16.3M
}
3023
3024
static PyObject*
3025
_PyBytes_FromBuffer(PyObject *x)
3026
15.9M
{
3027
15.9M
    Py_buffer view;
3028
15.9M
    if (PyObject_GetBuffer(x, &view, PyBUF_FULL_RO) < 0)
3029
0
        return NULL;
3030
3031
15.9M
    PyBytesWriter *writer = PyBytesWriter_Create(view.len);
3032
15.9M
    if (writer == NULL) {
3033
0
        goto fail;
3034
0
    }
3035
3036
15.9M
    if (PyBuffer_ToContiguous(PyBytesWriter_GetData(writer),
3037
15.9M
                              &view, view.len, 'C') < 0) {
3038
0
        goto fail;
3039
0
    }
3040
3041
15.9M
    PyBuffer_Release(&view);
3042
15.9M
    return PyBytesWriter_Finish(writer);
3043
3044
0
fail:
3045
0
    PyBytesWriter_Discard(writer);
3046
0
    PyBuffer_Release(&view);
3047
0
    return NULL;
3048
15.9M
}
3049
3050
/* Fast path for a list or tuple of ints.
3051
   Return 1 on success (*result set to the new bytes object),
3052
   0 to fall back to the slow path, or -1 on error (with an exception set). */
3053
static int
3054
_PyBytes_FromSequence_lock_held(PyObject *x, PyObject **result)
3055
9.18k
{
3056
9.18k
    *result = NULL;
3057
9.18k
    Py_ssize_t size = PySequence_Fast_GET_SIZE(x);
3058
9.18k
    PyBytesWriter *writer = PyBytesWriter_Create(size);
3059
9.18k
    if (writer == NULL) {
3060
0
        return -1;
3061
0
    }
3062
9.18k
    char *str = PyBytesWriter_GetData(writer);
3063
3064
9.18k
    PyObject *const *items = PySequence_Fast_ITEMS(x);
3065
723k
    for (Py_ssize_t i = 0; i < size; i++) {
3066
714k
        Py_ssize_t value = PyLong_AsSsize_t(items[i]);
3067
714k
        if (value == -1 && PyErr_Occurred()) {
3068
0
            PyBytesWriter_Discard(writer);
3069
0
            PyErr_Clear();
3070
0
            return 0;
3071
0
        }
3072
3073
714k
        if (value < 0 || value >= 256) {
3074
0
            PyErr_SetString(PyExc_ValueError,
3075
0
                            "bytes must be in range(0, 256)");
3076
0
            PyBytesWriter_Discard(writer);
3077
0
            return -1;
3078
0
        }
3079
714k
        *str++ = (char) value;
3080
714k
    }
3081
9.18k
    *result = PyBytesWriter_Finish(writer);
3082
9.18k
    return *result != NULL ? 1 : -1;
3083
9.18k
}
3084
3085
static PyObject *
3086
_PyBytes_FromIterator(PyObject *it, PyObject *x)
3087
180
{
3088
180
    Py_ssize_t i, size;
3089
3090
    /* For iterator version, create a bytes object and resize as needed */
3091
180
    size = PyObject_LengthHint(x, 64);
3092
180
    if (size == -1 && PyErr_Occurred())
3093
0
        return NULL;
3094
3095
180
    PyBytesWriter *writer = PyBytesWriter_Create(size);
3096
180
    if (writer == NULL) {
3097
0
        return NULL;
3098
0
    }
3099
180
    size = _PyBytesWriter_ResizeToAllocated(writer);
3100
180
    char *str = PyBytesWriter_GetData(writer);
3101
3102
    /* Run the iterator to exhaustion */
3103
1.14k
    for (i = 0; ; i++) {
3104
1.14k
        PyObject *item;
3105
1.14k
        Py_ssize_t value;
3106
3107
        /* Get the next item */
3108
1.14k
        item = PyIter_Next(it);
3109
1.14k
        if (item == NULL) {
3110
180
            if (PyErr_Occurred())
3111
0
                goto error;
3112
180
            break;
3113
180
        }
3114
3115
        /* Interpret it as an int (__index__) */
3116
968
        value = PyNumber_AsSsize_t(item, NULL);
3117
968
        Py_DECREF(item);
3118
968
        if (value == -1 && PyErr_Occurred())
3119
0
            goto error;
3120
3121
        /* Range check */
3122
968
        if (value < 0 || value >= 256) {
3123
0
            PyErr_SetString(PyExc_ValueError,
3124
0
                            "bytes must be in range(0, 256)");
3125
0
            goto error;
3126
0
        }
3127
3128
        /* Append the byte */
3129
968
        if (i >= size) {
3130
0
            str = _PyBytesWriter_ResizeAndUpdatePointer(writer, size + 1, str);
3131
0
            if (str == NULL) {
3132
0
                goto error;
3133
0
            }
3134
3135
            // Set the writer size to its allocated size
3136
0
            size = _PyBytesWriter_ResizeToAllocated(writer);
3137
0
        }
3138
968
        *str++ = (char) value;
3139
968
    }
3140
180
    return PyBytesWriter_FinishWithPointer(writer, str);
3141
3142
0
  error:
3143
0
    PyBytesWriter_Discard(writer);
3144
0
    return NULL;
3145
180
}
3146
3147
PyObject *
3148
PyBytes_FromObject(PyObject *x)
3149
15.9M
{
3150
15.9M
    PyObject *it, *result;
3151
3152
15.9M
    if (x == NULL) {
3153
0
        PyErr_BadInternalCall();
3154
0
        return NULL;
3155
0
    }
3156
3157
15.9M
    if (PyBytes_CheckExact(x)) {
3158
0
        return Py_NewRef(x);
3159
0
    }
3160
3161
    /* Use the modern buffer interface */
3162
15.9M
    if (PyObject_CheckBuffer(x))
3163
15.9M
        return _PyBytes_FromBuffer(x);
3164
3165
9.36k
    if (PyList_CheckExact(x) || PyTuple_CheckExact(x)) {
3166
9.18k
        int rc;
3167
9.18k
        Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST(x);
3168
9.18k
        rc = _PyBytes_FromSequence_lock_held(x, &result);
3169
9.18k
        Py_END_CRITICAL_SECTION_SEQUENCE_FAST();
3170
9.18k
        if (rc != 0) {
3171
9.18k
            return result;
3172
9.18k
        }
3173
9.18k
    }
3174
3175
180
    if (!PyUnicode_Check(x)) {
3176
180
        it = PyObject_GetIter(x);
3177
180
        if (it != NULL) {
3178
180
            result = _PyBytes_FromIterator(it, x);
3179
180
            Py_DECREF(it);
3180
180
            return result;
3181
180
        }
3182
0
        if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
3183
0
            return NULL;
3184
0
        }
3185
0
    }
3186
3187
0
    PyErr_Format(PyExc_TypeError,
3188
0
                 "cannot convert '%.200s' object to bytes",
3189
0
                 Py_TYPE(x)->tp_name);
3190
0
    return NULL;
3191
180
}
3192
3193
/* This allocator is needed for subclasses don't want to use __new__.
3194
 * See https://github.com/python/cpython/issues/91020#issuecomment-1096793239
3195
 *
3196
 * This allocator will be removed when ob_shash is removed.
3197
 */
3198
static PyObject *
3199
bytes_type_alloc(PyTypeObject *self, Py_ssize_t nitems)
3200
0
{
3201
    // Initialize memory to zero
3202
0
    PyBytesObject *obj = (PyBytesObject*)PyType_GenericAlloc(self, nitems);
3203
0
    if (obj == NULL) {
3204
0
        return NULL;
3205
0
    }
3206
0
    set_ob_shash_unsafe(obj, -1);
3207
0
    return (PyObject*)obj;
3208
0
}
3209
3210
static PyObject *
3211
bytes_subtype_new(PyTypeObject *type, PyObject *tmp)
3212
0
{
3213
0
    PyObject *pnew;
3214
0
    Py_ssize_t n;
3215
3216
0
    assert(PyType_IsSubtype(type, &PyBytes_Type));
3217
0
    assert(PyBytes_Check(tmp));
3218
0
    n = PyBytes_GET_SIZE(tmp);
3219
0
    pnew = type->tp_alloc(type, n);
3220
0
    if (pnew != NULL) {
3221
0
        memcpy(PyBytes_AS_STRING(pnew), PyBytes_AS_STRING(tmp), n+1);
3222
0
        set_ob_shash_unsafe((PyBytesObject*)pnew,
3223
0
                            get_ob_shash((PyBytesObject *)tmp));
3224
0
    }
3225
0
    return pnew;
3226
0
}
3227
3228
PyDoc_STRVAR(bytes_doc,
3229
"bytes(iterable_of_ints) -> bytes\n\
3230
bytes(string, encoding[, errors]) -> bytes\n\
3231
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer\n\
3232
bytes(int) -> bytes object of size given by the parameter initialized with null bytes\n\
3233
bytes() -> empty bytes object\n\
3234
\n\
3235
Construct an immutable array of bytes from:\n\
3236
  - an iterable yielding integers in range(256)\n\
3237
  - a text string encoded using the specified encoding\n\
3238
  - any object implementing the buffer API.\n\
3239
  - an integer");
3240
3241
static PyObject *bytes_iter(PyObject *seq);
3242
3243
3244
static _PyObjectIndexPair
3245
bytes_iteritem(PyObject *obj, Py_ssize_t index)
3246
1.34k
{
3247
1.34k
    PyBytesObject *a = _PyBytes_CAST(obj);
3248
1.34k
    if (index >= Py_SIZE(a)) {
3249
39
        return (_PyObjectIndexPair) { .object = NULL, .index = index };
3250
39
    }
3251
1.30k
    PyObject *l = _PyLong_FromUnsignedChar((unsigned char)a->ob_sval[index]);
3252
1.30k
    return (_PyObjectIndexPair) { .object = l, .index = index + 1 };
3253
1.34k
}
3254
3255
#ifdef Py_DEBUG
3256
void
3257
_PyBytes_CheckOverflow(PyObject *self, void *addr, const char *type_name)
3258
{
3259
    // Make sure that the trailing null byte was not modified
3260
    char *data = PyBytes_AS_STRING(self);
3261
    Py_ssize_t size = PyBytes_GET_SIZE(self);
3262
    if (data[size] != '\0') {
3263
        _Py_FatalErrorFormat(__func__,
3264
                             "Buffer overflow detected in %s object %p "
3265
                             "at position %zd",
3266
                             type_name, addr, size);
3267
    }
3268
}
3269
3270
3271
static void
3272
bytes_dealloc(PyObject *op)
3273
{
3274
    PyBytesObject *self = _PyBytes_CAST(op);
3275
    _PyBytes_CheckOverflow(op, op, "bytes");
3276
    Py_TYPE(self)->tp_free((PyObject *)self);
3277
}
3278
#endif
3279
3280
3281
PyTypeObject PyBytes_Type = {
3282
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3283
    "bytes",
3284
    PyBytesObject_SIZE,
3285
    sizeof(char),
3286
#ifdef Py_DEBUG
3287
    bytes_dealloc,                              /* tp_dealloc */
3288
#else
3289
    0,                                          /* tp_dealloc */
3290
#endif
3291
    0,                                          /* tp_vectorcall_offset */
3292
    0,                                          /* tp_getattr */
3293
    0,                                          /* tp_setattr */
3294
    0,                                          /* tp_as_async */
3295
    bytes_repr,                                 /* tp_repr */
3296
    &bytes_as_number,                           /* tp_as_number */
3297
    &bytes_as_sequence,                         /* tp_as_sequence */
3298
    &bytes_as_mapping,                          /* tp_as_mapping */
3299
    bytes_hash,                                 /* tp_hash */
3300
    0,                                          /* tp_call */
3301
    bytes_str,                                  /* tp_str */
3302
    PyObject_GenericGetAttr,                    /* tp_getattro */
3303
    0,                                          /* tp_setattro */
3304
    &bytes_as_buffer,                           /* tp_as_buffer */
3305
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3306
        Py_TPFLAGS_BYTES_SUBCLASS |
3307
        _Py_TPFLAGS_MATCH_SELF,               /* tp_flags */
3308
    bytes_doc,                                  /* tp_doc */
3309
    0,                                          /* tp_traverse */
3310
    0,                                          /* tp_clear */
3311
    bytes_richcompare,                          /* tp_richcompare */
3312
    0,                                          /* tp_weaklistoffset */
3313
    bytes_iter,                                 /* tp_iter */
3314
    0,                                          /* tp_iternext */
3315
    bytes_methods,                              /* tp_methods */
3316
    0,                                          /* tp_members */
3317
    0,                                          /* tp_getset */
3318
    0,                                          /* tp_base */
3319
    0,                                          /* tp_dict */
3320
    0,                                          /* tp_descr_get */
3321
    0,                                          /* tp_descr_set */
3322
    0,                                          /* tp_dictoffset */
3323
    0,                                          /* tp_init */
3324
    bytes_type_alloc,                           /* tp_alloc */
3325
    bytes_new,                                  /* tp_new */
3326
    PyObject_Free,                              /* tp_free */
3327
    .tp_vectorcall = bytes_vectorcall,
3328
    .tp_version_tag = _Py_TYPE_VERSION_BYTES,
3329
    ._tp_iteritem = bytes_iteritem,
3330
};
3331
3332
void
3333
PyBytes_Concat(PyObject **pv, PyObject *w)
3334
0
{
3335
0
    assert(pv != NULL);
3336
0
    if (*pv == NULL)
3337
0
        return;
3338
0
    if (w == NULL) {
3339
0
        Py_CLEAR(*pv);
3340
0
        return;
3341
0
    }
3342
3343
0
    if (_PyObject_IsUniquelyReferenced(*pv) && PyBytes_CheckExact(*pv)) {
3344
        /* Only one reference, so we can resize in place */
3345
0
        Py_ssize_t oldsize;
3346
0
        Py_buffer wb;
3347
3348
0
        if (PyObject_GetBuffer(w, &wb, PyBUF_SIMPLE) != 0) {
3349
0
            PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
3350
0
                         Py_TYPE(w)->tp_name, Py_TYPE(*pv)->tp_name);
3351
0
            Py_CLEAR(*pv);
3352
0
            return;
3353
0
        }
3354
3355
0
        oldsize = PyBytes_GET_SIZE(*pv);
3356
0
        if (oldsize > PY_SSIZE_T_MAX - wb.len) {
3357
0
            PyErr_NoMemory();
3358
0
            goto error;
3359
0
        }
3360
0
        if (_PyBytes_Resize(pv, oldsize + wb.len) < 0)
3361
0
            goto error;
3362
3363
0
        memcpy(PyBytes_AS_STRING(*pv) + oldsize, wb.buf, wb.len);
3364
0
        PyBuffer_Release(&wb);
3365
0
        return;
3366
3367
0
      error:
3368
0
        PyBuffer_Release(&wb);
3369
0
        Py_CLEAR(*pv);
3370
0
        return;
3371
0
    }
3372
3373
0
    else {
3374
        /* Multiple references, need to create new object */
3375
0
        PyObject *v;
3376
0
        v = _PyBytes_Concat(*pv, w);
3377
0
        Py_SETREF(*pv, v);
3378
0
    }
3379
0
}
3380
3381
void
3382
PyBytes_ConcatAndDel(PyObject **pv, PyObject *w)
3383
0
{
3384
0
    PyBytes_Concat(pv, w);
3385
0
    Py_XDECREF(w);
3386
0
}
3387
3388
3389
#ifndef NDEBUG
3390
// Make sure that a bytes object can still be mutated.
3391
//
3392
// Usage: assert(_PyBytes_IsMutable(obj)).
3393
int
3394
_PyBytes_IsMutable(PyObject *self)
3395
{
3396
    assert(PyBytes_Check(self));
3397
    // Do not use _PyObject_IsUniquelyReferenced(): this function is called
3398
    // by bytearray and PyBytesWriter which can be used by multiple threads.
3399
    assert(Py_REFCNT(self) == 1);
3400
    assert(!_Py_IsImmortal(self));
3401
3402
    // Check that the object is not a singleton
3403
    Py_ssize_t size = PyBytes_GET_SIZE(self);
3404
    if (size == 0) {
3405
        assert(self != bytes_get_empty());
3406
    }
3407
    else if (size == 1) {
3408
        unsigned char ch = PyBytes_AS_STRING(self)[0];
3409
        assert(self != (PyObject*)CHARACTER(ch));
3410
    }
3411
3412
    // gh-158219: The hash value must not be cached yet. Otherwise, it means
3413
    // that the bytes object was already used in Python somehow (ex: as a
3414
    // dictionary key).
3415
    assert(get_ob_shash((PyBytesObject *)self) == -1);
3416
3417
    return 1;
3418
}
3419
#endif
3420
3421
3422
static inline int
3423
bytes_resize_inplace(PyObject **pv, Py_ssize_t newsize)
3424
9.52M
{
3425
9.52M
    PyObject *v = *pv;
3426
    // Do not test _PyObject_IsUniquelyReferenced(). The function is used by
3427
    // PyBytesWriter_FinishWithSize() and its caller can have its own lock.
3428
9.52M
    assert(Py_REFCNT(v) == 1);
3429
9.52M
    assert(PyBytes_GET_SIZE(v) >= 1);
3430
9.52M
    assert(newsize >= 1);
3431
9.52M
    assert(get_ob_shash((PyBytesObject *)v) == -1);
3432
3433
    // Only mutable bytes can be resized in-place
3434
9.52M
    assert(_PyBytes_IsMutable(v));
3435
3436
9.52M
    if ((size_t)newsize > (size_t)PY_SSIZE_T_MAX - PyBytesObject_SIZE) {
3437
0
        PyErr_SetString(PyExc_OverflowError,
3438
0
                        "byte string is too large");
3439
0
        return -1;
3440
0
    }
3441
3442
#ifdef Py_TRACE_REFS
3443
    _Py_ForgetReference(v);
3444
#endif
3445
9.52M
    _PyReftracerTrack(v, PyRefTracer_DESTROY);
3446
3447
9.52M
    PyObject *result = PyObject_Realloc(v, PyBytesObject_SIZE + newsize);
3448
9.52M
    if (result == NULL) {
3449
#ifdef Py_TRACE_REFS
3450
        _Py_AddToAllObjects(v);
3451
#endif
3452
0
        _PyReftracerTrack(v, PyRefTracer_CREATE);
3453
3454
0
        PyErr_NoMemory();
3455
0
        return -1;
3456
0
    }
3457
3458
9.52M
    *pv = result;
3459
9.52M
    v = result;
3460
9.52M
    _Py_NewReferenceNoTotal(v);
3461
9.52M
    PyBytesObject *sv = (PyBytesObject *)v;
3462
9.52M
    Py_SET_SIZE(sv, newsize);
3463
9.52M
    sv->ob_sval[newsize] = '\0';
3464
9.52M
    assert(_PyBytes_IsMutable(*pv));
3465
9.52M
    return 0;
3466
9.52M
}
3467
3468
3469
/* The following function breaks the notion that bytes are immutable:
3470
   it changes the size of a bytes object.  You can think of it
3471
   as creating a new bytes object and destroying the old one, only
3472
   more efficiently.
3473
   Note that if there's not enough memory to resize the bytes object, the
3474
   original bytes object at *pv is deallocated, *pv is set to NULL, an "out of
3475
   memory" exception is set, and -1 is returned.  Else (on success) 0 is
3476
   returned, and the value in *pv may or may not be the same as on input.
3477
   As always, an extra byte is allocated for a trailing \0 byte (newsize
3478
   does *not* include that), and a trailing \0 byte is stored.
3479
*/
3480
3481
// Similar to _PyBytes_Resize(), but leaves the object unchanged on error.
3482
int
3483
_PyBytes_ResizeKeepOnError(PyObject **pv, Py_ssize_t newsize)
3484
35.7M
{
3485
35.7M
    PyObject *v = *pv;
3486
3487
35.7M
    if (!PyBytes_Check(v) || newsize < 0) {
3488
0
        PyErr_BadInternalCall();
3489
0
        return -1;
3490
0
    }
3491
3492
35.7M
    Py_ssize_t oldsize = PyBytes_GET_SIZE(v);
3493
35.7M
    if (oldsize == newsize) {
3494
        // Leave the object unchanged if the new size is the same as the old
3495
        // size, even if the object is not uniquely referenced or if the hash
3496
        // value was already computed.
3497
5.70M
        return 0;
3498
5.70M
    }
3499
3500
30.0M
    if (oldsize == 0) {
3501
21.1M
        assert(newsize >= 1);
3502
21.1M
        PyObject *result = bytes_alloc(newsize);
3503
21.1M
        if (result == NULL) {
3504
0
            return -1;
3505
0
        }
3506
21.1M
        *pv = result;
3507
21.1M
        Py_DECREF(v);
3508
21.1M
        assert(_PyBytes_IsMutable(*pv));
3509
21.1M
        return 0;
3510
21.1M
    }
3511
3512
8.91M
    if (newsize == 0) {
3513
4.07k
        *pv = bytes_get_empty();  // cannot fail
3514
4.07k
        Py_DECREF(v);
3515
4.07k
        return 0;
3516
4.07k
    }
3517
3518
8.90M
    if (!_PyObject_IsUniquelyReferenced(v)
3519
        // Return a copy if the hash value was already computed
3520
8.90M
        || get_ob_shash((PyBytesObject *)v) != -1)
3521
0
    {
3522
        // Allocate and then copy so we don't get a shared immortal
3523
        // one-character singleton!
3524
0
        PyObject *result = bytes_alloc(newsize);
3525
0
        if (!result) {
3526
0
            return -1;
3527
0
        }
3528
3529
0
        memcpy(PyBytes_AS_STRING(result), PyBytes_AS_STRING(v),
3530
0
               Py_MIN(oldsize, newsize));
3531
0
        *pv = result;
3532
0
        Py_DECREF(v);
3533
0
        assert(_PyBytes_IsMutable(*pv));
3534
0
        return 0;
3535
0
    }
3536
3537
8.90M
    return bytes_resize_inplace(pv, newsize);
3538
8.90M
}
3539
3540
3541
int
3542
_PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
3543
23.6k
{
3544
23.6k
    int res = _PyBytes_ResizeKeepOnError(pv, newsize);
3545
23.6k
    if (res < 0) {
3546
0
        PyObject *v = *pv;
3547
0
        *pv = NULL;
3548
0
        Py_DECREF(v);
3549
0
    }
3550
23.6k
    return res;
3551
23.6k
}
3552
3553
3554
/*********************** Bytes Iterator ****************************/
3555
3556
typedef struct {
3557
    PyObject_HEAD
3558
    Py_ssize_t it_index;
3559
    PyBytesObject *it_seq; /* Set to NULL when iterator is exhausted */
3560
} striterobject;
3561
3562
309
#define _striterobject_CAST(op)  ((striterobject *)(op))
3563
3564
static void
3565
striter_dealloc(PyObject *op)
3566
41
{
3567
41
    striterobject *it = _striterobject_CAST(op);
3568
41
    _PyObject_GC_UNTRACK(it);
3569
41
    Py_XDECREF(it->it_seq);
3570
41
    PyObject_GC_Del(it);
3571
41
}
3572
3573
static int
3574
striter_traverse(PyObject *op, visitproc visit, void *arg)
3575
0
{
3576
0
    striterobject *it = _striterobject_CAST(op);
3577
0
    Py_VISIT(it->it_seq);
3578
0
    return 0;
3579
0
}
3580
3581
static PyObject *
3582
striter_next(PyObject *op)
3583
268
{
3584
268
    striterobject *it = _striterobject_CAST(op);
3585
268
    PyBytesObject *seq;
3586
3587
268
    assert(it != NULL);
3588
268
    seq = it->it_seq;
3589
268
    if (seq == NULL)
3590
0
        return NULL;
3591
268
    assert(PyBytes_Check(seq));
3592
3593
268
    if (it->it_index < PyBytes_GET_SIZE(seq)) {
3594
264
        return _PyLong_FromUnsignedChar(
3595
264
            (unsigned char)seq->ob_sval[it->it_index++]);
3596
264
    }
3597
3598
4
    it->it_seq = NULL;
3599
4
    Py_DECREF(seq);
3600
4
    return NULL;
3601
268
}
3602
3603
static PyObject *
3604
striter_len(PyObject *op, PyObject *Py_UNUSED(ignored))
3605
0
{
3606
0
    striterobject *it = _striterobject_CAST(op);
3607
0
    Py_ssize_t len = 0;
3608
0
    if (it->it_seq)
3609
0
        len = PyBytes_GET_SIZE(it->it_seq) - it->it_index;
3610
0
    return PyLong_FromSsize_t(len);
3611
0
}
3612
3613
PyDoc_STRVAR(length_hint_doc,
3614
             "Private method returning an estimate of len(list(it)).");
3615
3616
static PyObject *
3617
striter_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
3618
0
{
3619
0
    PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
3620
3621
    /* _PyEval_GetBuiltin can invoke arbitrary code,
3622
     * call must be before access of iterator pointers.
3623
     * see issue #101765 */
3624
0
    striterobject *it = _striterobject_CAST(op);
3625
0
    if (it->it_seq != NULL) {
3626
0
        return Py_BuildValue("N(O)n", iter, it->it_seq, it->it_index);
3627
0
    } else {
3628
0
        return Py_BuildValue("N(())", iter);
3629
0
    }
3630
0
}
3631
3632
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3633
3634
static PyObject *
3635
striter_setstate(PyObject *op, PyObject *state)
3636
0
{
3637
0
    Py_ssize_t index = PyLong_AsSsize_t(state);
3638
0
    if (index == -1 && PyErr_Occurred())
3639
0
        return NULL;
3640
0
    striterobject *it = _striterobject_CAST(op);
3641
0
    if (it->it_seq != NULL) {
3642
0
        if (index < 0)
3643
0
            index = 0;
3644
0
        else if (index > PyBytes_GET_SIZE(it->it_seq))
3645
0
            index = PyBytes_GET_SIZE(it->it_seq); /* iterator exhausted */
3646
0
        it->it_index = index;
3647
0
    }
3648
0
    Py_RETURN_NONE;
3649
0
}
3650
3651
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
3652
3653
static PyMethodDef striter_methods[] = {
3654
    {"__length_hint__", striter_len, METH_NOARGS, length_hint_doc},
3655
    {"__reduce__",      striter_reduce, METH_NOARGS, reduce_doc},
3656
    {"__setstate__",    striter_setstate, METH_O, setstate_doc},
3657
    {NULL,              NULL}           /* sentinel */
3658
};
3659
3660
PyTypeObject PyBytesIter_Type = {
3661
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3662
    "bytes_iterator",                           /* tp_name */
3663
    sizeof(striterobject),                      /* tp_basicsize */
3664
    0,                                          /* tp_itemsize */
3665
    /* methods */
3666
    striter_dealloc,                            /* tp_dealloc */
3667
    0,                                          /* tp_vectorcall_offset */
3668
    0,                                          /* tp_getattr */
3669
    0,                                          /* tp_setattr */
3670
    0,                                          /* tp_as_async */
3671
    0,                                          /* tp_repr */
3672
    0,                                          /* tp_as_number */
3673
    0,                                          /* tp_as_sequence */
3674
    0,                                          /* tp_as_mapping */
3675
    0,                                          /* tp_hash */
3676
    0,                                          /* tp_call */
3677
    0,                                          /* tp_str */
3678
    PyObject_GenericGetAttr,                    /* tp_getattro */
3679
    0,                                          /* tp_setattro */
3680
    0,                                          /* tp_as_buffer */
3681
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3682
    0,                                          /* tp_doc */
3683
    striter_traverse,                           /* tp_traverse */
3684
    0,                                          /* tp_clear */
3685
    0,                                          /* tp_richcompare */
3686
    0,                                          /* tp_weaklistoffset */
3687
    PyObject_SelfIter,                          /* tp_iter */
3688
    striter_next,                               /* tp_iternext */
3689
    striter_methods,                            /* tp_methods */
3690
    0,
3691
};
3692
3693
static PyObject *
3694
bytes_iter(PyObject *seq)
3695
41
{
3696
41
    striterobject *it;
3697
3698
41
    if (!PyBytes_Check(seq)) {
3699
0
        PyErr_BadInternalCall();
3700
0
        return NULL;
3701
0
    }
3702
41
    it = PyObject_GC_New(striterobject, &PyBytesIter_Type);
3703
41
    if (it == NULL)
3704
0
        return NULL;
3705
41
    it->it_index = 0;
3706
41
    it->it_seq = (PyBytesObject *)Py_NewRef(seq);
3707
41
    _PyObject_GC_TRACK(it);
3708
41
    return (PyObject *)it;
3709
41
}
3710
3711
3712
void
3713
_PyBytes_RepeatBuffer(char* dest, Py_ssize_t len_dest,
3714
    const char* src, Py_ssize_t len_src)
3715
122k
{
3716
122k
    if (len_dest == 0) {
3717
0
        return;
3718
0
    }
3719
122k
    if (len_src == 1) {
3720
120k
        memset(dest, src[0], len_dest);
3721
120k
    }
3722
2.29k
    else {
3723
2.29k
        if (src != dest) {
3724
2.29k
            memcpy(dest, src, len_src);
3725
2.29k
        }
3726
2.29k
        Py_ssize_t copied = len_src;
3727
5.07k
        while (copied < len_dest) {
3728
2.77k
            Py_ssize_t bytes_to_copy = Py_MIN(copied, len_dest - copied);
3729
2.77k
            memcpy(dest + copied, dest, bytes_to_copy);
3730
2.77k
            copied += bytes_to_copy;
3731
2.77k
        }
3732
2.29k
    }
3733
122k
}
3734
3735
3736
// --- PyBytesWriter API -----------------------------------------------------
3737
3738
// Byte pattern to fill newly allocated bytes
3739
#define PyBytesWrite_NEW_BYTE 0xff
3740
3741
// Use a value different than NUL (0) to be able to detect overflow writing
3742
// one extra NUL byte which is a common error.
3743
#define PyBytesWriter_CANARY_BYTE PYMEM_DEADBYTE
3744
3745
3746
static inline Py_ssize_t
3747
byteswriter_allocated(PyBytesWriter *writer)
3748
802k
{
3749
802k
    if (writer->obj == NULL) {
3750
        // Reserve the last byte for the canary byte
3751
777k
        return sizeof(writer->small_buffer) - 1;
3752
777k
    }
3753
24.6k
    else if (writer->use_bytearray) {
3754
0
        return PyByteArray_GET_SIZE(writer->obj);
3755
0
    }
3756
24.6k
    else {
3757
24.6k
        return PyBytes_GET_SIZE(writer->obj);
3758
24.6k
    }
3759
802k
}
3760
3761
3762
#ifdef Py_DEBUG
3763
static void
3764
byteswriter_write_canary_byte(PyBytesWriter *writer)
3765
{
3766
    unsigned char *data = (unsigned char*)_PyBytesWriter_GetData(writer);
3767
    data[writer->size] = PyBytesWriter_CANARY_BYTE;
3768
}
3769
3770
3771
static void
3772
byteswriter_reset_trailing_byte(PyBytesWriter *writer)
3773
{
3774
    // PyBytesWriter writes non-zero canary byte as the last byte.
3775
    // bytes/bytearray expects the last byte to be a null byte.
3776
    // Reset the last byte to null for bytes/bytearray.
3777
    Py_ssize_t allocated = byteswriter_allocated(writer);
3778
    char *data = _PyBytesWriter_GetData(writer);
3779
    data[allocated] = '\0';
3780
}
3781
#endif
3782
3783
3784
#ifndef NDEBUG
3785
static int
3786
byteswriter_check_consistency(PyBytesWriter *writer)
3787
{
3788
    PyObject *obj = writer->obj;
3789
    if (obj != NULL) {
3790
        if (writer->use_bytearray) {
3791
            assert(PyByteArray_CheckExact(obj));
3792
            // Do not use _PyObject_IsUniquelyReferenced(): the caller can have
3793
            // its own lock to prevent a writer from being used by two threads
3794
            // at the same time.
3795
            assert(Py_REFCNT(obj) == 1);
3796
            PyByteArrayObject *bytearray = (PyByteArrayObject*)obj;
3797
            obj = bytearray->ob_bytes_object;
3798
            assert(obj != NULL);
3799
        }
3800
3801
        // Code adapted from _PyBytes_IsMutable()
3802
        assert(PyBytes_CheckExact(obj));
3803
        assert(_PyBytes_IsMutable(obj));
3804
        // -1 since the last small buffer byte is used as the canary byte
3805
        assert((size_t)PyBytes_GET_SIZE(obj) > (sizeof(writer->small_buffer) - 1));
3806
    }
3807
3808
#ifdef Py_DEBUG
3809
    const unsigned char *data = (const unsigned char*)_PyBytesWriter_GetData(writer);
3810
    unsigned char canary = data[writer->size];
3811
    if (canary != PyBytesWriter_CANARY_BYTE) {
3812
        _Py_FatalErrorFormat(__func__,
3813
                             "Buffer overflow detected in PyBytesWriter %p "
3814
                             "at position %zd",
3815
                             writer, writer->size);
3816
    }
3817
#endif
3818
    return 1;
3819
}
3820
#endif
3821
3822
3823
#ifdef MS_WINDOWS
3824
   /* On Windows, overallocate by 50% is the best factor */
3825
#  define OVERALLOCATE_FACTOR 2
3826
#else
3827
   /* On Linux, overallocate by 25% is the best factor */
3828
52.8k
#  define OVERALLOCATE_FACTOR 4
3829
#endif
3830
3831
static inline int
3832
byteswriter_resize(PyBytesWriter *writer, Py_ssize_t new_size, int resize)
3833
802k
{
3834
802k
    assert(new_size >= 1);
3835
3836
802k
    Py_ssize_t old_allocated = byteswriter_allocated(writer);
3837
802k
    if (new_size <= old_allocated) {
3838
        // Do not shrink the buffer before PyBytesWriter_FinishWithSize()
3839
5.35k
        return 0;
3840
5.35k
    }
3841
3842
796k
    Py_ssize_t alloc = new_size;
3843
796k
    if (resize && writer->overallocate) {
3844
26.4k
        if (alloc <= (PY_SSIZE_T_MAX - alloc / OVERALLOCATE_FACTOR)) {
3845
26.4k
            alloc += alloc / OVERALLOCATE_FACTOR;
3846
26.4k
        }
3847
26.4k
    }
3848
3849
796k
    if (writer->obj != NULL) {
3850
24.6k
        if (writer->use_bytearray) {
3851
0
            if (PyByteArray_Resize(writer->obj, alloc)) {
3852
#ifdef Py_DEBUG
3853
                // bytearray can override the canary byte on error
3854
                byteswriter_write_canary_byte(writer);
3855
#endif
3856
0
                assert(byteswriter_check_consistency(writer));
3857
0
                return -1;
3858
0
            }
3859
0
        }
3860
24.6k
        else {
3861
            // Can raise MemoryError or OverflowError
3862
24.6k
            if (_PyBytes_ResizeKeepOnError(&writer->obj, alloc)) {
3863
0
                assert(writer->obj != NULL);
3864
0
                assert(byteswriter_check_consistency(writer));
3865
0
                return -1;
3866
0
            }
3867
24.6k
            assert(_PyBytes_IsMutable(writer->obj));
3868
24.6k
        }
3869
24.6k
        assert(writer->obj != NULL);
3870
24.6k
    }
3871
772k
    else {
3872
772k
        char *data;
3873
772k
        if (writer->use_bytearray) {
3874
0
            writer->obj = PyByteArray_FromStringAndSize(NULL, alloc);
3875
0
            if (writer->obj == NULL) {
3876
0
                return -1;
3877
0
            }
3878
0
            data = PyByteArray_AS_STRING(writer->obj);
3879
0
        }
3880
772k
        else {
3881
772k
            writer->obj = bytes_alloc(alloc);
3882
772k
            if (writer->obj == NULL) {
3883
0
                return -1;
3884
0
            }
3885
772k
            assert(_PyBytes_IsMutable(writer->obj));
3886
772k
            data = PyBytes_AS_STRING(writer->obj);
3887
772k
        }
3888
3889
772k
        if (resize) {
3890
            // Copy data from the small buffer
3891
1.77k
            Py_ssize_t old_size = writer->size;
3892
1.77k
            assert((size_t)old_size <= sizeof(writer->small_buffer));
3893
1.77k
            assert(old_size <= alloc);
3894
1.77k
            memcpy(data, writer->small_buffer, old_size);
3895
1.77k
        }
3896
772k
    }
3897
3898
#ifdef Py_DEBUG
3899
    Py_ssize_t allocated = byteswriter_allocated(writer);
3900
    if (resize) {
3901
        Py_ssize_t old_size = writer->size;
3902
        assert(allocated > old_size);
3903
        memset(_PyBytesWriter_GetData(writer) + old_size, PyBytesWrite_NEW_BYTE,
3904
               allocated - old_size);
3905
    }
3906
#endif
3907
3908
796k
    return 0;
3909
796k
}
3910
3911
3912
static PyBytesWriter*
3913
byteswriter_create(Py_ssize_t size, int use_bytearray)
3914
28.3M
{
3915
28.3M
    if (size < 0) {
3916
0
        PyErr_SetString(PyExc_ValueError, "size must be >= 0");
3917
0
        return NULL;
3918
0
    }
3919
3920
28.3M
    PyBytesWriter *writer = _Py_FREELIST_POP_MEM(bytes_writers);
3921
28.3M
    if (writer == NULL) {
3922
33.7k
        writer = (PyBytesWriter *)PyMem_Malloc(sizeof(PyBytesWriter));
3923
33.7k
        if (writer == NULL) {
3924
0
            PyErr_NoMemory();
3925
0
            return NULL;
3926
0
        }
3927
33.7k
    }
3928
28.3M
    writer->obj = NULL;
3929
28.3M
    writer->size = size;
3930
28.3M
    writer->use_bytearray = use_bytearray;
3931
28.3M
    writer->overallocate = !use_bytearray;
3932
3933
28.3M
    Py_ssize_t allocated = sizeof(writer->small_buffer) - 1;
3934
28.3M
    if (size > allocated) {
3935
770k
        if (byteswriter_resize(writer, size, 0) < 0) {
3936
#ifdef Py_DEBUG
3937
            // Write the canary byte so byteswriter_check_consistency()
3938
            // doesn't fail in PyBytesWriter_Discard()
3939
            writer->size = 0;
3940
            byteswriter_write_canary_byte(writer);
3941
#endif
3942
0
            PyBytesWriter_Discard(writer);
3943
0
            return NULL;
3944
0
        }
3945
770k
    }
3946
#ifdef Py_DEBUG
3947
    memset(_PyBytesWriter_GetData(writer), PyBytesWrite_NEW_BYTE,
3948
           byteswriter_allocated(writer));
3949
    byteswriter_write_canary_byte(writer);
3950
#endif
3951
28.3M
    assert(byteswriter_check_consistency(writer));
3952
28.3M
    return writer;
3953
28.3M
}
3954
3955
PyBytesWriter*
3956
PyBytesWriter_Create(Py_ssize_t size)
3957
28.3M
{
3958
28.3M
    return byteswriter_create(size, 0);
3959
28.3M
}
3960
3961
PyBytesWriter*
3962
_PyBytesWriter_CreateByteArray(Py_ssize_t size)
3963
0
{
3964
0
    return byteswriter_create(size, 1);
3965
0
}
3966
3967
3968
void
3969
PyBytesWriter_Discard(PyBytesWriter *writer)
3970
3.32M
{
3971
3.32M
    if (writer == NULL) {
3972
150k
        return;
3973
150k
    }
3974
3975
3.32M
    assert(byteswriter_check_consistency(writer));
3976
3.17M
    if (writer->obj != NULL) {
3977
#ifdef Py_DEBUG
3978
        byteswriter_reset_trailing_byte(writer);
3979
#endif
3980
59.6k
        Py_DECREF(writer->obj);
3981
59.6k
    }
3982
3.17M
    _Py_FREELIST_FREE(bytes_writers, writer, PyMem_Free);
3983
3.17M
}
3984
3985
3986
static inline PyObject*
3987
byteswriter_finish_with_size(PyBytesWriter *writer, Py_ssize_t final_size)
3988
25.1M
{
3989
25.1M
    assert(byteswriter_check_consistency(writer));
3990
3991
25.1M
    PyObject *result;
3992
25.1M
    if (final_size == 0 && !writer->use_bytearray) {
3993
69.3k
        result = bytes_get_empty();
3994
69.3k
        if (writer->obj != NULL) {
3995
#ifdef Py_DEBUG
3996
            byteswriter_reset_trailing_byte(writer);
3997
#endif
3998
57.6k
            Py_DECREF(writer->obj);
3999
57.6k
            writer->obj = NULL;
4000
57.6k
        }
4001
69.3k
    }
4002
25.1M
    else if (writer->obj != NULL) {
4003
        // Truncate the bytes/bytearray object if needed
4004
#ifdef Py_DEBUG
4005
        byteswriter_reset_trailing_byte(writer);
4006
#endif
4007
4008
654k
        if (writer->use_bytearray) {
4009
0
            if (final_size != PyByteArray_GET_SIZE(writer->obj)) {
4010
0
                if (PyByteArray_Resize(writer->obj, final_size)) {
4011
0
                    goto error;
4012
0
                }
4013
0
            }
4014
0
        }
4015
654k
        else {
4016
654k
            if (final_size == 1) {
4017
337
                unsigned char ch = PyBytes_AS_STRING(writer->obj)[0];
4018
337
                Py_SETREF(writer->obj, bytes_get_char(ch));
4019
337
            }
4020
654k
            else if (final_size != PyBytes_GET_SIZE(writer->obj)) {
4021
616k
                if (bytes_resize_inplace(&writer->obj, final_size)) {
4022
0
                    goto error;
4023
0
                }
4024
616k
            }
4025
654k
        }
4026
4027
654k
        result = writer->obj;
4028
654k
        writer->obj = NULL;
4029
654k
    }
4030
24.4M
    else {
4031
        // Create an object from the small buffer
4032
24.4M
        const char *buffer = (const char *)writer->small_buffer;
4033
24.4M
        if (writer->use_bytearray) {
4034
0
            result = PyByteArray_FromStringAndSize(buffer, final_size);
4035
0
        }
4036
24.4M
        else {
4037
24.4M
            if (final_size == 1) {
4038
7.85M
                result = bytes_get_char((uint8_t)buffer[0]);
4039
7.85M
            }
4040
16.5M
            else {
4041
16.5M
                result = bytes_alloc(final_size);
4042
16.5M
                if (result == NULL) {
4043
0
                    goto error;
4044
0
                }
4045
16.5M
                memcpy(PyBytes_AS_STRING(result), buffer, final_size);
4046
16.5M
            }
4047
24.4M
        }
4048
24.4M
    }
4049
4050
25.1M
    assert(writer->obj == NULL);
4051
25.1M
    _Py_FREELIST_FREE(bytes_writers, writer, PyMem_Free);
4052
25.1M
    return result;
4053
4054
0
error:
4055
0
    PyBytesWriter_Discard(writer);
4056
0
    return NULL;
4057
25.1M
}
4058
4059
PyObject*
4060
PyBytesWriter_FinishWithSize(PyBytesWriter *writer, Py_ssize_t size)
4061
9.16M
{
4062
9.16M
    if (size < 0) {
4063
0
        PyErr_Format(PyExc_ValueError, "size must be positive");
4064
0
        goto error;
4065
0
    }
4066
9.16M
    if (size > writer->size) {
4067
0
        PyErr_SetString(PyExc_ValueError, "size larger than allocated size");
4068
0
        goto error;
4069
0
    }
4070
9.16M
    return byteswriter_finish_with_size(writer, size);
4071
4072
0
error:
4073
0
    PyBytesWriter_Discard(writer);
4074
0
    return NULL;
4075
9.16M
}
4076
4077
PyObject*
4078
PyBytesWriter_Finish(PyBytesWriter *writer)
4079
16.0M
{
4080
16.0M
    return byteswriter_finish_with_size(writer, writer->size);
4081
16.0M
}
4082
4083
4084
PyObject*
4085
PyBytesWriter_FinishWithPointer(PyBytesWriter *writer, void *buf)
4086
9.06M
{
4087
9.06M
    Py_ssize_t size = (char*)buf - _PyBytesWriter_GetData(writer);
4088
    // Call PyBytesWriter_FinishWithSize() to check size
4089
9.06M
    return PyBytesWriter_FinishWithSize(writer, size);
4090
9.06M
}
4091
4092
4093
void*
4094
PyBytesWriter_GetData(PyBytesWriter *writer)
4095
29.0M
{
4096
29.0M
    assert(byteswriter_check_consistency(writer));
4097
4098
29.0M
    return _PyBytesWriter_GetData(writer);
4099
29.0M
}
4100
4101
4102
Py_ssize_t
4103
PyBytesWriter_GetSize(PyBytesWriter *writer)
4104
256k
{
4105
256k
    assert(byteswriter_check_consistency(writer));
4106
4107
256k
    return _PyBytesWriter_GetSize(writer);
4108
256k
}
4109
4110
4111
int
4112
PyBytesWriter_Resize(PyBytesWriter *writer, Py_ssize_t new_size)
4113
8.41k
{
4114
8.41k
    assert(byteswriter_check_consistency(writer));
4115
4116
8.41k
    if (new_size < 0) {
4117
0
        PyErr_SetString(PyExc_ValueError, "size must be >= 0");
4118
0
        return -1;
4119
0
    }
4120
8.41k
    if (writer->size < new_size) {
4121
8.41k
        if (byteswriter_resize(writer, new_size, 1) < 0) {
4122
0
            return -1;
4123
0
        }
4124
8.41k
    }
4125
0
    else {
4126
        // The buffer is already large enough. Never shrink the buffer.
4127
0
    }
4128
4129
8.41k
    writer->size = new_size;
4130
#ifdef Py_DEBUG
4131
    byteswriter_write_canary_byte(writer);
4132
#endif
4133
8.41k
    assert(byteswriter_check_consistency(writer));
4134
8.41k
    return 0;
4135
8.41k
}
4136
4137
4138
static void*
4139
_PyBytesWriter_ResizeAndUpdatePointer(PyBytesWriter *writer, Py_ssize_t size,
4140
                                      void *data)
4141
0
{
4142
0
    Py_ssize_t pos = (char*)data - _PyBytesWriter_GetData(writer);
4143
0
    if (PyBytesWriter_Resize(writer, size) < 0) {
4144
0
        return NULL;
4145
0
    }
4146
0
    return _PyBytesWriter_GetData(writer) + pos;
4147
0
}
4148
4149
4150
int
4151
PyBytesWriter_Grow(PyBytesWriter *writer, Py_ssize_t grow)
4152
23.3k
{
4153
23.3k
    assert(byteswriter_check_consistency(writer));
4154
4155
23.3k
    if (grow == 0) {
4156
        // Nothing to do
4157
0
        return 0;
4158
0
    }
4159
4160
23.3k
    if (grow > 0) {
4161
23.3k
        if (grow > PY_SSIZE_T_MAX - writer->size) {
4162
0
            PyErr_NoMemory();
4163
0
            return -1;
4164
0
        }
4165
23.3k
        Py_ssize_t new_size = writer->size + grow;
4166
4167
23.3k
        if (byteswriter_resize(writer, new_size, 1) < 0) {
4168
0
            return -1;
4169
0
        }
4170
23.3k
        writer->size = new_size;
4171
23.3k
    }
4172
0
    else {
4173
0
        if (writer->size + grow < 0) {
4174
0
            PyErr_SetString(PyExc_ValueError, "invalid size");
4175
0
            return -1;
4176
0
        }
4177
        // The buffer is already large enough. Never shrink the buffer.
4178
0
        writer->size = writer->size + grow;
4179
0
    }
4180
4181
#ifdef Py_DEBUG
4182
    byteswriter_write_canary_byte(writer);
4183
#endif
4184
23.3k
    assert(byteswriter_check_consistency(writer));
4185
23.3k
    return 0;
4186
23.3k
}
4187
4188
4189
void*
4190
PyBytesWriter_GrowAndUpdatePointer(PyBytesWriter *writer, Py_ssize_t size,
4191
                                   void *buf)
4192
0
{
4193
0
    Py_ssize_t pos = (char*)buf - _PyBytesWriter_GetData(writer);
4194
0
    if (PyBytesWriter_Grow(writer, size) < 0) {
4195
0
        return NULL;
4196
0
    }
4197
0
    return _PyBytesWriter_GetData(writer) + pos;
4198
0
}
4199
4200
4201
int
4202
PyBytesWriter_WriteBytes(PyBytesWriter *writer,
4203
                         const void *bytes, Py_ssize_t size)
4204
10
{
4205
10
    if (size < 0) {
4206
0
        size_t len = strlen(bytes);
4207
0
        if (len > (size_t)PY_SSIZE_T_MAX) {
4208
0
            PyErr_NoMemory();
4209
0
            return -1;
4210
0
        }
4211
0
        size = (Py_ssize_t)len;
4212
0
    }
4213
4214
10
    Py_ssize_t pos = writer->size;
4215
10
    if (PyBytesWriter_Grow(writer, size) < 0) {
4216
0
        return -1;
4217
0
    }
4218
10
    char *buf = _PyBytesWriter_GetData(writer);
4219
10
    memcpy(buf + pos, bytes, size);
4220
4221
10
    assert(byteswriter_check_consistency(writer));
4222
10
    return 0;
4223
10
}
4224
4225
4226
int
4227
PyBytesWriter_Format(PyBytesWriter *writer, const char *format, ...)
4228
0
{
4229
0
    Py_ssize_t pos = writer->size;
4230
0
    Py_ssize_t old_pos = pos;
4231
0
    if (PyBytesWriter_Grow(writer, strlen(format)) < 0) {
4232
0
        return -1;
4233
0
    }
4234
4235
0
    va_list vargs;
4236
0
    va_start(vargs, format);
4237
0
    char *buf = bytes_fromformat(writer, pos, format, vargs);
4238
0
    va_end(vargs);
4239
4240
0
    if (buf == NULL) {
4241
        // On error, reset the writer to its previous state (undo any write)
4242
0
        writer->size = old_pos;
4243
#ifdef Py_DEBUG
4244
        byteswriter_write_canary_byte(writer);
4245
#endif
4246
0
        return -1;
4247
0
    }
4248
4249
0
    Py_ssize_t size = buf - _PyBytesWriter_GetData(writer);
4250
0
    return PyBytesWriter_Resize(writer, size);
4251
0
}
4252
4253
4254
// Resize the writer to its allocated size.
4255
// Return the new size.
4256
// The function cannot fail.
4257
static Py_ssize_t
4258
_PyBytesWriter_ResizeToAllocated(PyBytesWriter *writer)
4259
180
{
4260
180
    Py_ssize_t allocated = byteswriter_allocated(writer);
4261
180
    writer->size = allocated;
4262
#ifdef Py_DEBUG
4263
    byteswriter_write_canary_byte(writer);
4264
#endif
4265
4266
    assert(byteswriter_check_consistency(writer));
4267
180
    return allocated;
4268
180
}