You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4145 lines
119 KiB

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