/Objects/stringobject.c

http://unladen-swallow.googlecode.com/ · C · 5242 lines · 4329 code · 538 blank · 375 comment · 1221 complexity · a1c18aba068e8f25c3e3da8e22507f9f MD5 · raw file

Large files are truncated click here to view the full file

  1. /* String (str/bytes) object implementation */
  2. #define PY_SSIZE_T_CLEAN
  3. #include "Python.h"
  4. #include <ctype.h>
  5. #ifdef COUNT_ALLOCS
  6. int null_strings, one_strings;
  7. #endif
  8. static PyStringObject *characters[UCHAR_MAX + 1];
  9. static PyStringObject *nullstring;
  10. /* This dictionary holds all interned strings. Note that references to
  11. strings in this dictionary are *not* counted in the string's ob_refcnt.
  12. When the interned string reaches a refcnt of 0 the string deallocation
  13. function will delete the reference from this dictionary.
  14. Another way to look at this is that to say that the actual reference
  15. count of a string is: s->ob_refcnt + (s->ob_sstate?2:0)
  16. */
  17. static PyObject *interned;
  18. /*
  19. For both PyString_FromString() and PyString_FromStringAndSize(), the
  20. parameter `size' denotes number of characters to allocate, not counting any
  21. null terminating character.
  22. For PyString_FromString(), the parameter `str' points to a null-terminated
  23. string containing exactly `size' bytes.
  24. For PyString_FromStringAndSize(), the parameter the parameter `str' is
  25. either NULL or else points to a string containing at least `size' bytes.
  26. For PyString_FromStringAndSize(), the string in the `str' parameter does
  27. not have to be null-terminated. (Therefore it is safe to construct a
  28. substring by calling `PyString_FromStringAndSize(origstring, substrlen)'.)
  29. If `str' is NULL then PyString_FromStringAndSize() will allocate `size+1'
  30. bytes (setting the last byte to the null terminating character) and you can
  31. fill in the data yourself. If `str' is non-NULL then the resulting
  32. PyString object must be treated as immutable and you must not fill in nor
  33. alter the data yourself, since the strings may be shared.
  34. The PyObject member `op->ob_size', which denotes the number of "extra
  35. items" in a variable-size object, will contain the number of bytes
  36. allocated for string data, not counting the null terminating character. It
  37. is therefore equal to the equal to the `size' parameter (for
  38. PyString_FromStringAndSize()) or the length of the string in the `str'
  39. parameter (for PyString_FromString()).
  40. */
  41. PyObject *
  42. PyString_FromStringAndSize(const char *str, Py_ssize_t size)
  43. {
  44. register PyStringObject *op;
  45. if (size < 0) {
  46. PyErr_SetString(PyExc_SystemError,
  47. "Negative size passed to PyString_FromStringAndSize");
  48. return NULL;
  49. }
  50. if (size == 0 && (op = nullstring) != NULL) {
  51. #ifdef COUNT_ALLOCS
  52. null_strings++;
  53. #endif
  54. Py_INCREF(op);
  55. return (PyObject *)op;
  56. }
  57. if (size == 1 && str != NULL &&
  58. (op = characters[*str & UCHAR_MAX]) != NULL)
  59. {
  60. #ifdef COUNT_ALLOCS
  61. one_strings++;
  62. #endif
  63. Py_INCREF(op);
  64. return (PyObject *)op;
  65. }
  66. if (size > PY_SSIZE_T_MAX - sizeof(PyStringObject)) {
  67. PyErr_SetString(PyExc_OverflowError, "string is too large");
  68. return NULL;
  69. }
  70. /* Inline PyObject_NewVar */
  71. op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
  72. if (op == NULL)
  73. return PyErr_NoMemory();
  74. PyObject_INIT_VAR(op, &PyString_Type, size);
  75. op->ob_shash = -1;
  76. op->ob_sstate = SSTATE_NOT_INTERNED;
  77. if (str != NULL)
  78. Py_MEMCPY(op->ob_sval, str, size);
  79. op->ob_sval[size] = '\0';
  80. /* share short strings */
  81. if (size == 0) {
  82. PyObject *t = (PyObject *)op;
  83. PyString_InternInPlace(&t);
  84. op = (PyStringObject *)t;
  85. nullstring = op;
  86. Py_INCREF(op);
  87. } else if (size == 1 && str != NULL) {
  88. PyObject *t = (PyObject *)op;
  89. PyString_InternInPlace(&t);
  90. op = (PyStringObject *)t;
  91. characters[*str & UCHAR_MAX] = op;
  92. Py_INCREF(op);
  93. }
  94. return (PyObject *) op;
  95. }
  96. PyObject *
  97. PyString_FromString(const char *str)
  98. {
  99. register size_t size;
  100. register PyStringObject *op;
  101. assert(str != NULL);
  102. size = strlen(str);
  103. if (size > PY_SSIZE_T_MAX - sizeof(PyStringObject)) {
  104. PyErr_SetString(PyExc_OverflowError,
  105. "string is too long for a Python string");
  106. return NULL;
  107. }
  108. if (size == 0 && (op = nullstring) != NULL) {
  109. #ifdef COUNT_ALLOCS
  110. null_strings++;
  111. #endif
  112. Py_INCREF(op);
  113. return (PyObject *)op;
  114. }
  115. if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
  116. #ifdef COUNT_ALLOCS
  117. one_strings++;
  118. #endif
  119. Py_INCREF(op);
  120. return (PyObject *)op;
  121. }
  122. /* Inline PyObject_NewVar */
  123. op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
  124. if (op == NULL)
  125. return PyErr_NoMemory();
  126. PyObject_INIT_VAR(op, &PyString_Type, size);
  127. op->ob_shash = -1;
  128. op->ob_sstate = SSTATE_NOT_INTERNED;
  129. Py_MEMCPY(op->ob_sval, str, size+1);
  130. /* share short strings */
  131. if (size == 0) {
  132. PyObject *t = (PyObject *)op;
  133. PyString_InternInPlace(&t);
  134. op = (PyStringObject *)t;
  135. nullstring = op;
  136. Py_INCREF(op);
  137. } else if (size == 1) {
  138. PyObject *t = (PyObject *)op;
  139. PyString_InternInPlace(&t);
  140. op = (PyStringObject *)t;
  141. characters[*str & UCHAR_MAX] = op;
  142. Py_INCREF(op);
  143. }
  144. return (PyObject *) op;
  145. }
  146. PyObject *
  147. PyString_FromFormatV(const char *format, va_list vargs)
  148. {
  149. va_list count;
  150. Py_ssize_t n = 0;
  151. const char* f;
  152. char *s;
  153. PyObject* string;
  154. #ifdef VA_LIST_IS_ARRAY
  155. Py_MEMCPY(count, vargs, sizeof(va_list));
  156. #else
  157. #ifdef __va_copy
  158. __va_copy(count, vargs);
  159. #else
  160. count = vargs;
  161. #endif
  162. #endif
  163. /* step 1: figure out how large a buffer we need */
  164. for (f = format; *f; f++) {
  165. if (*f == '%') {
  166. const char* p = f;
  167. while (*++f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
  168. ;
  169. /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
  170. * they don't affect the amount of space we reserve.
  171. */
  172. if ((*f == 'l' || *f == 'z') &&
  173. (f[1] == 'd' || f[1] == 'u'))
  174. ++f;
  175. switch (*f) {
  176. case 'c':
  177. (void)va_arg(count, int);
  178. /* fall through... */
  179. case '%':
  180. n++;
  181. break;
  182. case 'd': case 'u': case 'i': case 'x':
  183. (void) va_arg(count, int);
  184. /* 20 bytes is enough to hold a 64-bit
  185. integer. Decimal takes the most space.
  186. This isn't enough for octal. */
  187. n += 20;
  188. break;
  189. case 's':
  190. s = va_arg(count, char*);
  191. n += strlen(s);
  192. break;
  193. case 'p':
  194. (void) va_arg(count, int);
  195. /* maximum 64-bit pointer representation:
  196. * 0xffffffffffffffff
  197. * so 19 characters is enough.
  198. * XXX I count 18 -- what's the extra for?
  199. */
  200. n += 19;
  201. break;
  202. default:
  203. /* if we stumble upon an unknown
  204. formatting code, copy the rest of
  205. the format string to the output
  206. string. (we cannot just skip the
  207. code, since there's no way to know
  208. what's in the argument list) */
  209. n += strlen(p);
  210. goto expand;
  211. }
  212. } else
  213. n++;
  214. }
  215. expand:
  216. /* step 2: fill the buffer */
  217. /* Since we've analyzed how much space we need for the worst case,
  218. use sprintf directly instead of the slower PyOS_snprintf. */
  219. string = PyString_FromStringAndSize(NULL, n);
  220. if (!string)
  221. return NULL;
  222. s = PyString_AsString(string);
  223. for (f = format; *f; f++) {
  224. if (*f == '%') {
  225. const char* p = f++;
  226. Py_ssize_t i;
  227. int longflag = 0;
  228. int size_tflag = 0;
  229. /* parse the width.precision part (we're only
  230. interested in the precision value, if any) */
  231. n = 0;
  232. while (isdigit(Py_CHARMASK(*f)))
  233. n = (n*10) + *f++ - '0';
  234. if (*f == '.') {
  235. f++;
  236. n = 0;
  237. while (isdigit(Py_CHARMASK(*f)))
  238. n = (n*10) + *f++ - '0';
  239. }
  240. while (*f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
  241. f++;
  242. /* handle the long flag, but only for %ld and %lu.
  243. others can be added when necessary. */
  244. if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
  245. longflag = 1;
  246. ++f;
  247. }
  248. /* handle the size_t flag. */
  249. if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
  250. size_tflag = 1;
  251. ++f;
  252. }
  253. switch (*f) {
  254. case 'c':
  255. *s++ = va_arg(vargs, int);
  256. break;
  257. case 'd':
  258. if (longflag)
  259. sprintf(s, "%ld", va_arg(vargs, long));
  260. else if (size_tflag)
  261. sprintf(s, "%" PY_FORMAT_SIZE_T "d",
  262. va_arg(vargs, Py_ssize_t));
  263. else
  264. sprintf(s, "%d", va_arg(vargs, int));
  265. s += strlen(s);
  266. break;
  267. case 'u':
  268. if (longflag)
  269. sprintf(s, "%lu",
  270. va_arg(vargs, unsigned long));
  271. else if (size_tflag)
  272. sprintf(s, "%" PY_FORMAT_SIZE_T "u",
  273. va_arg(vargs, size_t));
  274. else
  275. sprintf(s, "%u",
  276. va_arg(vargs, unsigned int));
  277. s += strlen(s);
  278. break;
  279. case 'i':
  280. sprintf(s, "%i", va_arg(vargs, int));
  281. s += strlen(s);
  282. break;
  283. case 'x':
  284. sprintf(s, "%x", va_arg(vargs, int));
  285. s += strlen(s);
  286. break;
  287. case 's':
  288. p = va_arg(vargs, char*);
  289. i = strlen(p);
  290. if (n > 0 && i > n)
  291. i = n;
  292. Py_MEMCPY(s, p, i);
  293. s += i;
  294. break;
  295. case 'p':
  296. sprintf(s, "%p", va_arg(vargs, void*));
  297. /* %p is ill-defined: ensure leading 0x. */
  298. if (s[1] == 'X')
  299. s[1] = 'x';
  300. else if (s[1] != 'x') {
  301. memmove(s+2, s, strlen(s)+1);
  302. s[0] = '0';
  303. s[1] = 'x';
  304. }
  305. s += strlen(s);
  306. break;
  307. case '%':
  308. *s++ = '%';
  309. break;
  310. default:
  311. strcpy(s, p);
  312. s += strlen(s);
  313. goto end;
  314. }
  315. } else
  316. *s++ = *f;
  317. }
  318. end:
  319. _PyString_Resize(&string, s - PyString_AS_STRING(string));
  320. return string;
  321. }
  322. PyObject *
  323. PyString_FromFormat(const char *format, ...)
  324. {
  325. PyObject* ret;
  326. va_list vargs;
  327. #ifdef HAVE_STDARG_PROTOTYPES
  328. va_start(vargs, format);
  329. #else
  330. va_start(vargs);
  331. #endif
  332. ret = PyString_FromFormatV(format, vargs);
  333. va_end(vargs);
  334. return ret;
  335. }
  336. PyObject *PyString_Decode(const char *s,
  337. Py_ssize_t size,
  338. const char *encoding,
  339. const char *errors)
  340. {
  341. PyObject *v, *str;
  342. str = PyString_FromStringAndSize(s, size);
  343. if (str == NULL)
  344. return NULL;
  345. v = PyString_AsDecodedString(str, encoding, errors);
  346. Py_DECREF(str);
  347. return v;
  348. }
  349. PyObject *PyString_AsDecodedObject(PyObject *str,
  350. const char *encoding,
  351. const char *errors)
  352. {
  353. PyObject *v;
  354. if (!PyString_Check(str)) {
  355. PyErr_BadArgument();
  356. goto onError;
  357. }
  358. if (encoding == NULL) {
  359. #ifdef Py_USING_UNICODE
  360. encoding = PyUnicode_GetDefaultEncoding();
  361. #else
  362. PyErr_SetString(PyExc_ValueError, "no encoding specified");
  363. goto onError;
  364. #endif
  365. }
  366. /* Decode via the codec registry */
  367. v = PyCodec_Decode(str, encoding, errors);
  368. if (v == NULL)
  369. goto onError;
  370. return v;
  371. onError:
  372. return NULL;
  373. }
  374. PyObject *PyString_AsDecodedString(PyObject *str,
  375. const char *encoding,
  376. const char *errors)
  377. {
  378. PyObject *v;
  379. v = PyString_AsDecodedObject(str, encoding, errors);
  380. if (v == NULL)
  381. goto onError;
  382. #ifdef Py_USING_UNICODE
  383. /* Convert Unicode to a string using the default encoding */
  384. if (PyUnicode_Check(v)) {
  385. PyObject *temp = v;
  386. v = PyUnicode_AsEncodedString(v, NULL, NULL);
  387. Py_DECREF(temp);
  388. if (v == NULL)
  389. goto onError;
  390. }
  391. #endif
  392. if (!PyString_Check(v)) {
  393. PyErr_Format(PyExc_TypeError,
  394. "decoder did not return a string object (type=%.400s)",
  395. Py_TYPE(v)->tp_name);
  396. Py_DECREF(v);
  397. goto onError;
  398. }
  399. return v;
  400. onError:
  401. return NULL;
  402. }
  403. PyObject *PyString_Encode(const char *s,
  404. Py_ssize_t size,
  405. const char *encoding,
  406. const char *errors)
  407. {
  408. PyObject *v, *str;
  409. str = PyString_FromStringAndSize(s, size);
  410. if (str == NULL)
  411. return NULL;
  412. v = PyString_AsEncodedString(str, encoding, errors);
  413. Py_DECREF(str);
  414. return v;
  415. }
  416. PyObject *PyString_AsEncodedObject(PyObject *str,
  417. const char *encoding,
  418. const char *errors)
  419. {
  420. PyObject *v;
  421. if (!PyString_Check(str)) {
  422. PyErr_BadArgument();
  423. goto onError;
  424. }
  425. if (encoding == NULL) {
  426. #ifdef Py_USING_UNICODE
  427. encoding = PyUnicode_GetDefaultEncoding();
  428. #else
  429. PyErr_SetString(PyExc_ValueError, "no encoding specified");
  430. goto onError;
  431. #endif
  432. }
  433. /* Encode via the codec registry */
  434. v = PyCodec_Encode(str, encoding, errors);
  435. if (v == NULL)
  436. goto onError;
  437. return v;
  438. onError:
  439. return NULL;
  440. }
  441. PyObject *PyString_AsEncodedString(PyObject *str,
  442. const char *encoding,
  443. const char *errors)
  444. {
  445. PyObject *v;
  446. v = PyString_AsEncodedObject(str, encoding, errors);
  447. if (v == NULL)
  448. goto onError;
  449. #ifdef Py_USING_UNICODE
  450. /* Convert Unicode to a string using the default encoding */
  451. if (PyUnicode_Check(v)) {
  452. PyObject *temp = v;
  453. v = PyUnicode_AsEncodedString(v, NULL, NULL);
  454. Py_DECREF(temp);
  455. if (v == NULL)
  456. goto onError;
  457. }
  458. #endif
  459. if (!PyString_Check(v)) {
  460. PyErr_Format(PyExc_TypeError,
  461. "encoder did not return a string object (type=%.400s)",
  462. Py_TYPE(v)->tp_name);
  463. Py_DECREF(v);
  464. goto onError;
  465. }
  466. return v;
  467. onError:
  468. return NULL;
  469. }
  470. static void
  471. string_dealloc(PyObject *op)
  472. {
  473. switch (PyString_CHECK_INTERNED(op)) {
  474. case SSTATE_NOT_INTERNED:
  475. break;
  476. case SSTATE_INTERNED_MORTAL:
  477. /* revive dead object temporarily for DelItem */
  478. Py_REFCNT(op) = 3;
  479. if (PyDict_DelItem(interned, op) != 0)
  480. Py_FatalError(
  481. "deletion of interned string failed");
  482. break;
  483. case SSTATE_INTERNED_IMMORTAL:
  484. Py_FatalError("Immortal interned string died.");
  485. default:
  486. Py_FatalError("Inconsistent interned string state.");
  487. }
  488. Py_TYPE(op)->tp_free(op);
  489. }
  490. /* Unescape a backslash-escaped string. If unicode is non-zero,
  491. the string is a u-literal. If recode_encoding is non-zero,
  492. the string is UTF-8 encoded and should be re-encoded in the
  493. specified encoding. */
  494. PyObject *PyString_DecodeEscape(const char *s,
  495. Py_ssize_t len,
  496. const char *errors,
  497. Py_ssize_t unicode,
  498. const char *recode_encoding)
  499. {
  500. int c;
  501. char *p, *buf;
  502. const char *end;
  503. PyObject *v;
  504. Py_ssize_t newlen = recode_encoding ? 4*len:len;
  505. v = PyString_FromStringAndSize((char *)NULL, newlen);
  506. if (v == NULL)
  507. return NULL;
  508. p = buf = PyString_AsString(v);
  509. end = s + len;
  510. while (s < end) {
  511. if (*s != '\\') {
  512. non_esc:
  513. #ifdef Py_USING_UNICODE
  514. if (recode_encoding && (*s & 0x80)) {
  515. PyObject *u, *w;
  516. char *r;
  517. const char* t;
  518. Py_ssize_t rn;
  519. t = s;
  520. /* Decode non-ASCII bytes as UTF-8. */
  521. while (t < end && (*t & 0x80)) t++;
  522. u = PyUnicode_DecodeUTF8(s, t - s, errors);
  523. if(!u) goto failed;
  524. /* Recode them in target encoding. */
  525. w = PyUnicode_AsEncodedString(
  526. u, recode_encoding, errors);
  527. Py_DECREF(u);
  528. if (!w) goto failed;
  529. /* Append bytes to output buffer. */
  530. assert(PyString_Check(w));
  531. r = PyString_AS_STRING(w);
  532. rn = PyString_GET_SIZE(w);
  533. Py_MEMCPY(p, r, rn);
  534. p += rn;
  535. Py_DECREF(w);
  536. s = t;
  537. } else {
  538. *p++ = *s++;
  539. }
  540. #else
  541. *p++ = *s++;
  542. #endif
  543. continue;
  544. }
  545. s++;
  546. if (s==end) {
  547. PyErr_SetString(PyExc_ValueError,
  548. "Trailing \\ in string");
  549. goto failed;
  550. }
  551. switch (*s++) {
  552. /* XXX This assumes ASCII! */
  553. case '\n': break;
  554. case '\\': *p++ = '\\'; break;
  555. case '\'': *p++ = '\''; break;
  556. case '\"': *p++ = '\"'; break;
  557. case 'b': *p++ = '\b'; break;
  558. case 'f': *p++ = '\014'; break; /* FF */
  559. case 't': *p++ = '\t'; break;
  560. case 'n': *p++ = '\n'; break;
  561. case 'r': *p++ = '\r'; break;
  562. case 'v': *p++ = '\013'; break; /* VT */
  563. case 'a': *p++ = '\007'; break; /* BEL, not classic C */
  564. case '0': case '1': case '2': case '3':
  565. case '4': case '5': case '6': case '7':
  566. c = s[-1] - '0';
  567. if (s < end && '0' <= *s && *s <= '7') {
  568. c = (c<<3) + *s++ - '0';
  569. if (s < end && '0' <= *s && *s <= '7')
  570. c = (c<<3) + *s++ - '0';
  571. }
  572. *p++ = c;
  573. break;
  574. case 'x':
  575. if (s+1 < end &&
  576. isxdigit(Py_CHARMASK(s[0])) &&
  577. isxdigit(Py_CHARMASK(s[1])))
  578. {
  579. unsigned int x = 0;
  580. c = Py_CHARMASK(*s);
  581. s++;
  582. if (isdigit(c))
  583. x = c - '0';
  584. else if (islower(c))
  585. x = 10 + c - 'a';
  586. else
  587. x = 10 + c - 'A';
  588. x = x << 4;
  589. c = Py_CHARMASK(*s);
  590. s++;
  591. if (isdigit(c))
  592. x += c - '0';
  593. else if (islower(c))
  594. x += 10 + c - 'a';
  595. else
  596. x += 10 + c - 'A';
  597. *p++ = x;
  598. break;
  599. }
  600. if (!errors || strcmp(errors, "strict") == 0) {
  601. PyErr_SetString(PyExc_ValueError,
  602. "invalid \\x escape");
  603. goto failed;
  604. }
  605. if (strcmp(errors, "replace") == 0) {
  606. *p++ = '?';
  607. } else if (strcmp(errors, "ignore") == 0)
  608. /* do nothing */;
  609. else {
  610. PyErr_Format(PyExc_ValueError,
  611. "decoding error; "
  612. "unknown error handling code: %.400s",
  613. errors);
  614. goto failed;
  615. }
  616. #ifndef Py_USING_UNICODE
  617. case 'u':
  618. case 'U':
  619. case 'N':
  620. if (unicode) {
  621. PyErr_SetString(PyExc_ValueError,
  622. "Unicode escapes not legal "
  623. "when Unicode disabled");
  624. goto failed;
  625. }
  626. #endif
  627. default:
  628. *p++ = '\\';
  629. s--;
  630. goto non_esc; /* an arbitry number of unescaped
  631. UTF-8 bytes may follow. */
  632. }
  633. }
  634. if (p-buf < newlen)
  635. _PyString_Resize(&v, p - buf);
  636. return v;
  637. failed:
  638. Py_DECREF(v);
  639. return NULL;
  640. }
  641. /* -------------------------------------------------------------------- */
  642. /* object api */
  643. static Py_ssize_t
  644. string_getsize(register PyObject *op)
  645. {
  646. char *s;
  647. Py_ssize_t len;
  648. if (PyString_AsStringAndSize(op, &s, &len))
  649. return -1;
  650. return len;
  651. }
  652. static /*const*/ char *
  653. string_getbuffer(register PyObject *op)
  654. {
  655. char *s;
  656. Py_ssize_t len;
  657. if (PyString_AsStringAndSize(op, &s, &len))
  658. return NULL;
  659. return s;
  660. }
  661. Py_ssize_t
  662. PyString_Size(register PyObject *op)
  663. {
  664. if (!PyString_Check(op))
  665. return string_getsize(op);
  666. return Py_SIZE(op);
  667. }
  668. /*const*/ char *
  669. PyString_AsString(register PyObject *op)
  670. {
  671. if (!PyString_Check(op))
  672. return string_getbuffer(op);
  673. return ((PyStringObject *)op) -> ob_sval;
  674. }
  675. int
  676. PyString_AsStringAndSize(register PyObject *obj,
  677. register char **s,
  678. register Py_ssize_t *len)
  679. {
  680. if (s == NULL) {
  681. PyErr_BadInternalCall();
  682. return -1;
  683. }
  684. if (!PyString_Check(obj)) {
  685. #ifdef Py_USING_UNICODE
  686. if (PyUnicode_Check(obj)) {
  687. obj = _PyUnicode_AsDefaultEncodedString(obj, NULL);
  688. if (obj == NULL)
  689. return -1;
  690. }
  691. else
  692. #endif
  693. {
  694. PyErr_Format(PyExc_TypeError,
  695. "expected string or Unicode object, "
  696. "%.200s found", Py_TYPE(obj)->tp_name);
  697. return -1;
  698. }
  699. }
  700. *s = PyString_AS_STRING(obj);
  701. if (len != NULL)
  702. *len = PyString_GET_SIZE(obj);
  703. else if (strlen(*s) != (size_t)PyString_GET_SIZE(obj)) {
  704. PyErr_SetString(PyExc_TypeError,
  705. "expected string without null bytes");
  706. return -1;
  707. }
  708. return 0;
  709. }
  710. /* -------------------------------------------------------------------- */
  711. /* Methods */
  712. #include "stringlib/stringdefs.h"
  713. #include "stringlib/fastsearch.h"
  714. #include "stringlib/count.h"
  715. #include "stringlib/find.h"
  716. #include "stringlib/partition.h"
  717. #define _Py_InsertThousandsGrouping _PyString_InsertThousandsGrouping
  718. #include "stringlib/localeutil.h"
  719. static int
  720. string_print(PyStringObject *op, FILE *fp, int flags)
  721. {
  722. Py_ssize_t i, str_len;
  723. char c;
  724. int quote;
  725. /* XXX Ought to check for interrupts when writing long strings */
  726. if (! PyString_CheckExact(op)) {
  727. int ret;
  728. /* A str subclass may have its own __str__ method. */
  729. op = (PyStringObject *) PyObject_Str((PyObject *)op);
  730. if (op == NULL)
  731. return -1;
  732. ret = string_print(op, fp, flags);
  733. Py_DECREF(op);
  734. return ret;
  735. }
  736. if (flags & Py_PRINT_RAW) {
  737. char *data = op->ob_sval;
  738. Py_ssize_t size = Py_SIZE(op);
  739. Py_BEGIN_ALLOW_THREADS
  740. while (size > INT_MAX) {
  741. /* Very long strings cannot be written atomically.
  742. * But don't write exactly INT_MAX bytes at a time
  743. * to avoid memory aligment issues.
  744. */
  745. const int chunk_size = INT_MAX & ~0x3FFF;
  746. fwrite(data, 1, chunk_size, fp);
  747. data += chunk_size;
  748. size -= chunk_size;
  749. }
  750. #ifdef __VMS
  751. if (size) fwrite(data, (int)size, 1, fp);
  752. #else
  753. fwrite(data, 1, (int)size, fp);
  754. #endif
  755. Py_END_ALLOW_THREADS
  756. return 0;
  757. }
  758. /* figure out which quote to use; single is preferred */
  759. quote = '\'';
  760. if (memchr(op->ob_sval, '\'', Py_SIZE(op)) &&
  761. !memchr(op->ob_sval, '"', Py_SIZE(op)))
  762. quote = '"';
  763. str_len = Py_SIZE(op);
  764. Py_BEGIN_ALLOW_THREADS
  765. fputc(quote, fp);
  766. for (i = 0; i < str_len; i++) {
  767. /* Since strings are immutable and the caller should have a
  768. reference, accessing the interal buffer should not be an issue
  769. with the GIL released. */
  770. c = op->ob_sval[i];
  771. if (c == quote || c == '\\')
  772. fprintf(fp, "\\%c", c);
  773. else if (c == '\t')
  774. fprintf(fp, "\\t");
  775. else if (c == '\n')
  776. fprintf(fp, "\\n");
  777. else if (c == '\r')
  778. fprintf(fp, "\\r");
  779. else if (c < ' ' || c >= 0x7f)
  780. fprintf(fp, "\\x%02x", c & 0xff);
  781. else
  782. fputc(c, fp);
  783. }
  784. fputc(quote, fp);
  785. Py_END_ALLOW_THREADS
  786. return 0;
  787. }
  788. PyObject *
  789. PyString_Repr(PyObject *obj, int smartquotes)
  790. {
  791. register PyStringObject* op = (PyStringObject*) obj;
  792. size_t newsize = 2 + 4 * Py_SIZE(op);
  793. PyObject *v;
  794. if (newsize > PY_SSIZE_T_MAX || newsize / 4 != Py_SIZE(op)) {
  795. PyErr_SetString(PyExc_OverflowError,
  796. "string is too large to make repr");
  797. return NULL;
  798. }
  799. v = PyString_FromStringAndSize((char *)NULL, newsize);
  800. if (v == NULL) {
  801. return NULL;
  802. }
  803. else {
  804. register Py_ssize_t i;
  805. register char c;
  806. register char *p;
  807. int quote;
  808. /* figure out which quote to use; single is preferred */
  809. quote = '\'';
  810. if (smartquotes &&
  811. memchr(op->ob_sval, '\'', Py_SIZE(op)) &&
  812. !memchr(op->ob_sval, '"', Py_SIZE(op)))
  813. quote = '"';
  814. p = PyString_AS_STRING(v);
  815. *p++ = quote;
  816. for (i = 0; i < Py_SIZE(op); i++) {
  817. /* There's at least enough room for a hex escape
  818. and a closing quote. */
  819. assert(newsize - (p - PyString_AS_STRING(v)) >= 5);
  820. c = op->ob_sval[i];
  821. if (c == quote || c == '\\')
  822. *p++ = '\\', *p++ = c;
  823. else if (c == '\t')
  824. *p++ = '\\', *p++ = 't';
  825. else if (c == '\n')
  826. *p++ = '\\', *p++ = 'n';
  827. else if (c == '\r')
  828. *p++ = '\\', *p++ = 'r';
  829. else if (c < ' ' || c >= 0x7f) {
  830. /* For performance, we don't want to call
  831. PyOS_snprintf here (extra layers of
  832. function call). */
  833. sprintf(p, "\\x%02x", c & 0xff);
  834. p += 4;
  835. }
  836. else
  837. *p++ = c;
  838. }
  839. assert(newsize - (p - PyString_AS_STRING(v)) >= 1);
  840. *p++ = quote;
  841. *p = '\0';
  842. _PyString_Resize(
  843. &v, (p - PyString_AS_STRING(v)));
  844. return v;
  845. }
  846. }
  847. static PyObject *
  848. string_repr(PyObject *op)
  849. {
  850. return PyString_Repr(op, 1);
  851. }
  852. static PyObject *
  853. string_str(PyObject *s)
  854. {
  855. assert(PyString_Check(s));
  856. if (PyString_CheckExact(s)) {
  857. Py_INCREF(s);
  858. return s;
  859. }
  860. else {
  861. /* Subtype -- return genuine string with the same value. */
  862. PyStringObject *t = (PyStringObject *) s;
  863. return PyString_FromStringAndSize(t->ob_sval, Py_SIZE(t));
  864. }
  865. }
  866. static Py_ssize_t
  867. string_length(PyStringObject *a)
  868. {
  869. return Py_SIZE(a);
  870. }
  871. static PyObject *
  872. string_concat(register PyStringObject *a, register PyObject *bb)
  873. {
  874. register Py_ssize_t size;
  875. register PyStringObject *op;
  876. if (!PyString_Check(bb)) {
  877. #ifdef Py_USING_UNICODE
  878. if (PyUnicode_Check(bb))
  879. return PyUnicode_Concat((PyObject *)a, bb);
  880. #endif
  881. if (PyByteArray_Check(bb))
  882. return PyByteArray_Concat((PyObject *)a, bb);
  883. PyErr_Format(PyExc_TypeError,
  884. "cannot concatenate 'str' and '%.200s' objects",
  885. Py_TYPE(bb)->tp_name);
  886. return NULL;
  887. }
  888. #define b ((PyStringObject *)bb)
  889. /* Optimize cases with empty left or right operand */
  890. if ((Py_SIZE(a) == 0 || Py_SIZE(b) == 0) &&
  891. PyString_CheckExact(a) && PyString_CheckExact(b)) {
  892. if (Py_SIZE(a) == 0) {
  893. Py_INCREF(bb);
  894. return bb;
  895. }
  896. Py_INCREF(a);
  897. return (PyObject *)a;
  898. }
  899. size = Py_SIZE(a) + Py_SIZE(b);
  900. /* Check that string sizes are not negative, to prevent an
  901. overflow in cases where we are passed incorrectly-created
  902. strings with negative lengths (due to a bug in other code).
  903. */
  904. if (Py_SIZE(a) < 0 || Py_SIZE(b) < 0 ||
  905. Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
  906. PyErr_SetString(PyExc_OverflowError,
  907. "strings are too large to concat");
  908. return NULL;
  909. }
  910. /* Inline PyObject_NewVar */
  911. if (size > PY_SSIZE_T_MAX - sizeof(PyStringObject)) {
  912. PyErr_SetString(PyExc_OverflowError,
  913. "strings are too large to concat");
  914. return NULL;
  915. }
  916. op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
  917. if (op == NULL)
  918. return PyErr_NoMemory();
  919. PyObject_INIT_VAR(op, &PyString_Type, size);
  920. op->ob_shash = -1;
  921. op->ob_sstate = SSTATE_NOT_INTERNED;
  922. Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
  923. Py_MEMCPY(op->ob_sval + Py_SIZE(a), b->ob_sval, Py_SIZE(b));
  924. op->ob_sval[size] = '\0';
  925. return (PyObject *) op;
  926. #undef b
  927. }
  928. static PyObject *
  929. string_repeat(register PyStringObject *a, register Py_ssize_t n)
  930. {
  931. register Py_ssize_t i;
  932. register Py_ssize_t j;
  933. register Py_ssize_t size;
  934. register PyStringObject *op;
  935. size_t nbytes;
  936. if (n < 0)
  937. n = 0;
  938. /* watch out for overflows: the size can overflow int,
  939. * and the # of bytes needed can overflow size_t
  940. */
  941. size = Py_SIZE(a) * n;
  942. if (n && size / n != Py_SIZE(a)) {
  943. PyErr_SetString(PyExc_OverflowError,
  944. "repeated string is too long");
  945. return NULL;
  946. }
  947. if (size == Py_SIZE(a) && PyString_CheckExact(a)) {
  948. Py_INCREF(a);
  949. return (PyObject *)a;
  950. }
  951. nbytes = (size_t)size;
  952. if (nbytes + sizeof(PyStringObject) <= nbytes) {
  953. PyErr_SetString(PyExc_OverflowError,
  954. "repeated string is too long");
  955. return NULL;
  956. }
  957. op = (PyStringObject *)
  958. PyObject_MALLOC(sizeof(PyStringObject) + nbytes);
  959. if (op == NULL)
  960. return PyErr_NoMemory();
  961. PyObject_INIT_VAR(op, &PyString_Type, size);
  962. op->ob_shash = -1;
  963. op->ob_sstate = SSTATE_NOT_INTERNED;
  964. op->ob_sval[size] = '\0';
  965. if (Py_SIZE(a) == 1 && n > 0) {
  966. memset(op->ob_sval, a->ob_sval[0] , n);
  967. return (PyObject *) op;
  968. }
  969. i = 0;
  970. if (i < size) {
  971. Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
  972. i = Py_SIZE(a);
  973. }
  974. while (i < size) {
  975. j = (i <= size-i) ? i : size-i;
  976. Py_MEMCPY(op->ob_sval+i, op->ob_sval, j);
  977. i += j;
  978. }
  979. return (PyObject *) op;
  980. }
  981. /* String slice a[i:j] consists of characters a[i] ... a[j-1] */
  982. static PyObject *
  983. string_slice(register PyStringObject *a, register Py_ssize_t i,
  984. register Py_ssize_t j)
  985. /* j -- may be negative! */
  986. {
  987. if (i < 0)
  988. i = 0;
  989. if (j < 0)
  990. j = 0; /* Avoid signed/unsigned bug in next line */
  991. if (j > Py_SIZE(a))
  992. j = Py_SIZE(a);
  993. if (i == 0 && j == Py_SIZE(a) && PyString_CheckExact(a)) {
  994. /* It's the same as a */
  995. Py_INCREF(a);
  996. return (PyObject *)a;
  997. }
  998. if (j < i)
  999. j = i;
  1000. return PyString_FromStringAndSize(a->ob_sval + i, j-i);
  1001. }
  1002. static int
  1003. string_contains(PyObject *str_obj, PyObject *sub_obj)
  1004. {
  1005. if (!PyString_CheckExact(sub_obj)) {
  1006. #ifdef Py_USING_UNICODE
  1007. if (PyUnicode_Check(sub_obj))
  1008. return PyUnicode_Contains(str_obj, sub_obj);
  1009. #endif
  1010. if (!PyString_Check(sub_obj)) {
  1011. PyErr_Format(PyExc_TypeError,
  1012. "'in <string>' requires string as left operand, "
  1013. "not %.200s", Py_TYPE(sub_obj)->tp_name);
  1014. return -1;
  1015. }
  1016. }
  1017. return stringlib_contains_obj(str_obj, sub_obj);
  1018. }
  1019. static PyObject *
  1020. string_item(PyStringObject *a, register Py_ssize_t i)
  1021. {
  1022. char pchar;
  1023. PyObject *v;
  1024. if (i < 0 || i >= Py_SIZE(a)) {
  1025. PyErr_SetString(PyExc_IndexError, "string index out of range");
  1026. return NULL;
  1027. }
  1028. pchar = a->ob_sval[i];
  1029. v = (PyObject *)characters[pchar & UCHAR_MAX];
  1030. if (v == NULL)
  1031. v = PyString_FromStringAndSize(&pchar, 1);
  1032. else {
  1033. #ifdef COUNT_ALLOCS
  1034. one_strings++;
  1035. #endif
  1036. Py_INCREF(v);
  1037. }
  1038. return v;
  1039. }
  1040. static PyObject*
  1041. string_richcompare(PyStringObject *a, PyStringObject *b, int op)
  1042. {
  1043. int c;
  1044. Py_ssize_t len_a, len_b;
  1045. Py_ssize_t min_len;
  1046. PyObject *result;
  1047. /* Make sure both arguments are strings. */
  1048. if (!(PyString_Check(a) && PyString_Check(b))) {
  1049. result = Py_NotImplemented;
  1050. goto out;
  1051. }
  1052. if (a == b) {
  1053. switch (op) {
  1054. case Py_EQ:case Py_LE:case Py_GE:
  1055. result = Py_True;
  1056. goto out;
  1057. case Py_NE:case Py_LT:case Py_GT:
  1058. result = Py_False;
  1059. goto out;
  1060. }
  1061. }
  1062. if (op == Py_EQ) {
  1063. /* Supporting Py_NE here as well does not save
  1064. much time, since Py_NE is rarely used. */
  1065. if (Py_SIZE(a) == Py_SIZE(b)
  1066. && (a->ob_sval[0] == b->ob_sval[0]
  1067. && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0)) {
  1068. result = Py_True;
  1069. } else {
  1070. result = Py_False;
  1071. }
  1072. goto out;
  1073. }
  1074. len_a = Py_SIZE(a); len_b = Py_SIZE(b);
  1075. min_len = (len_a < len_b) ? len_a : len_b;
  1076. if (min_len > 0) {
  1077. c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
  1078. if (c==0)
  1079. c = memcmp(a->ob_sval, b->ob_sval, min_len);
  1080. } else
  1081. c = 0;
  1082. if (c == 0)
  1083. c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
  1084. switch (op) {
  1085. case Py_LT: c = c < 0; break;
  1086. case Py_LE: c = c <= 0; break;
  1087. case Py_EQ: assert(0); break; /* unreachable */
  1088. case Py_NE: c = c != 0; break;
  1089. case Py_GT: c = c > 0; break;
  1090. case Py_GE: c = c >= 0; break;
  1091. default:
  1092. result = Py_NotImplemented;
  1093. goto out;
  1094. }
  1095. result = c ? Py_True : Py_False;
  1096. out:
  1097. Py_INCREF(result);
  1098. return result;
  1099. }
  1100. int
  1101. _PyString_Eq(PyObject *o1, PyObject *o2)
  1102. {
  1103. PyStringObject *a = (PyStringObject*) o1;
  1104. PyStringObject *b = (PyStringObject*) o2;
  1105. return Py_SIZE(a) == Py_SIZE(b)
  1106. && *a->ob_sval == *b->ob_sval
  1107. && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0;
  1108. }
  1109. static long
  1110. string_hash(PyStringObject *a)
  1111. {
  1112. register Py_ssize_t len;
  1113. register unsigned char *p;
  1114. register long x;
  1115. if (a->ob_shash != -1)
  1116. return a->ob_shash;
  1117. len = Py_SIZE(a);
  1118. p = (unsigned char *) a->ob_sval;
  1119. x = *p << 7;
  1120. while (--len >= 0)
  1121. x = (1000003*x) ^ *p++;
  1122. x ^= Py_SIZE(a);
  1123. if (x == -1)
  1124. x = -2;
  1125. a->ob_shash = x;
  1126. return x;
  1127. }
  1128. static PyObject*
  1129. string_subscript(PyStringObject* self, PyObject* item)
  1130. {
  1131. if (PyIndex_Check(item)) {
  1132. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  1133. if (i == -1 && PyErr_Occurred())
  1134. return NULL;
  1135. if (i < 0)
  1136. i += PyString_GET_SIZE(self);
  1137. return string_item(self, i);
  1138. }
  1139. else if (PySlice_Check(item)) {
  1140. Py_ssize_t start, stop, step, slicelength, cur, i;
  1141. char* source_buf;
  1142. char* result_buf;
  1143. PyObject* result;
  1144. if (PySlice_GetIndicesEx((PySliceObject*)item,
  1145. PyString_GET_SIZE(self),
  1146. &start, &stop, &step, &slicelength) < 0) {
  1147. return NULL;
  1148. }
  1149. if (slicelength <= 0) {
  1150. return PyString_FromStringAndSize("", 0);
  1151. }
  1152. else if (start == 0 && step == 1 &&
  1153. slicelength == PyString_GET_SIZE(self) &&
  1154. PyString_CheckExact(self)) {
  1155. Py_INCREF(self);
  1156. return (PyObject *)self;
  1157. }
  1158. else if (step == 1) {
  1159. return PyString_FromStringAndSize(
  1160. PyString_AS_STRING(self) + start,
  1161. slicelength);
  1162. }
  1163. else {
  1164. source_buf = PyString_AsString((PyObject*)self);
  1165. result_buf = (char *)PyMem_Malloc(slicelength);
  1166. if (result_buf == NULL)
  1167. return PyErr_NoMemory();
  1168. for (cur = start, i = 0; i < slicelength;
  1169. cur += step, i++) {
  1170. result_buf[i] = source_buf[cur];
  1171. }
  1172. result = PyString_FromStringAndSize(result_buf,
  1173. slicelength);
  1174. PyMem_Free(result_buf);
  1175. return result;
  1176. }
  1177. }
  1178. else {
  1179. PyErr_Format(PyExc_TypeError,
  1180. "string indices must be integers, not %.200s",
  1181. Py_TYPE(item)->tp_name);
  1182. return NULL;
  1183. }
  1184. }
  1185. static Py_ssize_t
  1186. string_buffer_getreadbuf(PyStringObject *self, Py_ssize_t index, const void **ptr)
  1187. {
  1188. if ( index != 0 ) {
  1189. PyErr_SetString(PyExc_SystemError,
  1190. "accessing non-existent string segment");
  1191. return -1;
  1192. }
  1193. *ptr = (void *)self->ob_sval;
  1194. return Py_SIZE(self);
  1195. }
  1196. static Py_ssize_t
  1197. string_buffer_getwritebuf(PyStringObject *self, Py_ssize_t index, const void **ptr)
  1198. {
  1199. PyErr_SetString(PyExc_TypeError,
  1200. "Cannot use string as modifiable buffer");
  1201. return -1;
  1202. }
  1203. static Py_ssize_t
  1204. string_buffer_getsegcount(PyStringObject *self, Py_ssize_t *lenp)
  1205. {
  1206. if ( lenp )
  1207. *lenp = Py_SIZE(self);
  1208. return 1;
  1209. }
  1210. static Py_ssize_t
  1211. string_buffer_getcharbuf(PyStringObject *self, Py_ssize_t index, const char **ptr)
  1212. {
  1213. if ( index != 0 ) {
  1214. PyErr_SetString(PyExc_SystemError,
  1215. "accessing non-existent string segment");
  1216. return -1;
  1217. }
  1218. *ptr = self->ob_sval;
  1219. return Py_SIZE(self);
  1220. }
  1221. static int
  1222. string_buffer_getbuffer(PyStringObject *self, Py_buffer *view, int flags)
  1223. {
  1224. return PyBuffer_FillInfo(view, (PyObject*)self,
  1225. (void *)self->ob_sval, Py_SIZE(self),
  1226. 1, flags);
  1227. }
  1228. static PySequenceMethods string_as_sequence = {
  1229. (lenfunc)string_length, /*sq_length*/
  1230. (binaryfunc)string_concat, /*sq_concat*/
  1231. (ssizeargfunc)string_repeat, /*sq_repeat*/
  1232. (ssizeargfunc)string_item, /*sq_item*/
  1233. (ssizessizeargfunc)string_slice, /*sq_slice*/
  1234. 0, /*sq_ass_item*/
  1235. 0, /*sq_ass_slice*/
  1236. (objobjproc)string_contains /*sq_contains*/
  1237. };
  1238. static PyMappingMethods string_as_mapping = {
  1239. (lenfunc)string_length,
  1240. (binaryfunc)string_subscript,
  1241. 0,
  1242. };
  1243. static PyBufferProcs string_as_buffer = {
  1244. (readbufferproc)string_buffer_getreadbuf,
  1245. (writebufferproc)string_buffer_getwritebuf,
  1246. (segcountproc)string_buffer_getsegcount,
  1247. (charbufferproc)string_buffer_getcharbuf,
  1248. (getbufferproc)string_buffer_getbuffer,
  1249. 0, /* XXX */
  1250. };
  1251. #define LEFTSTRIP 0
  1252. #define RIGHTSTRIP 1
  1253. #define BOTHSTRIP 2
  1254. /* Arrays indexed by above */
  1255. static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
  1256. #define STRIPNAME(i) (stripformat[i]+3)
  1257. /* Don't call if length < 2 */
  1258. #define Py_STRING_MATCH(target, offset, pattern, length) \
  1259. (target[offset] == pattern[0] && \
  1260. target[offset+length-1] == pattern[length-1] && \
  1261. !memcmp(target+offset+1, pattern+1, length-2) )
  1262. /* Overallocate the initial list to reduce the number of reallocs for small
  1263. split sizes. Eg, "A A A A A A A A A A".split() (10 elements) has three
  1264. resizes, to sizes 4, 8, then 16. Most observed string splits are for human
  1265. text (roughly 11 words per line) and field delimited data (usually 1-10
  1266. fields). For large strings the split algorithms are bandwidth limited
  1267. so increasing the preallocation likely will not improve things.*/
  1268. #define MAX_PREALLOC 12
  1269. /* 5 splits gives 6 elements */
  1270. #define PREALLOC_SIZE(maxsplit) \
  1271. (maxsplit >= MAX_PREALLOC ? MAX_PREALLOC : maxsplit+1)
  1272. #define SPLIT_APPEND(data, left, right) \
  1273. str = PyString_FromStringAndSize((data) + (left), \
  1274. (right) - (left)); \
  1275. if (str == NULL) \
  1276. goto onError; \
  1277. if (PyList_Append(list, str)) { \
  1278. Py_DECREF(str); \
  1279. goto onError; \
  1280. } \
  1281. else \
  1282. Py_DECREF(str);
  1283. #define SPLIT_ADD(data, left, right) { \
  1284. str = PyString_FromStringAndSize((data) + (left), \
  1285. (right) - (left)); \
  1286. if (str == NULL) \
  1287. goto onError; \
  1288. if (count < MAX_PREALLOC) { \
  1289. PyList_SET_ITEM(list, count, str); \
  1290. } else { \
  1291. if (PyList_Append(list, str)) { \
  1292. Py_DECREF(str); \
  1293. goto onError; \
  1294. } \
  1295. else \
  1296. Py_DECREF(str); \
  1297. } \
  1298. count++; }
  1299. /* Always force the list to the expected size. */
  1300. #define FIX_PREALLOC_SIZE(list) Py_SIZE(list) = count
  1301. #define SKIP_SPACE(s, i, len) { while (i<len && isspace(Py_CHARMASK(s[i]))) i++; }
  1302. #define SKIP_NONSPACE(s, i, len) { while (i<len && !isspace(Py_CHARMASK(s[i]))) i++; }
  1303. #define RSKIP_SPACE(s, i) { while (i>=0 && isspace(Py_CHARMASK(s[i]))) i--; }
  1304. #define RSKIP_NONSPACE(s, i) { while (i>=0 && !isspace(Py_CHARMASK(s[i]))) i--; }
  1305. Py_LOCAL_INLINE(PyObject *)
  1306. split_whitespace(PyStringObject *self, Py_ssize_t len, Py_ssize_t maxsplit)
  1307. {
  1308. const char *s = PyString_AS_STRING(self);
  1309. Py_ssize_t i, j, count=0;
  1310. PyObject *str;
  1311. PyObject *list = PyList_New(PREALLOC_SIZE(maxsplit));
  1312. if (list == NULL)
  1313. return NULL;
  1314. i = j = 0;
  1315. while (maxsplit-- > 0) {
  1316. SKIP_SPACE(s, i, len);
  1317. if (i==len) break;
  1318. j = i; i++;
  1319. SKIP_NONSPACE(s, i, len);
  1320. if (j == 0 && i == len && PyString_CheckExact(self)) {
  1321. /* No whitespace in self, so just use it as list[0] */
  1322. Py_INCREF(self);
  1323. PyList_SET_ITEM(list, 0, (PyObject *)self);
  1324. count++;
  1325. break;
  1326. }
  1327. SPLIT_ADD(s, j, i);
  1328. }
  1329. if (i < len) {
  1330. /* Only occurs when maxsplit was reached */
  1331. /* Skip any remaining whitespace and copy to end of string */
  1332. SKIP_SPACE(s, i, len);
  1333. if (i != len)
  1334. SPLIT_ADD(s, i, len);
  1335. }
  1336. FIX_PREALLOC_SIZE(list);
  1337. return list;
  1338. onError:
  1339. Py_DECREF(list);
  1340. return NULL;
  1341. }
  1342. Py_LOCAL_INLINE(PyObject *)
  1343. split_char(PyStringObject *self, Py_ssize_t len, char ch, Py_ssize_t maxcount)
  1344. {
  1345. const char *s = PyString_AS_STRING(self);
  1346. register Py_ssize_t i, j, count=0;
  1347. PyObject *str;
  1348. PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
  1349. if (list == NULL)
  1350. return NULL;
  1351. i = j = 0;
  1352. while ((j < len) && (maxcount-- > 0)) {
  1353. for(; j<len; j++) {
  1354. /* I found that using memchr makes no difference */
  1355. if (s[j] == ch) {
  1356. SPLIT_ADD(s, i, j);
  1357. i = j = j + 1;
  1358. break;
  1359. }
  1360. }
  1361. }
  1362. if (i == 0 && count == 0 && PyString_CheckExact(self)) {
  1363. /* ch not in self, so just use self as list[0] */
  1364. Py_INCREF(self);
  1365. PyList_SET_ITEM(list, 0, (PyObject *)self);
  1366. count++;
  1367. }
  1368. else if (i <= len) {
  1369. SPLIT_ADD(s, i, len);
  1370. }
  1371. FIX_PREALLOC_SIZE(list);
  1372. return list;
  1373. onError:
  1374. Py_DECREF(list);
  1375. return NULL;
  1376. }
  1377. PyDoc_STRVAR(split__doc__,
  1378. "S.split([sep [,maxsplit]]) -> list of strings\n\
  1379. \n\
  1380. Return a list of the words in the string S, using sep as the\n\
  1381. delimiter string. If maxsplit is given, at most maxsplit\n\
  1382. splits are done. If sep is not specified or is None, any\n\
  1383. whitespace string is a separator and empty strings are removed\n\
  1384. from the result.");
  1385. static PyObject *
  1386. string_split(PyStringObject *self, PyObject *args)
  1387. {
  1388. Py_ssize_t len = PyString_GET_SIZE(self), n, i, j;
  1389. Py_ssize_t maxsplit = -1, count=0;
  1390. const char *s = PyString_AS_STRING(self), *sub;
  1391. PyObject *list, *str, *subobj = Py_None;
  1392. #ifdef USE_FAST
  1393. Py_ssize_t pos;
  1394. #endif
  1395. if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
  1396. return NULL;
  1397. if (maxsplit < 0)
  1398. maxsplit = PY_SSIZE_T_MAX;
  1399. if (subobj == Py_None)
  1400. return split_whitespace(self, len, maxsplit);
  1401. if (PyString_Check(subobj)) {
  1402. sub = PyString_AS_STRING(subobj);
  1403. n = PyString_GET_SIZE(subobj);
  1404. }
  1405. #ifdef Py_USING_UNICODE
  1406. else if (PyUnicode_Check(subobj))
  1407. return PyUnicode_Split((PyObject *)self, subobj, maxsplit);
  1408. #endif
  1409. else if (PyObject_AsCharBuffer(subobj, &sub, &n))
  1410. return NULL;
  1411. if (n == 0) {
  1412. PyErr_SetString(PyExc_ValueError, "empty separator");
  1413. return NULL;
  1414. }
  1415. else if (n == 1)
  1416. return split_char(self, len, sub[0], maxsplit);
  1417. list = PyList_New(PREALLOC_SIZE(maxsplit));
  1418. if (list == NULL)
  1419. return NULL;
  1420. #ifdef USE_FAST
  1421. i = j = 0;
  1422. while (maxsplit-- > 0) {
  1423. pos = fastsearch(s+i, len-i, sub, n, FAST_SEARCH);
  1424. if (pos < 0)
  1425. break;
  1426. j = i+pos;
  1427. SPLIT_ADD(s, i, j);
  1428. i = j + n;
  1429. }
  1430. #else
  1431. i = j = 0;
  1432. while ((j+n <= len) && (maxsplit-- > 0)) {
  1433. for (; j+n <= len; j++) {
  1434. if (Py_STRING_MATCH(s, j, sub, n)) {
  1435. SPLIT_ADD(s, i, j);
  1436. i = j = j + n;
  1437. break;
  1438. }
  1439. }
  1440. }
  1441. #endif
  1442. SPLIT_ADD(s, i, len);
  1443. FIX_PREALLOC_SIZE(list);
  1444. return list;
  1445. onError:
  1446. Py_DECREF(list);
  1447. return NULL;
  1448. }
  1449. PyDoc_STRVAR(partition__doc__,
  1450. "S.partition(sep) -> (head, sep, tail)\n\
  1451. \n\
  1452. Search for the separator sep in S, and return the part before it,\n\
  1453. the separator itself, and the part after it. If the separator is not\n\
  1454. found, return S and two empty strings.");
  1455. static PyObject *
  1456. string_partition(PyStringObject *self, PyObject *sep_obj)
  1457. {
  1458. const char *sep;
  1459. Py_ssize_t sep_len;
  1460. if (PyString_Check(sep_obj)) {
  1461. sep = PyString_AS_STRING(sep_obj);
  1462. sep_len = PyString_GET_SIZE(sep_obj);
  1463. }
  1464. #ifdef Py_USING_UNICODE
  1465. else if (PyUnicode_Check(sep_obj))
  1466. return PyUnicode_Partition((PyObject *) self, sep_obj);
  1467. #endif
  1468. else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
  1469. return NULL;
  1470. return stringlib_partition(
  1471. (PyObject*) self,
  1472. PyString_AS_STRING(self), PyString_GET_SIZE(self),
  1473. sep_obj, sep, sep_len
  1474. );
  1475. }
  1476. PyDoc_STRVAR(rpartition__doc__,
  1477. "S.rpartition(sep) -> (tail, sep, head)\n\
  1478. \n\
  1479. Search for the separator sep in S, starting at the end of S, and return\n\
  1480. the part before it, the separator itself, and the part after it. If the\n\
  1481. separator is not found, return two empty strings and S.");
  1482. static PyObject *
  1483. string_rpartition(PyStringObject *self, PyObject *sep_obj)
  1484. {
  1485. const char *sep;
  1486. Py_ssize_t sep_len;
  1487. if (PyString_Check(sep_obj)) {
  1488. sep = PyString_AS_STRING(sep_obj);
  1489. sep_len = PyString_GET_SIZE(sep_obj);
  1490. }
  1491. #ifdef Py_USING_UNICODE
  1492. else if (PyUnicode_Check(sep_obj))
  1493. return PyUnicode_RPartition((PyObject *) self, sep_obj);
  1494. #endif
  1495. else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
  1496. return NULL;
  1497. return stringlib_rpartition(
  1498. (PyObject*) self,
  1499. PyString_AS_STRING(self), PyString_GET_SIZE(self),
  1500. sep_obj, sep, sep_len
  1501. );
  1502. }
  1503. Py_LOCAL_INLINE(PyObject *)
  1504. rsplit_whitespace(PyStringObject *self, Py_ssize_t len, Py_ssize_t maxsplit)
  1505. {
  1506. const char *s = PyString_AS_STRING(self);
  1507. Py_ssize_t i, j, count=0;
  1508. PyObject *str;
  1509. PyObject *list = PyList_New(PREALLOC_SIZE(maxsplit));
  1510. if (list == NULL)
  1511. return NULL;
  1512. i = j = len-1;
  1513. while (maxsplit-- > 0) {
  1514. RSKIP_SPACE(s, i);
  1515. if (i<0) break;
  1516. j = i; i--;
  1517. RSKIP_NONSPACE(s, i);
  1518. if (j == len-1 && i < 0 && PyString_CheckExact(self)) {
  1519. /* No whitespace in self, so just use it as list[0] */
  1520. Py_INCREF(self);
  1521. PyList_SET_ITEM(list, 0, (PyObject *)self);
  1522. count++;
  1523. break;
  1524. }
  1525. SPLIT_ADD(s, i + 1, j + 1);
  1526. }
  1527. if (i >= 0) {
  1528. /* Only occurs when maxsplit was reached */
  1529. /* Skip any remaining whitespace and copy to beginning of string */
  1530. RSKIP_SPACE(s, i);
  1531. if (i >= 0)
  1532. SPLIT_ADD(s, 0, i + 1);
  1533. }
  1534. FIX_PREALLOC_SIZE(list);
  1535. if (PyList_Reverse(list) < 0)
  1536. goto onError;
  1537. return list;
  1538. onError:
  1539. Py_DECREF(list);
  1540. return NULL;
  1541. }
  1542. Py_LOCAL_INLINE(PyObject *)
  1543. rsplit_char(PyStringObject *self, Py_ssize_t len, char ch, Py_ssize_t maxcount)
  1544. {
  1545. const char *s = PyString_AS_STRING(self);
  1546. register Py_ssize_t i, j, count=0;
  1547. PyObject *str;
  1548. PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
  1549. if (list == NULL)
  1550. return NULL;
  1551. i = j = len - 1;
  1552. while ((i >= 0) && (maxcount-- > 0)) {
  1553. for (; i >= 0; i--) {
  1554. if (s[i] == ch) {
  1555. SPLIT_ADD(s, i + 1, j + 1);
  1556. j = i = i - 1;
  1557. break;
  1558. }
  1559. }
  1560. }
  1561. if (i < 0 && count == 0 && PyString_CheckExact(self)) {
  1562. /* ch not in self, so just use self as list[0] */
  1563. Py_INCREF(self);
  1564. PyList_SET_ITEM(list, 0, (PyObject *)self);
  1565. count++;
  1566. }
  1567. else if (j >= -1) {
  1568. SPLIT_ADD(s, 0, j + 1);
  1569. }
  1570. FIX_PREALLOC_SIZE(list);
  1571. if (PyList_Reverse(list) < 0)
  1572. goto onError;
  1573. return list;
  1574. onError:
  1575. Py_DECREF(list);
  1576. return NULL;
  1577. }
  1578. PyDoc_STRVAR(rsplit__doc__,
  1579. "S.rsplit([sep [,maxsplit]]) -> list of strings\n\
  1580. \n\
  1581. Return a list of the words in the string S, using sep as the\n\
  1582. delimiter string, starting at the end of the string and working\n\
  1583. to the front. If maxsplit is given, at most maxsplit splits are\n\
  1584. done. If sep is not specified or is None, any whitespace string\n\
  1585. is a separator.");
  1586. static PyObject *
  1587. string_rsplit(PyStringObject *self, PyObject *args)
  1588. {
  1589. Py_ssize_t len = PyString_GET_SIZE(self), n, i, j;
  1590. Py_ssize_t maxsplit = -1, count=0;
  1591. const char *s, *sub;
  1592. PyObject *list, *str, *subobj = Py_None;
  1593. if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
  1594. return NULL;
  1595. if (maxsplit < 0)
  1596. maxsplit = PY_SSIZE_T_MAX;
  1597. if (subobj == Py_None)
  1598. return rsplit_whitespace(self, len, maxsplit);
  1599. if (PyString_Check(subobj)) {
  1600. sub = PyString_AS_STRING(subobj);
  1601. n = PyString_GET_SIZE(subobj);
  1602. }
  1603. #ifdef Py_USING_UNICODE
  1604. else if (PyUnicode_Check(subobj))
  1605. return PyUnicode_RSplit((PyObject *)self, subobj, maxsplit);
  1606. #endif
  1607. else if (PyObject_AsCharBuffer(subobj, &sub, &n))
  1608. return NULL;
  1609. if (n == 0) {
  1610. PyErr_SetString(PyExc_ValueError, "empty separator");
  1611. return NULL;
  1612. }
  1613. else if (n == 1)
  1614. return rsplit_char(self, len, sub[0], maxsplit);
  1615. list = PyList_New(PREALLOC_SIZE(maxsplit));
  1616. if (list == NULL)
  1617. return NULL;
  1618. j = len;
  1619. i = j - n;
  1620. s = PyString_AS_STRING(self);
  1621. while ( (i >= 0) && (maxsplit-- > 0) ) {
  1622. for (; i>=0; i--) {
  1623. if (Py_STRING_MATCH(s, i, sub, n)) {
  1624. SPLIT_ADD(s, i + n, j);
  1625. j = i;
  1626. i -= n;
  1627. break;
  1628. }
  1629. }
  1630. }
  1631. SPLIT_ADD(s, 0, j);
  1632. FIX_PREALLOC_SIZE(list);
  1633. if (PyList_Reverse(list) < 0)
  1634. goto onError;
  1635. return list;
  1636. onError:
  1637. Py_DECREF(list);
  1638. return NULL;
  1639. }
  1640. PyDoc_STRVAR(join__doc__,
  1641. "S.join(sequence) -> string\n\
  1642. \n\
  1643. Return a string which is the concatenation of the strings in the\n\
  1644. sequence. The separator between elements is S.");
  1645. static PyObject *
  1646. string_join(PyStringObject *self, PyObject *orig)
  1647. {
  1648. char *sep = PyString_AS_STRING(self);
  1649. const Py_ssize_t seplen = PyString_GET_SIZE(self);
  1650. PyObject *res = NULL;
  1651. char *p;
  1652. Py_ssize_t seqlen = 0;
  1653. size_t sz = 0;
  1654. Py_ssize_t i;
  1655. PyObject *seq, *item;
  1656. seq = PySequence_Fast(orig, "");
  1657. if (seq == NULL) {
  1658. return NULL;
  1659. }
  1660. seqlen = PySequence_Size(seq);
  1661. if (seqlen == 0) {
  1662. Py_DECREF(seq);
  1663. return PyString_FromString("");
  1664. }
  1665. if (seqlen == 1) {
  1666. item = PySequence_Fast_GET_ITEM(seq, 0);
  1667. if (PyString_CheckExact(item) || PyUnicode_CheckExact(item)) {
  1668. Py_INCREF(item);
  1669. Py_DECREF(seq);
  1670. return item;
  1671. }
  1672. }
  1673. /* There are at least two things to join, or else we have a subclass
  1674. * of the builtin types in the sequence.
  1675. * Do a pre-pass to figure out the total amount of space we'll
  1676. * need (sz), see whether any argument is absurd, and defer to
  1677. * the Unicode join if appropriate.
  1678. */
  1679. for (i = 0; i < seqlen; i++) {
  1680. const size_t old_sz = sz;
  1681. item = PySequence_Fast_GET_ITEM(seq, i);
  1682. if (!PyString_Check(item)){
  1683. #ifdef Py_USING_UNICODE
  1684. if (PyUnicode_Check(item)) {
  1685. /* Defer to Unicode join.
  1686. * CAUTION: There's no gurantee that the
  1687. * original sequence can be iterated over
  1688. * again, so we must pass seq here.
  1689. */
  1690. PyObject *result;
  1691. result = PyUnicode_Join((PyObject *)self, seq);
  1692. Py_DECREF(seq);
  1693. return result;
  1694. }
  1695. #endif
  1696. PyErr_Format(PyExc_TypeError,
  1697. "sequence item %zd: expected string,"
  1698. " %.80s found",
  1699. i, Py_TYPE(item)->tp_name);
  1700. Py_DECREF(seq);
  1701. return NULL;
  1702. }
  1703. sz += PyString_GET_SIZE(item);
  1704. if (i != 0)
  1705. sz += seplen;
  1706. if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
  1707. PyErr_SetString(PyExc_OverflowError,
  1708. "join() result is too long for a Python string");
  1709. Py_DECREF(seq);
  1710. return NULL;
  1711. }
  1712. }
  1713. /* Allocate result space. */
  1714. res = PyString_FromStringAndSize((char*)NULL, sz);
  1715. if (res == NULL) {
  1716. Py_DECREF(seq);
  1717. return NULL;
  1718. }
  1719. /* Catenate everything. */
  1720. p = PyString_AS_STRING(res);
  1721. for (i = 0; i < seqlen; ++i) {
  1722. size_t n;
  1723. item = PySequence_Fast_GET_ITEM(seq, i);
  1724. n = PyString_GET_SIZE(item);
  1725. Py_MEMCPY(p, PyString_AS_STRING(item), n);
  1726. p += n;
  1727. if (i < seqlen - 1) {
  1728. Py_MEMCPY(p, sep, seplen);
  1729. p += seplen;
  1730. }
  1731. }
  1732. Py_DECREF(seq);
  1733. return res;
  1734. }
  1735. PyObject *
  1736. _PyString_Join(PyObject *sep, PyObject *x)
  1737. {
  1738. assert(sep != NULL && PyString_Check(sep));
  1739. assert(x != NULL);
  1740. return string_join((PyStringObject *)sep, x);
  1741. }
  1742. Py_LOCAL_INLINE(void)
  1743. string_adjust_indices(Py_ssize_t *start, Py_ssize_t *end, Py_ssize_t len)
  1744. {
  1745. if (*end > len)
  1746. *end = len;
  1747. else if (*end < 0)
  1748. *end += len;
  1749. if (*end < 0)
  1750. *end = 0;
  1751. if (*start < 0)
  1752. *start += len;
  1753. if (*start < 0)
  1754. *start = 0;
  1755. }
  1756. Py_LOCAL_INLINE(Py_ssize_t)
  1757. string_find_internal(PyStringObject *self, PyObject *args, int dir)
  1758. {
  1759. PyObject *subobj;
  1760. const char *sub;
  1761. Py_ssize_t sub_len;
  1762. Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
  1763. PyObject *obj_start=Py_None, *obj_end=Py_None;
  1764. if (!PyArg_ParseTuple(args, "O|OO:find/rfind/index/rindex", &subobj,
  1765. &obj_start, &obj_end))
  1766. return -2;
  1767. /* To support None in "start" and "end" arguments, meaning
  1768. the same as if they were not passed.
  1769. */
  1770. if (obj_start != Py_None)
  1771. if (!_PyEval_SliceIndex(obj_start, &start))
  1772. return -2;
  1773. if (obj_end != Py_None)
  1774. if (!_PyEval_SliceIndex(obj_end, &end))
  1775. return -2;
  1776. if (PyString_Check(subobj)) {
  1777. sub = PyString_AS_STRING(subobj);
  1778. sub_len = PyString_GET_SIZE(subobj);
  1779. }
  1780. #ifdef Py_USING_UNICODE
  1781. else if (PyUnicode_Check(subobj))
  1782. return PyUnicode_Find(
  1783. (PyObject *)self, subobj, start, end, dir);
  1784. #endif
  1785. else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len))
  1786. /* XXX - the "expected a character buffer object" is pretty
  1787. confusing for a non-expert. remap to something else ? */
  1788. return -2;
  1789. if (dir > 0)
  1790. return stringlib_find_slice(
  1791. PyString_AS_STRING(self), PyString_GET_SIZE(self),
  1792. sub, sub_len, start, end);
  1793. else
  1794. return stringlib_rfind_slice(
  1795. PyString_AS_STRING(self), PyString_GET_SIZE(self),
  1796. sub, sub_len, start, end);
  1797. }
  1798. PyDoc_STRVAR(find__doc__,
  1799. "S.find(sub [,start [,end]]) -> int\n\
  1800. \n\
  1801. Return the lowest index in S where substring sub is found,\n\
  1802. such that sub is contained within s[start:end]. Optional\n\
  1803. arguments start and end are interpreted as in slice notation.\n\
  1804. \n\
  1805. Return -1 on failure.");
  1806. static PyObject *
  1807. string_find(PyStringObject *self, PyObject *args)
  1808. {
  1809. Py_ssize_t result = string_find_internal(self, args, +1);
  1810. if (result == -2)
  1811. return NULL;
  1812. return PyInt_FromSsize_t(result);
  1813. }
  1814. PyDoc_STRVAR(index__doc__,
  1815. "S.index(sub [,start [,end]]) -> int\n\
  1816. \n\
  1817. Like S.find() but raise ValueError when the substring is not found.");
  1818. static PyObject *
  1819. string_index(PyStringObject *self, PyObject *args)
  1820. {
  1821. Py_ssize_t result = string_find_internal(self, args, +1);
  1822. if (result == -2)
  1823. return NULL;
  1824. if (result == -1) {
  1825. PyErr_SetString(PyExc_ValueError,
  1826. "substring not found");
  1827. return NULL;
  1828. }
  1829. return PyInt_FromSsize_t(result);
  1830. }
  1831. PyDoc_STRVAR(rfind__doc__,
  1832. "S.rfind(sub [,start [,end]]) -> int\n\
  1833. \n\
  1834. Return the highest index in S where substring sub is found,\n\
  1835. such that sub is contained within s[start:end]. Optional\n\
  1836. arguments start and end are interpreted as in slice notation.\n\
  1837. \n\
  1838. Return -1 on failure.");
  1839. static PyObject *
  1840. string_rfind(PyStringObject *self, PyObject *args)
  1841. {
  1842. Py_ssize_t result = string_find_internal(self, args, -1);
  1843. if (result == -2)
  1844. return NULL;
  1845. return PyInt_FromSsize_t(result);
  1846. }
  1847. PyDoc_STRVAR(rindex__doc__,
  1848. "S.rindex(sub [,start [,end]]) -> int\n\
  1849. \n\
  1850. Like S.rfind() but raise ValueError when the substring is not found.");
  1851. static PyObject *
  1852. string_rindex(PyStringObject *self, PyObject *args)
  1853. {
  1854. Py_ssize_t result = string_find_internal(self, args, -1);
  1855. if (result == -2)
  1856. return NULL;
  1857. if (result == -1) {
  1858. PyErr_SetString(PyExc_ValueError,
  1859. "substring not found");
  1860. return NULL;
  1861. }
  1862. return PyInt_FromSsize_t(result);
  1863. }
  1864. Py_LOCAL_INLINE(PyObject *)
  1865. do_xstrip(PyStringObject *self, int striptype, PyObject *sepobj)
  1866. {
  1867. char *s = PyString_AS_STRING(self);
  1868. Py_ssize_