Branch data Line data Source code
1 : : /* bytes object implementation */
2 : :
3 : : #define PY_SSIZE_T_CLEAN
4 : :
5 : : #include "Python.h"
6 : : #include "pycore_abstract.h" // _PyIndex_Check()
7 : : #include "pycore_bytesobject.h" // _PyBytes_Find(), _PyBytes_Repeat()
8 : : #include "pycore_bytes_methods.h" // _Py_bytes_startswith()
9 : : #include "pycore_call.h" // _PyObject_CallNoArgs()
10 : : #include "pycore_format.h" // F_LJUST
11 : : #include "pycore_global_objects.h" // _Py_GET_GLOBAL_OBJECT()
12 : : #include "pycore_initconfig.h" // _PyStatus_OK()
13 : : #include "pycore_long.h" // _PyLong_DigitValue
14 : : #include "pycore_object.h" // _PyObject_GC_TRACK
15 : : #include "pycore_pymem.h" // PYMEM_CLEANBYTE
16 : : #include "pycore_strhex.h" // _Py_strhex_with_sep()
17 : :
18 : : #include <stddef.h>
19 : :
20 : : /*[clinic input]
21 : : class bytes "PyBytesObject *" "&PyBytes_Type"
22 : : [clinic start generated code]*/
23 : : /*[clinic end generated code: output=da39a3ee5e6b4b0d input=7a238f965d64892b]*/
24 : :
25 : : #include "clinic/bytesobject.c.h"
26 : :
27 : : /* PyBytesObject_SIZE gives the basic size of a bytes object; any memory allocation
28 : : for a bytes object of length n should request PyBytesObject_SIZE + n bytes.
29 : :
30 : : Using PyBytesObject_SIZE instead of sizeof(PyBytesObject) saves
31 : : 3 or 7 bytes per bytes object allocation on a typical system.
32 : : */
33 : : #define PyBytesObject_SIZE (offsetof(PyBytesObject, ob_sval) + 1)
34 : :
35 : : /* Forward declaration */
36 : : Py_LOCAL_INLINE(Py_ssize_t) _PyBytesWriter_GetSize(_PyBytesWriter *writer,
37 : : char *str);
38 : :
39 : :
40 : : #define CHARACTERS _Py_SINGLETON(bytes_characters)
41 : : #define CHARACTER(ch) \
42 : : ((PyBytesObject *)&(CHARACTERS[ch]));
43 : : #define EMPTY (&_Py_SINGLETON(bytes_empty))
44 : :
45 : :
46 : : // Return a borrowed reference to the empty bytes string singleton.
47 : 0 : static inline PyObject* bytes_get_empty(void)
48 : : {
49 : 0 : return &EMPTY->ob_base.ob_base;
50 : : }
51 : :
52 : :
53 : : // Return a strong reference to the empty bytes string singleton.
54 : 121622 : static inline PyObject* bytes_new_empty(void)
55 : : {
56 : 121622 : return Py_NewRef(EMPTY);
57 : : }
58 : :
59 : :
60 : : /*
61 : : For PyBytes_FromString(), the parameter `str' points to a null-terminated
62 : : string containing exactly `size' bytes.
63 : :
64 : : For PyBytes_FromStringAndSize(), the parameter `str' is
65 : : either NULL or else points to a string containing at least `size' bytes.
66 : : For PyBytes_FromStringAndSize(), the string in the `str' parameter does
67 : : not have to be null-terminated. (Therefore it is safe to construct a
68 : : substring by calling `PyBytes_FromStringAndSize(origstring, substrlen)'.)
69 : : If `str' is NULL then PyBytes_FromStringAndSize() will allocate `size+1'
70 : : bytes (setting the last byte to the null terminating character) and you can
71 : : fill in the data yourself. If `str' is non-NULL then the resulting
72 : : PyBytes object must be treated as immutable and you must not fill in nor
73 : : alter the data yourself, since the strings may be shared.
74 : :
75 : : The PyObject member `op->ob_size', which denotes the number of "extra
76 : : items" in a variable-size object, will contain the number of bytes
77 : : allocated for string data, not counting the null terminating character.
78 : : It is therefore equal to the `size' parameter (for
79 : : PyBytes_FromStringAndSize()) or the length of the string in the `str'
80 : : parameter (for PyBytes_FromString()).
81 : : */
82 : : static PyObject *
83 : 635637 : _PyBytes_FromSize(Py_ssize_t size, int use_calloc)
84 : : {
85 : : PyBytesObject *op;
86 : : assert(size >= 0);
87 : :
88 [ - + ]: 635637 : if (size == 0) {
89 : 0 : return bytes_new_empty();
90 : : }
91 : :
92 [ - + ]: 635637 : if ((size_t)size > (size_t)PY_SSIZE_T_MAX - PyBytesObject_SIZE) {
93 : 0 : PyErr_SetString(PyExc_OverflowError,
94 : : "byte string is too large");
95 : 0 : return NULL;
96 : : }
97 : :
98 : : /* Inline PyObject_NewVar */
99 [ - + ]: 635637 : if (use_calloc)
100 : 0 : op = (PyBytesObject *)PyObject_Calloc(1, PyBytesObject_SIZE + size);
101 : : else
102 : 635637 : op = (PyBytesObject *)PyObject_Malloc(PyBytesObject_SIZE + size);
103 [ - + ]: 635637 : if (op == NULL) {
104 : 0 : return PyErr_NoMemory();
105 : : }
106 : 635637 : _PyObject_InitVar((PyVarObject*)op, &PyBytes_Type, size);
107 : : _Py_COMP_DIAG_PUSH
108 : : _Py_COMP_DIAG_IGNORE_DEPR_DECLS
109 : 635637 : op->ob_shash = -1;
110 : : _Py_COMP_DIAG_POP
111 [ + - ]: 635637 : if (!use_calloc) {
112 : 635637 : op->ob_sval[size] = '\0';
113 : : }
114 : 635637 : return (PyObject *) op;
115 : : }
116 : :
117 : : PyObject *
118 : 1564910 : PyBytes_FromStringAndSize(const char *str, Py_ssize_t size)
119 : : {
120 : : PyBytesObject *op;
121 [ - + ]: 1564910 : if (size < 0) {
122 : 0 : PyErr_SetString(PyExc_SystemError,
123 : : "Negative size passed to PyBytes_FromStringAndSize");
124 : 0 : return NULL;
125 : : }
126 [ + + + + ]: 1564910 : if (size == 1 && str != NULL) {
127 : 814727 : op = CHARACTER(*str & 255);
128 : 814727 : return Py_NewRef(op);
129 : : }
130 [ + + ]: 750183 : if (size == 0) {
131 : 114546 : return bytes_new_empty();
132 : : }
133 : :
134 : 635637 : op = (PyBytesObject *)_PyBytes_FromSize(size, 0);
135 [ - + ]: 635637 : if (op == NULL)
136 : 0 : return NULL;
137 [ + + ]: 635637 : if (str == NULL)
138 : 103245 : return (PyObject *) op;
139 : :
140 : 532392 : memcpy(op->ob_sval, str, size);
141 : 532392 : return (PyObject *) op;
142 : : }
143 : :
144 : : PyObject *
145 : 714 : PyBytes_FromString(const char *str)
146 : : {
147 : : size_t size;
148 : : PyBytesObject *op;
149 : :
150 : : assert(str != NULL);
151 : 714 : size = strlen(str);
152 [ - + ]: 714 : if (size > PY_SSIZE_T_MAX - PyBytesObject_SIZE) {
153 : 0 : PyErr_SetString(PyExc_OverflowError,
154 : : "byte string is too long");
155 : 0 : return NULL;
156 : : }
157 : :
158 [ - + ]: 714 : if (size == 0) {
159 : 0 : return bytes_new_empty();
160 : : }
161 [ - + ]: 714 : else if (size == 1) {
162 : 0 : op = CHARACTER(*str & 255);
163 : 0 : return Py_NewRef(op);
164 : : }
165 : :
166 : : /* Inline PyObject_NewVar */
167 : 714 : op = (PyBytesObject *)PyObject_Malloc(PyBytesObject_SIZE + size);
168 [ - + ]: 714 : if (op == NULL) {
169 : 0 : return PyErr_NoMemory();
170 : : }
171 : 714 : _PyObject_InitVar((PyVarObject*)op, &PyBytes_Type, size);
172 : : _Py_COMP_DIAG_PUSH
173 : : _Py_COMP_DIAG_IGNORE_DEPR_DECLS
174 : 714 : op->ob_shash = -1;
175 : : _Py_COMP_DIAG_POP
176 : 714 : memcpy(op->ob_sval, str, size+1);
177 : 714 : return (PyObject *) op;
178 : : }
179 : :
180 : : PyObject *
181 : 0 : PyBytes_FromFormatV(const char *format, va_list vargs)
182 : : {
183 : : char *s;
184 : : const char *f;
185 : : const char *p;
186 : : Py_ssize_t prec;
187 : : int longflag;
188 : : int size_tflag;
189 : : /* Longest 64-bit formatted numbers:
190 : : - "18446744073709551615\0" (21 bytes)
191 : : - "-9223372036854775808\0" (21 bytes)
192 : : Decimal takes the most space (it isn't enough for octal.)
193 : :
194 : : Longest 64-bit pointer representation:
195 : : "0xffffffffffffffff\0" (19 bytes). */
196 : : char buffer[21];
197 : : _PyBytesWriter writer;
198 : :
199 : 0 : _PyBytesWriter_Init(&writer);
200 : :
201 : 0 : s = _PyBytesWriter_Alloc(&writer, strlen(format));
202 [ # # ]: 0 : if (s == NULL)
203 : 0 : return NULL;
204 : 0 : writer.overallocate = 1;
205 : :
206 : : #define WRITE_BYTES(str) \
207 : : do { \
208 : : s = _PyBytesWriter_WriteBytes(&writer, s, (str), strlen(str)); \
209 : : if (s == NULL) \
210 : : goto error; \
211 : : } while (0)
212 : :
213 [ # # ]: 0 : for (f = format; *f; f++) {
214 [ # # ]: 0 : if (*f != '%') {
215 : 0 : *s++ = *f;
216 : 0 : continue;
217 : : }
218 : :
219 : 0 : p = f++;
220 : :
221 : : /* ignore the width (ex: 10 in "%10s") */
222 [ # # ]: 0 : while (Py_ISDIGIT(*f))
223 : 0 : f++;
224 : :
225 : : /* parse the precision (ex: 10 in "%.10s") */
226 : 0 : prec = 0;
227 [ # # ]: 0 : if (*f == '.') {
228 : 0 : f++;
229 [ # # ]: 0 : for (; Py_ISDIGIT(*f); f++) {
230 : 0 : prec = (prec * 10) + (*f - '0');
231 : : }
232 : : }
233 : :
234 [ # # # # : 0 : while (*f && *f != '%' && !Py_ISALPHA(*f))
# # ]
235 : 0 : f++;
236 : :
237 : : /* handle the long flag ('l'), but only for %ld and %lu.
238 : : others can be added when necessary. */
239 : 0 : longflag = 0;
240 [ # # # # : 0 : if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
# # ]
241 : 0 : longflag = 1;
242 : 0 : ++f;
243 : : }
244 : :
245 : : /* handle the size_t flag ('z'). */
246 : 0 : size_tflag = 0;
247 [ # # # # : 0 : if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
# # ]
248 : 0 : size_tflag = 1;
249 : 0 : ++f;
250 : : }
251 : :
252 : : /* subtract bytes preallocated for the format string
253 : : (ex: 2 for "%s") */
254 : 0 : writer.min_size -= (f - p + 1);
255 : :
256 [ # # # # : 0 : switch (*f) {
# # # #
# ]
257 : 0 : case 'c':
258 : : {
259 : 0 : int c = va_arg(vargs, int);
260 [ # # # # ]: 0 : if (c < 0 || c > 255) {
261 : 0 : PyErr_SetString(PyExc_OverflowError,
262 : : "PyBytes_FromFormatV(): %c format "
263 : : "expects an integer in range [0; 255]");
264 : 0 : goto error;
265 : : }
266 : 0 : writer.min_size++;
267 : 0 : *s++ = (unsigned char)c;
268 : 0 : break;
269 : : }
270 : :
271 : 0 : case 'd':
272 [ # # ]: 0 : if (longflag) {
273 : 0 : sprintf(buffer, "%ld", va_arg(vargs, long));
274 : : }
275 [ # # ]: 0 : else if (size_tflag) {
276 : 0 : sprintf(buffer, "%zd", va_arg(vargs, Py_ssize_t));
277 : : }
278 : : else {
279 : 0 : sprintf(buffer, "%d", va_arg(vargs, int));
280 : : }
281 : : assert(strlen(buffer) < sizeof(buffer));
282 [ # # ]: 0 : WRITE_BYTES(buffer);
283 : 0 : break;
284 : :
285 : 0 : case 'u':
286 [ # # ]: 0 : if (longflag) {
287 : 0 : sprintf(buffer, "%lu", va_arg(vargs, unsigned long));
288 : : }
289 [ # # ]: 0 : else if (size_tflag) {
290 : 0 : sprintf(buffer, "%zu", va_arg(vargs, size_t));
291 : : }
292 : : else {
293 : 0 : sprintf(buffer, "%u", va_arg(vargs, unsigned int));
294 : : }
295 : : assert(strlen(buffer) < sizeof(buffer));
296 [ # # ]: 0 : WRITE_BYTES(buffer);
297 : 0 : break;
298 : :
299 : 0 : case 'i':
300 : 0 : sprintf(buffer, "%i", va_arg(vargs, int));
301 : : assert(strlen(buffer) < sizeof(buffer));
302 [ # # ]: 0 : WRITE_BYTES(buffer);
303 : 0 : break;
304 : :
305 : 0 : case 'x':
306 : 0 : sprintf(buffer, "%x", va_arg(vargs, int));
307 : : assert(strlen(buffer) < sizeof(buffer));
308 [ # # ]: 0 : WRITE_BYTES(buffer);
309 : 0 : break;
310 : :
311 : 0 : case 's':
312 : : {
313 : : Py_ssize_t i;
314 : :
315 : 0 : p = va_arg(vargs, const char*);
316 [ # # ]: 0 : if (prec <= 0) {
317 : 0 : i = strlen(p);
318 : : }
319 : : else {
320 : 0 : i = 0;
321 [ # # # # ]: 0 : while (i < prec && p[i]) {
322 : 0 : i++;
323 : : }
324 : : }
325 : 0 : s = _PyBytesWriter_WriteBytes(&writer, s, p, i);
326 [ # # ]: 0 : if (s == NULL)
327 : 0 : goto error;
328 : 0 : break;
329 : : }
330 : :
331 : 0 : case 'p':
332 : 0 : sprintf(buffer, "%p", va_arg(vargs, void*));
333 : : assert(strlen(buffer) < sizeof(buffer));
334 : : /* %p is ill-defined: ensure leading 0x. */
335 [ # # ]: 0 : if (buffer[1] == 'X')
336 : 0 : buffer[1] = 'x';
337 [ # # ]: 0 : else if (buffer[1] != 'x') {
338 : 0 : memmove(buffer+2, buffer, strlen(buffer)+1);
339 : 0 : buffer[0] = '0';
340 : 0 : buffer[1] = 'x';
341 : : }
342 [ # # ]: 0 : WRITE_BYTES(buffer);
343 : 0 : break;
344 : :
345 : 0 : case '%':
346 : 0 : writer.min_size++;
347 : 0 : *s++ = '%';
348 : 0 : break;
349 : :
350 : 0 : default:
351 [ # # ]: 0 : if (*f == 0) {
352 : : /* fix min_size if we reached the end of the format string */
353 : 0 : writer.min_size++;
354 : : }
355 : :
356 : : /* invalid format string: copy unformatted string and exit */
357 [ # # ]: 0 : WRITE_BYTES(p);
358 : 0 : return _PyBytesWriter_Finish(&writer, s);
359 : : }
360 : : }
361 : :
362 : : #undef WRITE_BYTES
363 : :
364 : 0 : return _PyBytesWriter_Finish(&writer, s);
365 : :
366 : 0 : error:
367 : 0 : _PyBytesWriter_Dealloc(&writer);
368 : 0 : return NULL;
369 : : }
370 : :
371 : : PyObject *
372 : 0 : PyBytes_FromFormat(const char *format, ...)
373 : : {
374 : : PyObject* ret;
375 : : va_list vargs;
376 : :
377 : 0 : va_start(vargs, format);
378 : 0 : ret = PyBytes_FromFormatV(format, vargs);
379 : 0 : va_end(vargs);
380 : 0 : return ret;
381 : : }
382 : :
383 : : /* Helpers for formatstring */
384 : :
385 : : Py_LOCAL_INLINE(PyObject *)
386 : 0 : getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
387 : : {
388 : 0 : Py_ssize_t argidx = *p_argidx;
389 [ # # ]: 0 : if (argidx < arglen) {
390 : 0 : (*p_argidx)++;
391 [ # # ]: 0 : if (arglen < 0)
392 : 0 : return args;
393 : : else
394 : 0 : return PyTuple_GetItem(args, argidx);
395 : : }
396 : 0 : PyErr_SetString(PyExc_TypeError,
397 : : "not enough arguments for format string");
398 : 0 : return NULL;
399 : : }
400 : :
401 : : /* Returns a new reference to a PyBytes object, or NULL on failure. */
402 : :
403 : : static char*
404 : 0 : formatfloat(PyObject *v, int flags, int prec, int type,
405 : : PyObject **p_result, _PyBytesWriter *writer, char *str)
406 : : {
407 : : char *p;
408 : : PyObject *result;
409 : : double x;
410 : : size_t len;
411 : 0 : int dtoa_flags = 0;
412 : :
413 : 0 : x = PyFloat_AsDouble(v);
414 [ # # # # ]: 0 : if (x == -1.0 && PyErr_Occurred()) {
415 : 0 : PyErr_Format(PyExc_TypeError, "float argument required, "
416 : 0 : "not %.200s", Py_TYPE(v)->tp_name);
417 : 0 : return NULL;
418 : : }
419 : :
420 [ # # ]: 0 : if (prec < 0)
421 : 0 : prec = 6;
422 : :
423 [ # # ]: 0 : if (flags & F_ALT) {
424 : 0 : dtoa_flags |= Py_DTSF_ALT;
425 : : }
426 [ # # ]: 0 : if (flags & F_NO_NEG_0) {
427 : 0 : dtoa_flags |= Py_DTSF_NO_NEG_0;
428 : : }
429 : 0 : p = PyOS_double_to_string(x, type, prec, dtoa_flags, NULL);
430 : :
431 [ # # ]: 0 : if (p == NULL)
432 : 0 : return NULL;
433 : :
434 : 0 : len = strlen(p);
435 [ # # ]: 0 : if (writer != NULL) {
436 : 0 : str = _PyBytesWriter_Prepare(writer, str, len);
437 [ # # ]: 0 : if (str == NULL) {
438 : 0 : PyMem_Free(p);
439 : 0 : return NULL;
440 : : }
441 : 0 : memcpy(str, p, len);
442 : 0 : PyMem_Free(p);
443 : 0 : str += len;
444 : 0 : return str;
445 : : }
446 : :
447 : 0 : result = PyBytes_FromStringAndSize(p, len);
448 : 0 : PyMem_Free(p);
449 : 0 : *p_result = result;
450 [ # # ]: 0 : return result != NULL ? str : NULL;
451 : : }
452 : :
453 : : static PyObject *
454 : 0 : formatlong(PyObject *v, int flags, int prec, int type)
455 : : {
456 : : PyObject *result, *iobj;
457 [ # # ]: 0 : if (type == 'i')
458 : 0 : type = 'd';
459 [ # # ]: 0 : if (PyLong_Check(v))
460 : 0 : return _PyUnicode_FormatLong(v, flags & F_ALT, prec, type);
461 [ # # ]: 0 : if (PyNumber_Check(v)) {
462 : : /* make sure number is a type of integer for o, x, and X */
463 [ # # # # : 0 : if (type == 'o' || type == 'x' || type == 'X')
# # ]
464 : 0 : iobj = _PyNumber_Index(v);
465 : : else
466 : 0 : iobj = PyNumber_Long(v);
467 [ # # ]: 0 : if (iobj != NULL) {
468 : : assert(PyLong_Check(iobj));
469 : 0 : result = _PyUnicode_FormatLong(iobj, flags & F_ALT, prec, type);
470 : 0 : Py_DECREF(iobj);
471 : 0 : return result;
472 : : }
473 [ # # ]: 0 : if (!PyErr_ExceptionMatches(PyExc_TypeError))
474 : 0 : return NULL;
475 : : }
476 [ # # ]: 0 : PyErr_Format(PyExc_TypeError,
477 : : "%%%c format: %s is required, not %.200s", type,
478 [ # # # # ]: 0 : (type == 'o' || type == 'x' || type == 'X') ? "an integer"
479 : : : "a real number",
480 : 0 : Py_TYPE(v)->tp_name);
481 : 0 : return NULL;
482 : : }
483 : :
484 : : static int
485 : 0 : byte_converter(PyObject *arg, char *p)
486 : : {
487 [ # # # # ]: 0 : if (PyBytes_Check(arg) && PyBytes_GET_SIZE(arg) == 1) {
488 : 0 : *p = PyBytes_AS_STRING(arg)[0];
489 : 0 : return 1;
490 : : }
491 [ # # # # ]: 0 : else if (PyByteArray_Check(arg) && PyByteArray_GET_SIZE(arg) == 1) {
492 : 0 : *p = PyByteArray_AS_STRING(arg)[0];
493 : 0 : return 1;
494 : : }
495 : : else {
496 : : int overflow;
497 : 0 : long ival = PyLong_AsLongAndOverflow(arg, &overflow);
498 [ # # # # ]: 0 : if (ival == -1 && PyErr_Occurred()) {
499 [ # # ]: 0 : if (PyErr_ExceptionMatches(PyExc_TypeError)) {
500 : 0 : goto onError;
501 : : }
502 : 0 : return 0;
503 : : }
504 [ # # # # ]: 0 : if (!(0 <= ival && ival <= 255)) {
505 : : /* this includes an overflow in converting to C long */
506 : 0 : PyErr_SetString(PyExc_OverflowError,
507 : : "%c arg not in range(256)");
508 : 0 : return 0;
509 : : }
510 : 0 : *p = (char)ival;
511 : 0 : return 1;
512 : : }
513 : 0 : onError:
514 : 0 : PyErr_SetString(PyExc_TypeError,
515 : : "%c requires an integer in range(256) or a single byte");
516 : 0 : return 0;
517 : : }
518 : :
519 : : static PyObject *_PyBytes_FromBuffer(PyObject *x);
520 : :
521 : : static PyObject *
522 : 0 : format_obj(PyObject *v, const char **pbuf, Py_ssize_t *plen)
523 : : {
524 : : PyObject *func, *result;
525 : : /* is it a bytes object? */
526 [ # # ]: 0 : if (PyBytes_Check(v)) {
527 : 0 : *pbuf = PyBytes_AS_STRING(v);
528 : 0 : *plen = PyBytes_GET_SIZE(v);
529 : 0 : return Py_NewRef(v);
530 : : }
531 [ # # ]: 0 : if (PyByteArray_Check(v)) {
532 : 0 : *pbuf = PyByteArray_AS_STRING(v);
533 : 0 : *plen = PyByteArray_GET_SIZE(v);
534 : 0 : return Py_NewRef(v);
535 : : }
536 : : /* does it support __bytes__? */
537 : 0 : func = _PyObject_LookupSpecial(v, &_Py_ID(__bytes__));
538 [ # # ]: 0 : if (func != NULL) {
539 : 0 : result = _PyObject_CallNoArgs(func);
540 : 0 : Py_DECREF(func);
541 [ # # ]: 0 : if (result == NULL)
542 : 0 : return NULL;
543 [ # # ]: 0 : if (!PyBytes_Check(result)) {
544 : 0 : PyErr_Format(PyExc_TypeError,
545 : : "__bytes__ returned non-bytes (type %.200s)",
546 : 0 : Py_TYPE(result)->tp_name);
547 : 0 : Py_DECREF(result);
548 : 0 : return NULL;
549 : : }
550 : 0 : *pbuf = PyBytes_AS_STRING(result);
551 : 0 : *plen = PyBytes_GET_SIZE(result);
552 : 0 : return result;
553 : : }
554 : : /* does it support buffer protocol? */
555 [ # # ]: 0 : if (PyObject_CheckBuffer(v)) {
556 : : /* maybe we can avoid making a copy of the buffer object here? */
557 : 0 : result = _PyBytes_FromBuffer(v);
558 [ # # ]: 0 : if (result == NULL)
559 : 0 : return NULL;
560 : 0 : *pbuf = PyBytes_AS_STRING(result);
561 : 0 : *plen = PyBytes_GET_SIZE(result);
562 : 0 : return result;
563 : : }
564 : 0 : PyErr_Format(PyExc_TypeError,
565 : : "%%b requires a bytes-like object, "
566 : : "or an object that implements __bytes__, not '%.100s'",
567 : 0 : Py_TYPE(v)->tp_name);
568 : 0 : return NULL;
569 : : }
570 : :
571 : : /* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...) */
572 : :
573 : : PyObject *
574 : 0 : _PyBytes_FormatEx(const char *format, Py_ssize_t format_len,
575 : : PyObject *args, int use_bytearray)
576 : : {
577 : : const char *fmt;
578 : : char *res;
579 : : Py_ssize_t arglen, argidx;
580 : : Py_ssize_t fmtcnt;
581 : 0 : int args_owned = 0;
582 : 0 : PyObject *dict = NULL;
583 : : _PyBytesWriter writer;
584 : :
585 [ # # ]: 0 : if (args == NULL) {
586 : 0 : PyErr_BadInternalCall();
587 : 0 : return NULL;
588 : : }
589 : 0 : fmt = format;
590 : 0 : fmtcnt = format_len;
591 : :
592 : 0 : _PyBytesWriter_Init(&writer);
593 : 0 : writer.use_bytearray = use_bytearray;
594 : :
595 : 0 : res = _PyBytesWriter_Alloc(&writer, fmtcnt);
596 [ # # ]: 0 : if (res == NULL)
597 : 0 : return NULL;
598 [ # # ]: 0 : if (!use_bytearray)
599 : 0 : writer.overallocate = 1;
600 : :
601 [ # # ]: 0 : if (PyTuple_Check(args)) {
602 : 0 : arglen = PyTuple_GET_SIZE(args);
603 : 0 : argidx = 0;
604 : : }
605 : : else {
606 : 0 : arglen = -1;
607 : 0 : argidx = -2;
608 : : }
609 [ # # # # : 0 : if (Py_TYPE(args)->tp_as_mapping && Py_TYPE(args)->tp_as_mapping->mp_subscript &&
# # ]
610 [ # # # # : 0 : !PyTuple_Check(args) && !PyBytes_Check(args) && !PyUnicode_Check(args) &&
# # ]
611 : 0 : !PyByteArray_Check(args)) {
612 : 0 : dict = args;
613 : : }
614 : :
615 [ # # ]: 0 : while (--fmtcnt >= 0) {
616 [ # # ]: 0 : if (*fmt != '%') {
617 : : Py_ssize_t len;
618 : : char *pos;
619 : :
620 : 0 : pos = (char *)memchr(fmt + 1, '%', fmtcnt);
621 [ # # ]: 0 : if (pos != NULL)
622 : 0 : len = pos - fmt;
623 : : else
624 : 0 : len = fmtcnt + 1;
625 : : assert(len != 0);
626 : :
627 : 0 : memcpy(res, fmt, len);
628 : 0 : res += len;
629 : 0 : fmt += len;
630 : 0 : fmtcnt -= (len - 1);
631 : : }
632 : : else {
633 : : /* Got a format specifier */
634 : 0 : int flags = 0;
635 : 0 : Py_ssize_t width = -1;
636 : 0 : int prec = -1;
637 : 0 : int c = '\0';
638 : : int fill;
639 : 0 : PyObject *v = NULL;
640 : 0 : PyObject *temp = NULL;
641 : 0 : const char *pbuf = NULL;
642 : : int sign;
643 : 0 : Py_ssize_t len = 0;
644 : : char onechar; /* For byte_converter() */
645 : : Py_ssize_t alloc;
646 : :
647 : 0 : fmt++;
648 [ # # ]: 0 : if (*fmt == '%') {
649 : 0 : *res++ = '%';
650 : 0 : fmt++;
651 : 0 : fmtcnt--;
652 : 0 : continue;
653 : : }
654 [ # # ]: 0 : if (*fmt == '(') {
655 : : const char *keystart;
656 : : Py_ssize_t keylen;
657 : : PyObject *key;
658 : 0 : int pcount = 1;
659 : :
660 [ # # ]: 0 : if (dict == NULL) {
661 : 0 : PyErr_SetString(PyExc_TypeError,
662 : : "format requires a mapping");
663 : 0 : goto error;
664 : : }
665 : 0 : ++fmt;
666 : 0 : --fmtcnt;
667 : 0 : keystart = fmt;
668 : : /* Skip over balanced parentheses */
669 [ # # # # ]: 0 : while (pcount > 0 && --fmtcnt >= 0) {
670 [ # # ]: 0 : if (*fmt == ')')
671 : 0 : --pcount;
672 [ # # ]: 0 : else if (*fmt == '(')
673 : 0 : ++pcount;
674 : 0 : fmt++;
675 : : }
676 : 0 : keylen = fmt - keystart - 1;
677 [ # # # # ]: 0 : if (fmtcnt < 0 || pcount > 0) {
678 : 0 : PyErr_SetString(PyExc_ValueError,
679 : : "incomplete format key");
680 : 0 : goto error;
681 : : }
682 : 0 : key = PyBytes_FromStringAndSize(keystart,
683 : : keylen);
684 [ # # ]: 0 : if (key == NULL)
685 : 0 : goto error;
686 [ # # ]: 0 : if (args_owned) {
687 : 0 : Py_DECREF(args);
688 : 0 : args_owned = 0;
689 : : }
690 : 0 : args = PyObject_GetItem(dict, key);
691 : 0 : Py_DECREF(key);
692 [ # # ]: 0 : if (args == NULL) {
693 : 0 : goto error;
694 : : }
695 : 0 : args_owned = 1;
696 : 0 : arglen = -1;
697 : 0 : argidx = -2;
698 : : }
699 : :
700 : : /* Parse flags. Example: "%+i" => flags=F_SIGN. */
701 [ # # ]: 0 : while (--fmtcnt >= 0) {
702 [ # # # # : 0 : switch (c = *fmt++) {
# # # ]
703 : 0 : case '-': flags |= F_LJUST; continue;
704 : 0 : case '+': flags |= F_SIGN; continue;
705 : 0 : case ' ': flags |= F_BLANK; continue;
706 : 0 : case '#': flags |= F_ALT; continue;
707 : 0 : case '0': flags |= F_ZERO; continue;
708 : 0 : case 'z': flags |= F_NO_NEG_0; continue;
709 : : }
710 : 0 : break;
711 : : }
712 : :
713 : : /* Parse width. Example: "%10s" => width=10 */
714 [ # # ]: 0 : if (c == '*') {
715 : 0 : v = getnextarg(args, arglen, &argidx);
716 [ # # ]: 0 : if (v == NULL)
717 : 0 : goto error;
718 [ # # ]: 0 : if (!PyLong_Check(v)) {
719 : 0 : PyErr_SetString(PyExc_TypeError,
720 : : "* wants int");
721 : 0 : goto error;
722 : : }
723 : 0 : width = PyLong_AsSsize_t(v);
724 [ # # # # ]: 0 : if (width == -1 && PyErr_Occurred())
725 : 0 : goto error;
726 [ # # ]: 0 : if (width < 0) {
727 : 0 : flags |= F_LJUST;
728 : 0 : width = -width;
729 : : }
730 [ # # ]: 0 : if (--fmtcnt >= 0)
731 : 0 : c = *fmt++;
732 : : }
733 [ # # # # ]: 0 : else if (c >= 0 && isdigit(c)) {
734 : 0 : width = c - '0';
735 [ # # ]: 0 : while (--fmtcnt >= 0) {
736 : 0 : c = Py_CHARMASK(*fmt++);
737 [ # # ]: 0 : if (!isdigit(c))
738 : 0 : break;
739 [ # # ]: 0 : if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
740 : 0 : PyErr_SetString(
741 : : PyExc_ValueError,
742 : : "width too big");
743 : 0 : goto error;
744 : : }
745 : 0 : width = width*10 + (c - '0');
746 : : }
747 : : }
748 : :
749 : : /* Parse precision. Example: "%.3f" => prec=3 */
750 [ # # ]: 0 : if (c == '.') {
751 : 0 : prec = 0;
752 [ # # ]: 0 : if (--fmtcnt >= 0)
753 : 0 : c = *fmt++;
754 [ # # ]: 0 : if (c == '*') {
755 : 0 : v = getnextarg(args, arglen, &argidx);
756 [ # # ]: 0 : if (v == NULL)
757 : 0 : goto error;
758 [ # # ]: 0 : if (!PyLong_Check(v)) {
759 : 0 : PyErr_SetString(
760 : : PyExc_TypeError,
761 : : "* wants int");
762 : 0 : goto error;
763 : : }
764 : 0 : prec = _PyLong_AsInt(v);
765 [ # # # # ]: 0 : if (prec == -1 && PyErr_Occurred())
766 : 0 : goto error;
767 [ # # ]: 0 : if (prec < 0)
768 : 0 : prec = 0;
769 [ # # ]: 0 : if (--fmtcnt >= 0)
770 : 0 : c = *fmt++;
771 : : }
772 [ # # # # ]: 0 : else if (c >= 0 && isdigit(c)) {
773 : 0 : prec = c - '0';
774 [ # # ]: 0 : while (--fmtcnt >= 0) {
775 : 0 : c = Py_CHARMASK(*fmt++);
776 [ # # ]: 0 : if (!isdigit(c))
777 : 0 : break;
778 [ # # ]: 0 : if (prec > (INT_MAX - ((int)c - '0')) / 10) {
779 : 0 : PyErr_SetString(
780 : : PyExc_ValueError,
781 : : "prec too big");
782 : 0 : goto error;
783 : : }
784 : 0 : prec = prec*10 + (c - '0');
785 : : }
786 : : }
787 : : } /* prec */
788 [ # # ]: 0 : if (fmtcnt >= 0) {
789 [ # # # # : 0 : if (c == 'h' || c == 'l' || c == 'L') {
# # ]
790 [ # # ]: 0 : if (--fmtcnt >= 0)
791 : 0 : c = *fmt++;
792 : : }
793 : : }
794 [ # # ]: 0 : if (fmtcnt < 0) {
795 : 0 : PyErr_SetString(PyExc_ValueError,
796 : : "incomplete format");
797 : 0 : goto error;
798 : : }
799 : 0 : v = getnextarg(args, arglen, &argidx);
800 [ # # ]: 0 : if (v == NULL)
801 : 0 : goto error;
802 : :
803 [ # # ]: 0 : if (fmtcnt == 0) {
804 : : /* last write: disable writer overallocation */
805 : 0 : writer.overallocate = 0;
806 : : }
807 : :
808 : 0 : sign = 0;
809 : 0 : fill = ' ';
810 [ # # # # : 0 : switch (c) {
# # ]
811 : 0 : case 'r':
812 : : // %r is only for 2/3 code; 3 only code should use %a
813 : : case 'a':
814 : 0 : temp = PyObject_ASCII(v);
815 [ # # ]: 0 : if (temp == NULL)
816 : 0 : goto error;
817 : : assert(PyUnicode_IS_ASCII(temp));
818 : 0 : pbuf = (const char *)PyUnicode_1BYTE_DATA(temp);
819 : 0 : len = PyUnicode_GET_LENGTH(temp);
820 [ # # # # ]: 0 : if (prec >= 0 && len > prec)
821 : 0 : len = prec;
822 : 0 : break;
823 : :
824 : 0 : case 's':
825 : : // %s is only for 2/3 code; 3 only code should use %b
826 : : case 'b':
827 : 0 : temp = format_obj(v, &pbuf, &len);
828 [ # # ]: 0 : if (temp == NULL)
829 : 0 : goto error;
830 [ # # # # ]: 0 : if (prec >= 0 && len > prec)
831 : 0 : len = prec;
832 : 0 : break;
833 : :
834 : 0 : case 'i':
835 : : case 'd':
836 : : case 'u':
837 : : case 'o':
838 : : case 'x':
839 : : case 'X':
840 [ # # ]: 0 : if (PyLong_CheckExact(v)
841 [ # # # # ]: 0 : && width == -1 && prec == -1
842 [ # # ]: 0 : && !(flags & (F_SIGN | F_BLANK))
843 [ # # ]: 0 : && c != 'X')
844 : : {
845 : : /* Fast path */
846 [ # # # # ]: 0 : int alternate = flags & F_ALT;
847 : : int base;
848 : :
849 : : switch(c)
850 : : {
851 : 0 : default:
852 : 0 : Py_UNREACHABLE();
853 : 0 : case 'd':
854 : : case 'i':
855 : : case 'u':
856 : 0 : base = 10;
857 : 0 : break;
858 : 0 : case 'o':
859 : 0 : base = 8;
860 : 0 : break;
861 : 0 : case 'x':
862 : : case 'X':
863 : 0 : base = 16;
864 : 0 : break;
865 : : }
866 : :
867 : : /* Fast path */
868 : 0 : writer.min_size -= 2; /* size preallocated for "%d" */
869 : 0 : res = _PyLong_FormatBytesWriter(&writer, res,
870 : : v, base, alternate);
871 [ # # ]: 0 : if (res == NULL)
872 : 0 : goto error;
873 : 0 : continue;
874 : : }
875 : :
876 : 0 : temp = formatlong(v, flags, prec, c);
877 [ # # ]: 0 : if (!temp)
878 : 0 : goto error;
879 : : assert(PyUnicode_IS_ASCII(temp));
880 : 0 : pbuf = (const char *)PyUnicode_1BYTE_DATA(temp);
881 : 0 : len = PyUnicode_GET_LENGTH(temp);
882 : 0 : sign = 1;
883 [ # # ]: 0 : if (flags & F_ZERO)
884 : 0 : fill = '0';
885 : 0 : break;
886 : :
887 : 0 : case 'e':
888 : : case 'E':
889 : : case 'f':
890 : : case 'F':
891 : : case 'g':
892 : : case 'G':
893 [ # # # # ]: 0 : if (width == -1 && prec == -1
894 [ # # ]: 0 : && !(flags & (F_SIGN | F_BLANK)))
895 : : {
896 : : /* Fast path */
897 : 0 : writer.min_size -= 2; /* size preallocated for "%f" */
898 : 0 : res = formatfloat(v, flags, prec, c, NULL, &writer, res);
899 [ # # ]: 0 : if (res == NULL)
900 : 0 : goto error;
901 : 0 : continue;
902 : : }
903 : :
904 [ # # ]: 0 : if (!formatfloat(v, flags, prec, c, &temp, NULL, res))
905 : 0 : goto error;
906 : 0 : pbuf = PyBytes_AS_STRING(temp);
907 : 0 : len = PyBytes_GET_SIZE(temp);
908 : 0 : sign = 1;
909 [ # # ]: 0 : if (flags & F_ZERO)
910 : 0 : fill = '0';
911 : 0 : break;
912 : :
913 : 0 : case 'c':
914 : 0 : pbuf = &onechar;
915 : 0 : len = byte_converter(v, &onechar);
916 [ # # ]: 0 : if (!len)
917 : 0 : goto error;
918 [ # # ]: 0 : if (width == -1) {
919 : : /* Fast path */
920 : 0 : *res++ = onechar;
921 : 0 : continue;
922 : : }
923 : 0 : break;
924 : :
925 : 0 : default:
926 : 0 : PyErr_Format(PyExc_ValueError,
927 : : "unsupported format character '%c' (0x%x) "
928 : : "at index %zd",
929 : : c, c,
930 : 0 : (Py_ssize_t)(fmt - 1 - format));
931 : 0 : goto error;
932 : : }
933 : :
934 [ # # ]: 0 : if (sign) {
935 [ # # # # ]: 0 : if (*pbuf == '-' || *pbuf == '+') {
936 : 0 : sign = *pbuf++;
937 : 0 : len--;
938 : : }
939 [ # # ]: 0 : else if (flags & F_SIGN)
940 : 0 : sign = '+';
941 [ # # ]: 0 : else if (flags & F_BLANK)
942 : 0 : sign = ' ';
943 : : else
944 : 0 : sign = 0;
945 : : }
946 [ # # ]: 0 : if (width < len)
947 : 0 : width = len;
948 : :
949 : 0 : alloc = width;
950 [ # # # # ]: 0 : if (sign != 0 && len == width)
951 : 0 : alloc++;
952 : : /* 2: size preallocated for %s */
953 [ # # ]: 0 : if (alloc > 2) {
954 : 0 : res = _PyBytesWriter_Prepare(&writer, res, alloc - 2);
955 [ # # ]: 0 : if (res == NULL)
956 : 0 : goto error;
957 : : }
958 : : #ifndef NDEBUG
959 : : char *before = res;
960 : : #endif
961 : :
962 : : /* Write the sign if needed */
963 [ # # ]: 0 : if (sign) {
964 [ # # ]: 0 : if (fill != ' ')
965 : 0 : *res++ = sign;
966 [ # # ]: 0 : if (width > len)
967 : 0 : width--;
968 : : }
969 : :
970 : : /* Write the numeric prefix for "x", "X" and "o" formats
971 : : if the alternate form is used.
972 : : For example, write "0x" for the "%#x" format. */
973 [ # # # # : 0 : if ((flags & F_ALT) && (c == 'o' || c == 'x' || c == 'X')) {
# # # # ]
974 : : assert(pbuf[0] == '0');
975 : : assert(pbuf[1] == c);
976 [ # # ]: 0 : if (fill != ' ') {
977 : 0 : *res++ = *pbuf++;
978 : 0 : *res++ = *pbuf++;
979 : : }
980 : 0 : width -= 2;
981 [ # # ]: 0 : if (width < 0)
982 : 0 : width = 0;
983 : 0 : len -= 2;
984 : : }
985 : :
986 : : /* Pad left with the fill character if needed */
987 [ # # # # ]: 0 : if (width > len && !(flags & F_LJUST)) {
988 : 0 : memset(res, fill, width - len);
989 : 0 : res += (width - len);
990 : 0 : width = len;
991 : : }
992 : :
993 : : /* If padding with spaces: write sign if needed and/or numeric
994 : : prefix if the alternate form is used */
995 [ # # ]: 0 : if (fill == ' ') {
996 [ # # ]: 0 : if (sign)
997 : 0 : *res++ = sign;
998 [ # # # # : 0 : if ((flags & F_ALT) && (c == 'o' || c == 'x' || c == 'X')) {
# # # # ]
999 : : assert(pbuf[0] == '0');
1000 : : assert(pbuf[1] == c);
1001 : 0 : *res++ = *pbuf++;
1002 : 0 : *res++ = *pbuf++;
1003 : : }
1004 : : }
1005 : :
1006 : : /* Copy bytes */
1007 : 0 : memcpy(res, pbuf, len);
1008 : 0 : res += len;
1009 : :
1010 : : /* Pad right with the fill character if needed */
1011 [ # # ]: 0 : if (width > len) {
1012 : 0 : memset(res, ' ', width - len);
1013 : 0 : res += (width - len);
1014 : : }
1015 : :
1016 [ # # # # ]: 0 : if (dict && (argidx < arglen)) {
1017 : 0 : PyErr_SetString(PyExc_TypeError,
1018 : : "not all arguments converted during bytes formatting");
1019 : 0 : Py_XDECREF(temp);
1020 : 0 : goto error;
1021 : : }
1022 : 0 : Py_XDECREF(temp);
1023 : :
1024 : : #ifndef NDEBUG
1025 : : /* check that we computed the exact size for this write */
1026 : : assert((res - before) == alloc);
1027 : : #endif
1028 : : } /* '%' */
1029 : :
1030 : : /* If overallocation was disabled, ensure that it was the last
1031 : : write. Otherwise, we missed an optimization */
1032 : : assert(writer.overallocate || fmtcnt == 0 || use_bytearray);
1033 : : } /* until end */
1034 : :
1035 [ # # # # ]: 0 : if (argidx < arglen && !dict) {
1036 : 0 : PyErr_SetString(PyExc_TypeError,
1037 : : "not all arguments converted during bytes formatting");
1038 : 0 : goto error;
1039 : : }
1040 : :
1041 [ # # ]: 0 : if (args_owned) {
1042 : 0 : Py_DECREF(args);
1043 : : }
1044 : 0 : return _PyBytesWriter_Finish(&writer, res);
1045 : :
1046 : 0 : error:
1047 : 0 : _PyBytesWriter_Dealloc(&writer);
1048 [ # # ]: 0 : if (args_owned) {
1049 : 0 : Py_DECREF(args);
1050 : : }
1051 : 0 : return NULL;
1052 : : }
1053 : :
1054 : : /* Unescape a backslash-escaped string. */
1055 : 65 : PyObject *_PyBytes_DecodeEscape(const char *s,
1056 : : Py_ssize_t len,
1057 : : const char *errors,
1058 : : const char **first_invalid_escape)
1059 : : {
1060 : : int c;
1061 : : char *p;
1062 : : const char *end;
1063 : : _PyBytesWriter writer;
1064 : :
1065 : 65 : _PyBytesWriter_Init(&writer);
1066 : :
1067 : 65 : p = _PyBytesWriter_Alloc(&writer, len);
1068 [ - + ]: 65 : if (p == NULL)
1069 : 0 : return NULL;
1070 : 65 : writer.overallocate = 1;
1071 : :
1072 : 65 : *first_invalid_escape = NULL;
1073 : :
1074 : 65 : end = s + len;
1075 [ + + ]: 230 : while (s < end) {
1076 [ + + ]: 165 : if (*s != '\\') {
1077 : 43 : *p++ = *s++;
1078 : 43 : continue;
1079 : : }
1080 : :
1081 : 122 : s++;
1082 [ - + ]: 122 : if (s == end) {
1083 : 0 : PyErr_SetString(PyExc_ValueError,
1084 : : "Trailing \\ in string");
1085 : 0 : goto failed;
1086 : : }
1087 : :
1088 [ - + + - : 122 : switch (*s++) {
- + + + +
+ - + +
- ]
1089 : : /* XXX This assumes ASCII! */
1090 : 0 : case '\n': break;
1091 : 27 : case '\\': *p++ = '\\'; break;
1092 : 1 : case '\'': *p++ = '\''; break;
1093 : 0 : case '\"': *p++ = '\"'; break;
1094 : 0 : case 'b': *p++ = '\b'; break;
1095 : 1 : case 'f': *p++ = '\014'; break; /* FF */
1096 : 2 : case 't': *p++ = '\t'; break;
1097 : 14 : case 'n': *p++ = '\n'; break;
1098 : 7 : case 'r': *p++ = '\r'; break;
1099 : 2 : case 'v': *p++ = '\013'; break; /* VT */
1100 : 0 : case 'a': *p++ = '\007'; break; /* BEL, not classic C */
1101 : 8 : case '0': case '1': case '2': case '3':
1102 : : case '4': case '5': case '6': case '7':
1103 : 8 : c = s[-1] - '0';
1104 [ + + + - : 8 : if (s < end && '0' <= *s && *s <= '7') {
- + ]
1105 : 0 : c = (c<<3) + *s++ - '0';
1106 [ # # # # : 0 : if (s < end && '0' <= *s && *s <= '7')
# # ]
1107 : 0 : c = (c<<3) + *s++ - '0';
1108 : : }
1109 [ - + ]: 8 : if (c > 0377) {
1110 [ # # ]: 0 : if (*first_invalid_escape == NULL) {
1111 : 0 : *first_invalid_escape = s-3; /* Back up 3 chars, since we've
1112 : : already incremented s. */
1113 : : }
1114 : : }
1115 : 8 : *p++ = c;
1116 : 8 : break;
1117 : 60 : case 'x':
1118 [ + - ]: 60 : if (s+1 < end) {
1119 : : int digit1, digit2;
1120 : 60 : digit1 = _PyLong_DigitValue[Py_CHARMASK(s[0])];
1121 : 60 : digit2 = _PyLong_DigitValue[Py_CHARMASK(s[1])];
1122 [ + - + - ]: 60 : if (digit1 < 16 && digit2 < 16) {
1123 : 60 : *p++ = (unsigned char)((digit1 << 4) + digit2);
1124 : 60 : s += 2;
1125 : 60 : break;
1126 : : }
1127 : : }
1128 : : /* invalid hexadecimal digits */
1129 : :
1130 [ # # # # ]: 0 : if (!errors || strcmp(errors, "strict") == 0) {
1131 : 0 : PyErr_Format(PyExc_ValueError,
1132 : : "invalid \\x escape at position %zd",
1133 : 0 : s - 2 - (end - len));
1134 : 0 : goto failed;
1135 : : }
1136 [ # # ]: 0 : if (strcmp(errors, "replace") == 0) {
1137 : 0 : *p++ = '?';
1138 [ # # ]: 0 : } else if (strcmp(errors, "ignore") == 0)
1139 : : /* do nothing */;
1140 : : else {
1141 : 0 : PyErr_Format(PyExc_ValueError,
1142 : : "decoding error; unknown "
1143 : : "error handling code: %.400s",
1144 : : errors);
1145 : 0 : goto failed;
1146 : : }
1147 : : /* skip \x */
1148 [ # # # # ]: 0 : if (s < end && Py_ISXDIGIT(s[0]))
1149 : 0 : s++; /* and a hexdigit */
1150 : 0 : break;
1151 : :
1152 : 0 : default:
1153 [ # # ]: 0 : if (*first_invalid_escape == NULL) {
1154 : 0 : *first_invalid_escape = s-1; /* Back up one char, since we've
1155 : : already incremented s. */
1156 : : }
1157 : 0 : *p++ = '\\';
1158 : 0 : s--;
1159 : : }
1160 : : }
1161 : :
1162 : 65 : return _PyBytesWriter_Finish(&writer, p);
1163 : :
1164 : 0 : failed:
1165 : 0 : _PyBytesWriter_Dealloc(&writer);
1166 : 0 : return NULL;
1167 : : }
1168 : :
1169 : 0 : PyObject *PyBytes_DecodeEscape(const char *s,
1170 : : Py_ssize_t len,
1171 : : const char *errors,
1172 : : Py_ssize_t Py_UNUSED(unicode),
1173 : : const char *Py_UNUSED(recode_encoding))
1174 : : {
1175 : : const char* first_invalid_escape;
1176 : 0 : PyObject *result = _PyBytes_DecodeEscape(s, len, errors,
1177 : : &first_invalid_escape);
1178 [ # # ]: 0 : if (result == NULL)
1179 : 0 : return NULL;
1180 [ # # ]: 0 : if (first_invalid_escape != NULL) {
1181 : 0 : unsigned char c = *first_invalid_escape;
1182 [ # # # # ]: 0 : if ('4' <= c && c <= '7') {
1183 [ # # ]: 0 : if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1184 : : "invalid octal escape sequence '\\%.3s'",
1185 : : first_invalid_escape) < 0)
1186 : : {
1187 : 0 : Py_DECREF(result);
1188 : 0 : return NULL;
1189 : : }
1190 : : }
1191 : : else {
1192 [ # # ]: 0 : if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1193 : : "invalid escape sequence '\\%c'",
1194 : : c) < 0)
1195 : : {
1196 : 0 : Py_DECREF(result);
1197 : 0 : return NULL;
1198 : : }
1199 : : }
1200 : : }
1201 : 0 : return result;
1202 : :
1203 : : }
1204 : : /* -------------------------------------------------------------------- */
1205 : : /* object api */
1206 : :
1207 : : Py_ssize_t
1208 : 0 : PyBytes_Size(PyObject *op)
1209 : : {
1210 [ # # ]: 0 : if (!PyBytes_Check(op)) {
1211 : 0 : PyErr_Format(PyExc_TypeError,
1212 : 0 : "expected bytes, %.200s found", Py_TYPE(op)->tp_name);
1213 : 0 : return -1;
1214 : : }
1215 : 0 : return Py_SIZE(op);
1216 : : }
1217 : :
1218 : : char *
1219 : 1439098 : PyBytes_AsString(PyObject *op)
1220 : : {
1221 [ - + ]: 1439098 : if (!PyBytes_Check(op)) {
1222 : 0 : PyErr_Format(PyExc_TypeError,
1223 : 0 : "expected bytes, %.200s found", Py_TYPE(op)->tp_name);
1224 : 0 : return NULL;
1225 : : }
1226 : 1439098 : return ((PyBytesObject *)op)->ob_sval;
1227 : : }
1228 : :
1229 : : int
1230 : 0 : PyBytes_AsStringAndSize(PyObject *obj,
1231 : : char **s,
1232 : : Py_ssize_t *len)
1233 : : {
1234 [ # # ]: 0 : if (s == NULL) {
1235 : 0 : PyErr_BadInternalCall();
1236 : 0 : return -1;
1237 : : }
1238 : :
1239 [ # # ]: 0 : if (!PyBytes_Check(obj)) {
1240 : 0 : PyErr_Format(PyExc_TypeError,
1241 : 0 : "expected bytes, %.200s found", Py_TYPE(obj)->tp_name);
1242 : 0 : return -1;
1243 : : }
1244 : :
1245 : 0 : *s = PyBytes_AS_STRING(obj);
1246 [ # # ]: 0 : if (len != NULL)
1247 : 0 : *len = PyBytes_GET_SIZE(obj);
1248 [ # # ]: 0 : else if (strlen(*s) != (size_t)PyBytes_GET_SIZE(obj)) {
1249 : 0 : PyErr_SetString(PyExc_ValueError,
1250 : : "embedded null byte");
1251 : 0 : return -1;
1252 : : }
1253 : 0 : return 0;
1254 : : }
1255 : :
1256 : : /* -------------------------------------------------------------------- */
1257 : : /* Methods */
1258 : :
1259 : : #define STRINGLIB_GET_EMPTY() bytes_get_empty()
1260 : :
1261 : : #include "stringlib/stringdefs.h"
1262 : : #define STRINGLIB_MUTABLE 0
1263 : :
1264 : : #include "stringlib/fastsearch.h"
1265 : : #include "stringlib/count.h"
1266 : : #include "stringlib/find.h"
1267 : : #include "stringlib/join.h"
1268 : : #include "stringlib/partition.h"
1269 : : #include "stringlib/split.h"
1270 : : #include "stringlib/ctype.h"
1271 : :
1272 : : #include "stringlib/transmogrify.h"
1273 : :
1274 : : #undef STRINGLIB_GET_EMPTY
1275 : :
1276 : : Py_ssize_t
1277 : 0 : _PyBytes_Find(const char *haystack, Py_ssize_t len_haystack,
1278 : : const char *needle, Py_ssize_t len_needle,
1279 : : Py_ssize_t offset)
1280 : : {
1281 : 0 : return stringlib_find(haystack, len_haystack,
1282 : : needle, len_needle, offset);
1283 : : }
1284 : :
1285 : : Py_ssize_t
1286 : 0 : _PyBytes_ReverseFind(const char *haystack, Py_ssize_t len_haystack,
1287 : : const char *needle, Py_ssize_t len_needle,
1288 : : Py_ssize_t offset)
1289 : : {
1290 : 0 : return stringlib_rfind(haystack, len_haystack,
1291 : : needle, len_needle, offset);
1292 : : }
1293 : :
1294 : : PyObject *
1295 : 15220 : PyBytes_Repr(PyObject *obj, int smartquotes)
1296 : : {
1297 : 15220 : PyBytesObject* op = (PyBytesObject*) obj;
1298 : 15220 : Py_ssize_t i, length = Py_SIZE(op);
1299 : : Py_ssize_t newsize, squotes, dquotes;
1300 : : PyObject *v;
1301 : : unsigned char quote;
1302 : : const unsigned char *s;
1303 : : Py_UCS1 *p;
1304 : :
1305 : : /* Compute size of output string */
1306 : 15220 : squotes = dquotes = 0;
1307 : 15220 : newsize = 3; /* b'' */
1308 : 15220 : s = (const unsigned char*)op->ob_sval;
1309 [ + + ]: 795270 : for (i = 0; i < length; i++) {
1310 : 780050 : Py_ssize_t incr = 1;
1311 [ + + + + ]: 780050 : switch(s[i]) {
1312 : 1877 : case '\'': squotes++; break;
1313 : 2196 : case '"': dquotes++; break;
1314 : 15457 : case '\\': case '\t': case '\n': case '\r':
1315 : 15457 : incr = 2; break; /* \C */
1316 : 760520 : default:
1317 [ + + + + ]: 760520 : if (s[i] < ' ' || s[i] >= 0x7f)
1318 : 607687 : incr = 4; /* \xHH */
1319 : : }
1320 [ - + ]: 780050 : if (newsize > PY_SSIZE_T_MAX - incr)
1321 : 0 : goto overflow;
1322 : 780050 : newsize += incr;
1323 : : }
1324 : 15220 : quote = '\'';
1325 [ + - + + : 15220 : if (smartquotes && squotes && !dquotes)
+ + ]
1326 : 653 : quote = '"';
1327 [ + + + + ]: 15220 : if (squotes && quote == '\'') {
1328 [ - + ]: 393 : if (newsize > PY_SSIZE_T_MAX - squotes)
1329 : 0 : goto overflow;
1330 : 393 : newsize += squotes;
1331 : : }
1332 : :
1333 : 15220 : v = PyUnicode_New(newsize, 127);
1334 [ - + ]: 15220 : if (v == NULL) {
1335 : 0 : return NULL;
1336 : : }
1337 : 15220 : p = PyUnicode_1BYTE_DATA(v);
1338 : :
1339 : 15220 : *p++ = 'b', *p++ = quote;
1340 [ + + ]: 795270 : for (i = 0; i < length; i++) {
1341 : 780050 : unsigned char c = op->ob_sval[i];
1342 [ + + + + ]: 780050 : if (c == quote || c == '\\')
1343 : 1575 : *p++ = '\\', *p++ = c;
1344 [ + + ]: 778475 : else if (c == '\t')
1345 : 6867 : *p++ = '\\', *p++ = 't';
1346 [ + + ]: 771608 : else if (c == '\n')
1347 : 3563 : *p++ = '\\', *p++ = 'n';
1348 [ + + ]: 768045 : else if (c == '\r')
1349 : 4244 : *p++ = '\\', *p++ = 'r';
1350 [ + + + + ]: 763801 : else if (c < ' ' || c >= 0x7f) {
1351 : 607687 : *p++ = '\\';
1352 : 607687 : *p++ = 'x';
1353 : 607687 : *p++ = Py_hexdigits[(c & 0xf0) >> 4];
1354 : 607687 : *p++ = Py_hexdigits[c & 0xf];
1355 : : }
1356 : : else
1357 : 156114 : *p++ = c;
1358 : : }
1359 : 15220 : *p++ = quote;
1360 : : assert(_PyUnicode_CheckConsistency(v, 1));
1361 : 15220 : return v;
1362 : :
1363 : 0 : overflow:
1364 : 0 : PyErr_SetString(PyExc_OverflowError,
1365 : : "bytes object is too large to make repr");
1366 : 0 : return NULL;
1367 : : }
1368 : :
1369 : : static PyObject *
1370 : 15220 : bytes_repr(PyObject *op)
1371 : : {
1372 : 15220 : return PyBytes_Repr(op, 1);
1373 : : }
1374 : :
1375 : : static PyObject *
1376 : 0 : bytes_str(PyObject *op)
1377 : : {
1378 [ # # ]: 0 : if (_Py_GetConfig()->bytes_warning) {
1379 [ # # ]: 0 : if (PyErr_WarnEx(PyExc_BytesWarning,
1380 : : "str() on a bytes instance", 1)) {
1381 : 0 : return NULL;
1382 : : }
1383 : : }
1384 : 0 : return bytes_repr(op);
1385 : : }
1386 : :
1387 : : static Py_ssize_t
1388 : 6808 : bytes_length(PyBytesObject *a)
1389 : : {
1390 : 6808 : return Py_SIZE(a);
1391 : : }
1392 : :
1393 : : /* This is also used by PyBytes_Concat() */
1394 : : static PyObject *
1395 : 4129 : bytes_concat(PyObject *a, PyObject *b)
1396 : : {
1397 : : Py_buffer va, vb;
1398 : 4129 : PyObject *result = NULL;
1399 : :
1400 : 4129 : va.len = -1;
1401 : 4129 : vb.len = -1;
1402 [ + - - + ]: 8258 : if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 ||
1403 : 4129 : PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) {
1404 : 0 : PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
1405 : 0 : Py_TYPE(b)->tp_name, Py_TYPE(a)->tp_name);
1406 : 0 : goto done;
1407 : : }
1408 : :
1409 : : /* Optimize end cases */
1410 [ + + + - ]: 4129 : if (va.len == 0 && PyBytes_CheckExact(b)) {
1411 : 4102 : result = Py_NewRef(b);
1412 : 4102 : goto done;
1413 : : }
1414 [ - + - - ]: 27 : if (vb.len == 0 && PyBytes_CheckExact(a)) {
1415 : 0 : result = Py_NewRef(a);
1416 : 0 : goto done;
1417 : : }
1418 : :
1419 [ - + ]: 27 : if (va.len > PY_SSIZE_T_MAX - vb.len) {
1420 : 0 : PyErr_NoMemory();
1421 : 0 : goto done;
1422 : : }
1423 : :
1424 : 27 : result = PyBytes_FromStringAndSize(NULL, va.len + vb.len);
1425 [ - + ]: 27 : if (result != NULL) {
1426 : 27 : memcpy(PyBytes_AS_STRING(result), va.buf, va.len);
1427 : 27 : memcpy(PyBytes_AS_STRING(result) + va.len, vb.buf, vb.len);
1428 : : }
1429 : :
1430 : 0 : done:
1431 [ + - ]: 4129 : if (va.len != -1)
1432 : 4129 : PyBuffer_Release(&va);
1433 [ + - ]: 4129 : if (vb.len != -1)
1434 : 4129 : PyBuffer_Release(&vb);
1435 : 4129 : return result;
1436 : : }
1437 : :
1438 : : static PyObject *
1439 : 5 : bytes_repeat(PyBytesObject *a, Py_ssize_t n)
1440 : : {
1441 : : Py_ssize_t size;
1442 : : PyBytesObject *op;
1443 : : size_t nbytes;
1444 [ - + ]: 5 : if (n < 0)
1445 : 0 : n = 0;
1446 : : /* watch out for overflows: the size can overflow int,
1447 : : * and the # of bytes needed can overflow size_t
1448 : : */
1449 [ + - - + ]: 5 : if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n) {
1450 : 0 : PyErr_SetString(PyExc_OverflowError,
1451 : : "repeated bytes are too long");
1452 : 0 : return NULL;
1453 : : }
1454 : 5 : size = Py_SIZE(a) * n;
1455 [ - + - - ]: 5 : if (size == Py_SIZE(a) && PyBytes_CheckExact(a)) {
1456 : 0 : return Py_NewRef(a);
1457 : : }
1458 : 5 : nbytes = (size_t)size;
1459 [ - + ]: 5 : if (nbytes + PyBytesObject_SIZE <= nbytes) {
1460 : 0 : PyErr_SetString(PyExc_OverflowError,
1461 : : "repeated bytes are too long");
1462 : 0 : return NULL;
1463 : : }
1464 : 5 : op = (PyBytesObject *)PyObject_Malloc(PyBytesObject_SIZE + nbytes);
1465 [ - + ]: 5 : if (op == NULL) {
1466 : 0 : return PyErr_NoMemory();
1467 : : }
1468 : 5 : _PyObject_InitVar((PyVarObject*)op, &PyBytes_Type, size);
1469 : : _Py_COMP_DIAG_PUSH
1470 : : _Py_COMP_DIAG_IGNORE_DEPR_DECLS
1471 : 5 : op->ob_shash = -1;
1472 : : _Py_COMP_DIAG_POP
1473 : 5 : op->ob_sval[size] = '\0';
1474 : :
1475 : 5 : _PyBytes_Repeat(op->ob_sval, size, a->ob_sval, Py_SIZE(a));
1476 : :
1477 : 5 : return (PyObject *) op;
1478 : : }
1479 : :
1480 : : static int
1481 : 0 : bytes_contains(PyObject *self, PyObject *arg)
1482 : : {
1483 : 0 : return _Py_bytes_contains(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), arg);
1484 : : }
1485 : :
1486 : : static PyObject *
1487 : 0 : bytes_item(PyBytesObject *a, Py_ssize_t i)
1488 : : {
1489 [ # # # # ]: 0 : if (i < 0 || i >= Py_SIZE(a)) {
1490 : 0 : PyErr_SetString(PyExc_IndexError, "index out of range");
1491 : 0 : return NULL;
1492 : : }
1493 : 0 : return _PyLong_FromUnsignedChar((unsigned char)a->ob_sval[i]);
1494 : : }
1495 : :
1496 : : static int
1497 : 6499 : bytes_compare_eq(PyBytesObject *a, PyBytesObject *b)
1498 : : {
1499 : : int cmp;
1500 : : Py_ssize_t len;
1501 : :
1502 : 6499 : len = Py_SIZE(a);
1503 [ + + ]: 6499 : if (Py_SIZE(b) != len)
1504 : 986 : return 0;
1505 : :
1506 [ + + ]: 5513 : if (a->ob_sval[0] != b->ob_sval[0])
1507 : 22 : return 0;
1508 : :
1509 : 5491 : cmp = memcmp(a->ob_sval, b->ob_sval, len);
1510 : 5491 : return (cmp == 0);
1511 : : }
1512 : :
1513 : : static PyObject*
1514 : 6611 : bytes_richcompare(PyBytesObject *a, PyBytesObject *b, int op)
1515 : : {
1516 : : int c;
1517 : : Py_ssize_t len_a, len_b;
1518 : : Py_ssize_t min_len;
1519 : :
1520 : : /* Make sure both arguments are strings. */
1521 [ + - - + ]: 6611 : if (!(PyBytes_Check(a) && PyBytes_Check(b))) {
1522 [ # # # # : 0 : if (_Py_GetConfig()->bytes_warning && (op == Py_EQ || op == Py_NE)) {
# # ]
1523 [ # # # # ]: 0 : if (PyUnicode_Check(a) || PyUnicode_Check(b)) {
1524 [ # # ]: 0 : if (PyErr_WarnEx(PyExc_BytesWarning,
1525 : : "Comparison between bytes and string", 1))
1526 : 0 : return NULL;
1527 : : }
1528 [ # # # # ]: 0 : if (PyLong_Check(a) || PyLong_Check(b)) {
1529 [ # # ]: 0 : if (PyErr_WarnEx(PyExc_BytesWarning,
1530 : : "Comparison between bytes and int", 1))
1531 : 0 : return NULL;
1532 : : }
1533 : : }
1534 : 0 : Py_RETURN_NOTIMPLEMENTED;
1535 : : }
1536 [ + + ]: 6611 : else if (a == b) {
1537 [ + - - ]: 1 : switch (op) {
1538 : 1 : case Py_EQ:
1539 : : case Py_LE:
1540 : : case Py_GE:
1541 : : /* a byte string is equal to itself */
1542 : 1 : Py_RETURN_TRUE;
1543 : 0 : case Py_NE:
1544 : : case Py_LT:
1545 : : case Py_GT:
1546 : 0 : Py_RETURN_FALSE;
1547 : 0 : default:
1548 : 0 : PyErr_BadArgument();
1549 : 0 : return NULL;
1550 : : }
1551 : : }
1552 [ + + + + ]: 6610 : else if (op == Py_EQ || op == Py_NE) {
1553 : 6499 : int eq = bytes_compare_eq(a, b);
1554 : 6499 : eq ^= (op == Py_NE);
1555 : 6499 : return PyBool_FromLong(eq);
1556 : : }
1557 : : else {
1558 : 111 : len_a = Py_SIZE(a);
1559 : 111 : len_b = Py_SIZE(b);
1560 : 111 : min_len = Py_MIN(len_a, len_b);
1561 [ + - ]: 111 : if (min_len > 0) {
1562 : 111 : c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
1563 [ + + ]: 111 : if (c == 0)
1564 : 105 : c = memcmp(a->ob_sval, b->ob_sval, min_len);
1565 : : }
1566 : : else
1567 : 0 : c = 0;
1568 [ + - ]: 111 : if (c != 0)
1569 [ - - + - : 111 : Py_RETURN_RICHCOMPARE(c, 0, op);
- - - - -
- - + + -
- - - -
- ]
1570 [ # # # # : 0 : Py_RETURN_RICHCOMPARE(len_a, len_b, op);
# # # # #
# # # # #
# # # #
# ]
1571 : : }
1572 : : }
1573 : :
1574 : : static Py_hash_t
1575 : 166784 : bytes_hash(PyBytesObject *a)
1576 : : {
1577 : : _Py_COMP_DIAG_PUSH
1578 : : _Py_COMP_DIAG_IGNORE_DEPR_DECLS
1579 [ + + ]: 166784 : if (a->ob_shash == -1) {
1580 : : /* Can't fail */
1581 : 22503 : a->ob_shash = _Py_HashBytes(a->ob_sval, Py_SIZE(a));
1582 : : }
1583 : 166784 : return a->ob_shash;
1584 : : _Py_COMP_DIAG_POP
1585 : : }
1586 : :
1587 : : static PyObject*
1588 : 154111 : bytes_subscript(PyBytesObject* self, PyObject* item)
1589 : : {
1590 [ + + ]: 154111 : if (_PyIndex_Check(item)) {
1591 : 85131 : Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1592 [ - + - - ]: 85131 : if (i == -1 && PyErr_Occurred())
1593 : 0 : return NULL;
1594 [ - + ]: 85131 : if (i < 0)
1595 : 0 : i += PyBytes_GET_SIZE(self);
1596 [ + - - + ]: 85131 : if (i < 0 || i >= PyBytes_GET_SIZE(self)) {
1597 : 0 : PyErr_SetString(PyExc_IndexError,
1598 : : "index out of range");
1599 : 0 : return NULL;
1600 : : }
1601 : 85131 : return _PyLong_FromUnsignedChar((unsigned char)self->ob_sval[i]);
1602 : : }
1603 [ + - ]: 68980 : else if (PySlice_Check(item)) {
1604 : : Py_ssize_t start, stop, step, slicelength, i;
1605 : : size_t cur;
1606 : : const char* source_buf;
1607 : : char* result_buf;
1608 : : PyObject* result;
1609 : :
1610 [ - + ]: 68980 : if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
1611 : 0 : return NULL;
1612 : : }
1613 : 68980 : slicelength = PySlice_AdjustIndices(PyBytes_GET_SIZE(self), &start,
1614 : : &stop, step);
1615 : :
1616 [ + + ]: 68980 : if (slicelength <= 0) {
1617 : 4136 : return PyBytes_FromStringAndSize("", 0);
1618 : : }
1619 [ + + + + : 65329 : else if (start == 0 && step == 1 &&
- + ]
1620 [ - - ]: 485 : slicelength == PyBytes_GET_SIZE(self) &&
1621 : 0 : PyBytes_CheckExact(self)) {
1622 : 0 : return Py_NewRef(self);
1623 : : }
1624 [ + + ]: 64844 : else if (step == 1) {
1625 : 64072 : return PyBytes_FromStringAndSize(
1626 : 64072 : PyBytes_AS_STRING(self) + start,
1627 : : slicelength);
1628 : : }
1629 : : else {
1630 : 772 : source_buf = PyBytes_AS_STRING(self);
1631 : 772 : result = PyBytes_FromStringAndSize(NULL, slicelength);
1632 [ - + ]: 772 : if (result == NULL)
1633 : 0 : return NULL;
1634 : :
1635 : 772 : result_buf = PyBytes_AS_STRING(result);
1636 [ + + ]: 65912 : for (cur = start, i = 0; i < slicelength;
1637 : 65140 : cur += step, i++) {
1638 : 65140 : result_buf[i] = source_buf[cur];
1639 : : }
1640 : :
1641 : 772 : return result;
1642 : : }
1643 : : }
1644 : : else {
1645 : 0 : PyErr_Format(PyExc_TypeError,
1646 : : "byte indices must be integers or slices, not %.200s",
1647 : 0 : Py_TYPE(item)->tp_name);
1648 : 0 : return NULL;
1649 : : }
1650 : : }
1651 : :
1652 : : static int
1653 : 18901 : bytes_buffer_getbuffer(PyBytesObject *self, Py_buffer *view, int flags)
1654 : : {
1655 : 18901 : return PyBuffer_FillInfo(view, (PyObject*)self, (void *)self->ob_sval, Py_SIZE(self),
1656 : : 1, flags);
1657 : : }
1658 : :
1659 : : static PySequenceMethods bytes_as_sequence = {
1660 : : (lenfunc)bytes_length, /*sq_length*/
1661 : : (binaryfunc)bytes_concat, /*sq_concat*/
1662 : : (ssizeargfunc)bytes_repeat, /*sq_repeat*/
1663 : : (ssizeargfunc)bytes_item, /*sq_item*/
1664 : : 0, /*sq_slice*/
1665 : : 0, /*sq_ass_item*/
1666 : : 0, /*sq_ass_slice*/
1667 : : (objobjproc)bytes_contains /*sq_contains*/
1668 : : };
1669 : :
1670 : : static PyMappingMethods bytes_as_mapping = {
1671 : : (lenfunc)bytes_length,
1672 : : (binaryfunc)bytes_subscript,
1673 : : 0,
1674 : : };
1675 : :
1676 : : static PyBufferProcs bytes_as_buffer = {
1677 : : (getbufferproc)bytes_buffer_getbuffer,
1678 : : NULL,
1679 : : };
1680 : :
1681 : :
1682 : : /*[clinic input]
1683 : : bytes.__bytes__
1684 : : Convert this value to exact type bytes.
1685 : : [clinic start generated code]*/
1686 : :
1687 : : static PyObject *
1688 : 1 : bytes___bytes___impl(PyBytesObject *self)
1689 : : /*[clinic end generated code: output=63a306a9bc0caac5 input=34ec5ddba98bd6bb]*/
1690 : : {
1691 [ + - ]: 1 : if (PyBytes_CheckExact(self)) {
1692 : 1 : return Py_NewRef(self);
1693 : : }
1694 : : else {
1695 : 0 : return PyBytes_FromStringAndSize(self->ob_sval, Py_SIZE(self));
1696 : : }
1697 : : }
1698 : :
1699 : :
1700 : : #define LEFTSTRIP 0
1701 : : #define RIGHTSTRIP 1
1702 : : #define BOTHSTRIP 2
1703 : :
1704 : : /*[clinic input]
1705 : : bytes.split
1706 : :
1707 : : sep: object = None
1708 : : The delimiter according which to split the bytes.
1709 : : None (the default value) means split on ASCII whitespace characters
1710 : : (space, tab, return, newline, formfeed, vertical tab).
1711 : : maxsplit: Py_ssize_t = -1
1712 : : Maximum number of splits to do.
1713 : : -1 (the default value) means no limit.
1714 : :
1715 : : Return a list of the sections in the bytes, using sep as the delimiter.
1716 : : [clinic start generated code]*/
1717 : :
1718 : : static PyObject *
1719 : 0 : bytes_split_impl(PyBytesObject *self, PyObject *sep, Py_ssize_t maxsplit)
1720 : : /*[clinic end generated code: output=52126b5844c1d8ef input=8b809b39074abbfa]*/
1721 : : {
1722 : 0 : Py_ssize_t len = PyBytes_GET_SIZE(self), n;
1723 : 0 : const char *s = PyBytes_AS_STRING(self), *sub;
1724 : : Py_buffer vsub;
1725 : : PyObject *list;
1726 : :
1727 [ # # ]: 0 : if (maxsplit < 0)
1728 : 0 : maxsplit = PY_SSIZE_T_MAX;
1729 [ # # ]: 0 : if (sep == Py_None)
1730 : 0 : return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
1731 [ # # ]: 0 : if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
1732 : 0 : return NULL;
1733 : 0 : sub = vsub.buf;
1734 : 0 : n = vsub.len;
1735 : :
1736 : 0 : list = stringlib_split((PyObject*) self, s, len, sub, n, maxsplit);
1737 : 0 : PyBuffer_Release(&vsub);
1738 : 0 : return list;
1739 : : }
1740 : :
1741 : : /*[clinic input]
1742 : : bytes.partition
1743 : :
1744 : : sep: Py_buffer
1745 : : /
1746 : :
1747 : : Partition the bytes into three parts using the given separator.
1748 : :
1749 : : This will search for the separator sep in the bytes. If the separator is found,
1750 : : returns a 3-tuple containing the part before the separator, the separator
1751 : : itself, and the part after it.
1752 : :
1753 : : If the separator is not found, returns a 3-tuple containing the original bytes
1754 : : object and two empty bytes objects.
1755 : : [clinic start generated code]*/
1756 : :
1757 : : static PyObject *
1758 : 0 : bytes_partition_impl(PyBytesObject *self, Py_buffer *sep)
1759 : : /*[clinic end generated code: output=f532b392a17ff695 input=61cca95519406099]*/
1760 : : {
1761 : 0 : return stringlib_partition(
1762 : : (PyObject*) self,
1763 : 0 : PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
1764 : 0 : sep->obj, (const char *)sep->buf, sep->len
1765 : : );
1766 : : }
1767 : :
1768 : : /*[clinic input]
1769 : : bytes.rpartition
1770 : :
1771 : : sep: Py_buffer
1772 : : /
1773 : :
1774 : : Partition the bytes into three parts using the given separator.
1775 : :
1776 : : This will search for the separator sep in the bytes, starting at the end. If
1777 : : the separator is found, returns a 3-tuple containing the part before the
1778 : : separator, the separator itself, and the part after it.
1779 : :
1780 : : If the separator is not found, returns a 3-tuple containing two empty bytes
1781 : : objects and the original bytes object.
1782 : : [clinic start generated code]*/
1783 : :
1784 : : static PyObject *
1785 : 0 : bytes_rpartition_impl(PyBytesObject *self, Py_buffer *sep)
1786 : : /*[clinic end generated code: output=191b114cbb028e50 input=d78db010c8cfdbe1]*/
1787 : : {
1788 : 0 : return stringlib_rpartition(
1789 : : (PyObject*) self,
1790 : 0 : PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
1791 : 0 : sep->obj, (const char *)sep->buf, sep->len
1792 : : );
1793 : : }
1794 : :
1795 : : /*[clinic input]
1796 : : bytes.rsplit = bytes.split
1797 : :
1798 : : Return a list of the sections in the bytes, using sep as the delimiter.
1799 : :
1800 : : Splitting is done starting at the end of the bytes and working to the front.
1801 : : [clinic start generated code]*/
1802 : :
1803 : : static PyObject *
1804 : 0 : bytes_rsplit_impl(PyBytesObject *self, PyObject *sep, Py_ssize_t maxsplit)
1805 : : /*[clinic end generated code: output=ba698d9ea01e1c8f input=0f86c9f28f7d7b7b]*/
1806 : : {
1807 : 0 : Py_ssize_t len = PyBytes_GET_SIZE(self), n;
1808 : 0 : const char *s = PyBytes_AS_STRING(self), *sub;
1809 : : Py_buffer vsub;
1810 : : PyObject *list;
1811 : :
1812 [ # # ]: 0 : if (maxsplit < 0)
1813 : 0 : maxsplit = PY_SSIZE_T_MAX;
1814 [ # # ]: 0 : if (sep == Py_None)
1815 : 0 : return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
1816 [ # # ]: 0 : if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0)
1817 : 0 : return NULL;
1818 : 0 : sub = vsub.buf;
1819 : 0 : n = vsub.len;
1820 : :
1821 : 0 : list = stringlib_rsplit((PyObject*) self, s, len, sub, n, maxsplit);
1822 : 0 : PyBuffer_Release(&vsub);
1823 : 0 : return list;
1824 : : }
1825 : :
1826 : :
1827 : : /*[clinic input]
1828 : : bytes.join
1829 : :
1830 : : iterable_of_bytes: object
1831 : : /
1832 : :
1833 : : Concatenate any number of bytes objects.
1834 : :
1835 : : The bytes whose method is called is inserted in between each pair.
1836 : :
1837 : : The result is returned as a new bytes object.
1838 : :
1839 : : Example: b'.'.join([b'ab', b'pq', b'rs']) -> b'ab.pq.rs'.
1840 : : [clinic start generated code]*/
1841 : :
1842 : : static PyObject *
1843 : 1 : bytes_join(PyBytesObject *self, PyObject *iterable_of_bytes)
1844 : : /*[clinic end generated code: output=a046f379f626f6f8 input=7fe377b95bd549d2]*/
1845 : : {
1846 : 1 : return stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
1847 : : }
1848 : :
1849 : : PyObject *
1850 : 1 : _PyBytes_Join(PyObject *sep, PyObject *x)
1851 : : {
1852 : : assert(sep != NULL && PyBytes_Check(sep));
1853 : : assert(x != NULL);
1854 : 1 : return bytes_join((PyBytesObject*)sep, x);
1855 : : }
1856 : :
1857 : : static PyObject *
1858 : 0 : bytes_find(PyBytesObject *self, PyObject *args)
1859 : : {
1860 : 0 : return _Py_bytes_find(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args);
1861 : : }
1862 : :
1863 : : static PyObject *
1864 : 0 : bytes_index(PyBytesObject *self, PyObject *args)
1865 : : {
1866 : 0 : return _Py_bytes_index(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args);
1867 : : }
1868 : :
1869 : :
1870 : : static PyObject *
1871 : 22 : bytes_rfind(PyBytesObject *self, PyObject *args)
1872 : : {
1873 : 22 : return _Py_bytes_rfind(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args);
1874 : : }
1875 : :
1876 : :
1877 : : static PyObject *
1878 : 0 : bytes_rindex(PyBytesObject *self, PyObject *args)
1879 : : {
1880 : 0 : return _Py_bytes_rindex(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args);
1881 : : }
1882 : :
1883 : :
1884 : : Py_LOCAL_INLINE(PyObject *)
1885 : 0 : do_xstrip(PyBytesObject *self, int striptype, PyObject *sepobj)
1886 : : {
1887 : : Py_buffer vsep;
1888 : 0 : const char *s = PyBytes_AS_STRING(self);
1889 : 0 : Py_ssize_t len = PyBytes_GET_SIZE(self);
1890 : : char *sep;
1891 : : Py_ssize_t seplen;
1892 : : Py_ssize_t i, j;
1893 : :
1894 [ # # ]: 0 : if (PyObject_GetBuffer(sepobj, &vsep, PyBUF_SIMPLE) != 0)
1895 : 0 : return NULL;
1896 : 0 : sep = vsep.buf;
1897 : 0 : seplen = vsep.len;
1898 : :
1899 : 0 : i = 0;
1900 [ # # ]: 0 : if (striptype != RIGHTSTRIP) {
1901 [ # # # # ]: 0 : while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) {
1902 : 0 : i++;
1903 : : }
1904 : : }
1905 : :
1906 : 0 : j = len;
1907 [ # # ]: 0 : if (striptype != LEFTSTRIP) {
1908 : : do {
1909 : 0 : j--;
1910 [ # # # # ]: 0 : } while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen));
1911 : 0 : j++;
1912 : : }
1913 : :
1914 : 0 : PyBuffer_Release(&vsep);
1915 : :
1916 [ # # # # : 0 : if (i == 0 && j == len && PyBytes_CheckExact(self)) {
# # ]
1917 : 0 : return Py_NewRef(self);
1918 : : }
1919 : : else
1920 : 0 : return PyBytes_FromStringAndSize(s+i, j-i);
1921 : : }
1922 : :
1923 : :
1924 : : Py_LOCAL_INLINE(PyObject *)
1925 : 0 : do_strip(PyBytesObject *self, int striptype)
1926 : : {
1927 : 0 : const char *s = PyBytes_AS_STRING(self);
1928 : 0 : Py_ssize_t len = PyBytes_GET_SIZE(self), i, j;
1929 : :
1930 : 0 : i = 0;
1931 [ # # ]: 0 : if (striptype != RIGHTSTRIP) {
1932 [ # # # # ]: 0 : while (i < len && Py_ISSPACE(s[i])) {
1933 : 0 : i++;
1934 : : }
1935 : : }
1936 : :
1937 : 0 : j = len;
1938 [ # # ]: 0 : if (striptype != LEFTSTRIP) {
1939 : : do {
1940 : 0 : j--;
1941 [ # # # # ]: 0 : } while (j >= i && Py_ISSPACE(s[j]));
1942 : 0 : j++;
1943 : : }
1944 : :
1945 [ # # # # : 0 : if (i == 0 && j == len && PyBytes_CheckExact(self)) {
# # ]
1946 : 0 : return Py_NewRef(self);
1947 : : }
1948 : : else
1949 : 0 : return PyBytes_FromStringAndSize(s+i, j-i);
1950 : : }
1951 : :
1952 : :
1953 : : Py_LOCAL_INLINE(PyObject *)
1954 : 0 : do_argstrip(PyBytesObject *self, int striptype, PyObject *bytes)
1955 : : {
1956 [ # # ]: 0 : if (bytes != Py_None) {
1957 : 0 : return do_xstrip(self, striptype, bytes);
1958 : : }
1959 : 0 : return do_strip(self, striptype);
1960 : : }
1961 : :
1962 : : /*[clinic input]
1963 : : bytes.strip
1964 : :
1965 : : bytes: object = None
1966 : : /
1967 : :
1968 : : Strip leading and trailing bytes contained in the argument.
1969 : :
1970 : : If the argument is omitted or None, strip leading and trailing ASCII whitespace.
1971 : : [clinic start generated code]*/
1972 : :
1973 : : static PyObject *
1974 : 0 : bytes_strip_impl(PyBytesObject *self, PyObject *bytes)
1975 : : /*[clinic end generated code: output=c7c228d3bd104a1b input=8a354640e4e0b3ef]*/
1976 : : {
1977 : 0 : return do_argstrip(self, BOTHSTRIP, bytes);
1978 : : }
1979 : :
1980 : : /*[clinic input]
1981 : : bytes.lstrip
1982 : :
1983 : : bytes: object = None
1984 : : /
1985 : :
1986 : : Strip leading bytes contained in the argument.
1987 : :
1988 : : If the argument is omitted or None, strip leading ASCII whitespace.
1989 : : [clinic start generated code]*/
1990 : :
1991 : : static PyObject *
1992 : 0 : bytes_lstrip_impl(PyBytesObject *self, PyObject *bytes)
1993 : : /*[clinic end generated code: output=28602e586f524e82 input=9baff4398c3f6857]*/
1994 : : {
1995 : 0 : return do_argstrip(self, LEFTSTRIP, bytes);
1996 : : }
1997 : :
1998 : : /*[clinic input]
1999 : : bytes.rstrip
2000 : :
2001 : : bytes: object = None
2002 : : /
2003 : :
2004 : : Strip trailing bytes contained in the argument.
2005 : :
2006 : : If the argument is omitted or None, strip trailing ASCII whitespace.
2007 : : [clinic start generated code]*/
2008 : :
2009 : : static PyObject *
2010 : 0 : bytes_rstrip_impl(PyBytesObject *self, PyObject *bytes)
2011 : : /*[clinic end generated code: output=547e3815c95447da input=b78af445c727e32b]*/
2012 : : {
2013 : 0 : return do_argstrip(self, RIGHTSTRIP, bytes);
2014 : : }
2015 : :
2016 : :
2017 : : static PyObject *
2018 : 0 : bytes_count(PyBytesObject *self, PyObject *args)
2019 : : {
2020 : 0 : return _Py_bytes_count(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args);
2021 : : }
2022 : :
2023 : :
2024 : : /*[clinic input]
2025 : : bytes.translate
2026 : :
2027 : : table: object
2028 : : Translation table, which must be a bytes object of length 256.
2029 : : /
2030 : : delete as deletechars: object(c_default="NULL") = b''
2031 : :
2032 : : Return a copy with each character mapped by the given translation table.
2033 : :
2034 : : All characters occurring in the optional argument delete are removed.
2035 : : The remaining characters are mapped through the given translation table.
2036 : : [clinic start generated code]*/
2037 : :
2038 : : static PyObject *
2039 : 0 : bytes_translate_impl(PyBytesObject *self, PyObject *table,
2040 : : PyObject *deletechars)
2041 : : /*[clinic end generated code: output=43be3437f1956211 input=0ecdf159f654233c]*/
2042 : : {
2043 : : const char *input;
2044 : : char *output;
2045 : 0 : Py_buffer table_view = {NULL, NULL};
2046 : 0 : Py_buffer del_table_view = {NULL, NULL};
2047 : : const char *table_chars;
2048 : 0 : Py_ssize_t i, c, changed = 0;
2049 : 0 : PyObject *input_obj = (PyObject*)self;
2050 : 0 : const char *output_start, *del_table_chars=NULL;
2051 : 0 : Py_ssize_t inlen, tablen, dellen = 0;
2052 : : PyObject *result;
2053 : : int trans_table[256];
2054 : :
2055 [ # # ]: 0 : if (PyBytes_Check(table)) {
2056 : 0 : table_chars = PyBytes_AS_STRING(table);
2057 : 0 : tablen = PyBytes_GET_SIZE(table);
2058 : : }
2059 [ # # ]: 0 : else if (table == Py_None) {
2060 : 0 : table_chars = NULL;
2061 : 0 : tablen = 256;
2062 : : }
2063 : : else {
2064 [ # # ]: 0 : if (PyObject_GetBuffer(table, &table_view, PyBUF_SIMPLE) != 0)
2065 : 0 : return NULL;
2066 : 0 : table_chars = table_view.buf;
2067 : 0 : tablen = table_view.len;
2068 : : }
2069 : :
2070 [ # # ]: 0 : if (tablen != 256) {
2071 : 0 : PyErr_SetString(PyExc_ValueError,
2072 : : "translation table must be 256 characters long");
2073 : 0 : PyBuffer_Release(&table_view);
2074 : 0 : return NULL;
2075 : : }
2076 : :
2077 [ # # ]: 0 : if (deletechars != NULL) {
2078 [ # # ]: 0 : if (PyBytes_Check(deletechars)) {
2079 : 0 : del_table_chars = PyBytes_AS_STRING(deletechars);
2080 : 0 : dellen = PyBytes_GET_SIZE(deletechars);
2081 : : }
2082 : : else {
2083 [ # # ]: 0 : if (PyObject_GetBuffer(deletechars, &del_table_view, PyBUF_SIMPLE) != 0) {
2084 : 0 : PyBuffer_Release(&table_view);
2085 : 0 : return NULL;
2086 : : }
2087 : 0 : del_table_chars = del_table_view.buf;
2088 : 0 : dellen = del_table_view.len;
2089 : : }
2090 : : }
2091 : : else {
2092 : 0 : del_table_chars = NULL;
2093 : 0 : dellen = 0;
2094 : : }
2095 : :
2096 : 0 : inlen = PyBytes_GET_SIZE(input_obj);
2097 : 0 : result = PyBytes_FromStringAndSize((char *)NULL, inlen);
2098 [ # # ]: 0 : if (result == NULL) {
2099 : 0 : PyBuffer_Release(&del_table_view);
2100 : 0 : PyBuffer_Release(&table_view);
2101 : 0 : return NULL;
2102 : : }
2103 : 0 : output_start = output = PyBytes_AS_STRING(result);
2104 : 0 : input = PyBytes_AS_STRING(input_obj);
2105 : :
2106 [ # # # # ]: 0 : if (dellen == 0 && table_chars != NULL) {
2107 : : /* If no deletions are required, use faster code */
2108 [ # # ]: 0 : for (i = inlen; --i >= 0; ) {
2109 : 0 : c = Py_CHARMASK(*input++);
2110 [ # # ]: 0 : if (Py_CHARMASK((*output++ = table_chars[c])) != c)
2111 : 0 : changed = 1;
2112 : : }
2113 [ # # # # ]: 0 : if (!changed && PyBytes_CheckExact(input_obj)) {
2114 : 0 : Py_SETREF(result, Py_NewRef(input_obj));
2115 : : }
2116 : 0 : PyBuffer_Release(&del_table_view);
2117 : 0 : PyBuffer_Release(&table_view);
2118 : 0 : return result;
2119 : : }
2120 : :
2121 [ # # ]: 0 : if (table_chars == NULL) {
2122 [ # # ]: 0 : for (i = 0; i < 256; i++)
2123 : 0 : trans_table[i] = Py_CHARMASK(i);
2124 : : } else {
2125 [ # # ]: 0 : for (i = 0; i < 256; i++)
2126 : 0 : trans_table[i] = Py_CHARMASK(table_chars[i]);
2127 : : }
2128 : 0 : PyBuffer_Release(&table_view);
2129 : :
2130 [ # # ]: 0 : for (i = 0; i < dellen; i++)
2131 : 0 : trans_table[(int) Py_CHARMASK(del_table_chars[i])] = -1;
2132 : 0 : PyBuffer_Release(&del_table_view);
2133 : :
2134 [ # # ]: 0 : for (i = inlen; --i >= 0; ) {
2135 : 0 : c = Py_CHARMASK(*input++);
2136 [ # # ]: 0 : if (trans_table[c] != -1)
2137 [ # # ]: 0 : if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
2138 : 0 : continue;
2139 : 0 : changed = 1;
2140 : : }
2141 [ # # # # ]: 0 : if (!changed && PyBytes_CheckExact(input_obj)) {
2142 : 0 : Py_DECREF(result);
2143 : 0 : return Py_NewRef(input_obj);
2144 : : }
2145 : : /* Fix the size of the resulting byte string */
2146 [ # # ]: 0 : if (inlen > 0)
2147 : 0 : _PyBytes_Resize(&result, output - output_start);
2148 : 0 : return result;
2149 : : }
2150 : :
2151 : :
2152 : : /*[clinic input]
2153 : :
2154 : : @staticmethod
2155 : : bytes.maketrans
2156 : :
2157 : : frm: Py_buffer
2158 : : to: Py_buffer
2159 : : /
2160 : :
2161 : : Return a translation table useable for the bytes or bytearray translate method.
2162 : :
2163 : : The returned table will be one where each byte in frm is mapped to the byte at
2164 : : the same position in to.
2165 : :
2166 : : The bytes objects frm and to must be of the same length.
2167 : : [clinic start generated code]*/
2168 : :
2169 : : static PyObject *
2170 : 2 : bytes_maketrans_impl(Py_buffer *frm, Py_buffer *to)
2171 : : /*[clinic end generated code: output=a36f6399d4b77f6f input=de7a8fc5632bb8f1]*/
2172 : : {
2173 : 2 : return _Py_bytes_maketrans(frm, to);
2174 : : }
2175 : :
2176 : :
2177 : : /*[clinic input]
2178 : : bytes.replace
2179 : :
2180 : : old: Py_buffer
2181 : : new: Py_buffer
2182 : : count: Py_ssize_t = -1
2183 : : Maximum number of occurrences to replace.
2184 : : -1 (the default value) means replace all occurrences.
2185 : : /
2186 : :
2187 : : Return a copy with all occurrences of substring old replaced by new.
2188 : :
2189 : : If the optional argument count is given, only the first count occurrences are
2190 : : replaced.
2191 : : [clinic start generated code]*/
2192 : :
2193 : : static PyObject *
2194 : 114 : bytes_replace_impl(PyBytesObject *self, Py_buffer *old, Py_buffer *new,
2195 : : Py_ssize_t count)
2196 : : /*[clinic end generated code: output=994fa588b6b9c104 input=b2fbbf0bf04de8e5]*/
2197 : : {
2198 : 228 : return stringlib_replace((PyObject *)self,
2199 : 114 : (const char *)old->buf, old->len,
2200 : 114 : (const char *)new->buf, new->len, count);
2201 : : }
2202 : :
2203 : : /** End DALKE **/
2204 : :
2205 : : /*[clinic input]
2206 : : bytes.removeprefix as bytes_removeprefix
2207 : :
2208 : : prefix: Py_buffer
2209 : : /
2210 : :
2211 : : Return a bytes object with the given prefix string removed if present.
2212 : :
2213 : : If the bytes starts with the prefix string, return bytes[len(prefix):].
2214 : : Otherwise, return a copy of the original bytes.
2215 : : [clinic start generated code]*/
2216 : :
2217 : : static PyObject *
2218 : 0 : bytes_removeprefix_impl(PyBytesObject *self, Py_buffer *prefix)
2219 : : /*[clinic end generated code: output=f006865331a06ab6 input=0c93bac817a8502c]*/
2220 : : {
2221 : 0 : const char *self_start = PyBytes_AS_STRING(self);
2222 : 0 : Py_ssize_t self_len = PyBytes_GET_SIZE(self);
2223 : 0 : const char *prefix_start = prefix->buf;
2224 : 0 : Py_ssize_t prefix_len = prefix->len;
2225 : :
2226 [ # # ]: 0 : if (self_len >= prefix_len
2227 [ # # ]: 0 : && prefix_len > 0
2228 [ # # ]: 0 : && memcmp(self_start, prefix_start, prefix_len) == 0)
2229 : : {
2230 : 0 : return PyBytes_FromStringAndSize(self_start + prefix_len,
2231 : : self_len - prefix_len);
2232 : : }
2233 : :
2234 [ # # ]: 0 : if (PyBytes_CheckExact(self)) {
2235 : 0 : return Py_NewRef(self);
2236 : : }
2237 : :
2238 : 0 : return PyBytes_FromStringAndSize(self_start, self_len);
2239 : : }
2240 : :
2241 : : /*[clinic input]
2242 : : bytes.removesuffix as bytes_removesuffix
2243 : :
2244 : : suffix: Py_buffer
2245 : : /
2246 : :
2247 : : Return a bytes object with the given suffix string removed if present.
2248 : :
2249 : : If the bytes ends with the suffix string and that suffix is not empty,
2250 : : return bytes[:-len(prefix)]. Otherwise, return a copy of the original
2251 : : bytes.
2252 : : [clinic start generated code]*/
2253 : :
2254 : : static PyObject *
2255 : 0 : bytes_removesuffix_impl(PyBytesObject *self, Py_buffer *suffix)
2256 : : /*[clinic end generated code: output=d887d308e3242eeb input=9f4e1da8c637bbf1]*/
2257 : : {
2258 : 0 : const char *self_start = PyBytes_AS_STRING(self);
2259 : 0 : Py_ssize_t self_len = PyBytes_GET_SIZE(self);
2260 : 0 : const char *suffix_start = suffix->buf;
2261 : 0 : Py_ssize_t suffix_len = suffix->len;
2262 : :
2263 [ # # ]: 0 : if (self_len >= suffix_len
2264 [ # # ]: 0 : && suffix_len > 0
2265 [ # # ]: 0 : && memcmp(self_start + self_len - suffix_len,
2266 : : suffix_start, suffix_len) == 0)
2267 : : {
2268 : 0 : return PyBytes_FromStringAndSize(self_start,
2269 : : self_len - suffix_len);
2270 : : }
2271 : :
2272 [ # # ]: 0 : if (PyBytes_CheckExact(self)) {
2273 : 0 : return Py_NewRef(self);
2274 : : }
2275 : :
2276 : 0 : return PyBytes_FromStringAndSize(self_start, self_len);
2277 : : }
2278 : :
2279 : : static PyObject *
2280 : 1 : bytes_startswith(PyBytesObject *self, PyObject *args)
2281 : : {
2282 : 1 : return _Py_bytes_startswith(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args);
2283 : : }
2284 : :
2285 : : static PyObject *
2286 : 0 : bytes_endswith(PyBytesObject *self, PyObject *args)
2287 : : {
2288 : 0 : return _Py_bytes_endswith(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args);
2289 : : }
2290 : :
2291 : :
2292 : : /*[clinic input]
2293 : : bytes.decode
2294 : :
2295 : : encoding: str(c_default="NULL") = 'utf-8'
2296 : : The encoding with which to decode the bytes.
2297 : : errors: str(c_default="NULL") = 'strict'
2298 : : The error handling scheme to use for the handling of decoding errors.
2299 : : The default is 'strict' meaning that decoding errors raise a
2300 : : UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
2301 : : as well as any other name registered with codecs.register_error that
2302 : : can handle UnicodeDecodeErrors.
2303 : :
2304 : : Decode the bytes using the codec registered for encoding.
2305 : : [clinic start generated code]*/
2306 : :
2307 : : static PyObject *
2308 : 7065 : bytes_decode_impl(PyBytesObject *self, const char *encoding,
2309 : : const char *errors)
2310 : : /*[clinic end generated code: output=5649a53dde27b314 input=958174769d2a40ca]*/
2311 : : {
2312 : 7065 : return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
2313 : : }
2314 : :
2315 : :
2316 : : /*[clinic input]
2317 : : bytes.splitlines
2318 : :
2319 : : keepends: bool = False
2320 : :
2321 : : Return a list of the lines in the bytes, breaking at line boundaries.
2322 : :
2323 : : Line breaks are not included in the resulting list unless keepends is given and
2324 : : true.
2325 : : [clinic start generated code]*/
2326 : :
2327 : : static PyObject *
2328 : 0 : bytes_splitlines_impl(PyBytesObject *self, int keepends)
2329 : : /*[clinic end generated code: output=3484149a5d880ffb input=5d7b898af2fe55c0]*/
2330 : : {
2331 : 0 : return stringlib_splitlines(
2332 : 0 : (PyObject*) self, PyBytes_AS_STRING(self),
2333 : : PyBytes_GET_SIZE(self), keepends
2334 : : );
2335 : : }
2336 : :
2337 : : /*[clinic input]
2338 : : @classmethod
2339 : : bytes.fromhex
2340 : :
2341 : : string: unicode
2342 : : /
2343 : :
2344 : : Create a bytes object from a string of hexadecimal numbers.
2345 : :
2346 : : Spaces between two numbers are accepted.
2347 : : Example: bytes.fromhex('B9 01EF') -> b'\\xb9\\x01\\xef'.
2348 : : [clinic start generated code]*/
2349 : :
2350 : : static PyObject *
2351 : 0 : bytes_fromhex_impl(PyTypeObject *type, PyObject *string)
2352 : : /*[clinic end generated code: output=0973acc63661bb2e input=bf4d1c361670acd3]*/
2353 : : {
2354 : 0 : PyObject *result = _PyBytes_FromHex(string, 0);
2355 [ # # # # ]: 0 : if (type != &PyBytes_Type && result != NULL) {
2356 : 0 : Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
2357 : : }
2358 : 0 : return result;
2359 : : }
2360 : :
2361 : : PyObject*
2362 : 0 : _PyBytes_FromHex(PyObject *string, int use_bytearray)
2363 : : {
2364 : : char *buf;
2365 : : Py_ssize_t hexlen, invalid_char;
2366 : : unsigned int top, bot;
2367 : : const Py_UCS1 *str, *end;
2368 : : _PyBytesWriter writer;
2369 : :
2370 : 0 : _PyBytesWriter_Init(&writer);
2371 : 0 : writer.use_bytearray = use_bytearray;
2372 : :
2373 : : assert(PyUnicode_Check(string));
2374 [ # # ]: 0 : if (PyUnicode_READY(string))
2375 : 0 : return NULL;
2376 : 0 : hexlen = PyUnicode_GET_LENGTH(string);
2377 : :
2378 [ # # ]: 0 : if (!PyUnicode_IS_ASCII(string)) {
2379 : 0 : const void *data = PyUnicode_DATA(string);
2380 : 0 : int kind = PyUnicode_KIND(string);
2381 : : Py_ssize_t i;
2382 : :
2383 : : /* search for the first non-ASCII character */
2384 [ # # ]: 0 : for (i = 0; i < hexlen; i++) {
2385 [ # # ]: 0 : if (PyUnicode_READ(kind, data, i) >= 128)
2386 : 0 : break;
2387 : : }
2388 : 0 : invalid_char = i;
2389 : 0 : goto error;
2390 : : }
2391 : :
2392 : : assert(PyUnicode_KIND(string) == PyUnicode_1BYTE_KIND);
2393 : 0 : str = PyUnicode_1BYTE_DATA(string);
2394 : :
2395 : : /* This overestimates if there are spaces */
2396 : 0 : buf = _PyBytesWriter_Alloc(&writer, hexlen / 2);
2397 [ # # ]: 0 : if (buf == NULL)
2398 : 0 : return NULL;
2399 : :
2400 : 0 : end = str + hexlen;
2401 [ # # ]: 0 : while (str < end) {
2402 : : /* skip over spaces in the input */
2403 [ # # ]: 0 : if (Py_ISSPACE(*str)) {
2404 : : do {
2405 : 0 : str++;
2406 [ # # ]: 0 : } while (Py_ISSPACE(*str));
2407 [ # # ]: 0 : if (str >= end)
2408 : 0 : break;
2409 : : }
2410 : :
2411 : 0 : top = _PyLong_DigitValue[*str];
2412 [ # # ]: 0 : if (top >= 16) {
2413 : 0 : invalid_char = str - PyUnicode_1BYTE_DATA(string);
2414 : 0 : goto error;
2415 : : }
2416 : 0 : str++;
2417 : :
2418 : 0 : bot = _PyLong_DigitValue[*str];
2419 [ # # ]: 0 : if (bot >= 16) {
2420 : 0 : invalid_char = str - PyUnicode_1BYTE_DATA(string);
2421 : 0 : goto error;
2422 : : }
2423 : 0 : str++;
2424 : :
2425 : 0 : *buf++ = (unsigned char)((top << 4) + bot);
2426 : : }
2427 : :
2428 : 0 : return _PyBytesWriter_Finish(&writer, buf);
2429 : :
2430 : 0 : error:
2431 : 0 : PyErr_Format(PyExc_ValueError,
2432 : : "non-hexadecimal number found in "
2433 : : "fromhex() arg at position %zd", invalid_char);
2434 : 0 : _PyBytesWriter_Dealloc(&writer);
2435 : 0 : return NULL;
2436 : : }
2437 : :
2438 : : /*[clinic input]
2439 : : bytes.hex
2440 : :
2441 : : sep: object = NULL
2442 : : An optional single character or byte to separate hex bytes.
2443 : : bytes_per_sep: int = 1
2444 : : How many bytes between separators. Positive values count from the
2445 : : right, negative values count from the left.
2446 : :
2447 : : Create a string of hexadecimal numbers from a bytes object.
2448 : :
2449 : : Example:
2450 : : >>> value = b'\xb9\x01\xef'
2451 : : >>> value.hex()
2452 : : 'b901ef'
2453 : : >>> value.hex(':')
2454 : : 'b9:01:ef'
2455 : : >>> value.hex(':', 2)
2456 : : 'b9:01ef'
2457 : : >>> value.hex(':', -2)
2458 : : 'b901:ef'
2459 : : [clinic start generated code]*/
2460 : :
2461 : : static PyObject *
2462 : 0 : bytes_hex_impl(PyBytesObject *self, PyObject *sep, int bytes_per_sep)
2463 : : /*[clinic end generated code: output=1f134da504064139 input=1a21282b1f1ae595]*/
2464 : : {
2465 : 0 : const char *argbuf = PyBytes_AS_STRING(self);
2466 : 0 : Py_ssize_t arglen = PyBytes_GET_SIZE(self);
2467 : 0 : return _Py_strhex_with_sep(argbuf, arglen, sep, bytes_per_sep);
2468 : : }
2469 : :
2470 : : static PyObject *
2471 : 0 : bytes_getnewargs(PyBytesObject *v, PyObject *Py_UNUSED(ignored))
2472 : : {
2473 : 0 : return Py_BuildValue("(y#)", v->ob_sval, Py_SIZE(v));
2474 : : }
2475 : :
2476 : :
2477 : : static PyMethodDef
2478 : : bytes_methods[] = {
2479 : : {"__getnewargs__", (PyCFunction)bytes_getnewargs, METH_NOARGS},
2480 : : BYTES___BYTES___METHODDEF
2481 : : {"capitalize", stringlib_capitalize, METH_NOARGS,
2482 : : _Py_capitalize__doc__},
2483 : : STRINGLIB_CENTER_METHODDEF
2484 : : {"count", (PyCFunction)bytes_count, METH_VARARGS,
2485 : : _Py_count__doc__},
2486 : : BYTES_DECODE_METHODDEF
2487 : : {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS,
2488 : : _Py_endswith__doc__},
2489 : : STRINGLIB_EXPANDTABS_METHODDEF
2490 : : {"find", (PyCFunction)bytes_find, METH_VARARGS,
2491 : : _Py_find__doc__},
2492 : : BYTES_FROMHEX_METHODDEF
2493 : : BYTES_HEX_METHODDEF
2494 : : {"index", (PyCFunction)bytes_index, METH_VARARGS, _Py_index__doc__},
2495 : : {"isalnum", stringlib_isalnum, METH_NOARGS,
2496 : : _Py_isalnum__doc__},
2497 : : {"isalpha", stringlib_isalpha, METH_NOARGS,
2498 : : _Py_isalpha__doc__},
2499 : : {"isascii", stringlib_isascii, METH_NOARGS,
2500 : : _Py_isascii__doc__},
2501 : : {"isdigit", stringlib_isdigit, METH_NOARGS,
2502 : : _Py_isdigit__doc__},
2503 : : {"islower", stringlib_islower, METH_NOARGS,
2504 : : _Py_islower__doc__},
2505 : : {"isspace", stringlib_isspace, METH_NOARGS,
2506 : : _Py_isspace__doc__},
2507 : : {"istitle", stringlib_istitle, METH_NOARGS,
2508 : : _Py_istitle__doc__},
2509 : : {"isupper", stringlib_isupper, METH_NOARGS,
2510 : : _Py_isupper__doc__},
2511 : : BYTES_JOIN_METHODDEF
2512 : : STRINGLIB_LJUST_METHODDEF
2513 : : {"lower", stringlib_lower, METH_NOARGS, _Py_lower__doc__},
2514 : : BYTES_LSTRIP_METHODDEF
2515 : : BYTES_MAKETRANS_METHODDEF
2516 : : BYTES_PARTITION_METHODDEF
2517 : : BYTES_REPLACE_METHODDEF
2518 : : BYTES_REMOVEPREFIX_METHODDEF
2519 : : BYTES_REMOVESUFFIX_METHODDEF
2520 : : {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, _Py_rfind__doc__},
2521 : : {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, _Py_rindex__doc__},
2522 : : STRINGLIB_RJUST_METHODDEF
2523 : : BYTES_RPARTITION_METHODDEF
2524 : : BYTES_RSPLIT_METHODDEF
2525 : : BYTES_RSTRIP_METHODDEF
2526 : : BYTES_SPLIT_METHODDEF
2527 : : BYTES_SPLITLINES_METHODDEF
2528 : : {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS,
2529 : : _Py_startswith__doc__},
2530 : : BYTES_STRIP_METHODDEF
2531 : : {"swapcase", stringlib_swapcase, METH_NOARGS,
2532 : : _Py_swapcase__doc__},
2533 : : {"title", stringlib_title, METH_NOARGS, _Py_title__doc__},
2534 : : BYTES_TRANSLATE_METHODDEF
2535 : : {"upper", stringlib_upper, METH_NOARGS, _Py_upper__doc__},
2536 : : STRINGLIB_ZFILL_METHODDEF
2537 : : {NULL, NULL} /* sentinel */
2538 : : };
2539 : :
2540 : : static PyObject *
2541 : 0 : bytes_mod(PyObject *self, PyObject *arg)
2542 : : {
2543 [ # # ]: 0 : if (!PyBytes_Check(self)) {
2544 : 0 : Py_RETURN_NOTIMPLEMENTED;
2545 : : }
2546 : 0 : return _PyBytes_FormatEx(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
2547 : : arg, 0);
2548 : : }
2549 : :
2550 : : static PyNumberMethods bytes_as_number = {
2551 : : 0, /*nb_add*/
2552 : : 0, /*nb_subtract*/
2553 : : 0, /*nb_multiply*/
2554 : : bytes_mod, /*nb_remainder*/
2555 : : };
2556 : :
2557 : : static PyObject *
2558 : : bytes_subtype_new(PyTypeObject *, PyObject *);
2559 : :
2560 : : /*[clinic input]
2561 : : @classmethod
2562 : : bytes.__new__ as bytes_new
2563 : :
2564 : : source as x: object = NULL
2565 : : encoding: str = NULL
2566 : : errors: str = NULL
2567 : :
2568 : : [clinic start generated code]*/
2569 : :
2570 : : static PyObject *
2571 : 800 : bytes_new_impl(PyTypeObject *type, PyObject *x, const char *encoding,
2572 : : const char *errors)
2573 : : /*[clinic end generated code: output=1e0c471be311a425 input=f0a966d19b7262b4]*/
2574 : : {
2575 : : PyObject *bytes;
2576 : : PyObject *func;
2577 : : Py_ssize_t size;
2578 : :
2579 [ - + ]: 800 : if (x == NULL) {
2580 [ # # # # ]: 0 : if (encoding != NULL || errors != NULL) {
2581 [ # # ]: 0 : PyErr_SetString(PyExc_TypeError,
2582 : : encoding != NULL ?
2583 : : "encoding without a string argument" :
2584 : : "errors without a string argument");
2585 : 0 : return NULL;
2586 : : }
2587 : 0 : bytes = PyBytes_FromStringAndSize(NULL, 0);
2588 : : }
2589 [ - + ]: 800 : else if (encoding != NULL) {
2590 : : /* Encode via the codec registry */
2591 [ # # ]: 0 : if (!PyUnicode_Check(x)) {
2592 : 0 : PyErr_SetString(PyExc_TypeError,
2593 : : "encoding without a string argument");
2594 : 0 : return NULL;
2595 : : }
2596 : 0 : bytes = PyUnicode_AsEncodedString(x, encoding, errors);
2597 : : }
2598 [ - + ]: 800 : else if (errors != NULL) {
2599 [ # # ]: 0 : PyErr_SetString(PyExc_TypeError,
2600 : 0 : PyUnicode_Check(x) ?
2601 : : "string argument without an encoding" :
2602 : : "errors without a string argument");
2603 : 0 : return NULL;
2604 : : }
2605 : : /* We'd like to call PyObject_Bytes here, but we need to check for an
2606 : : integer argument before deferring to PyBytes_FromObject, something
2607 : : PyObject_Bytes doesn't do. */
2608 [ + + ]: 800 : else if ((func = _PyObject_LookupSpecial(x, &_Py_ID(__bytes__))) != NULL) {
2609 : 1 : bytes = _PyObject_CallNoArgs(func);
2610 : 1 : Py_DECREF(func);
2611 [ - + ]: 1 : if (bytes == NULL)
2612 : 0 : return NULL;
2613 [ - + ]: 1 : if (!PyBytes_Check(bytes)) {
2614 : 0 : PyErr_Format(PyExc_TypeError,
2615 : : "__bytes__ returned non-bytes (type %.200s)",
2616 : 0 : Py_TYPE(bytes)->tp_name);
2617 : 0 : Py_DECREF(bytes);
2618 : 0 : return NULL;
2619 : : }
2620 : : }
2621 [ - + ]: 799 : else if (PyErr_Occurred())
2622 : 0 : return NULL;
2623 [ - + ]: 799 : else if (PyUnicode_Check(x)) {
2624 : 0 : PyErr_SetString(PyExc_TypeError,
2625 : : "string argument without an encoding");
2626 : 0 : return NULL;
2627 : : }
2628 : : /* Is it an integer? */
2629 [ - + ]: 799 : else if (_PyIndex_Check(x)) {
2630 : 0 : size = PyNumber_AsSsize_t(x, PyExc_OverflowError);
2631 [ # # # # ]: 0 : if (size == -1 && PyErr_Occurred()) {
2632 [ # # ]: 0 : if (!PyErr_ExceptionMatches(PyExc_TypeError))
2633 : 0 : return NULL;
2634 : 0 : PyErr_Clear(); /* fall through */
2635 : 0 : bytes = PyBytes_FromObject(x);
2636 : : }
2637 : : else {
2638 [ # # ]: 0 : if (size < 0) {
2639 : 0 : PyErr_SetString(PyExc_ValueError, "negative count");
2640 : 0 : return NULL;
2641 : : }
2642 : 0 : bytes = _PyBytes_FromSize(size, 1);
2643 : : }
2644 : : }
2645 : : else {
2646 : 799 : bytes = PyBytes_FromObject(x);
2647 : : }
2648 : :
2649 [ + - - + ]: 800 : if (bytes != NULL && type != &PyBytes_Type) {
2650 : 0 : Py_SETREF(bytes, bytes_subtype_new(type, bytes));
2651 : : }
2652 : :
2653 : 800 : return bytes;
2654 : : }
2655 : :
2656 : : static PyObject*
2657 : 3 : _PyBytes_FromBuffer(PyObject *x)
2658 : : {
2659 : : PyObject *new;
2660 : : Py_buffer view;
2661 : :
2662 [ - + ]: 3 : if (PyObject_GetBuffer(x, &view, PyBUF_FULL_RO) < 0)
2663 : 0 : return NULL;
2664 : :
2665 : 3 : new = PyBytes_FromStringAndSize(NULL, view.len);
2666 [ - + ]: 3 : if (!new)
2667 : 0 : goto fail;
2668 [ - + ]: 3 : if (PyBuffer_ToContiguous(((PyBytesObject *)new)->ob_sval,
2669 : : &view, view.len, 'C') < 0)
2670 : 0 : goto fail;
2671 : 3 : PyBuffer_Release(&view);
2672 : 3 : return new;
2673 : :
2674 : 0 : fail:
2675 : 0 : Py_XDECREF(new);
2676 : 0 : PyBuffer_Release(&view);
2677 : 0 : return NULL;
2678 : : }
2679 : :
2680 : : static PyObject*
2681 : 0 : _PyBytes_FromList(PyObject *x)
2682 : : {
2683 : 0 : Py_ssize_t i, size = PyList_GET_SIZE(x);
2684 : : Py_ssize_t value;
2685 : : char *str;
2686 : : PyObject *item;
2687 : : _PyBytesWriter writer;
2688 : :
2689 : 0 : _PyBytesWriter_Init(&writer);
2690 : 0 : str = _PyBytesWriter_Alloc(&writer, size);
2691 [ # # ]: 0 : if (str == NULL)
2692 : 0 : return NULL;
2693 : 0 : writer.overallocate = 1;
2694 : 0 : size = writer.allocated;
2695 : :
2696 [ # # ]: 0 : for (i = 0; i < PyList_GET_SIZE(x); i++) {
2697 : 0 : item = PyList_GET_ITEM(x, i);
2698 : 0 : Py_INCREF(item);
2699 : 0 : value = PyNumber_AsSsize_t(item, NULL);
2700 : 0 : Py_DECREF(item);
2701 [ # # # # ]: 0 : if (value == -1 && PyErr_Occurred())
2702 : 0 : goto error;
2703 : :
2704 [ # # # # ]: 0 : if (value < 0 || value >= 256) {
2705 : 0 : PyErr_SetString(PyExc_ValueError,
2706 : : "bytes must be in range(0, 256)");
2707 : 0 : goto error;
2708 : : }
2709 : :
2710 [ # # ]: 0 : if (i >= size) {
2711 : 0 : str = _PyBytesWriter_Resize(&writer, str, size+1);
2712 [ # # ]: 0 : if (str == NULL)
2713 : 0 : return NULL;
2714 : 0 : size = writer.allocated;
2715 : : }
2716 : 0 : *str++ = (char) value;
2717 : : }
2718 : 0 : return _PyBytesWriter_Finish(&writer, str);
2719 : :
2720 : 0 : error:
2721 : 0 : _PyBytesWriter_Dealloc(&writer);
2722 : 0 : return NULL;
2723 : : }
2724 : :
2725 : : static PyObject*
2726 : 23 : _PyBytes_FromTuple(PyObject *x)
2727 : : {
2728 : : PyObject *bytes;
2729 : 23 : Py_ssize_t i, size = PyTuple_GET_SIZE(x);
2730 : : Py_ssize_t value;
2731 : : char *str;
2732 : : PyObject *item;
2733 : :
2734 : 23 : bytes = PyBytes_FromStringAndSize(NULL, size);
2735 [ - + ]: 23 : if (bytes == NULL)
2736 : 0 : return NULL;
2737 : 23 : str = ((PyBytesObject *)bytes)->ob_sval;
2738 : :
2739 [ + + ]: 406242 : for (i = 0; i < size; i++) {
2740 : 406219 : item = PyTuple_GET_ITEM(x, i);
2741 : 406219 : value = PyNumber_AsSsize_t(item, NULL);
2742 [ - + - - ]: 406219 : if (value == -1 && PyErr_Occurred())
2743 : 0 : goto error;
2744 : :
2745 [ + - - + ]: 406219 : if (value < 0 || value >= 256) {
2746 : 0 : PyErr_SetString(PyExc_ValueError,
2747 : : "bytes must be in range(0, 256)");
2748 : 0 : goto error;
2749 : : }
2750 : 406219 : *str++ = (char) value;
2751 : : }
2752 : 23 : return bytes;
2753 : :
2754 : 0 : error:
2755 : 0 : Py_DECREF(bytes);
2756 : 0 : return NULL;
2757 : : }
2758 : :
2759 : : static PyObject *
2760 : 773 : _PyBytes_FromIterator(PyObject *it, PyObject *x)
2761 : : {
2762 : : char *str;
2763 : : Py_ssize_t i, size;
2764 : : _PyBytesWriter writer;
2765 : :
2766 : : /* For iterator version, create a bytes object and resize as needed */
2767 : 773 : size = PyObject_LengthHint(x, 64);
2768 [ - + - - ]: 773 : if (size == -1 && PyErr_Occurred())
2769 : 0 : return NULL;
2770 : :
2771 : 773 : _PyBytesWriter_Init(&writer);
2772 : 773 : str = _PyBytesWriter_Alloc(&writer, size);
2773 [ - + ]: 773 : if (str == NULL)
2774 : 0 : return NULL;
2775 : 773 : writer.overallocate = 1;
2776 : 773 : size = writer.allocated;
2777 : :
2778 : : /* Run the iterator to exhaustion */
2779 : 773 : for (i = 0; ; i++) {
2780 : : PyObject *item;
2781 : : Py_ssize_t value;
2782 : :
2783 : : /* Get the next item */
2784 : 3072 : item = PyIter_Next(it);
2785 [ + + ]: 3072 : if (item == NULL) {
2786 [ - + ]: 773 : if (PyErr_Occurred())
2787 : 0 : goto error;
2788 : 773 : break;
2789 : : }
2790 : :
2791 : : /* Interpret it as an int (__index__) */
2792 : 2299 : value = PyNumber_AsSsize_t(item, NULL);
2793 : 2299 : Py_DECREF(item);
2794 [ - + - - ]: 2299 : if (value == -1 && PyErr_Occurred())
2795 : 0 : goto error;
2796 : :
2797 : : /* Range check */
2798 [ + - - + ]: 2299 : if (value < 0 || value >= 256) {
2799 : 0 : PyErr_SetString(PyExc_ValueError,
2800 : : "bytes must be in range(0, 256)");
2801 : 0 : goto error;
2802 : : }
2803 : :
2804 : : /* Append the byte */
2805 [ - + ]: 2299 : if (i >= size) {
2806 : 0 : str = _PyBytesWriter_Resize(&writer, str, size+1);
2807 [ # # ]: 0 : if (str == NULL)
2808 : 0 : return NULL;
2809 : 0 : size = writer.allocated;
2810 : : }
2811 : 2299 : *str++ = (char) value;
2812 : : }
2813 : :
2814 : 773 : return _PyBytesWriter_Finish(&writer, str);
2815 : :
2816 : 0 : error:
2817 : 0 : _PyBytesWriter_Dealloc(&writer);
2818 : 0 : return NULL;
2819 : : }
2820 : :
2821 : : PyObject *
2822 : 799 : PyBytes_FromObject(PyObject *x)
2823 : : {
2824 : : PyObject *it, *result;
2825 : :
2826 [ - + ]: 799 : if (x == NULL) {
2827 : 0 : PyErr_BadInternalCall();
2828 : 0 : return NULL;
2829 : : }
2830 : :
2831 [ - + ]: 799 : if (PyBytes_CheckExact(x)) {
2832 : 0 : return Py_NewRef(x);
2833 : : }
2834 : :
2835 : : /* Use the modern buffer interface */
2836 [ + + ]: 799 : if (PyObject_CheckBuffer(x))
2837 : 3 : return _PyBytes_FromBuffer(x);
2838 : :
2839 [ - + ]: 796 : if (PyList_CheckExact(x))
2840 : 0 : return _PyBytes_FromList(x);
2841 : :
2842 [ + + ]: 796 : if (PyTuple_CheckExact(x))
2843 : 23 : return _PyBytes_FromTuple(x);
2844 : :
2845 [ + - ]: 773 : if (!PyUnicode_Check(x)) {
2846 : 773 : it = PyObject_GetIter(x);
2847 [ + - ]: 773 : if (it != NULL) {
2848 : 773 : result = _PyBytes_FromIterator(it, x);
2849 : 773 : Py_DECREF(it);
2850 : 773 : return result;
2851 : : }
2852 [ # # ]: 0 : if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
2853 : 0 : return NULL;
2854 : : }
2855 : : }
2856 : :
2857 : 0 : PyErr_Format(PyExc_TypeError,
2858 : : "cannot convert '%.200s' object to bytes",
2859 : 0 : Py_TYPE(x)->tp_name);
2860 : 0 : return NULL;
2861 : : }
2862 : :
2863 : : /* This allocator is needed for subclasses don't want to use __new__.
2864 : : * See https://github.com/python/cpython/issues/91020#issuecomment-1096793239
2865 : : *
2866 : : * This allocator will be removed when ob_shash is removed.
2867 : : */
2868 : : static PyObject *
2869 : 0 : bytes_alloc(PyTypeObject *self, Py_ssize_t nitems)
2870 : : {
2871 : 0 : PyBytesObject *obj = (PyBytesObject*)PyType_GenericAlloc(self, nitems);
2872 [ # # ]: 0 : if (obj == NULL) {
2873 : 0 : return NULL;
2874 : : }
2875 : : _Py_COMP_DIAG_PUSH
2876 : : _Py_COMP_DIAG_IGNORE_DEPR_DECLS
2877 : 0 : obj->ob_shash = -1;
2878 : : _Py_COMP_DIAG_POP
2879 : 0 : return (PyObject*)obj;
2880 : : }
2881 : :
2882 : : static PyObject *
2883 : 0 : bytes_subtype_new(PyTypeObject *type, PyObject *tmp)
2884 : : {
2885 : : PyObject *pnew;
2886 : : Py_ssize_t n;
2887 : :
2888 : : assert(PyType_IsSubtype(type, &PyBytes_Type));
2889 : : assert(PyBytes_Check(tmp));
2890 : 0 : n = PyBytes_GET_SIZE(tmp);
2891 : 0 : pnew = type->tp_alloc(type, n);
2892 [ # # ]: 0 : if (pnew != NULL) {
2893 : 0 : memcpy(PyBytes_AS_STRING(pnew),
2894 : 0 : PyBytes_AS_STRING(tmp), n+1);
2895 : : _Py_COMP_DIAG_PUSH
2896 : : _Py_COMP_DIAG_IGNORE_DEPR_DECLS
2897 : 0 : ((PyBytesObject *)pnew)->ob_shash =
2898 : 0 : ((PyBytesObject *)tmp)->ob_shash;
2899 : : _Py_COMP_DIAG_POP
2900 : : }
2901 : 0 : return pnew;
2902 : : }
2903 : :
2904 : : PyDoc_STRVAR(bytes_doc,
2905 : : "bytes(iterable_of_ints) -> bytes\n\
2906 : : bytes(string, encoding[, errors]) -> bytes\n\
2907 : : bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer\n\
2908 : : bytes(int) -> bytes object of size given by the parameter initialized with null bytes\n\
2909 : : bytes() -> empty bytes object\n\
2910 : : \n\
2911 : : Construct an immutable array of bytes from:\n\
2912 : : - an iterable yielding integers in range(256)\n\
2913 : : - a text string encoded using the specified encoding\n\
2914 : : - any object implementing the buffer API.\n\
2915 : : - an integer");
2916 : :
2917 : : static PyObject *bytes_iter(PyObject *seq);
2918 : :
2919 : : PyTypeObject PyBytes_Type = {
2920 : : PyVarObject_HEAD_INIT(&PyType_Type, 0)
2921 : : "bytes",
2922 : : PyBytesObject_SIZE,
2923 : : sizeof(char),
2924 : : 0, /* tp_dealloc */
2925 : : 0, /* tp_vectorcall_offset */
2926 : : 0, /* tp_getattr */
2927 : : 0, /* tp_setattr */
2928 : : 0, /* tp_as_async */
2929 : : (reprfunc)bytes_repr, /* tp_repr */
2930 : : &bytes_as_number, /* tp_as_number */
2931 : : &bytes_as_sequence, /* tp_as_sequence */
2932 : : &bytes_as_mapping, /* tp_as_mapping */
2933 : : (hashfunc)bytes_hash, /* tp_hash */
2934 : : 0, /* tp_call */
2935 : : bytes_str, /* tp_str */
2936 : : PyObject_GenericGetAttr, /* tp_getattro */
2937 : : 0, /* tp_setattro */
2938 : : &bytes_as_buffer, /* tp_as_buffer */
2939 : : Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
2940 : : Py_TPFLAGS_BYTES_SUBCLASS |
2941 : : _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
2942 : : bytes_doc, /* tp_doc */
2943 : : 0, /* tp_traverse */
2944 : : 0, /* tp_clear */
2945 : : (richcmpfunc)bytes_richcompare, /* tp_richcompare */
2946 : : 0, /* tp_weaklistoffset */
2947 : : bytes_iter, /* tp_iter */
2948 : : 0, /* tp_iternext */
2949 : : bytes_methods, /* tp_methods */
2950 : : 0, /* tp_members */
2951 : : 0, /* tp_getset */
2952 : : 0, /* tp_base */
2953 : : 0, /* tp_dict */
2954 : : 0, /* tp_descr_get */
2955 : : 0, /* tp_descr_set */
2956 : : 0, /* tp_dictoffset */
2957 : : 0, /* tp_init */
2958 : : bytes_alloc, /* tp_alloc */
2959 : : bytes_new, /* tp_new */
2960 : : PyObject_Del, /* tp_free */
2961 : : };
2962 : :
2963 : : void
2964 : 17 : PyBytes_Concat(PyObject **pv, PyObject *w)
2965 : : {
2966 : : assert(pv != NULL);
2967 [ - + ]: 17 : if (*pv == NULL)
2968 : 0 : return;
2969 [ - + ]: 17 : if (w == NULL) {
2970 [ # # ]: 0 : Py_CLEAR(*pv);
2971 : 0 : return;
2972 : : }
2973 : :
2974 [ + + + - ]: 17 : if (Py_REFCNT(*pv) == 1 && PyBytes_CheckExact(*pv)) {
2975 : : /* Only one reference, so we can resize in place */
2976 : : Py_ssize_t oldsize;
2977 : : Py_buffer wb;
2978 : :
2979 [ - + ]: 9 : if (PyObject_GetBuffer(w, &wb, PyBUF_SIMPLE) != 0) {
2980 : 0 : PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
2981 : 0 : Py_TYPE(w)->tp_name, Py_TYPE(*pv)->tp_name);
2982 [ # # ]: 0 : Py_CLEAR(*pv);
2983 : 0 : return;
2984 : : }
2985 : :
2986 : 9 : oldsize = PyBytes_GET_SIZE(*pv);
2987 [ - + ]: 9 : if (oldsize > PY_SSIZE_T_MAX - wb.len) {
2988 : 0 : PyErr_NoMemory();
2989 : 0 : goto error;
2990 : : }
2991 [ - + ]: 9 : if (_PyBytes_Resize(pv, oldsize + wb.len) < 0)
2992 : 0 : goto error;
2993 : :
2994 : 9 : memcpy(PyBytes_AS_STRING(*pv) + oldsize, wb.buf, wb.len);
2995 : 9 : PyBuffer_Release(&wb);
2996 : 9 : return;
2997 : :
2998 : 0 : error:
2999 : 0 : PyBuffer_Release(&wb);
3000 [ # # ]: 0 : Py_CLEAR(*pv);
3001 : 0 : return;
3002 : : }
3003 : :
3004 : : else {
3005 : : /* Multiple references, need to create new object */
3006 : : PyObject *v;
3007 : 8 : v = bytes_concat(*pv, w);
3008 : 8 : Py_SETREF(*pv, v);
3009 : : }
3010 : : }
3011 : :
3012 : : void
3013 : 9 : PyBytes_ConcatAndDel(PyObject **pv, PyObject *w)
3014 : : {
3015 : 9 : PyBytes_Concat(pv, w);
3016 : 9 : Py_XDECREF(w);
3017 : 9 : }
3018 : :
3019 : :
3020 : : /* The following function breaks the notion that bytes are immutable:
3021 : : it changes the size of a bytes object. We get away with this only if there
3022 : : is only one module referencing the object. You can also think of it
3023 : : as creating a new bytes object and destroying the old one, only
3024 : : more efficiently. In any case, don't use this if the bytes object may
3025 : : already be known to some other part of the code...
3026 : : Note that if there's not enough memory to resize the bytes object, the
3027 : : original bytes object at *pv is deallocated, *pv is set to NULL, an "out of
3028 : : memory" exception is set, and -1 is returned. Else (on success) 0 is
3029 : : returned, and the value in *pv may or may not be the same as on input.
3030 : : As always, an extra byte is allocated for a trailing \0 byte (newsize
3031 : : does *not* include that), and a trailing \0 byte is stored.
3032 : : */
3033 : :
3034 : : int
3035 : 50071 : _PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
3036 : : {
3037 : : PyObject *v;
3038 : : PyBytesObject *sv;
3039 : 50071 : v = *pv;
3040 [ + - - + ]: 50071 : if (!PyBytes_Check(v) || newsize < 0) {
3041 : 0 : goto error;
3042 : : }
3043 [ - + ]: 50071 : if (Py_SIZE(v) == newsize) {
3044 : : /* return early if newsize equals to v->ob_size */
3045 : 0 : return 0;
3046 : : }
3047 [ - + ]: 50071 : if (Py_SIZE(v) == 0) {
3048 [ # # ]: 0 : if (newsize == 0) {
3049 : 0 : return 0;
3050 : : }
3051 : 0 : *pv = _PyBytes_FromSize(newsize, 0);
3052 : 0 : Py_DECREF(v);
3053 [ # # ]: 0 : return (*pv == NULL) ? -1 : 0;
3054 : : }
3055 [ - + ]: 50071 : if (Py_REFCNT(v) != 1) {
3056 : 0 : goto error;
3057 : : }
3058 [ + + ]: 50071 : if (newsize == 0) {
3059 : 7076 : *pv = bytes_new_empty();
3060 : 7076 : Py_DECREF(v);
3061 : 7076 : return 0;
3062 : : }
3063 : : #ifdef Py_TRACE_REFS
3064 : : _Py_ForgetReference(v);
3065 : : #endif
3066 : 42995 : *pv = (PyObject *)
3067 : 42995 : PyObject_Realloc(v, PyBytesObject_SIZE + newsize);
3068 [ - + ]: 42995 : if (*pv == NULL) {
3069 : : #ifdef Py_REF_DEBUG
3070 : : _Py_DecRefTotal();
3071 : : #endif
3072 : 0 : PyObject_Free(v);
3073 : 0 : PyErr_NoMemory();
3074 : 0 : return -1;
3075 : : }
3076 : 42995 : _Py_NewReferenceNoTotal(*pv);
3077 : 42995 : sv = (PyBytesObject *) *pv;
3078 : 42995 : Py_SET_SIZE(sv, newsize);
3079 : 42995 : sv->ob_sval[newsize] = '\0';
3080 : : _Py_COMP_DIAG_PUSH
3081 : : _Py_COMP_DIAG_IGNORE_DEPR_DECLS
3082 : 42995 : sv->ob_shash = -1; /* invalidate cached hash value */
3083 : : _Py_COMP_DIAG_POP
3084 : 42995 : return 0;
3085 : 0 : error:
3086 : 0 : *pv = 0;
3087 : 0 : Py_DECREF(v);
3088 : 0 : PyErr_BadInternalCall();
3089 : 0 : return -1;
3090 : : }
3091 : :
3092 : :
3093 : : PyStatus
3094 : 29 : _PyBytes_InitTypes(PyInterpreterState *interp)
3095 : : {
3096 [ - + ]: 29 : if (!_Py_IsMainInterpreter(interp)) {
3097 : 0 : return _PyStatus_OK();
3098 : : }
3099 : :
3100 [ - + ]: 29 : if (PyType_Ready(&PyBytes_Type) < 0) {
3101 : 0 : return _PyStatus_ERR("Can't initialize bytes type");
3102 : : }
3103 : :
3104 [ - + ]: 29 : if (PyType_Ready(&PyBytesIter_Type) < 0) {
3105 : 0 : return _PyStatus_ERR("Can't initialize bytes iterator type");
3106 : : }
3107 : :
3108 : 29 : return _PyStatus_OK();
3109 : : }
3110 : :
3111 : :
3112 : : /*********************** Bytes Iterator ****************************/
3113 : :
3114 : : typedef struct {
3115 : : PyObject_HEAD
3116 : : Py_ssize_t it_index;
3117 : : PyBytesObject *it_seq; /* Set to NULL when iterator is exhausted */
3118 : : } striterobject;
3119 : :
3120 : : static void
3121 : 30097 : striter_dealloc(striterobject *it)
3122 : : {
3123 : 30097 : _PyObject_GC_UNTRACK(it);
3124 : 30097 : Py_XDECREF(it->it_seq);
3125 : 30097 : PyObject_GC_Del(it);
3126 : 30097 : }
3127 : :
3128 : : static int
3129 : 0 : striter_traverse(striterobject *it, visitproc visit, void *arg)
3130 : : {
3131 [ # # # # ]: 0 : Py_VISIT(it->it_seq);
3132 : 0 : return 0;
3133 : : }
3134 : :
3135 : : static PyObject *
3136 : 622163 : striter_next(striterobject *it)
3137 : : {
3138 : : PyBytesObject *seq;
3139 : :
3140 : : assert(it != NULL);
3141 : 622163 : seq = it->it_seq;
3142 [ - + ]: 622163 : if (seq == NULL)
3143 : 0 : return NULL;
3144 : : assert(PyBytes_Check(seq));
3145 : :
3146 [ + + ]: 622163 : if (it->it_index < PyBytes_GET_SIZE(seq)) {
3147 : 601680 : return _PyLong_FromUnsignedChar(
3148 : 601680 : (unsigned char)seq->ob_sval[it->it_index++]);
3149 : : }
3150 : :
3151 : 20483 : it->it_seq = NULL;
3152 : 20483 : Py_DECREF(seq);
3153 : 20483 : return NULL;
3154 : : }
3155 : :
3156 : : static PyObject *
3157 : 0 : striter_len(striterobject *it, PyObject *Py_UNUSED(ignored))
3158 : : {
3159 : 0 : Py_ssize_t len = 0;
3160 [ # # ]: 0 : if (it->it_seq)
3161 : 0 : len = PyBytes_GET_SIZE(it->it_seq) - it->it_index;
3162 : 0 : return PyLong_FromSsize_t(len);
3163 : : }
3164 : :
3165 : : PyDoc_STRVAR(length_hint_doc,
3166 : : "Private method returning an estimate of len(list(it)).");
3167 : :
3168 : : static PyObject *
3169 : 0 : striter_reduce(striterobject *it, PyObject *Py_UNUSED(ignored))
3170 : : {
3171 : 0 : PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
3172 : :
3173 : : /* _PyEval_GetBuiltin can invoke arbitrary code,
3174 : : * call must be before access of iterator pointers.
3175 : : * see issue #101765 */
3176 : :
3177 [ # # ]: 0 : if (it->it_seq != NULL) {
3178 : 0 : return Py_BuildValue("N(O)n", iter, it->it_seq, it->it_index);
3179 : : } else {
3180 : 0 : return Py_BuildValue("N(())", iter);
3181 : : }
3182 : : }
3183 : :
3184 : : PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3185 : :
3186 : : static PyObject *
3187 : 0 : striter_setstate(striterobject *it, PyObject *state)
3188 : : {
3189 : 0 : Py_ssize_t index = PyLong_AsSsize_t(state);
3190 [ # # # # ]: 0 : if (index == -1 && PyErr_Occurred())
3191 : 0 : return NULL;
3192 [ # # ]: 0 : if (it->it_seq != NULL) {
3193 [ # # ]: 0 : if (index < 0)
3194 : 0 : index = 0;
3195 [ # # ]: 0 : else if (index > PyBytes_GET_SIZE(it->it_seq))
3196 : 0 : index = PyBytes_GET_SIZE(it->it_seq); /* iterator exhausted */
3197 : 0 : it->it_index = index;
3198 : : }
3199 : 0 : Py_RETURN_NONE;
3200 : : }
3201 : :
3202 : : PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
3203 : :
3204 : : static PyMethodDef striter_methods[] = {
3205 : : {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS,
3206 : : length_hint_doc},
3207 : : {"__reduce__", (PyCFunction)striter_reduce, METH_NOARGS,
3208 : : reduce_doc},
3209 : : {"__setstate__", (PyCFunction)striter_setstate, METH_O,
3210 : : setstate_doc},
3211 : : {NULL, NULL} /* sentinel */
3212 : : };
3213 : :
3214 : : PyTypeObject PyBytesIter_Type = {
3215 : : PyVarObject_HEAD_INIT(&PyType_Type, 0)
3216 : : "bytes_iterator", /* tp_name */
3217 : : sizeof(striterobject), /* tp_basicsize */
3218 : : 0, /* tp_itemsize */
3219 : : /* methods */
3220 : : (destructor)striter_dealloc, /* tp_dealloc */
3221 : : 0, /* tp_vectorcall_offset */
3222 : : 0, /* tp_getattr */
3223 : : 0, /* tp_setattr */
3224 : : 0, /* tp_as_async */
3225 : : 0, /* tp_repr */
3226 : : 0, /* tp_as_number */
3227 : : 0, /* tp_as_sequence */
3228 : : 0, /* tp_as_mapping */
3229 : : 0, /* tp_hash */
3230 : : 0, /* tp_call */
3231 : : 0, /* tp_str */
3232 : : PyObject_GenericGetAttr, /* tp_getattro */
3233 : : 0, /* tp_setattro */
3234 : : 0, /* tp_as_buffer */
3235 : : Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3236 : : 0, /* tp_doc */
3237 : : (traverseproc)striter_traverse, /* tp_traverse */
3238 : : 0, /* tp_clear */
3239 : : 0, /* tp_richcompare */
3240 : : 0, /* tp_weaklistoffset */
3241 : : PyObject_SelfIter, /* tp_iter */
3242 : : (iternextfunc)striter_next, /* tp_iternext */
3243 : : striter_methods, /* tp_methods */
3244 : : 0,
3245 : : };
3246 : :
3247 : : static PyObject *
3248 : 30097 : bytes_iter(PyObject *seq)
3249 : : {
3250 : : striterobject *it;
3251 : :
3252 [ - + ]: 30097 : if (!PyBytes_Check(seq)) {
3253 : 0 : PyErr_BadInternalCall();
3254 : 0 : return NULL;
3255 : : }
3256 : 30097 : it = PyObject_GC_New(striterobject, &PyBytesIter_Type);
3257 [ - + ]: 30097 : if (it == NULL)
3258 : 0 : return NULL;
3259 : 30097 : it->it_index = 0;
3260 : 30097 : it->it_seq = (PyBytesObject *)Py_NewRef(seq);
3261 : 30097 : _PyObject_GC_TRACK(it);
3262 : 30097 : return (PyObject *)it;
3263 : : }
3264 : :
3265 : :
3266 : : /* _PyBytesWriter API */
3267 : :
3268 : : #ifdef MS_WINDOWS
3269 : : /* On Windows, overallocate by 50% is the best factor */
3270 : : # define OVERALLOCATE_FACTOR 2
3271 : : #else
3272 : : /* On Linux, overallocate by 25% is the best factor */
3273 : : # define OVERALLOCATE_FACTOR 4
3274 : : #endif
3275 : :
3276 : : void
3277 : 1069 : _PyBytesWriter_Init(_PyBytesWriter *writer)
3278 : : {
3279 : : /* Set all attributes before small_buffer to 0 */
3280 : 1069 : memset(writer, 0, offsetof(_PyBytesWriter, small_buffer));
3281 : : #ifndef NDEBUG
3282 : : memset(writer->small_buffer, PYMEM_CLEANBYTE,
3283 : : sizeof(writer->small_buffer));
3284 : : #endif
3285 : 1069 : }
3286 : :
3287 : : void
3288 : 0 : _PyBytesWriter_Dealloc(_PyBytesWriter *writer)
3289 : : {
3290 [ # # ]: 0 : Py_CLEAR(writer->buffer);
3291 : 0 : }
3292 : :
3293 : : Py_LOCAL_INLINE(char*)
3294 : 1083 : _PyBytesWriter_AsString(_PyBytesWriter *writer)
3295 : : {
3296 [ + + ]: 1083 : if (writer->use_small_buffer) {
3297 : : assert(writer->buffer == NULL);
3298 : 1069 : return writer->small_buffer;
3299 : : }
3300 [ - + ]: 14 : else if (writer->use_bytearray) {
3301 : : assert(writer->buffer != NULL);
3302 : 0 : return PyByteArray_AS_STRING(writer->buffer);
3303 : : }
3304 : : else {
3305 : : assert(writer->buffer != NULL);
3306 : 14 : return PyBytes_AS_STRING(writer->buffer);
3307 : : }
3308 : : }
3309 : :
3310 : : Py_LOCAL_INLINE(Py_ssize_t)
3311 : 1076 : _PyBytesWriter_GetSize(_PyBytesWriter *writer, char *str)
3312 : : {
3313 : 1076 : const char *start = _PyBytesWriter_AsString(writer);
3314 : : assert(str != NULL);
3315 : : assert(str >= start);
3316 : : assert(str - start <= writer->allocated);
3317 : 1076 : return str - start;
3318 : : }
3319 : :
3320 : : #ifndef NDEBUG
3321 : : Py_LOCAL_INLINE(int)
3322 : : _PyBytesWriter_CheckConsistency(_PyBytesWriter *writer, char *str)
3323 : : {
3324 : : const char *start, *end;
3325 : :
3326 : : if (writer->use_small_buffer) {
3327 : : assert(writer->buffer == NULL);
3328 : : }
3329 : : else {
3330 : : assert(writer->buffer != NULL);
3331 : : if (writer->use_bytearray)
3332 : : assert(PyByteArray_CheckExact(writer->buffer));
3333 : : else
3334 : : assert(PyBytes_CheckExact(writer->buffer));
3335 : : assert(Py_REFCNT(writer->buffer) == 1);
3336 : : }
3337 : :
3338 : : if (writer->use_bytearray) {
3339 : : /* bytearray has its own overallocation algorithm,
3340 : : writer overallocation must be disabled */
3341 : : assert(!writer->overallocate);
3342 : : }
3343 : :
3344 : : assert(0 <= writer->allocated);
3345 : : assert(0 <= writer->min_size && writer->min_size <= writer->allocated);
3346 : : /* the last byte must always be null */
3347 : : start = _PyBytesWriter_AsString(writer);
3348 : : assert(start[writer->allocated] == 0);
3349 : :
3350 : : end = start + writer->allocated;
3351 : : assert(str != NULL);
3352 : : assert(start <= str && str <= end);
3353 : : return 1;
3354 : : }
3355 : : #endif
3356 : :
3357 : : void*
3358 : 7 : _PyBytesWriter_Resize(_PyBytesWriter *writer, void *str, Py_ssize_t size)
3359 : : {
3360 : : Py_ssize_t allocated, pos;
3361 : :
3362 : : assert(_PyBytesWriter_CheckConsistency(writer, str));
3363 : : assert(writer->allocated < size);
3364 : :
3365 : 7 : allocated = size;
3366 [ - + ]: 7 : if (writer->overallocate
3367 [ # # ]: 0 : && allocated <= (PY_SSIZE_T_MAX - allocated / OVERALLOCATE_FACTOR)) {
3368 : : /* overallocate to limit the number of realloc() */
3369 : 0 : allocated += allocated / OVERALLOCATE_FACTOR;
3370 : : }
3371 : :
3372 : 7 : pos = _PyBytesWriter_GetSize(writer, str);
3373 [ - + ]: 7 : if (!writer->use_small_buffer) {
3374 [ # # ]: 0 : if (writer->use_bytearray) {
3375 [ # # ]: 0 : if (PyByteArray_Resize(writer->buffer, allocated))
3376 : 0 : goto error;
3377 : : /* writer->allocated can be smaller than writer->buffer->ob_alloc,
3378 : : but we cannot use ob_alloc because bytes may need to be moved
3379 : : to use the whole buffer. bytearray uses an internal optimization
3380 : : to avoid moving or copying bytes when bytes are removed at the
3381 : : beginning (ex: del bytearray[:1]). */
3382 : : }
3383 : : else {
3384 [ # # ]: 0 : if (_PyBytes_Resize(&writer->buffer, allocated))
3385 : 0 : goto error;
3386 : : }
3387 : : }
3388 : : else {
3389 : : /* convert from stack buffer to bytes object buffer */
3390 : : assert(writer->buffer == NULL);
3391 : :
3392 [ - + ]: 7 : if (writer->use_bytearray)
3393 : 0 : writer->buffer = PyByteArray_FromStringAndSize(NULL, allocated);
3394 : : else
3395 : 7 : writer->buffer = PyBytes_FromStringAndSize(NULL, allocated);
3396 [ - + ]: 7 : if (writer->buffer == NULL)
3397 : 0 : goto error;
3398 : :
3399 [ - + ]: 7 : if (pos != 0) {
3400 : : char *dest;
3401 [ # # ]: 0 : if (writer->use_bytearray)
3402 : 0 : dest = PyByteArray_AS_STRING(writer->buffer);
3403 : : else
3404 : 0 : dest = PyBytes_AS_STRING(writer->buffer);
3405 : 0 : memcpy(dest,
3406 : 0 : writer->small_buffer,
3407 : : pos);
3408 : : }
3409 : :
3410 : 7 : writer->use_small_buffer = 0;
3411 : : #ifndef NDEBUG
3412 : : memset(writer->small_buffer, PYMEM_CLEANBYTE,
3413 : : sizeof(writer->small_buffer));
3414 : : #endif
3415 : : }
3416 : 7 : writer->allocated = allocated;
3417 : :
3418 : 7 : str = _PyBytesWriter_AsString(writer) + pos;
3419 : : assert(_PyBytesWriter_CheckConsistency(writer, str));
3420 : 7 : return str;
3421 : :
3422 : 0 : error:
3423 : 0 : _PyBytesWriter_Dealloc(writer);
3424 : 0 : return NULL;
3425 : : }
3426 : :
3427 : : void*
3428 : 1069 : _PyBytesWriter_Prepare(_PyBytesWriter *writer, void *str, Py_ssize_t size)
3429 : : {
3430 : : Py_ssize_t new_min_size;
3431 : :
3432 : : assert(_PyBytesWriter_CheckConsistency(writer, str));
3433 : : assert(size >= 0);
3434 : :
3435 [ + + ]: 1069 : if (size == 0) {
3436 : : /* nothing to do */
3437 : 112 : return str;
3438 : : }
3439 : :
3440 [ - + ]: 957 : if (writer->min_size > PY_SSIZE_T_MAX - size) {
3441 : 0 : PyErr_NoMemory();
3442 : 0 : _PyBytesWriter_Dealloc(writer);
3443 : 0 : return NULL;
3444 : : }
3445 : 957 : new_min_size = writer->min_size + size;
3446 : :
3447 [ + + ]: 957 : if (new_min_size > writer->allocated)
3448 : 7 : str = _PyBytesWriter_Resize(writer, str, new_min_size);
3449 : :
3450 : 957 : writer->min_size = new_min_size;
3451 : 957 : return str;
3452 : : }
3453 : :
3454 : : /* Allocate the buffer to write size bytes.
3455 : : Return the pointer to the beginning of buffer data.
3456 : : Raise an exception and return NULL on error. */
3457 : : void*
3458 : 1069 : _PyBytesWriter_Alloc(_PyBytesWriter *writer, Py_ssize_t size)
3459 : : {
3460 : : /* ensure that _PyBytesWriter_Alloc() is only called once */
3461 : : assert(writer->min_size == 0 && writer->buffer == NULL);
3462 : : assert(size >= 0);
3463 : :
3464 : 1069 : writer->use_small_buffer = 1;
3465 : : #ifndef NDEBUG
3466 : : writer->allocated = sizeof(writer->small_buffer) - 1;
3467 : : /* In debug mode, don't use the full small buffer because it is less
3468 : : efficient than bytes and bytearray objects to detect buffer underflow
3469 : : and buffer overflow. Use 10 bytes of the small buffer to test also
3470 : : code using the smaller buffer in debug mode.
3471 : :
3472 : : Don't modify the _PyBytesWriter structure (use a shorter small buffer)
3473 : : in debug mode to also be able to detect stack overflow when running
3474 : : tests in debug mode. The _PyBytesWriter is large (more than 512 bytes),
3475 : : if _Py_EnterRecursiveCall() is not used in deep C callback, we may hit a
3476 : : stack overflow. */
3477 : : writer->allocated = Py_MIN(writer->allocated, 10);
3478 : : /* _PyBytesWriter_CheckConsistency() requires the last byte to be 0,
3479 : : to detect buffer overflow */
3480 : : writer->small_buffer[writer->allocated] = 0;
3481 : : #else
3482 : 1069 : writer->allocated = sizeof(writer->small_buffer);
3483 : : #endif
3484 : 1069 : return _PyBytesWriter_Prepare(writer, writer->small_buffer, size);
3485 : : }
3486 : :
3487 : : PyObject *
3488 : 1069 : _PyBytesWriter_Finish(_PyBytesWriter *writer, void *str)
3489 : : {
3490 : : Py_ssize_t size;
3491 : : PyObject *result;
3492 : :
3493 : : assert(_PyBytesWriter_CheckConsistency(writer, str));
3494 : :
3495 : 1069 : size = _PyBytesWriter_GetSize(writer, str);
3496 [ + + + - ]: 1069 : if (size == 0 && !writer->use_bytearray) {
3497 [ - + ]: 112 : Py_CLEAR(writer->buffer);
3498 : : /* Get the empty byte string singleton */
3499 : 112 : result = PyBytes_FromStringAndSize(NULL, 0);
3500 : : }
3501 [ + + ]: 957 : else if (writer->use_small_buffer) {
3502 [ - + ]: 950 : if (writer->use_bytearray) {
3503 : 0 : result = PyByteArray_FromStringAndSize(writer->small_buffer, size);
3504 : : }
3505 : : else {
3506 : 950 : result = PyBytes_FromStringAndSize(writer->small_buffer, size);
3507 : : }
3508 : : }
3509 : : else {
3510 : 7 : result = writer->buffer;
3511 : 7 : writer->buffer = NULL;
3512 : :
3513 [ + - ]: 7 : if (size != writer->allocated) {
3514 [ - + ]: 7 : if (writer->use_bytearray) {
3515 [ # # ]: 0 : if (PyByteArray_Resize(result, size)) {
3516 : 0 : Py_DECREF(result);
3517 : 0 : return NULL;
3518 : : }
3519 : : }
3520 : : else {
3521 [ - + ]: 7 : if (_PyBytes_Resize(&result, size)) {
3522 : : assert(result == NULL);
3523 : 0 : return NULL;
3524 : : }
3525 : : }
3526 : : }
3527 : : }
3528 : 1069 : return result;
3529 : : }
3530 : :
3531 : : void*
3532 : 0 : _PyBytesWriter_WriteBytes(_PyBytesWriter *writer, void *ptr,
3533 : : const void *bytes, Py_ssize_t size)
3534 : : {
3535 : 0 : char *str = (char *)ptr;
3536 : :
3537 : 0 : str = _PyBytesWriter_Prepare(writer, str, size);
3538 [ # # ]: 0 : if (str == NULL)
3539 : 0 : return NULL;
3540 : :
3541 : 0 : memcpy(str, bytes, size);
3542 : 0 : str += size;
3543 : :
3544 : 0 : return str;
3545 : : }
3546 : :
3547 : :
3548 : : void
3549 : 78779 : _PyBytes_Repeat(char* dest, Py_ssize_t len_dest,
3550 : : const char* src, Py_ssize_t len_src)
3551 : : {
3552 [ - + ]: 78779 : if (len_dest == 0) {
3553 : 0 : return;
3554 : : }
3555 [ + + ]: 78779 : if (len_src == 1) {
3556 : 5 : memset(dest, src[0], len_dest);
3557 : : }
3558 : : else {
3559 [ + - ]: 78774 : if (src != dest) {
3560 : 78774 : memcpy(dest, src, len_src);
3561 : : }
3562 : 78774 : Py_ssize_t copied = len_src;
3563 [ + + ]: 195436 : while (copied < len_dest) {
3564 : 116662 : Py_ssize_t bytes_to_copy = Py_MIN(copied, len_dest - copied);
3565 : 116662 : memcpy(dest + copied, dest, bytes_to_copy);
3566 : 116662 : copied += bytes_to_copy;
3567 : : }
3568 : : }
3569 : : }
3570 : :
|