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.

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