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.

3067 lines
90 KiB

  1. /* bytes object implementation */
  2. #define PY_SSIZE_T_CLEAN
  3. #include "Python.h"
  4. #include "bytes_methods.h"
  5. #include <stddef.h>
  6. static Py_ssize_t
  7. _getbuffer(PyObject *obj, Py_buffer *view)
  8. {
  9. PyBufferProcs *buffer = Py_TYPE(obj)->tp_as_buffer;
  10. if (buffer == NULL || buffer->bf_getbuffer == NULL)
  11. {
  12. PyErr_Format(PyExc_TypeError,
  13. "Type %.100s doesn't support the buffer API",
  14. Py_TYPE(obj)->tp_name);
  15. return -1;
  16. }
  17. if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0)
  18. return -1;
  19. return view->len;
  20. }
  21. #ifdef COUNT_ALLOCS
  22. Py_ssize_t null_strings, one_strings;
  23. #endif
  24. static PyBytesObject *characters[UCHAR_MAX + 1];
  25. static PyBytesObject *nullstring;
  26. /* PyBytesObject_SIZE gives the basic size of a string; any memory allocation
  27. for a string of length n should request PyBytesObject_SIZE + n bytes.
  28. Using PyBytesObject_SIZE instead of sizeof(PyBytesObject) saves
  29. 3 bytes per string allocation on a typical system.
  30. */
  31. #define PyBytesObject_SIZE (offsetof(PyBytesObject, ob_sval) + 1)
  32. /*
  33. For PyBytes_FromString(), the parameter `str' points to a null-terminated
  34. string containing exactly `size' bytes.
  35. For PyBytes_FromStringAndSize(), the parameter the parameter `str' is
  36. either NULL or else points to a string containing at least `size' bytes.
  37. For PyBytes_FromStringAndSize(), the string in the `str' parameter does
  38. not have to be null-terminated. (Therefore it is safe to construct a
  39. substring by calling `PyBytes_FromStringAndSize(origstring, substrlen)'.)
  40. If `str' is NULL then PyBytes_FromStringAndSize() will allocate `size+1'
  41. bytes (setting the last byte to the null terminating character) and you can
  42. fill in the data yourself. If `str' is non-NULL then the resulting
  43. PyBytes object must be treated as immutable and you must not fill in nor
  44. alter the data yourself, since the strings may be shared.
  45. The PyObject member `op->ob_size', which denotes the number of "extra
  46. items" in a variable-size object, will contain the number of bytes
  47. allocated for string data, not counting the null terminating character.
  48. It is therefore equal to the `size' parameter (for
  49. PyBytes_FromStringAndSize()) or the length of the string in the `str'
  50. parameter (for PyBytes_FromString()).
  51. */
  52. PyObject *
  53. PyBytes_FromStringAndSize(const char *str, Py_ssize_t size)
  54. {
  55. register PyBytesObject *op;
  56. if (size < 0) {
  57. PyErr_SetString(PyExc_SystemError,
  58. "Negative size passed to PyBytes_FromStringAndSize");
  59. return NULL;
  60. }
  61. if (size == 0 && (op = nullstring) != NULL) {
  62. #ifdef COUNT_ALLOCS
  63. null_strings++;
  64. #endif
  65. Py_INCREF(op);
  66. return (PyObject *)op;
  67. }
  68. if (size == 1 && str != NULL &&
  69. (op = characters[*str & UCHAR_MAX]) != NULL)
  70. {
  71. #ifdef COUNT_ALLOCS
  72. one_strings++;
  73. #endif
  74. Py_INCREF(op);
  75. return (PyObject *)op;
  76. }
  77. if (size > PY_SSIZE_T_MAX - PyBytesObject_SIZE) {
  78. PyErr_SetString(PyExc_OverflowError,
  79. "byte string is too large");
  80. return NULL;
  81. }
  82. /* Inline PyObject_NewVar */
  83. op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size);
  84. if (op == NULL)
  85. return PyErr_NoMemory();
  86. PyObject_INIT_VAR(op, &PyBytes_Type, size);
  87. op->ob_shash = -1;
  88. if (str != NULL)
  89. Py_MEMCPY(op->ob_sval, str, size);
  90. op->ob_sval[size] = '\0';
  91. /* share short strings */
  92. if (size == 0) {
  93. nullstring = op;
  94. Py_INCREF(op);
  95. } else if (size == 1 && str != NULL) {
  96. characters[*str & UCHAR_MAX] = op;
  97. Py_INCREF(op);
  98. }
  99. return (PyObject *) op;
  100. }
  101. PyObject *
  102. PyBytes_FromString(const char *str)
  103. {
  104. register size_t size;
  105. register PyBytesObject *op;
  106. assert(str != NULL);
  107. size = strlen(str);
  108. if (size > PY_SSIZE_T_MAX - PyBytesObject_SIZE) {
  109. PyErr_SetString(PyExc_OverflowError,
  110. "byte string is too long");
  111. return NULL;
  112. }
  113. if (size == 0 && (op = nullstring) != NULL) {
  114. #ifdef COUNT_ALLOCS
  115. null_strings++;
  116. #endif
  117. Py_INCREF(op);
  118. return (PyObject *)op;
  119. }
  120. if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
  121. #ifdef COUNT_ALLOCS
  122. one_strings++;
  123. #endif
  124. Py_INCREF(op);
  125. return (PyObject *)op;
  126. }
  127. /* Inline PyObject_NewVar */
  128. op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size);
  129. if (op == NULL)
  130. return PyErr_NoMemory();
  131. PyObject_INIT_VAR(op, &PyBytes_Type, size);
  132. op->ob_shash = -1;
  133. Py_MEMCPY(op->ob_sval, str, size+1);
  134. /* share short strings */
  135. if (size == 0) {
  136. nullstring = op;
  137. Py_INCREF(op);
  138. } else if (size == 1) {
  139. characters[*str & UCHAR_MAX] = op;
  140. Py_INCREF(op);
  141. }
  142. return (PyObject *) op;
  143. }
  144. PyObject *
  145. PyBytes_FromFormatV(const char *format, va_list vargs)
  146. {
  147. va_list count;
  148. Py_ssize_t n = 0;
  149. const char* f;
  150. char *s;
  151. PyObject* string;
  152. Py_VA_COPY(count, vargs);
  153. /* step 1: figure out how large a buffer we need */
  154. for (f = format; *f; f++) {
  155. if (*f == '%') {
  156. const char* p = f;
  157. while (*++f && *f != '%' && !Py_ISALPHA(*f))
  158. ;
  159. /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
  160. * they don't affect the amount of space we reserve.
  161. */
  162. if ((*f == 'l' || *f == 'z') &&
  163. (f[1] == 'd' || f[1] == 'u'))
  164. ++f;
  165. switch (*f) {
  166. case 'c':
  167. {
  168. int c = va_arg(count, int);
  169. if (c < 0 || c > 255) {
  170. PyErr_SetString(PyExc_OverflowError,
  171. "PyBytes_FromFormatV(): %c format "
  172. "expects an integer in range [0; 255]");
  173. return NULL;
  174. }
  175. n++;
  176. break;
  177. }
  178. case '%':
  179. n++;
  180. break;
  181. case 'd': case 'u': case 'i': case 'x':
  182. (void) va_arg(count, int);
  183. /* 20 bytes is enough to hold a 64-bit
  184. integer. Decimal takes the most space.
  185. This isn't enough for octal. */
  186. n += 20;
  187. break;
  188. case 's':
  189. s = va_arg(count, char*);
  190. n += strlen(s);
  191. break;
  192. case 'p':
  193. (void) va_arg(count, int);
  194. /* maximum 64-bit pointer representation:
  195. * 0xffffffffffffffff
  196. * so 19 characters is enough.
  197. * XXX I count 18 -- what's the extra for?
  198. */
  199. n += 19;
  200. break;
  201. default:
  202. /* if we stumble upon an unknown
  203. formatting code, copy the rest of
  204. the format string to the output
  205. string. (we cannot just skip the
  206. code, since there's no way to know
  207. what's in the argument list) */
  208. n += strlen(p);
  209. goto expand;
  210. }
  211. } else
  212. n++;
  213. }
  214. expand:
  215. /* step 2: fill the buffer */
  216. /* Since we've analyzed how much space we need for the worst case,
  217. use sprintf directly instead of the slower PyOS_snprintf. */
  218. string = PyBytes_FromStringAndSize(NULL, n);
  219. if (!string)
  220. return NULL;
  221. s = PyBytes_AsString(string);
  222. for (f = format; *f; f++) {
  223. if (*f == '%') {
  224. const char* p = f++;
  225. Py_ssize_t i;
  226. int longflag = 0;
  227. int size_tflag = 0;
  228. /* parse the width.precision part (we're only
  229. interested in the precision value, if any) */
  230. n = 0;
  231. while (Py_ISDIGIT(*f))
  232. n = (n*10) + *f++ - '0';
  233. if (*f == '.') {
  234. f++;
  235. n = 0;
  236. while (Py_ISDIGIT(*f))
  237. n = (n*10) + *f++ - '0';
  238. }
  239. while (*f && *f != '%' && !Py_ISALPHA(*f))
  240. f++;
  241. /* handle the long flag, but only for %ld and %lu.
  242. others can be added when necessary. */
  243. if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
  244. longflag = 1;
  245. ++f;
  246. }
  247. /* handle the size_t flag. */
  248. if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
  249. size_tflag = 1;
  250. ++f;
  251. }
  252. switch (*f) {
  253. case 'c':
  254. {
  255. int c = va_arg(vargs, int);
  256. /* c has been checked for overflow in the first step */
  257. *s++ = (unsigned char)c;
  258. break;
  259. }
  260. case 'd':
  261. if (longflag)
  262. sprintf(s, "%ld", va_arg(vargs, long));
  263. else if (size_tflag)
  264. sprintf(s, "%" PY_FORMAT_SIZE_T "d",
  265. va_arg(vargs, Py_ssize_t));
  266. else
  267. sprintf(s, "%d", va_arg(vargs, int));
  268. s += strlen(s);
  269. break;
  270. case 'u':
  271. if (longflag)
  272. sprintf(s, "%lu",
  273. va_arg(vargs, unsigned long));
  274. else if (size_tflag)
  275. sprintf(s, "%" PY_FORMAT_SIZE_T "u",
  276. va_arg(vargs, size_t));
  277. else
  278. sprintf(s, "%u",
  279. va_arg(vargs, unsigned int));
  280. s += strlen(s);
  281. break;
  282. case 'i':
  283. sprintf(s, "%i", va_arg(vargs, int));
  284. s += strlen(s);
  285. break;
  286. case 'x':
  287. sprintf(s, "%x", va_arg(vargs, int));
  288. s += strlen(s);
  289. break;
  290. case 's':
  291. p = va_arg(vargs, char*);
  292. i = strlen(p);
  293. if (n > 0 && i > n)
  294. i = n;
  295. Py_MEMCPY(s, p, i);
  296. s += i;
  297. break;
  298. case 'p':
  299. sprintf(s, "%p", va_arg(vargs, void*));
  300. /* %p is ill-defined: ensure leading 0x. */
  301. if (s[1] == 'X')
  302. s[1] = 'x';
  303. else if (s[1] != 'x') {
  304. memmove(s+2, s, strlen(s)+1);
  305. s[0] = '0';
  306. s[1] = 'x';
  307. }
  308. s += strlen(s);
  309. break;
  310. case '%':
  311. *s++ = '%';
  312. break;
  313. default:
  314. strcpy(s, p);
  315. s += strlen(s);
  316. goto end;
  317. }
  318. } else
  319. *s++ = *f;
  320. }
  321. end:
  322. _PyBytes_Resize(&string, s - PyBytes_AS_STRING(string));
  323. return string;
  324. }
  325. PyObject *
  326. PyBytes_FromFormat(const char *format, ...)
  327. {
  328. PyObject* ret;
  329. va_list vargs;
  330. #ifdef HAVE_STDARG_PROTOTYPES
  331. va_start(vargs, format);
  332. #else
  333. va_start(vargs);
  334. #endif
  335. ret = PyBytes_FromFormatV(format, vargs);
  336. va_end(vargs);
  337. return ret;
  338. }
  339. static void
  340. bytes_dealloc(PyObject *op)
  341. {
  342. Py_TYPE(op)->tp_free(op);
  343. }
  344. /* Unescape a backslash-escaped string. If unicode is non-zero,
  345. the string is a u-literal. If recode_encoding is non-zero,
  346. the string is UTF-8 encoded and should be re-encoded in the
  347. specified encoding. */
  348. PyObject *PyBytes_DecodeEscape(const char *s,
  349. Py_ssize_t len,
  350. const char *errors,
  351. Py_ssize_t unicode,
  352. const char *recode_encoding)
  353. {
  354. int c;
  355. char *p, *buf;
  356. const char *end;
  357. PyObject *v;
  358. Py_ssize_t newlen = recode_encoding ? 4*len:len;
  359. v = PyBytes_FromStringAndSize((char *)NULL, newlen);
  360. if (v == NULL)
  361. return NULL;
  362. p = buf = PyBytes_AsString(v);
  363. end = s + len;
  364. while (s < end) {
  365. if (*s != '\\') {
  366. non_esc:
  367. if (recode_encoding && (*s & 0x80)) {
  368. PyObject *u, *w;
  369. char *r;
  370. const char* t;
  371. Py_ssize_t rn;
  372. t = s;
  373. /* Decode non-ASCII bytes as UTF-8. */
  374. while (t < end && (*t & 0x80)) t++;
  375. u = PyUnicode_DecodeUTF8(s, t - s, errors);
  376. if(!u) goto failed;
  377. /* Recode them in target encoding. */
  378. w = PyUnicode_AsEncodedString(
  379. u, recode_encoding, errors);
  380. Py_DECREF(u);
  381. if (!w) goto failed;
  382. /* Append bytes to output buffer. */
  383. assert(PyBytes_Check(w));
  384. r = PyBytes_AS_STRING(w);
  385. rn = PyBytes_GET_SIZE(w);
  386. Py_MEMCPY(p, r, rn);
  387. p += rn;
  388. Py_DECREF(w);
  389. s = t;
  390. } else {
  391. *p++ = *s++;
  392. }
  393. continue;
  394. }
  395. s++;
  396. if (s==end) {
  397. PyErr_SetString(PyExc_ValueError,
  398. "Trailing \\ in string");
  399. goto failed;
  400. }
  401. switch (*s++) {
  402. /* XXX This assumes ASCII! */
  403. case '\n': break;
  404. case '\\': *p++ = '\\'; break;
  405. case '\'': *p++ = '\''; break;
  406. case '\"': *p++ = '\"'; break;
  407. case 'b': *p++ = '\b'; break;
  408. case 'f': *p++ = '\014'; break; /* FF */
  409. case 't': *p++ = '\t'; break;
  410. case 'n': *p++ = '\n'; break;
  411. case 'r': *p++ = '\r'; break;
  412. case 'v': *p++ = '\013'; break; /* VT */
  413. case 'a': *p++ = '\007'; break; /* BEL, not classic C */
  414. case '0': case '1': case '2': case '3':
  415. case '4': case '5': case '6': case '7':
  416. c = s[-1] - '0';
  417. if (s < end && '0' <= *s && *s <= '7') {
  418. c = (c<<3) + *s++ - '0';
  419. if (s < end && '0' <= *s && *s <= '7')
  420. c = (c<<3) + *s++ - '0';
  421. }
  422. *p++ = c;
  423. break;
  424. case 'x':
  425. if (s+1 < end && Py_ISXDIGIT(s[0]) && Py_ISXDIGIT(s[1])) {
  426. unsigned int x = 0;
  427. c = Py_CHARMASK(*s);
  428. s++;
  429. if (Py_ISDIGIT(c))
  430. x = c - '0';
  431. else if (Py_ISLOWER(c))
  432. x = 10 + c - 'a';
  433. else
  434. x = 10 + c - 'A';
  435. x = x << 4;
  436. c = Py_CHARMASK(*s);
  437. s++;
  438. if (Py_ISDIGIT(c))
  439. x += c - '0';
  440. else if (Py_ISLOWER(c))
  441. x += 10 + c - 'a';
  442. else
  443. x += 10 + c - 'A';
  444. *p++ = x;
  445. break;
  446. }
  447. if (!errors || strcmp(errors, "strict") == 0) {
  448. PyErr_Format(PyExc_ValueError,
  449. "invalid \\x escape at position %d",
  450. s - 2 - (end - len));
  451. goto failed;
  452. }
  453. if (strcmp(errors, "replace") == 0) {
  454. *p++ = '?';
  455. } else if (strcmp(errors, "ignore") == 0)
  456. /* do nothing */;
  457. else {
  458. PyErr_Format(PyExc_ValueError,
  459. "decoding error; unknown "
  460. "error handling code: %.400s",
  461. errors);
  462. goto failed;
  463. }
  464. /* skip \x */
  465. if (s < end && Py_ISXDIGIT(s[0]))
  466. s++; /* and a hexdigit */
  467. break;
  468. default:
  469. *p++ = '\\';
  470. s--;
  471. goto non_esc; /* an arbitrary number of unescaped
  472. UTF-8 bytes may follow. */
  473. }
  474. }
  475. if (p-buf < newlen)
  476. _PyBytes_Resize(&v, p - buf);
  477. return v;
  478. failed:
  479. Py_DECREF(v);
  480. return NULL;
  481. }
  482. /* -------------------------------------------------------------------- */
  483. /* object api */
  484. Py_ssize_t
  485. PyBytes_Size(register PyObject *op)
  486. {
  487. if (!PyBytes_Check(op)) {
  488. PyErr_Format(PyExc_TypeError,
  489. "expected bytes, %.200s found", Py_TYPE(op)->tp_name);
  490. return -1;
  491. }
  492. return Py_SIZE(op);
  493. }
  494. char *
  495. PyBytes_AsString(register PyObject *op)
  496. {
  497. if (!PyBytes_Check(op)) {
  498. PyErr_Format(PyExc_TypeError,
  499. "expected bytes, %.200s found", Py_TYPE(op)->tp_name);
  500. return NULL;
  501. }
  502. return ((PyBytesObject *)op)->ob_sval;
  503. }
  504. int
  505. PyBytes_AsStringAndSize(register PyObject *obj,
  506. register char **s,
  507. register Py_ssize_t *len)
  508. {
  509. if (s == NULL) {
  510. PyErr_BadInternalCall();
  511. return -1;
  512. }
  513. if (!PyBytes_Check(obj)) {
  514. PyErr_Format(PyExc_TypeError,
  515. "expected bytes, %.200s found", Py_TYPE(obj)->tp_name);
  516. return -1;
  517. }
  518. *s = PyBytes_AS_STRING(obj);
  519. if (len != NULL)
  520. *len = PyBytes_GET_SIZE(obj);
  521. else if (strlen(*s) != (size_t)PyBytes_GET_SIZE(obj)) {
  522. PyErr_SetString(PyExc_TypeError,
  523. "expected bytes with no null");
  524. return -1;
  525. }
  526. return 0;
  527. }
  528. /* -------------------------------------------------------------------- */
  529. /* Methods */
  530. #include "stringlib/stringdefs.h"
  531. #include "stringlib/fastsearch.h"
  532. #include "stringlib/count.h"
  533. #include "stringlib/find.h"
  534. #include "stringlib/partition.h"
  535. #include "stringlib/split.h"
  536. #include "stringlib/ctype.h"
  537. #include "stringlib/transmogrify.h"
  538. PyObject *
  539. PyBytes_Repr(PyObject *obj, int smartquotes)
  540. {
  541. register PyBytesObject* op = (PyBytesObject*) obj;
  542. Py_ssize_t i, length = Py_SIZE(op);
  543. size_t newsize, squotes, dquotes;
  544. PyObject *v;
  545. unsigned char quote, *s, *p;
  546. /* Compute size of output string */
  547. squotes = dquotes = 0;
  548. newsize = 3; /* b'' */
  549. s = (unsigned char*)op->ob_sval;
  550. for (i = 0; i < length; i++) {
  551. switch(s[i]) {
  552. case '\'': squotes++; newsize++; break;
  553. case '"': dquotes++; newsize++; break;
  554. case '\\': case '\t': case '\n': case '\r':
  555. newsize += 2; break; /* \C */
  556. default:
  557. if (s[i] < ' ' || s[i] >= 0x7f)
  558. newsize += 4; /* \xHH */
  559. else
  560. newsize++;
  561. }
  562. }
  563. quote = '\'';
  564. if (smartquotes && squotes && !dquotes)
  565. quote = '"';
  566. if (squotes && quote == '\'')
  567. newsize += squotes;
  568. if (newsize > (PY_SSIZE_T_MAX - sizeof(PyUnicodeObject) - 1)) {
  569. PyErr_SetString(PyExc_OverflowError,
  570. "bytes object is too large to make repr");
  571. return NULL;
  572. }
  573. v = PyUnicode_New(newsize, 127);
  574. if (v == NULL) {
  575. return NULL;
  576. }
  577. p = PyUnicode_1BYTE_DATA(v);
  578. *p++ = 'b', *p++ = quote;
  579. for (i = 0; i < length; i++) {
  580. unsigned char c = op->ob_sval[i];
  581. if (c == quote || c == '\\')
  582. *p++ = '\\', *p++ = c;
  583. else if (c == '\t')
  584. *p++ = '\\', *p++ = 't';
  585. else if (c == '\n')
  586. *p++ = '\\', *p++ = 'n';
  587. else if (c == '\r')
  588. *p++ = '\\', *p++ = 'r';
  589. else if (c < ' ' || c >= 0x7f) {
  590. *p++ = '\\';
  591. *p++ = 'x';
  592. *p++ = Py_hexdigits[(c & 0xf0) >> 4];
  593. *p++ = Py_hexdigits[c & 0xf];
  594. }
  595. else
  596. *p++ = c;
  597. }
  598. *p++ = quote;
  599. assert(_PyUnicode_CheckConsistency(v, 1));
  600. return v;
  601. }
  602. static PyObject *
  603. bytes_repr(PyObject *op)
  604. {
  605. return PyBytes_Repr(op, 1);
  606. }
  607. static PyObject *
  608. bytes_str(PyObject *op)
  609. {
  610. if (Py_BytesWarningFlag) {
  611. if (PyErr_WarnEx(PyExc_BytesWarning,
  612. "str() on a bytes instance", 1))
  613. return NULL;
  614. }
  615. return bytes_repr(op);
  616. }
  617. static Py_ssize_t
  618. bytes_length(PyBytesObject *a)
  619. {
  620. return Py_SIZE(a);
  621. }
  622. /* This is also used by PyBytes_Concat() */
  623. static PyObject *
  624. bytes_concat(PyObject *a, PyObject *b)
  625. {
  626. Py_ssize_t size;
  627. Py_buffer va, vb;
  628. PyObject *result = NULL;
  629. va.len = -1;
  630. vb.len = -1;
  631. if (_getbuffer(a, &va) < 0 ||
  632. _getbuffer(b, &vb) < 0) {
  633. PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
  634. Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
  635. goto done;
  636. }
  637. /* Optimize end cases */
  638. if (va.len == 0 && PyBytes_CheckExact(b)) {
  639. result = b;
  640. Py_INCREF(result);
  641. goto done;
  642. }
  643. if (vb.len == 0 && PyBytes_CheckExact(a)) {
  644. result = a;
  645. Py_INCREF(result);
  646. goto done;
  647. }
  648. size = va.len + vb.len;
  649. if (size < 0) {
  650. PyErr_NoMemory();
  651. goto done;
  652. }
  653. result = PyBytes_FromStringAndSize(NULL, size);
  654. if (result != NULL) {
  655. memcpy(PyBytes_AS_STRING(result), va.buf, va.len);
  656. memcpy(PyBytes_AS_STRING(result) + va.len, vb.buf, vb.len);
  657. }
  658. done:
  659. if (va.len != -1)
  660. PyBuffer_Release(&va);
  661. if (vb.len != -1)
  662. PyBuffer_Release(&vb);
  663. return result;
  664. }
  665. static PyObject *
  666. bytes_repeat(register PyBytesObject *a, register Py_ssize_t n)
  667. {
  668. register Py_ssize_t i;
  669. register Py_ssize_t j;
  670. register Py_ssize_t size;
  671. register PyBytesObject *op;
  672. size_t nbytes;
  673. if (n < 0)
  674. n = 0;
  675. /* watch out for overflows: the size can overflow int,
  676. * and the # of bytes needed can overflow size_t
  677. */
  678. if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n) {
  679. PyErr_SetString(PyExc_OverflowError,
  680. "repeated bytes are too long");
  681. return NULL;
  682. }
  683. size = Py_SIZE(a) * n;
  684. if (size == Py_SIZE(a) && PyBytes_CheckExact(a)) {
  685. Py_INCREF(a);
  686. return (PyObject *)a;
  687. }
  688. nbytes = (size_t)size;
  689. if (nbytes + PyBytesObject_SIZE <= nbytes) {
  690. PyErr_SetString(PyExc_OverflowError,
  691. "repeated bytes are too long");
  692. return NULL;
  693. }
  694. op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + nbytes);
  695. if (op == NULL)
  696. return PyErr_NoMemory();
  697. PyObject_INIT_VAR(op, &PyBytes_Type, size);
  698. op->ob_shash = -1;
  699. op->ob_sval[size] = '\0';
  700. if (Py_SIZE(a) == 1 && n > 0) {
  701. memset(op->ob_sval, a->ob_sval[0] , n);
  702. return (PyObject *) op;
  703. }
  704. i = 0;
  705. if (i < size) {
  706. Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
  707. i = Py_SIZE(a);
  708. }
  709. while (i < size) {
  710. j = (i <= size-i) ? i : size-i;
  711. Py_MEMCPY(op->ob_sval+i, op->ob_sval, j);
  712. i += j;
  713. }
  714. return (PyObject *) op;
  715. }
  716. static int
  717. bytes_contains(PyObject *self, PyObject *arg)
  718. {
  719. Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
  720. if (ival == -1 && PyErr_Occurred()) {
  721. Py_buffer varg;
  722. Py_ssize_t pos;
  723. PyErr_Clear();
  724. if (_getbuffer(arg, &varg) < 0)
  725. return -1;
  726. pos = stringlib_find(PyBytes_AS_STRING(self), Py_SIZE(self),
  727. varg.buf, varg.len, 0);
  728. PyBuffer_Release(&varg);
  729. return pos >= 0;
  730. }
  731. if (ival < 0 || ival >= 256) {
  732. PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
  733. return -1;
  734. }
  735. return memchr(PyBytes_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
  736. }
  737. static PyObject *
  738. bytes_item(PyBytesObject *a, register Py_ssize_t i)
  739. {
  740. if (i < 0 || i >= Py_SIZE(a)) {
  741. PyErr_SetString(PyExc_IndexError, "index out of range");
  742. return NULL;
  743. }
  744. return PyLong_FromLong((unsigned char)a->ob_sval[i]);
  745. }
  746. static PyObject*
  747. bytes_richcompare(PyBytesObject *a, PyBytesObject *b, int op)
  748. {
  749. int c;
  750. Py_ssize_t len_a, len_b;
  751. Py_ssize_t min_len;
  752. PyObject *result;
  753. /* Make sure both arguments are strings. */
  754. if (!(PyBytes_Check(a) && PyBytes_Check(b))) {
  755. if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE) &&
  756. (PyObject_IsInstance((PyObject*)a,
  757. (PyObject*)&PyUnicode_Type) ||
  758. PyObject_IsInstance((PyObject*)b,
  759. (PyObject*)&PyUnicode_Type))) {
  760. if (PyErr_WarnEx(PyExc_BytesWarning,
  761. "Comparison between bytes and string", 1))
  762. return NULL;
  763. }
  764. result = Py_NotImplemented;
  765. goto out;
  766. }
  767. if (a == b) {
  768. switch (op) {
  769. case Py_EQ:case Py_LE:case Py_GE:
  770. result = Py_True;
  771. goto out;
  772. case Py_NE:case Py_LT:case Py_GT:
  773. result = Py_False;
  774. goto out;
  775. }
  776. }
  777. if (op == Py_EQ) {
  778. /* Supporting Py_NE here as well does not save
  779. much time, since Py_NE is rarely used. */
  780. if (Py_SIZE(a) == Py_SIZE(b)
  781. && (a->ob_sval[0] == b->ob_sval[0]
  782. && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0)) {
  783. result = Py_True;
  784. } else {
  785. result = Py_False;
  786. }
  787. goto out;
  788. }
  789. len_a = Py_SIZE(a); len_b = Py_SIZE(b);
  790. min_len = (len_a < len_b) ? len_a : len_b;
  791. if (min_len > 0) {
  792. c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
  793. if (c==0)
  794. c = memcmp(a->ob_sval, b->ob_sval, min_len);
  795. } else
  796. c = 0;
  797. if (c == 0)
  798. c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
  799. switch (op) {
  800. case Py_LT: c = c < 0; break;
  801. case Py_LE: c = c <= 0; break;
  802. case Py_EQ: assert(0); break; /* unreachable */
  803. case Py_NE: c = c != 0; break;
  804. case Py_GT: c = c > 0; break;
  805. case Py_GE: c = c >= 0; break;
  806. default:
  807. result = Py_NotImplemented;
  808. goto out;
  809. }
  810. result = c ? Py_True : Py_False;
  811. out:
  812. Py_INCREF(result);
  813. return result;
  814. }
  815. static Py_hash_t
  816. bytes_hash(PyBytesObject *a)
  817. {
  818. if (a->ob_shash == -1) {
  819. /* Can't fail */
  820. a->ob_shash = _Py_HashBytes((unsigned char *) a->ob_sval, Py_SIZE(a));
  821. }
  822. return a->ob_shash;
  823. }
  824. static PyObject*
  825. bytes_subscript(PyBytesObject* self, PyObject* item)
  826. {
  827. if (PyIndex_Check(item)) {
  828. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  829. if (i == -1 && PyErr_Occurred())
  830. return NULL;
  831. if (i < 0)
  832. i += PyBytes_GET_SIZE(self);
  833. if (i < 0 || i >= PyBytes_GET_SIZE(self)) {
  834. PyErr_SetString(PyExc_IndexError,
  835. "index out of range");
  836. return NULL;
  837. }
  838. return PyLong_FromLong((unsigned char)self->ob_sval[i]);
  839. }
  840. else if (PySlice_Check(item)) {
  841. Py_ssize_t start, stop, step, slicelength, cur, i;
  842. char* source_buf;
  843. char* result_buf;
  844. PyObject* result;
  845. if (PySlice_GetIndicesEx(item,
  846. PyBytes_GET_SIZE(self),
  847. &start, &stop, &step, &slicelength) < 0) {
  848. return NULL;
  849. }
  850. if (slicelength <= 0) {
  851. return PyBytes_FromStringAndSize("", 0);
  852. }
  853. else if (start == 0 && step == 1 &&
  854. slicelength == PyBytes_GET_SIZE(self) &&
  855. PyBytes_CheckExact(self)) {
  856. Py_INCREF(self);
  857. return (PyObject *)self;
  858. }
  859. else if (step == 1) {
  860. return PyBytes_FromStringAndSize(
  861. PyBytes_AS_STRING(self) + start,
  862. slicelength);
  863. }
  864. else {
  865. source_buf = PyBytes_AS_STRING(self);
  866. result = PyBytes_FromStringAndSize(NULL, slicelength);
  867. if (result == NULL)
  868. return NULL;
  869. result_buf = PyBytes_AS_STRING(result);
  870. for (cur = start, i = 0; i < slicelength;
  871. cur += step, i++) {
  872. result_buf[i] = source_buf[cur];
  873. }
  874. return result;
  875. }
  876. }
  877. else {
  878. PyErr_Format(PyExc_TypeError,
  879. "byte indices must be integers, not %.200s",
  880. Py_TYPE(item)->tp_name);
  881. return NULL;
  882. }
  883. }
  884. static int
  885. bytes_buffer_getbuffer(PyBytesObject *self, Py_buffer *view, int flags)
  886. {
  887. return PyBuffer_FillInfo(view, (PyObject*)self, (void *)self->ob_sval, Py_SIZE(self),
  888. 1, flags);
  889. }
  890. static PySequenceMethods bytes_as_sequence = {
  891. (lenfunc)bytes_length, /*sq_length*/
  892. (binaryfunc)bytes_concat, /*sq_concat*/
  893. (ssizeargfunc)bytes_repeat, /*sq_repeat*/
  894. (ssizeargfunc)bytes_item, /*sq_item*/
  895. 0, /*sq_slice*/
  896. 0, /*sq_ass_item*/
  897. 0, /*sq_ass_slice*/
  898. (objobjproc)bytes_contains /*sq_contains*/
  899. };
  900. static PyMappingMethods bytes_as_mapping = {
  901. (lenfunc)bytes_length,
  902. (binaryfunc)bytes_subscript,
  903. 0,
  904. };
  905. static PyBufferProcs bytes_as_buffer = {
  906. (getbufferproc)bytes_buffer_getbuffer,
  907. NULL,
  908. };
  909. #define LEFTSTRIP 0
  910. #define RIGHTSTRIP 1
  911. #define BOTHSTRIP 2
  912. /* Arrays indexed by above */
  913. static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
  914. #define STRIPNAME(i) (stripformat[i]+3)
  915. PyDoc_STRVAR(split__doc__,
  916. "B.split(sep=None, maxsplit=-1) -> list of bytes\n\
  917. \n\
  918. Return a list of the sections in B, using sep as the delimiter.\n\
  919. If sep is not specified or is None, B is split on ASCII whitespace\n\
  920. characters (space, tab, return, newline, formfeed, vertical tab).\n\
  921. If maxsplit is given, at most maxsplit splits are done.");
  922. static PyObject *
  923. bytes_split(PyBytesObject *self, PyObject *args, PyObject *kwds)
  924. {
  925. static char *kwlist[] = {"sep", "maxsplit", 0};
  926. Py_ssize_t len = PyBytes_GET_SIZE(self), n;
  927. Py_ssize_t maxsplit = -1;
  928. const char *s = PyBytes_AS_STRING(self), *sub;
  929. Py_buffer vsub;
  930. PyObject *list, *subobj = Py_None;
  931. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
  932. kwlist, &subobj, &maxsplit))
  933. return NULL;
  934. if (maxsplit < 0)
  935. maxsplit = PY_SSIZE_T_MAX;
  936. if (subobj == Py_None)
  937. return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
  938. if (_getbuffer(subobj, &vsub) < 0)
  939. return NULL;
  940. sub = vsub.buf;
  941. n = vsub.len;
  942. list = stringlib_split((PyObject*) self, s, len, sub, n, maxsplit);
  943. PyBuffer_Release(&vsub);
  944. return list;
  945. }
  946. PyDoc_STRVAR(partition__doc__,
  947. "B.partition(sep) -> (head, sep, tail)\n\
  948. \n\
  949. Search for the separator sep in B, and return the part before it,\n\
  950. the separator itself, and the part after it. If the separator is not\n\
  951. found, returns B and two empty bytes objects.");
  952. static PyObject *
  953. bytes_partition(PyBytesObject *self, PyObject *sep_obj)
  954. {
  955. const char *sep;
  956. Py_ssize_t sep_len;
  957. if (PyBytes_Check(sep_obj)) {
  958. sep = PyBytes_AS_STRING(sep_obj);
  959. sep_len = PyBytes_GET_SIZE(sep_obj);
  960. }
  961. else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
  962. return NULL;
  963. return stringlib_partition(
  964. (PyObject*) self,
  965. PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
  966. sep_obj, sep, sep_len
  967. );
  968. }
  969. PyDoc_STRVAR(rpartition__doc__,
  970. "B.rpartition(sep) -> (head, sep, tail)\n\
  971. \n\
  972. Search for the separator sep in B, starting at the end of B,\n\
  973. and return the part before it, the separator itself, and the\n\
  974. part after it. If the separator is not found, returns two empty\n\
  975. bytes objects and B.");
  976. static PyObject *
  977. bytes_rpartition(PyBytesObject *self, PyObject *sep_obj)
  978. {
  979. const char *sep;
  980. Py_ssize_t sep_len;
  981. if (PyBytes_Check(sep_obj)) {
  982. sep = PyBytes_AS_STRING(sep_obj);
  983. sep_len = PyBytes_GET_SIZE(sep_obj);
  984. }
  985. else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
  986. return NULL;
  987. return stringlib_rpartition(
  988. (PyObject*) self,
  989. PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
  990. sep_obj, sep, sep_len
  991. );
  992. }
  993. PyDoc_STRVAR(rsplit__doc__,
  994. "B.rsplit(sep=None, maxsplit=-1) -> list of bytes\n\
  995. \n\
  996. Return a list of the sections in B, using sep as the delimiter,\n\
  997. starting at the end of B and working to the front.\n\
  998. If sep is not given, B is split on ASCII whitespace characters\n\
  999. (space, tab, return, newline, formfeed, vertical tab).\n\
  1000. If maxsplit is given, at most maxsplit splits are done.");
  1001. static PyObject *
  1002. bytes_rsplit(PyBytesObject *self, PyObject *args, PyObject *kwds)
  1003. {
  1004. static char *kwlist[] = {"sep", "maxsplit", 0};
  1005. Py_ssize_t len = PyBytes_GET_SIZE(self), n;
  1006. Py_ssize_t maxsplit = -1;
  1007. const char *s = PyBytes_AS_STRING(self), *sub;
  1008. Py_buffer vsub;
  1009. PyObject *list, *subobj = Py_None;
  1010. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
  1011. kwlist, &subobj, &maxsplit))
  1012. return NULL;
  1013. if (maxsplit < 0)
  1014. maxsplit = PY_SSIZE_T_MAX;
  1015. if (subobj == Py_None)
  1016. return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
  1017. if (_getbuffer(subobj, &vsub) < 0)
  1018. return NULL;
  1019. sub = vsub.buf;
  1020. n = vsub.len;
  1021. list = stringlib_rsplit((PyObject*) self, s, len, sub, n, maxsplit);
  1022. PyBuffer_Release(&vsub);
  1023. return list;
  1024. }
  1025. PyDoc_STRVAR(join__doc__,
  1026. "B.join(iterable_of_bytes) -> bytes\n\
  1027. \n\
  1028. Concatenate any number of bytes objects, with B in between each pair.\n\
  1029. Example: b'.'.join([b'ab', b'pq', b'rs']) -> b'ab.pq.rs'.");
  1030. static PyObject *
  1031. bytes_join(PyObject *self, PyObject *orig)
  1032. {
  1033. char *sep = PyBytes_AS_STRING(self);
  1034. const Py_ssize_t seplen = PyBytes_GET_SIZE(self);
  1035. PyObject *res = NULL;
  1036. char *p;
  1037. Py_ssize_t seqlen = 0;
  1038. size_t sz = 0;
  1039. Py_ssize_t i;
  1040. PyObject *seq, *item;
  1041. seq = PySequence_Fast(orig, "");
  1042. if (seq == NULL) {
  1043. return NULL;
  1044. }
  1045. seqlen = PySequence_Size(seq);
  1046. if (seqlen == 0) {
  1047. Py_DECREF(seq);
  1048. return PyBytes_FromString("");
  1049. }
  1050. if (seqlen == 1) {
  1051. item = PySequence_Fast_GET_ITEM(seq, 0);
  1052. if (PyBytes_CheckExact(item)) {
  1053. Py_INCREF(item);
  1054. Py_DECREF(seq);
  1055. return item;
  1056. }
  1057. }
  1058. /* There are at least two things to join, or else we have a subclass
  1059. * of the builtin types in the sequence.
  1060. * Do a pre-pass to figure out the total amount of space we'll
  1061. * need (sz), and see whether all argument are bytes.
  1062. */
  1063. /* XXX Shouldn't we use _getbuffer() on these items instead? */
  1064. for (i = 0; i < seqlen; i++) {
  1065. const size_t old_sz = sz;
  1066. item = PySequence_Fast_GET_ITEM(seq, i);
  1067. if (!PyBytes_Check(item) && !PyByteArray_Check(item)) {
  1068. PyErr_Format(PyExc_TypeError,
  1069. "sequence item %zd: expected bytes,"
  1070. " %.80s found",
  1071. i, Py_TYPE(item)->tp_name);
  1072. Py_DECREF(seq);
  1073. return NULL;
  1074. }
  1075. sz += Py_SIZE(item);
  1076. if (i != 0)
  1077. sz += seplen;
  1078. if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
  1079. PyErr_SetString(PyExc_OverflowError,
  1080. "join() result is too long for bytes");
  1081. Py_DECREF(seq);
  1082. return NULL;
  1083. }
  1084. }
  1085. /* Allocate result space. */
  1086. res = PyBytes_FromStringAndSize((char*)NULL, sz);
  1087. if (res == NULL) {
  1088. Py_DECREF(seq);
  1089. return NULL;
  1090. }
  1091. /* Catenate everything. */
  1092. /* I'm not worried about a PyByteArray item growing because there's
  1093. nowhere in this function where we release the GIL. */
  1094. p = PyBytes_AS_STRING(res);
  1095. for (i = 0; i < seqlen; ++i) {
  1096. size_t n;
  1097. char *q;
  1098. if (i) {
  1099. Py_MEMCPY(p, sep, seplen);
  1100. p += seplen;
  1101. }
  1102. item = PySequence_Fast_GET_ITEM(seq, i);
  1103. n = Py_SIZE(item);
  1104. if (PyBytes_Check(item))
  1105. q = PyBytes_AS_STRING(item);
  1106. else
  1107. q = PyByteArray_AS_STRING(item);
  1108. Py_MEMCPY(p, q, n);
  1109. p += n;
  1110. }
  1111. Py_DECREF(seq);
  1112. return res;
  1113. }
  1114. PyObject *
  1115. _PyBytes_Join(PyObject *sep, PyObject *x)
  1116. {
  1117. assert(sep != NULL && PyBytes_Check(sep));
  1118. assert(x != NULL);
  1119. return bytes_join(sep, x);
  1120. }
  1121. /* helper macro to fixup start/end slice values */
  1122. #define ADJUST_INDICES(start, end, len) \
  1123. if (end > len) \
  1124. end = len; \
  1125. else if (end < 0) { \
  1126. end += len; \
  1127. if (end < 0) \
  1128. end = 0; \
  1129. } \
  1130. if (start < 0) { \
  1131. start += len; \
  1132. if (start < 0) \
  1133. start = 0; \
  1134. }
  1135. Py_LOCAL_INLINE(Py_ssize_t)
  1136. bytes_find_internal(PyBytesObject *self, PyObject *args, int dir)
  1137. {
  1138. PyObject *subobj;
  1139. char byte;
  1140. Py_buffer subbuf;
  1141. const char *sub;
  1142. Py_ssize_t sub_len;
  1143. Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
  1144. Py_ssize_t res;
  1145. if (!stringlib_parse_args_finds_byte("find/rfind/index/rindex",
  1146. args, &subobj, &byte, &start, &end))
  1147. return -2;
  1148. if (subobj) {
  1149. if (_getbuffer(subobj, &subbuf) < 0)
  1150. return -2;
  1151. sub = subbuf.buf;
  1152. sub_len = subbuf.len;
  1153. }
  1154. else {
  1155. sub = &byte;
  1156. sub_len = 1;
  1157. }
  1158. if (dir > 0)
  1159. res = stringlib_find_slice(
  1160. PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
  1161. sub, sub_len, start, end);
  1162. else
  1163. res = stringlib_rfind_slice(
  1164. PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
  1165. sub, sub_len, start, end);
  1166. if (subobj)
  1167. PyBuffer_Release(&subbuf);
  1168. return res;
  1169. }
  1170. PyDoc_STRVAR(find__doc__,
  1171. "B.find(sub[, start[, end]]) -> int\n\
  1172. \n\
  1173. Return the lowest index in B where substring sub is found,\n\
  1174. such that sub is contained within B[start:end]. Optional\n\
  1175. arguments start and end are interpreted as in slice notation.\n\
  1176. \n\
  1177. Return -1 on failure.");
  1178. static PyObject *
  1179. bytes_find(PyBytesObject *self, PyObject *args)
  1180. {
  1181. Py_ssize_t result = bytes_find_internal(self, args, +1);
  1182. if (result == -2)
  1183. return NULL;
  1184. return PyLong_FromSsize_t(result);
  1185. }
  1186. PyDoc_STRVAR(index__doc__,
  1187. "B.index(sub[, start[, end]]) -> int\n\
  1188. \n\
  1189. Like B.find() but raise ValueError when the substring is not found.");
  1190. static PyObject *
  1191. bytes_index(PyBytesObject *self, PyObject *args)
  1192. {
  1193. Py_ssize_t result = bytes_find_internal(self, args, +1);
  1194. if (result == -2)
  1195. return NULL;
  1196. if (result == -1) {
  1197. PyErr_SetString(PyExc_ValueError,
  1198. "substring not found");
  1199. return NULL;
  1200. }
  1201. return PyLong_FromSsize_t(result);
  1202. }
  1203. PyDoc_STRVAR(rfind__doc__,
  1204. "B.rfind(sub[, start[, end]]) -> int\n\
  1205. \n\
  1206. Return the highest index in B where substring sub is found,\n\
  1207. such that sub is contained within B[start:end]. Optional\n\
  1208. arguments start and end are interpreted as in slice notation.\n\
  1209. \n\
  1210. Return -1 on failure.");
  1211. static PyObject *
  1212. bytes_rfind(PyBytesObject *self, PyObject *args)
  1213. {
  1214. Py_ssize_t result = bytes_find_internal(self, args, -1);
  1215. if (result == -2)
  1216. return NULL;
  1217. return PyLong_FromSsize_t(result);
  1218. }
  1219. PyDoc_STRVAR(rindex__doc__,
  1220. "B.rindex(sub[, start[, end]]) -> int\n\
  1221. \n\
  1222. Like B.rfind() but raise ValueError when the substring is not found.");
  1223. static PyObject *
  1224. bytes_rindex(PyBytesObject *self, PyObject *args)
  1225. {
  1226. Py_ssize_t result = bytes_find_internal(self, args, -1);
  1227. if (result == -2)
  1228. return NULL;
  1229. if (result == -1) {
  1230. PyErr_SetString(PyExc_ValueError,
  1231. "substring not found");
  1232. return NULL;
  1233. }
  1234. return PyLong_FromSsize_t(result);
  1235. }
  1236. Py_LOCAL_INLINE(PyObject *)
  1237. do_xstrip(PyBytesObject *self, int striptype, PyObject *sepobj)
  1238. {
  1239. Py_buffer vsep;
  1240. char *s = PyBytes_AS_STRING(self);
  1241. Py_ssize_t len = PyBytes_GET_SIZE(self);
  1242. char *sep;
  1243. Py_ssize_t seplen;
  1244. Py_ssize_t i, j;
  1245. if (_getbuffer(sepobj, &vsep) < 0)
  1246. return NULL;
  1247. sep = vsep.buf;
  1248. seplen = vsep.len;
  1249. i = 0;
  1250. if (striptype != RIGHTSTRIP) {
  1251. while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) {
  1252. i++;
  1253. }
  1254. }
  1255. j = len;
  1256. if (striptype != LEFTSTRIP) {
  1257. do {
  1258. j--;
  1259. } while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen));
  1260. j++;
  1261. }
  1262. PyBuffer_Release(&vsep);
  1263. if (i == 0 && j == len && PyBytes_CheckExact(self)) {
  1264. Py_INCREF(self);
  1265. return (PyObject*)self;
  1266. }
  1267. else
  1268. return PyBytes_FromStringAndSize(s+i, j-i);
  1269. }
  1270. Py_LOCAL_INLINE(PyObject *)
  1271. do_strip(PyBytesObject *self, int striptype)
  1272. {
  1273. char *s = PyBytes_AS_STRING(self);
  1274. Py_ssize_t len = PyBytes_GET_SIZE(self), i, j;
  1275. i = 0;
  1276. if (striptype != RIGHTSTRIP) {
  1277. while (i < len && Py_ISSPACE(s[i])) {
  1278. i++;
  1279. }
  1280. }
  1281. j = len;
  1282. if (striptype != LEFTSTRIP) {
  1283. do {
  1284. j--;
  1285. } while (j >= i && Py_ISSPACE(s[j]));
  1286. j++;
  1287. }
  1288. if (i == 0 && j == len && PyBytes_CheckExact(self)) {
  1289. Py_INCREF(self);
  1290. return (PyObject*)self;
  1291. }
  1292. else
  1293. return PyBytes_FromStringAndSize(s+i, j-i);
  1294. }
  1295. Py_LOCAL_INLINE(PyObject *)
  1296. do_argstrip(PyBytesObject *self, int striptype, PyObject *args)
  1297. {
  1298. PyObject *sep = NULL;
  1299. if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
  1300. return NULL;
  1301. if (sep != NULL && sep != Py_None) {
  1302. return do_xstrip(self, striptype, sep);
  1303. }
  1304. return do_strip(self, striptype);
  1305. }
  1306. PyDoc_STRVAR(strip__doc__,
  1307. "B.strip([bytes]) -> bytes\n\
  1308. \n\
  1309. Strip leading and trailing bytes contained in the argument.\n\
  1310. If the argument is omitted, strip leading and trailing ASCII whitespace.");
  1311. static PyObject *
  1312. bytes_strip(PyBytesObject *self, PyObject *args)
  1313. {
  1314. if (PyTuple_GET_SIZE(args) == 0)
  1315. return do_strip(self, BOTHSTRIP); /* Common case */
  1316. else
  1317. return do_argstrip(self, BOTHSTRIP, args);
  1318. }
  1319. PyDoc_STRVAR(lstrip__doc__,
  1320. "B.lstrip([bytes]) -> bytes\n\
  1321. \n\
  1322. Strip leading bytes contained in the argument.\n\
  1323. If the argument is omitted, strip leading ASCII whitespace.");
  1324. static PyObject *
  1325. bytes_lstrip(PyBytesObject *self, PyObject *args)
  1326. {
  1327. if (PyTuple_GET_SIZE(args) == 0)
  1328. return do_strip(self, LEFTSTRIP); /* Common case */
  1329. else
  1330. return do_argstrip(self, LEFTSTRIP, args);
  1331. }
  1332. PyDoc_STRVAR(rstrip__doc__,
  1333. "B.rstrip([bytes]) -> bytes\n\
  1334. \n\
  1335. Strip trailing bytes contained in the argument.\n\
  1336. If the argument is omitted, strip trailing ASCII whitespace.");
  1337. static PyObject *
  1338. bytes_rstrip(PyBytesObject *self, PyObject *args)
  1339. {
  1340. if (PyTuple_GET_SIZE(args) == 0)
  1341. return do_strip(self, RIGHTSTRIP); /* Common case */
  1342. else
  1343. return do_argstrip(self, RIGHTSTRIP, args);
  1344. }
  1345. PyDoc_STRVAR(count__doc__,
  1346. "B.count(sub[, start[, end]]) -> int\n\
  1347. \n\
  1348. Return the number of non-overlapping occurrences of substring sub in\n\
  1349. string B[start:end]. Optional arguments start and end are interpreted\n\
  1350. as in slice notation.");
  1351. static PyObject *
  1352. bytes_count(PyBytesObject *self, PyObject *args)
  1353. {
  1354. PyObject *sub_obj;
  1355. const char *str = PyBytes_AS_STRING(self), *sub;
  1356. Py_ssize_t sub_len;
  1357. char byte;
  1358. Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
  1359. Py_buffer vsub;
  1360. PyObject *count_obj;
  1361. if (!stringlib_parse_args_finds_byte("count", args, &sub_obj, &byte,
  1362. &start, &end))
  1363. return NULL;
  1364. if (sub_obj) {
  1365. if (_getbuffer(sub_obj, &vsub) < 0)
  1366. return NULL;
  1367. sub = vsub.buf;
  1368. sub_len = vsub.len;
  1369. }
  1370. else {
  1371. sub = &byte;
  1372. sub_len = 1;
  1373. }
  1374. ADJUST_INDICES(start, end, PyBytes_GET_SIZE(self));
  1375. count_obj = PyLong_FromSsize_t(
  1376. stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX)
  1377. );
  1378. if (sub_obj)
  1379. PyBuffer_Release(&vsub);
  1380. return count_obj;
  1381. }
  1382. PyDoc_STRVAR(translate__doc__,
  1383. "B.translate(table[, deletechars]) -> bytes\n\
  1384. \n\
  1385. Return a copy of B, where all characters occurring in the\n\
  1386. optional argument deletechars are removed, and the remaining\n\
  1387. characters have been mapped through the given translation\n\
  1388. table, which must be a bytes object of length 256.");
  1389. static PyObject *
  1390. bytes_translate(PyBytesObject *self, PyObject *args)
  1391. {
  1392. register char *input, *output;
  1393. const char *table;
  1394. register Py_ssize_t i, c, changed = 0;
  1395. PyObject *input_obj = (PyObject*)self;
  1396. const char *output_start, *del_table=NULL;
  1397. Py_ssize_t inlen, tablen, dellen = 0;
  1398. PyObject *result;
  1399. int trans_table[256];
  1400. PyObject *tableobj, *delobj = NULL;
  1401. if (!PyArg_UnpackTuple(args, "translate", 1, 2,
  1402. &tableobj, &delobj))
  1403. return NULL;
  1404. if (PyBytes_Check(tableobj)) {
  1405. table = PyBytes_AS_STRING(tableobj);
  1406. tablen = PyBytes_GET_SIZE(tableobj);
  1407. }
  1408. else if (tableobj == Py_None) {
  1409. table = NULL;
  1410. tablen = 256;
  1411. }
  1412. else if (PyObject_AsCharBuffer(tableobj, &table, &tablen))
  1413. return NULL;
  1414. if (tablen != 256) {
  1415. PyErr_SetString(PyExc_ValueError,
  1416. "translation table must be 256 characters long");
  1417. return NULL;
  1418. }
  1419. if (delobj != NULL) {
  1420. if (PyBytes_Check(delobj)) {
  1421. del_table = PyBytes_AS_STRING(delobj);
  1422. dellen = PyBytes_GET_SIZE(delobj);
  1423. }
  1424. else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen))
  1425. return NULL;
  1426. }
  1427. else {
  1428. del_table = NULL;
  1429. dellen = 0;
  1430. }
  1431. inlen = PyBytes_GET_SIZE(input_obj);
  1432. result = PyBytes_FromStringAndSize((char *)NULL, inlen);
  1433. if (result == NULL)
  1434. return NULL;
  1435. output_start = output = PyBytes_AsString(result);
  1436. input = PyBytes_AS_STRING(input_obj);
  1437. if (dellen == 0 && table != NULL) {
  1438. /* If no deletions are required, use faster code */
  1439. for (i = inlen; --i >= 0; ) {
  1440. c = Py_CHARMASK(*input++);
  1441. if (Py_CHARMASK((*output++ = table[c])) != c)
  1442. changed = 1;
  1443. }
  1444. if (changed || !PyBytes_CheckExact(input_obj))
  1445. return result;
  1446. Py_DECREF(result);
  1447. Py_INCREF(input_obj);
  1448. return input_obj;
  1449. }
  1450. if (table == NULL) {
  1451. for (i = 0; i < 256; i++)
  1452. trans_table[i] = Py_CHARMASK(i);
  1453. } else {
  1454. for (i = 0; i < 256; i++)
  1455. trans_table[i] = Py_CHARMASK(table[i]);
  1456. }
  1457. for (i = 0; i < dellen; i++)
  1458. trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
  1459. for (i = inlen; --i >= 0; ) {
  1460. c = Py_CHARMASK(*input++);
  1461. if (trans_table[c] != -1)
  1462. if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
  1463. continue;
  1464. changed = 1;
  1465. }
  1466. if (!changed && PyBytes_CheckExact(input_obj)) {
  1467. Py_DECREF(result);
  1468. Py_INCREF(input_obj);
  1469. return input_obj;
  1470. }
  1471. /* Fix the size of the resulting string */
  1472. if (inlen > 0)
  1473. _PyBytes_Resize(&result, output - output_start);
  1474. return result;
  1475. }
  1476. static PyObject *
  1477. bytes_maketrans(PyObject *null, PyObject *args)
  1478. {
  1479. return _Py_bytes_maketrans(args);
  1480. }
  1481. /* find and count characters and substrings */
  1482. #define findchar(target, target_len, c) \
  1483. ((char *)memchr((const void *)(target), c, target_len))
  1484. /* String ops must return a string. */
  1485. /* If the object is subclass of string, create a copy */
  1486. Py_LOCAL(PyBytesObject *)
  1487. return_self(PyBytesObject *self)
  1488. {
  1489. if (PyBytes_CheckExact(self)) {
  1490. Py_INCREF(self);
  1491. return self;
  1492. }
  1493. return (PyBytesObject *)PyBytes_FromStringAndSize(
  1494. PyBytes_AS_STRING(self),
  1495. PyBytes_GET_SIZE(self));
  1496. }
  1497. Py_LOCAL_INLINE(Py_ssize_t)
  1498. countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
  1499. {
  1500. Py_ssize_t count=0;
  1501. const char *start=target;
  1502. const char *end=target+target_len;
  1503. while ( (start=findchar(start, end-start, c)) != NULL ) {
  1504. count++;
  1505. if (count >= maxcount)
  1506. break;
  1507. start += 1;
  1508. }
  1509. return count;
  1510. }
  1511. /* Algorithms for different cases of string replacement */
  1512. /* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
  1513. Py_LOCAL(PyBytesObject *)
  1514. replace_interleave(PyBytesObject *self,
  1515. const char *to_s, Py_ssize_t to_len,
  1516. Py_ssize_t maxcount)
  1517. {
  1518. char *self_s, *result_s;
  1519. Py_ssize_t self_len, result_len;
  1520. Py_ssize_t count, i;
  1521. PyBytesObject *result;
  1522. self_len = PyBytes_GET_SIZE(self);
  1523. /* 1 at the end plus 1 after every character;
  1524. count = min(maxcount, self_len + 1) */
  1525. if (maxcount <= self_len)
  1526. count = maxcount;
  1527. else
  1528. /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
  1529. count = self_len + 1;
  1530. /* Check for overflow */
  1531. /* result_len = count * to_len + self_len; */
  1532. assert(count > 0);
  1533. if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
  1534. PyErr_SetString(PyExc_OverflowError,
  1535. "replacement bytes are too long");
  1536. return NULL;
  1537. }
  1538. result_len = count * to_len + self_len;
  1539. if (! (result = (PyBytesObject *)
  1540. PyBytes_FromStringAndSize(NULL, result_len)) )
  1541. return NULL;
  1542. self_s = PyBytes_AS_STRING(self);
  1543. result_s = PyBytes_AS_STRING(result);
  1544. /* TODO: special case single character, which doesn't need memcpy */
  1545. /* Lay the first one down (guaranteed this will occur) */
  1546. Py_MEMCPY(result_s, to_s, to_len);
  1547. result_s += to_len;
  1548. count -= 1;
  1549. for (i=0; i<count; i++) {
  1550. *result_s++ = *self_s++;
  1551. Py_MEMCPY(result_s, to_s, to_len);
  1552. result_s += to_len;
  1553. }
  1554. /* Copy the rest of the original string */
  1555. Py_MEMCPY(result_s, self_s, self_len-i);
  1556. return result;
  1557. }
  1558. /* Special case for deleting a single character */
  1559. /* len(self)>=1, len(from)==1, to="", maxcount>=1 */
  1560. Py_LOCAL(PyBytesObject *)
  1561. replace_delete_single_character(PyBytesObject *self,
  1562. char from_c, Py_ssize_t maxcount)
  1563. {
  1564. char *self_s, *result_s;
  1565. char *start, *next, *end;
  1566. Py_ssize_t self_len, result_len;
  1567. Py_ssize_t count;
  1568. PyBytesObject *result;
  1569. self_len = PyBytes_GET_SIZE(self);
  1570. self_s = PyBytes_AS_STRING(self);
  1571. count = countchar(self_s, self_len, from_c, maxcount);
  1572. if (count == 0) {
  1573. return return_self(self);
  1574. }
  1575. result_len = self_len - count; /* from_len == 1 */
  1576. assert(result_len>=0);
  1577. if ( (result = (PyBytesObject *)
  1578. PyBytes_FromStringAndSize(NULL, result_len)) == NULL)
  1579. return NULL;
  1580. result_s = PyBytes_AS_STRING(result);
  1581. start = self_s;
  1582. end = self_s + self_len;
  1583. while (count-- > 0) {
  1584. next = findchar(start, end-start, from_c);
  1585. if (next == NULL)
  1586. break;
  1587. Py_MEMCPY(result_s, start, next-start);
  1588. result_s += (next-start);
  1589. start = next+1;
  1590. }
  1591. Py_MEMCPY(result_s, start, end-start);
  1592. return result;
  1593. }
  1594. /* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
  1595. Py_LOCAL(PyBytesObject *)
  1596. replace_delete_substring(PyBytesObject *self,
  1597. const char *from_s, Py_ssize_t from_len,
  1598. Py_ssize_t maxcount) {
  1599. char *self_s, *result_s;
  1600. char *start, *next, *end;
  1601. Py_ssize_t self_len, result_len;
  1602. Py_ssize_t count, offset;
  1603. PyBytesObject *result;
  1604. self_len = PyBytes_GET_SIZE(self);
  1605. self_s = PyBytes_AS_STRING(self);
  1606. count = stringlib_count(self_s, self_len,
  1607. from_s, from_len,
  1608. maxcount);
  1609. if (count == 0) {
  1610. /* no matches */
  1611. return return_self(self);
  1612. }
  1613. result_len = self_len - (count * from_len);
  1614. assert (result_len>=0);
  1615. if ( (result = (PyBytesObject *)
  1616. PyBytes_FromStringAndSize(NULL, result_len)) == NULL )
  1617. return NULL;
  1618. result_s = PyBytes_AS_STRING(result);
  1619. start = self_s;
  1620. end = self_s + self_len;
  1621. while (count-- > 0) {
  1622. offset = stringlib_find(start, end-start,
  1623. from_s, from_len,
  1624. 0);
  1625. if (offset == -1)
  1626. break;
  1627. next = start + offset;
  1628. Py_MEMCPY(result_s, start, next-start);
  1629. result_s += (next-start);
  1630. start = next+from_len;
  1631. }
  1632. Py_MEMCPY(result_s, start, end-start);
  1633. return result;
  1634. }
  1635. /* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
  1636. Py_LOCAL(PyBytesObject *)
  1637. replace_single_character_in_place(PyBytesObject *self,
  1638. char from_c, char to_c,
  1639. Py_ssize_t maxcount)
  1640. {
  1641. char *self_s, *result_s, *start, *end, *next;
  1642. Py_ssize_t self_len;
  1643. PyBytesObject *result;
  1644. /* The result string will be the same size */
  1645. self_s = PyBytes_AS_STRING(self);
  1646. self_len = PyBytes_GET_SIZE(self);
  1647. next = findchar(self_s, self_len, from_c);
  1648. if (next == NULL) {
  1649. /* No matches; return the original string */
  1650. return return_self(self);
  1651. }
  1652. /* Need to make a new string */
  1653. result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len);
  1654. if (result == NULL)
  1655. return NULL;
  1656. result_s = PyBytes_AS_STRING(result);
  1657. Py_MEMCPY(result_s, self_s, self_len);
  1658. /* change everything in-place, starting with this one */
  1659. start = result_s + (next-self_s);
  1660. *start = to_c;
  1661. start++;
  1662. end = result_s + self_len;
  1663. while (--maxcount > 0) {
  1664. next = findchar(start, end-start, from_c);
  1665. if (next == NULL)
  1666. break;
  1667. *next = to_c;
  1668. start = next+1;
  1669. }
  1670. return result;
  1671. }
  1672. /* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
  1673. Py_LOCAL(PyBytesObject *)
  1674. replace_substring_in_place(PyBytesObject *self,
  1675. const char *from_s, Py_ssize_t from_len,
  1676. const char *to_s, Py_ssize_t to_len,
  1677. Py_ssize_t maxcount)
  1678. {
  1679. char *result_s, *start, *end;
  1680. char *self_s;
  1681. Py_ssize_t self_len, offset;
  1682. PyBytesObject *result;
  1683. /* The result string will be the same size */
  1684. self_s = PyBytes_AS_STRING(self);
  1685. self_len = PyBytes_GET_SIZE(self);
  1686. offset = stringlib_find(self_s, self_len,
  1687. from_s, from_len,
  1688. 0);
  1689. if (offset == -1) {
  1690. /* No matches; return the original string */
  1691. return return_self(self);
  1692. }
  1693. /* Need to make a new string */
  1694. result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len);
  1695. if (result == NULL)
  1696. return NULL;
  1697. result_s = PyBytes_AS_STRING(result);
  1698. Py_MEMCPY(result_s, self_s, self_len);
  1699. /* change everything in-place, starting with this one */
  1700. start = result_s + offset;
  1701. Py_MEMCPY(start, to_s, from_len);
  1702. start += from_len;
  1703. end = result_s + self_len;
  1704. while ( --maxcount > 0) {
  1705. offset = stringlib_find(start, end-start,
  1706. from_s, from_len,
  1707. 0);
  1708. if (offset==-1)
  1709. break;
  1710. Py_MEMCPY(start+offset, to_s, from_len);
  1711. start += offset+from_len;
  1712. }
  1713. return result;
  1714. }
  1715. /* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
  1716. Py_LOCAL(PyBytesObject *)
  1717. replace_single_character(PyBytesObject *self,
  1718. char from_c,
  1719. const char *to_s, Py_ssize_t to_len,
  1720. Py_ssize_t maxcount)
  1721. {
  1722. char *self_s, *result_s;
  1723. char *start, *next, *end;
  1724. Py_ssize_t self_len, result_len;
  1725. Py_ssize_t count;
  1726. PyBytesObject *result;
  1727. self_s = PyBytes_AS_STRING(self);
  1728. self_len = PyBytes_GET_SIZE(self);
  1729. count = countchar(self_s, self_len, from_c, maxcount);
  1730. if (count == 0) {
  1731. /* no matches, return unchanged */
  1732. return return_self(self);
  1733. }
  1734. /* use the difference between current and new, hence the "-1" */
  1735. /* result_len = self_len + count * (to_len-1) */
  1736. assert(count > 0);
  1737. if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
  1738. PyErr_SetString(PyExc_OverflowError,
  1739. "replacement bytes are too long");
  1740. return NULL;
  1741. }
  1742. result_len = self_len + count * (to_len - 1);
  1743. if ( (result = (PyBytesObject *)
  1744. PyBytes_FromStringAndSize(NULL, result_len)) == NULL)
  1745. return NULL;
  1746. result_s = PyBytes_AS_STRING(result);
  1747. start = self_s;
  1748. end = self_s + self_len;
  1749. while (count-- > 0) {
  1750. next = findchar(start, end-start, from_c);
  1751. if (next == NULL)
  1752. break;
  1753. if (next == start) {
  1754. /* replace with the 'to' */
  1755. Py_MEMCPY(result_s, to_s, to_len);
  1756. result_s += to_len;
  1757. start += 1;
  1758. } else {
  1759. /* copy the unchanged old then the 'to' */
  1760. Py_MEMCPY(result_s, start, next-start);
  1761. result_s += (next-start);
  1762. Py_MEMCPY(result_s, to_s, to_len);
  1763. result_s += to_len;
  1764. start = next+1;
  1765. }
  1766. }
  1767. /* Copy the remainder of the remaining string */
  1768. Py_MEMCPY(result_s, start, end-start);
  1769. return result;
  1770. }
  1771. /* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
  1772. Py_LOCAL(PyBytesObject *)
  1773. replace_substring(PyBytesObject *self,
  1774. const char *from_s, Py_ssize_t from_len,
  1775. const char *to_s, Py_ssize_t to_len,
  1776. Py_ssize_t maxcount) {
  1777. char *self_s, *result_s;
  1778. char *start, *next, *end;
  1779. Py_ssize_t self_len, result_len;
  1780. Py_ssize_t count, offset;
  1781. PyBytesObject *result;
  1782. self_s = PyBytes_AS_STRING(self);
  1783. self_len = PyBytes_GET_SIZE(self);
  1784. count = stringlib_count(self_s, self_len,
  1785. from_s, from_len,
  1786. maxcount);
  1787. if (count == 0) {
  1788. /* no matches, return unchanged */
  1789. return return_self(self);
  1790. }
  1791. /* Check for overflow */
  1792. /* result_len = self_len + count * (to_len-from_len) */
  1793. assert(count > 0);
  1794. if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
  1795. PyErr_SetString(PyExc_OverflowError,
  1796. "replacement bytes are too long");
  1797. return NULL;
  1798. }
  1799. result_len = self_len + count * (to_len-from_len);
  1800. if ( (result = (PyBytesObject *)
  1801. PyBytes_FromStringAndSize(NULL, result_len)) == NULL)
  1802. return NULL;
  1803. result_s = PyBytes_AS_STRING(result);
  1804. start = self_s;
  1805. end = self_s + self_len;
  1806. while (count-- > 0) {
  1807. offset = stringlib_find(start, end-start,
  1808. from_s, from_len,
  1809. 0);
  1810. if (offset == -1)
  1811. break;
  1812. next = start+offset;
  1813. if (next == start) {
  1814. /* replace with the 'to' */
  1815. Py_MEMCPY(result_s, to_s, to_len);
  1816. result_s += to_len;
  1817. start += from_len;
  1818. } else {
  1819. /* copy the unchanged old then the 'to' */
  1820. Py_MEMCPY(result_s, start, next-start);
  1821. result_s += (next-start);
  1822. Py_MEMCPY(result_s, to_s, to_len);
  1823. result_s += to_len;
  1824. start = next+from_len;
  1825. }
  1826. }
  1827. /* Copy the remainder of the remaining string */
  1828. Py_MEMCPY(result_s, start, end-start);
  1829. return result;
  1830. }
  1831. Py_LOCAL(PyBytesObject *)
  1832. replace(PyBytesObject *self,
  1833. const char *from_s, Py_ssize_t from_len,
  1834. const char *to_s, Py_ssize_t to_len,
  1835. Py_ssize_t maxcount)
  1836. {
  1837. if (maxcount < 0) {
  1838. maxcount = PY_SSIZE_T_MAX;
  1839. } else if (maxcount == 0 || PyBytes_GET_SIZE(self) == 0) {
  1840. /* nothing to do; return the original string */
  1841. return return_self(self);
  1842. }
  1843. if (maxcount == 0 ||
  1844. (from_len == 0 && to_len == 0)) {
  1845. /* nothing to do; return the original string */
  1846. return return_self(self);
  1847. }
  1848. /* Handle zero-length special cases */
  1849. if (from_len == 0) {
  1850. /* insert the 'to' string everywhere. */
  1851. /* >>> "Python".replace("", ".") */
  1852. /* '.P.y.t.h.o.n.' */
  1853. return replace_interleave(self, to_s, to_len, maxcount);
  1854. }
  1855. /* Except for "".replace("", "A") == "A" there is no way beyond this */
  1856. /* point for an empty self string to generate a non-empty string */
  1857. /* Special case so the remaining code always gets a non-empty string */
  1858. if (PyBytes_GET_SIZE(self) == 0) {
  1859. return return_self(self);
  1860. }
  1861. if (to_len == 0) {
  1862. /* delete all occurrences of 'from' string */
  1863. if (from_len == 1) {
  1864. return replace_delete_single_character(
  1865. self, from_s[0], maxcount);
  1866. } else {
  1867. return replace_delete_substring(self, from_s,
  1868. from_len, maxcount);
  1869. }
  1870. }
  1871. /* Handle special case where both strings have the same length */
  1872. if (from_len == to_len) {
  1873. if (from_len == 1) {
  1874. return replace_single_character_in_place(
  1875. self,
  1876. from_s[0],
  1877. to_s[0],
  1878. maxcount);
  1879. } else {
  1880. return replace_substring_in_place(
  1881. self, from_s, from_len, to_s, to_len,
  1882. maxcount);
  1883. }
  1884. }
  1885. /* Otherwise use the more generic algorithms */
  1886. if (from_len == 1) {
  1887. return replace_single_character(self, from_s[0],
  1888. to_s, to_len, maxcount);
  1889. } else {
  1890. /* len('from')>=2, len('to')>=1 */
  1891. return replace_substring(self, from_s, from_len, to_s, to_len,
  1892. maxcount);
  1893. }
  1894. }
  1895. PyDoc_STRVAR(replace__doc__,
  1896. "B.replace(old, new[, count]) -> bytes\n\
  1897. \n\
  1898. Return a copy of B with all occurrences of subsection\n\
  1899. old replaced by new. If the optional argument count is\n\
  1900. given, only first count occurances are replaced.");
  1901. static PyObject *
  1902. bytes_replace(PyBytesObject *self, PyObject *args)
  1903. {
  1904. Py_ssize_t count = -1;
  1905. PyObject *from, *to;
  1906. const char *from_s, *to_s;
  1907. Py_ssize_t from_len, to_len;
  1908. if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
  1909. return NULL;
  1910. if (PyBytes_Check(from)) {
  1911. from_s = PyBytes_AS_STRING(from);
  1912. from_len = PyBytes_GET_SIZE(from);
  1913. }
  1914. else if (PyObject_AsCharBuffer(from, &from_s, &from_len))
  1915. return NULL;
  1916. if (PyBytes_Check(to)) {
  1917. to_s = PyBytes_AS_STRING(to);
  1918. to_len = PyBytes_GET_SIZE(to);
  1919. }
  1920. else if (PyObject_AsCharBuffer(to, &to_s, &to_len))
  1921. return NULL;
  1922. return (PyObject *)replace((PyBytesObject *) self,
  1923. from_s, from_len,
  1924. to_s, to_len, count);
  1925. }
  1926. /** End DALKE **/
  1927. /* Matches the end (direction >= 0) or start (direction < 0) of self
  1928. * against substr, using the start and end arguments. Returns
  1929. * -1 on error, 0 if not found and 1 if found.
  1930. */
  1931. Py_LOCAL(int)
  1932. _bytes_tailmatch(PyBytesObject *self, PyObject *substr, Py_ssize_t start,
  1933. Py_ssize_t end, int direction)
  1934. {
  1935. Py_ssize_t len = PyBytes_GET_SIZE(self);
  1936. Py_ssize_t slen;
  1937. const char* sub;
  1938. const char* str;
  1939. if (PyBytes_Check(substr)) {
  1940. sub = PyBytes_AS_STRING(substr);
  1941. slen = PyBytes_GET_SIZE(substr);
  1942. }
  1943. else if (PyObject_AsCharBuffer(substr, &sub, &slen))
  1944. return -1;
  1945. str = PyBytes_AS_STRING(self);
  1946. ADJUST_INDICES(start, end, len);
  1947. if (direction < 0) {
  1948. /* startswith */
  1949. if (start+slen > len)
  1950. return 0;
  1951. } else {
  1952. /* endswith */
  1953. if (end-start < slen || start > len)
  1954. return 0;
  1955. if (end-slen > start)
  1956. start = end - slen;
  1957. }
  1958. if (end-start >= slen)
  1959. return ! memcmp(str+start, sub, slen);
  1960. return 0;
  1961. }
  1962. PyDoc_STRVAR(startswith__doc__,
  1963. "B.startswith(prefix[, start[, end]]) -> bool\n\
  1964. \n\
  1965. Return True if B starts with the specified prefix, False otherwise.\n\
  1966. With optional start, test B beginning at that position.\n\
  1967. With optional end, stop comparing B at that position.\n\
  1968. prefix can also be a tuple of bytes to try.");
  1969. static PyObject *
  1970. bytes_startswith(PyBytesObject *self, PyObject *args)
  1971. {
  1972. Py_ssize_t start = 0;
  1973. Py_ssize_t end = PY_SSIZE_T_MAX;
  1974. PyObject *subobj;
  1975. int result;
  1976. if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
  1977. return NULL;
  1978. if (PyTuple_Check(subobj)) {
  1979. Py_ssize_t i;
  1980. for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
  1981. result = _bytes_tailmatch(self,
  1982. PyTuple_GET_ITEM(subobj, i),
  1983. start, end, -1);
  1984. if (result == -1)
  1985. return NULL;
  1986. else if (result) {
  1987. Py_RETURN_TRUE;
  1988. }
  1989. }
  1990. Py_RETURN_FALSE;
  1991. }
  1992. result = _bytes_tailmatch(self, subobj, start, end, -1);
  1993. if (result == -1) {
  1994. if (PyErr_ExceptionMatches(PyExc_TypeError))
  1995. PyErr_Format(PyExc_TypeError, "startswith first arg must be bytes "
  1996. "or a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
  1997. return NULL;
  1998. }
  1999. else
  2000. return PyBool_FromLong(result);
  2001. }
  2002. PyDoc_STRVAR(endswith__doc__,
  2003. "B.endswith(suffix[, start[, end]]) -> bool\n\
  2004. \n\
  2005. Return True if B ends with the specified suffix, False otherwise.\n\
  2006. With optional start, test B beginning at that position.\n\
  2007. With optional end, stop comparing B at that position.\n\
  2008. suffix can also be a tuple of bytes to try.");
  2009. static PyObject *
  2010. bytes_endswith(PyBytesObject *self, PyObject *args)
  2011. {
  2012. Py_ssize_t start = 0;
  2013. Py_ssize_t end = PY_SSIZE_T_MAX;
  2014. PyObject *subobj;
  2015. int result;
  2016. if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
  2017. return NULL;
  2018. if (PyTuple_Check(subobj)) {
  2019. Py_ssize_t i;
  2020. for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
  2021. result = _bytes_tailmatch(self,
  2022. PyTuple_GET_ITEM(subobj, i),
  2023. start, end, +1);
  2024. if (result == -1)
  2025. return NULL;
  2026. else if (result) {
  2027. Py_RETURN_TRUE;
  2028. }
  2029. }
  2030. Py_RETURN_FALSE;
  2031. }
  2032. result = _bytes_tailmatch(self, subobj, start, end, +1);
  2033. if (result == -1) {
  2034. if (PyErr_ExceptionMatches(PyExc_TypeError))
  2035. PyErr_Format(PyExc_TypeError, "endswith first arg must be bytes or "
  2036. "a tuple of bytes, not %s", Py_TYPE(subobj)->tp_name);
  2037. return NULL;
  2038. }
  2039. else
  2040. return PyBool_FromLong(result);
  2041. }
  2042. PyDoc_STRVAR(decode__doc__,
  2043. "B.decode(encoding='utf-8', errors='strict') -> str\n\
  2044. \n\
  2045. Decode B using the codec registered for encoding. Default encoding\n\
  2046. is 'utf-8'. errors may be given to set a different error\n\
  2047. handling scheme. Default is 'strict' meaning that encoding errors raise\n\
  2048. a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
  2049. as well as any other name registerd with codecs.register_error that is\n\
  2050. able to handle UnicodeDecodeErrors.");
  2051. static PyObject *
  2052. bytes_decode(PyObject *self, PyObject *args, PyObject *kwargs)
  2053. {
  2054. const char *encoding = NULL;
  2055. const char *errors = NULL;
  2056. static char *kwlist[] = {"encoding", "errors", 0};
  2057. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode", kwlist, &encoding, &errors))
  2058. return NULL;
  2059. if (encoding == NULL)
  2060. encoding = PyUnicode_GetDefaultEncoding();
  2061. return PyUnicode_FromEncodedObject(self, encoding, errors);
  2062. }
  2063. PyDoc_STRVAR(splitlines__doc__,
  2064. "B.splitlines([keepends]) -> list of lines\n\
  2065. \n\
  2066. Return a list of the lines in B, breaking at line boundaries.\n\
  2067. Line breaks are not included in the resulting list unless keepends\n\
  2068. is given and true.");
  2069. static PyObject*
  2070. bytes_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
  2071. {
  2072. static char *kwlist[] = {"keepends", 0};
  2073. int keepends = 0;
  2074. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
  2075. kwlist, &keepends))
  2076. return NULL;
  2077. return stringlib_splitlines(
  2078. (PyObject*) self, PyBytes_AS_STRING(self),
  2079. PyBytes_GET_SIZE(self), keepends
  2080. );
  2081. }
  2082. PyDoc_STRVAR(fromhex_doc,
  2083. "bytes.fromhex(string) -> bytes\n\
  2084. \n\
  2085. Create a bytes object from a string of hexadecimal numbers.\n\
  2086. Spaces between two numbers are accepted.\n\
  2087. Example: bytes.fromhex('B9 01EF') -> b'\\xb9\\x01\\xef'.");
  2088. static int
  2089. hex_digit_to_int(Py_UCS4 c)
  2090. {
  2091. if (c >= 128)
  2092. return -1;
  2093. if (Py_ISDIGIT(c))
  2094. return c - '0';
  2095. else {
  2096. if (Py_ISUPPER(c))
  2097. c = Py_TOLOWER(c);
  2098. if (c >= 'a' && c <= 'f')
  2099. return c - 'a' + 10;
  2100. }
  2101. return -1;
  2102. }
  2103. static PyObject *
  2104. bytes_fromhex(PyObject *cls, PyObject *args)
  2105. {
  2106. PyObject *newstring, *hexobj;
  2107. char *buf;
  2108. Py_ssize_t hexlen, byteslen, i, j;
  2109. int top, bot;
  2110. void *data;
  2111. unsigned int kind;
  2112. if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj))
  2113. return NULL;
  2114. assert(PyUnicode_Check(hexobj));
  2115. if (PyUnicode_READY(hexobj))
  2116. return NULL;
  2117. kind = PyUnicode_KIND(hexobj);
  2118. data = PyUnicode_DATA(hexobj);
  2119. hexlen = PyUnicode_GET_LENGTH(hexobj);
  2120. byteslen = hexlen/2; /* This overestimates if there are spaces */
  2121. newstring = PyBytes_FromStringAndSize(NULL, byteslen);
  2122. if (!newstring)
  2123. return NULL;
  2124. buf = PyBytes_AS_STRING(newstring);
  2125. for (i = j = 0; i < hexlen; i += 2) {
  2126. /* skip over spaces in the input */
  2127. while (PyUnicode_READ(kind, data, i) == ' ')
  2128. i++;
  2129. if (i >= hexlen)
  2130. break;
  2131. top = hex_digit_to_int(PyUnicode_READ(kind, data, i));
  2132. bot = hex_digit_to_int(PyUnicode_READ(kind, data, i+1));
  2133. if (top == -1 || bot == -1) {
  2134. PyErr_Format(PyExc_ValueError,
  2135. "non-hexadecimal number found in "
  2136. "fromhex() arg at position %zd", i);
  2137. goto error;
  2138. }
  2139. buf[j++] = (top << 4) + bot;
  2140. }
  2141. if (j != byteslen && _PyBytes_Resize(&newstring, j) < 0)
  2142. goto error;
  2143. return newstring;
  2144. error:
  2145. Py_XDECREF(newstring);
  2146. return NULL;
  2147. }
  2148. PyDoc_STRVAR(sizeof__doc__,
  2149. "B.__sizeof__() -> size of B in memory, in bytes");
  2150. static PyObject *
  2151. bytes_sizeof(PyBytesObject *v)
  2152. {
  2153. Py_ssize_t res;
  2154. res = PyBytesObject_SIZE + Py_SIZE(v) * Py_TYPE(v)->tp_itemsize;
  2155. return PyLong_FromSsize_t(res);
  2156. }
  2157. static PyObject *
  2158. bytes_getnewargs(PyBytesObject *v)
  2159. {
  2160. return Py_BuildValue("(y#)", v->ob_sval, Py_SIZE(v));
  2161. }
  2162. static PyMethodDef
  2163. bytes_methods[] = {
  2164. {"__getnewargs__", (PyCFunction)bytes_getnewargs, METH_NOARGS},
  2165. {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
  2166. _Py_capitalize__doc__},
  2167. {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__},
  2168. {"count", (PyCFunction)bytes_count, METH_VARARGS, count__doc__},
  2169. {"decode", (PyCFunction)bytes_decode, METH_VARARGS | METH_KEYWORDS, decode__doc__},
  2170. {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS,
  2171. endswith__doc__},
  2172. {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS,
  2173. expandtabs__doc__},
  2174. {"find", (PyCFunction)bytes_find, METH_VARARGS, find__doc__},
  2175. {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS,
  2176. fromhex_doc},
  2177. {"index", (PyCFunction)bytes_index, METH_VARARGS, index__doc__},
  2178. {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS,
  2179. _Py_isalnum__doc__},
  2180. {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS,
  2181. _Py_isalpha__doc__},
  2182. {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS,
  2183. _Py_isdigit__doc__},
  2184. {"islower", (PyCFunction)stringlib_islower, METH_NOARGS,
  2185. _Py_islower__doc__},
  2186. {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS,
  2187. _Py_isspace__doc__},
  2188. {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS,
  2189. _Py_istitle__doc__},
  2190. {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS,
  2191. _Py_isupper__doc__},
  2192. {"join", (PyCFunction)bytes_join, METH_O, join__doc__},
  2193. {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__},
  2194. {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__},
  2195. {"lstrip", (PyCFunction)bytes_lstrip, METH_VARARGS, lstrip__doc__},
  2196. {"maketrans", (PyCFunction)bytes_maketrans, METH_VARARGS|METH_STATIC,
  2197. _Py_maketrans__doc__},
  2198. {"partition", (PyCFunction)bytes_partition, METH_O, partition__doc__},
  2199. {"replace", (PyCFunction)bytes_replace, METH_VARARGS, replace__doc__},
  2200. {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, rfind__doc__},
  2201. {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, rindex__doc__},
  2202. {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__},
  2203. {"rpartition", (PyCFunction)bytes_rpartition, METH_O,
  2204. rpartition__doc__},
  2205. {"rsplit", (PyCFunction)bytes_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
  2206. {"rstrip", (PyCFunction)bytes_rstrip, METH_VARARGS, rstrip__doc__},
  2207. {"split", (PyCFunction)bytes_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
  2208. {"splitlines", (PyCFunction)bytes_splitlines, METH_VARARGS | METH_KEYWORDS,
  2209. splitlines__doc__},
  2210. {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS,
  2211. startswith__doc__},
  2212. {"strip", (PyCFunction)bytes_strip, METH_VARARGS, strip__doc__},
  2213. {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS,
  2214. _Py_swapcase__doc__},
  2215. {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__},
  2216. {"translate", (PyCFunction)bytes_translate, METH_VARARGS,
  2217. translate__doc__},
  2218. {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__},
  2219. {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__},
  2220. {"__sizeof__", (PyCFunction)bytes_sizeof, METH_NOARGS,
  2221. sizeof__doc__},
  2222. {NULL, NULL} /* sentinel */
  2223. };
  2224. static PyObject *
  2225. str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
  2226. static PyObject *
  2227. bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2228. {
  2229. PyObject *x = NULL;
  2230. const char *encoding = NULL;
  2231. const char *errors = NULL;
  2232. PyObject *new = NULL;
  2233. PyObject *func;
  2234. Py_ssize_t size;
  2235. static char *kwlist[] = {"source", "encoding", "errors", 0};
  2236. _Py_IDENTIFIER(__bytes__);
  2237. if (type != &PyBytes_Type)
  2238. return str_subtype_new(type, args, kwds);
  2239. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytes", kwlist, &x,
  2240. &encoding, &errors))
  2241. return NULL;
  2242. if (x == NULL) {
  2243. if (encoding != NULL || errors != NULL) {
  2244. PyErr_SetString(PyExc_TypeError,
  2245. "encoding or errors without sequence "
  2246. "argument");
  2247. return NULL;
  2248. }
  2249. return PyBytes_FromString("");
  2250. }
  2251. if (PyUnicode_Check(x)) {
  2252. /* Encode via the codec registry */
  2253. if (encoding == NULL) {
  2254. PyErr_SetString(PyExc_TypeError,
  2255. "string argument without an encoding");
  2256. return NULL;
  2257. }
  2258. new = PyUnicode_AsEncodedString(x, encoding, errors);
  2259. if (new == NULL)
  2260. return NULL;
  2261. assert(PyBytes_Check(new));
  2262. return new;
  2263. }
  2264. /* We'd like to call PyObject_Bytes here, but we need to check for an
  2265. integer argument before deferring to PyBytes_FromObject, something
  2266. PyObject_Bytes doesn't do. */
  2267. func = _PyObject_LookupSpecial(x, &PyId___bytes__);
  2268. if (func != NULL) {
  2269. new = PyObject_CallFunctionObjArgs(func, NULL);
  2270. Py_DECREF(func);
  2271. if (new == NULL)
  2272. return NULL;
  2273. if (!PyBytes_Check(new)) {
  2274. PyErr_Format(PyExc_TypeError,
  2275. "__bytes__ returned non-bytes (type %.200s)",
  2276. Py_TYPE(new)->tp_name);
  2277. Py_DECREF(new);
  2278. return NULL;
  2279. }
  2280. return new;
  2281. }
  2282. else if (PyErr_Occurred())
  2283. return NULL;
  2284. /* Is it an integer? */
  2285. size = PyNumber_AsSsize_t(x, PyExc_OverflowError);
  2286. if (size == -1 && PyErr_Occurred()) {
  2287. if (PyErr_ExceptionMatches(PyExc_OverflowError))
  2288. return NULL;
  2289. PyErr_Clear();
  2290. }
  2291. else if (size < 0) {
  2292. PyErr_SetString(PyExc_ValueError, "negative count");
  2293. return NULL;
  2294. }
  2295. else {
  2296. new = PyBytes_FromStringAndSize(NULL, size);
  2297. if (new == NULL)
  2298. return NULL;
  2299. if (size > 0)
  2300. memset(((PyBytesObject*)new)->ob_sval, 0, size);
  2301. return new;
  2302. }
  2303. /* If it's not unicode, there can't be encoding or errors */
  2304. if (encoding != NULL || errors != NULL) {
  2305. PyErr_SetString(PyExc_TypeError,
  2306. "encoding or errors without a string argument");
  2307. return NULL;
  2308. }
  2309. return PyBytes_FromObject(x);
  2310. }
  2311. PyObject *
  2312. PyBytes_FromObject(PyObject *x)
  2313. {
  2314. PyObject *new, *it;
  2315. Py_ssize_t i, size;
  2316. if (x == NULL) {
  2317. PyErr_BadInternalCall();
  2318. return NULL;
  2319. }
  2320. if (PyBytes_CheckExact(x)) {
  2321. Py_INCREF(x);
  2322. return x;
  2323. }
  2324. /* Use the modern buffer interface */
  2325. if (PyObject_CheckBuffer(x)) {
  2326. Py_buffer view;
  2327. if (PyObject_GetBuffer(x, &view, PyBUF_FULL_RO) < 0)
  2328. return NULL;
  2329. new = PyBytes_FromStringAndSize(NULL, view.len);
  2330. if (!new)
  2331. goto fail;
  2332. if (PyBuffer_ToContiguous(((PyBytesObject *)new)->ob_sval,
  2333. &view, view.len, 'C') < 0)
  2334. goto fail;
  2335. PyBuffer_Release(&view);
  2336. return new;
  2337. fail:
  2338. Py_XDECREF(new);
  2339. PyBuffer_Release(&view);
  2340. return NULL;
  2341. }
  2342. if (PyUnicode_Check(x)) {
  2343. PyErr_SetString(PyExc_TypeError,
  2344. "cannot convert unicode object to bytes");
  2345. return NULL;
  2346. }
  2347. if (PyList_CheckExact(x)) {
  2348. new = PyBytes_FromStringAndSize(NULL, Py_SIZE(x));
  2349. if (new == NULL)
  2350. return NULL;
  2351. for (i = 0; i < Py_SIZE(x); i++) {
  2352. Py_ssize_t value = PyNumber_AsSsize_t(
  2353. PyList_GET_ITEM(x, i), PyExc_ValueError);
  2354. if (value == -1 && PyErr_Occurred()) {
  2355. Py_DECREF(new);
  2356. return NULL;
  2357. }
  2358. if (value < 0 || value >= 256) {
  2359. PyErr_SetString(PyExc_ValueError,
  2360. "bytes must be in range(0, 256)");
  2361. Py_DECREF(new);
  2362. return NULL;
  2363. }
  2364. ((PyBytesObject *)new)->ob_sval[i] = (char) value;
  2365. }
  2366. return new;
  2367. }
  2368. if (PyTuple_CheckExact(x)) {
  2369. new = PyBytes_FromStringAndSize(NULL, Py_SIZE(x));
  2370. if (new == NULL)
  2371. return NULL;
  2372. for (i = 0; i < Py_SIZE(x); i++) {
  2373. Py_ssize_t value = PyNumber_AsSsize_t(
  2374. PyTuple_GET_ITEM(x, i), PyExc_ValueError);
  2375. if (value == -1 && PyErr_Occurred()) {
  2376. Py_DECREF(new);
  2377. return NULL;
  2378. }
  2379. if (value < 0 || value >= 256) {
  2380. PyErr_SetString(PyExc_ValueError,
  2381. "bytes must be in range(0, 256)");
  2382. Py_DECREF(new);
  2383. return NULL;
  2384. }
  2385. ((PyBytesObject *)new)->ob_sval[i] = (char) value;
  2386. }
  2387. return new;
  2388. }
  2389. /* For iterator version, create a string object and resize as needed */
  2390. size = _PyObject_LengthHint(x, 64);
  2391. if (size == -1 && PyErr_Occurred())
  2392. return NULL;
  2393. /* Allocate an extra byte to prevent PyBytes_FromStringAndSize() from
  2394. returning a shared empty bytes string. This required because we
  2395. want to call _PyBytes_Resize() the returned object, which we can
  2396. only do on bytes objects with refcount == 1. */
  2397. size += 1;
  2398. new = PyBytes_FromStringAndSize(NULL, size);
  2399. if (new == NULL)
  2400. return NULL;
  2401. /* Get the iterator */
  2402. it = PyObject_GetIter(x);
  2403. if (it == NULL)
  2404. goto error;
  2405. /* Run the iterator to exhaustion */
  2406. for (i = 0; ; i++) {
  2407. PyObject *item;
  2408. Py_ssize_t value;
  2409. /* Get the next item */
  2410. item = PyIter_Next(it);
  2411. if (item == NULL) {
  2412. if (PyErr_Occurred())
  2413. goto error;
  2414. break;
  2415. }
  2416. /* Interpret it as an int (__index__) */
  2417. value = PyNumber_AsSsize_t(item, PyExc_ValueError);
  2418. Py_DECREF(item);
  2419. if (value == -1 && PyErr_Occurred())
  2420. goto error;
  2421. /* Range check */
  2422. if (value < 0 || value >= 256) {
  2423. PyErr_SetString(PyExc_ValueError,
  2424. "bytes must be in range(0, 256)");
  2425. goto error;
  2426. }
  2427. /* Append the byte */
  2428. if (i >= size) {
  2429. size = 2 * size + 1;
  2430. if (_PyBytes_Resize(&new, size) < 0)
  2431. goto error;
  2432. }
  2433. ((PyBytesObject *)new)->ob_sval[i] = (char) value;
  2434. }
  2435. _PyBytes_Resize(&new, i);
  2436. /* Clean up and return success */
  2437. Py_DECREF(it);
  2438. return new;
  2439. error:
  2440. /* Error handling when new != NULL */
  2441. Py_XDECREF(it);
  2442. Py_DECREF(new);
  2443. return NULL;
  2444. }
  2445. static PyObject *
  2446. str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2447. {
  2448. PyObject *tmp, *pnew;
  2449. Py_ssize_t n;
  2450. assert(PyType_IsSubtype(type, &PyBytes_Type));
  2451. tmp = bytes_new(&PyBytes_Type, args, kwds);
  2452. if (tmp == NULL)
  2453. return NULL;
  2454. assert(PyBytes_CheckExact(tmp));
  2455. n = PyBytes_GET_SIZE(tmp);
  2456. pnew = type->tp_alloc(type, n);
  2457. if (pnew != NULL) {
  2458. Py_MEMCPY(PyBytes_AS_STRING(pnew),
  2459. PyBytes_AS_STRING(tmp), n+1);
  2460. ((PyBytesObject *)pnew)->ob_shash =
  2461. ((PyBytesObject *)tmp)->ob_shash;
  2462. }
  2463. Py_DECREF(tmp);
  2464. return pnew;
  2465. }
  2466. PyDoc_STRVAR(bytes_doc,
  2467. "bytes(iterable_of_ints) -> bytes\n\
  2468. bytes(string, encoding[, errors]) -> bytes\n\
  2469. bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer\n\
  2470. bytes(int) -> bytes object of size given by the parameter initialized with null bytes\n\
  2471. bytes() -> empty bytes object\n\
  2472. \n\
  2473. Construct an immutable array of bytes from:\n\
  2474. - an iterable yielding integers in range(256)\n\
  2475. - a text string encoded using the specified encoding\n\
  2476. - any object implementing the buffer API.\n\
  2477. - an integer");
  2478. static PyObject *bytes_iter(PyObject *seq);
  2479. PyTypeObject PyBytes_Type = {
  2480. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2481. "bytes",
  2482. PyBytesObject_SIZE,
  2483. sizeof(char),
  2484. bytes_dealloc, /* tp_dealloc */
  2485. 0, /* tp_print */
  2486. 0, /* tp_getattr */
  2487. 0, /* tp_setattr */
  2488. 0, /* tp_reserved */
  2489. (reprfunc)bytes_repr, /* tp_repr */
  2490. 0, /* tp_as_number */
  2491. &bytes_as_sequence, /* tp_as_sequence */
  2492. &bytes_as_mapping, /* tp_as_mapping */
  2493. (hashfunc)bytes_hash, /* tp_hash */
  2494. 0, /* tp_call */
  2495. bytes_str, /* tp_str */
  2496. PyObject_GenericGetAttr, /* tp_getattro */
  2497. 0, /* tp_setattro */
  2498. &bytes_as_buffer, /* tp_as_buffer */
  2499. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  2500. Py_TPFLAGS_BYTES_SUBCLASS, /* tp_flags */
  2501. bytes_doc, /* tp_doc */
  2502. 0, /* tp_traverse */
  2503. 0, /* tp_clear */
  2504. (richcmpfunc)bytes_richcompare, /* tp_richcompare */
  2505. 0, /* tp_weaklistoffset */
  2506. bytes_iter, /* tp_iter */
  2507. 0, /* tp_iternext */
  2508. bytes_methods, /* tp_methods */
  2509. 0, /* tp_members */
  2510. 0, /* tp_getset */
  2511. &PyBaseObject_Type, /* tp_base */
  2512. 0, /* tp_dict */
  2513. 0, /* tp_descr_get */
  2514. 0, /* tp_descr_set */
  2515. 0, /* tp_dictoffset */
  2516. 0, /* tp_init */
  2517. 0, /* tp_alloc */
  2518. bytes_new, /* tp_new */
  2519. PyObject_Del, /* tp_free */
  2520. };
  2521. void
  2522. PyBytes_Concat(register PyObject **pv, register PyObject *w)
  2523. {
  2524. register PyObject *v;
  2525. assert(pv != NULL);
  2526. if (*pv == NULL)
  2527. return;
  2528. if (w == NULL) {
  2529. Py_CLEAR(*pv);
  2530. return;
  2531. }
  2532. v = bytes_concat(*pv, w);
  2533. Py_DECREF(*pv);
  2534. *pv = v;
  2535. }
  2536. void
  2537. PyBytes_ConcatAndDel(register PyObject **pv, register PyObject *w)
  2538. {
  2539. PyBytes_Concat(pv, w);
  2540. Py_XDECREF(w);
  2541. }
  2542. /* The following function breaks the notion that strings are immutable:
  2543. it changes the size of a string. We get away with this only if there
  2544. is only one module referencing the object. You can also think of it
  2545. as creating a new string object and destroying the old one, only
  2546. more efficiently. In any case, don't use this if the string may
  2547. already be known to some other part of the code...
  2548. Note that if there's not enough memory to resize the string, the original
  2549. string object at *pv is deallocated, *pv is set to NULL, an "out of
  2550. memory" exception is set, and -1 is returned. Else (on success) 0 is
  2551. returned, and the value in *pv may or may not be the same as on input.
  2552. As always, an extra byte is allocated for a trailing \0 byte (newsize
  2553. does *not* include that), and a trailing \0 byte is stored.
  2554. */
  2555. int
  2556. _PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
  2557. {
  2558. register PyObject *v;
  2559. register PyBytesObject *sv;
  2560. v = *pv;
  2561. if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) {
  2562. *pv = 0;
  2563. Py_DECREF(v);
  2564. PyErr_BadInternalCall();
  2565. return -1;
  2566. }
  2567. /* XXX UNREF/NEWREF interface should be more symmetrical */
  2568. _Py_DEC_REFTOTAL;
  2569. _Py_ForgetReference(v);
  2570. *pv = (PyObject *)
  2571. PyObject_REALLOC((char *)v, PyBytesObject_SIZE + newsize);
  2572. if (*pv == NULL) {
  2573. PyObject_Del(v);
  2574. PyErr_NoMemory();
  2575. return -1;
  2576. }
  2577. _Py_NewReference(*pv);
  2578. sv = (PyBytesObject *) *pv;
  2579. Py_SIZE(sv) = newsize;
  2580. sv->ob_sval[newsize] = '\0';
  2581. sv->ob_shash = -1; /* invalidate cached hash value */
  2582. return 0;
  2583. }
  2584. void
  2585. PyBytes_Fini(void)
  2586. {
  2587. int i;
  2588. for (i = 0; i < UCHAR_MAX + 1; i++)
  2589. Py_CLEAR(characters[i]);
  2590. Py_CLEAR(nullstring);
  2591. }
  2592. /*********************** Bytes Iterator ****************************/
  2593. typedef struct {
  2594. PyObject_HEAD
  2595. Py_ssize_t it_index;
  2596. PyBytesObject *it_seq; /* Set to NULL when iterator is exhausted */
  2597. } striterobject;
  2598. static void
  2599. striter_dealloc(striterobject *it)
  2600. {
  2601. _PyObject_GC_UNTRACK(it);
  2602. Py_XDECREF(it->it_seq);
  2603. PyObject_GC_Del(it);
  2604. }
  2605. static int
  2606. striter_traverse(striterobject *it, visitproc visit, void *arg)
  2607. {
  2608. Py_VISIT(it->it_seq);
  2609. return 0;
  2610. }
  2611. static PyObject *
  2612. striter_next(striterobject *it)
  2613. {
  2614. PyBytesObject *seq;
  2615. PyObject *item;
  2616. assert(it != NULL);
  2617. seq = it->it_seq;
  2618. if (seq == NULL)
  2619. return NULL;
  2620. assert(PyBytes_Check(seq));
  2621. if (it->it_index < PyBytes_GET_SIZE(seq)) {
  2622. item = PyLong_FromLong(
  2623. (unsigned char)seq->ob_sval[it->it_index]);
  2624. if (item != NULL)
  2625. ++it->it_index;
  2626. return item;
  2627. }
  2628. Py_DECREF(seq);
  2629. it->it_seq = NULL;
  2630. return NULL;
  2631. }
  2632. static PyObject *
  2633. striter_len(striterobject *it)
  2634. {
  2635. Py_ssize_t len = 0;
  2636. if (it->it_seq)
  2637. len = PyBytes_GET_SIZE(it->it_seq) - it->it_index;
  2638. return PyLong_FromSsize_t(len);
  2639. }
  2640. PyDoc_STRVAR(length_hint_doc,
  2641. "Private method returning an estimate of len(list(it)).");
  2642. static PyObject *
  2643. striter_reduce(striterobject *it)
  2644. {
  2645. if (it->it_seq != NULL) {
  2646. return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
  2647. it->it_seq, it->it_index);
  2648. } else {
  2649. PyObject *u = PyUnicode_FromUnicode(NULL, 0);
  2650. if (u == NULL)
  2651. return NULL;
  2652. return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
  2653. }
  2654. }
  2655. PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
  2656. static PyObject *
  2657. striter_setstate(striterobject *it, PyObject *state)
  2658. {
  2659. Py_ssize_t index = PyLong_AsSsize_t(state);
  2660. if (index == -1 && PyErr_Occurred())
  2661. return NULL;
  2662. if (index < 0)
  2663. index = 0;
  2664. it->it_index = index;
  2665. Py_RETURN_NONE;
  2666. }
  2667. PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
  2668. static PyMethodDef striter_methods[] = {
  2669. {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS,
  2670. length_hint_doc},
  2671. {"__reduce__", (PyCFunction)striter_reduce, METH_NOARGS,
  2672. reduce_doc},
  2673. {"__setstate__", (PyCFunction)striter_setstate, METH_O,
  2674. setstate_doc},
  2675. {NULL, NULL} /* sentinel */
  2676. };
  2677. PyTypeObject PyBytesIter_Type = {
  2678. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2679. "bytes_iterator", /* tp_name */
  2680. sizeof(striterobject), /* tp_basicsize */
  2681. 0, /* tp_itemsize */
  2682. /* methods */
  2683. (destructor)striter_dealloc, /* tp_dealloc */
  2684. 0, /* tp_print */
  2685. 0, /* tp_getattr */
  2686. 0, /* tp_setattr */
  2687. 0, /* tp_reserved */
  2688. 0, /* tp_repr */
  2689. 0, /* tp_as_number */
  2690. 0, /* tp_as_sequence */
  2691. 0, /* tp_as_mapping */
  2692. 0, /* tp_hash */
  2693. 0, /* tp_call */
  2694. 0, /* tp_str */
  2695. PyObject_GenericGetAttr, /* tp_getattro */
  2696. 0, /* tp_setattro */
  2697. 0, /* tp_as_buffer */
  2698. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  2699. 0, /* tp_doc */
  2700. (traverseproc)striter_traverse, /* tp_traverse */
  2701. 0, /* tp_clear */
  2702. 0, /* tp_richcompare */
  2703. 0, /* tp_weaklistoffset */
  2704. PyObject_SelfIter, /* tp_iter */
  2705. (iternextfunc)striter_next, /* tp_iternext */
  2706. striter_methods, /* tp_methods */
  2707. 0,
  2708. };
  2709. static PyObject *
  2710. bytes_iter(PyObject *seq)
  2711. {
  2712. striterobject *it;
  2713. if (!PyBytes_Check(seq)) {
  2714. PyErr_BadInternalCall();
  2715. return NULL;
  2716. }
  2717. it = PyObject_GC_New(striterobject, &PyBytesIter_Type);
  2718. if (it == NULL)
  2719. return NULL;
  2720. it->it_index = 0;
  2721. Py_INCREF(seq);
  2722. it->it_seq = (PyBytesObject *)seq;
  2723. _PyObject_GC_TRACK(it);
  2724. return (PyObject *)it;
  2725. }