Coverage Report

Created: 2026-10-17 06:15

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