PageRenderTime 56ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/Objects/stringobject.c

http://unladen-swallow.googlecode.com/
C | 5242 lines | 4329 code | 538 blank | 375 comment | 1221 complexity | a1c18aba068e8f25c3e3da8e22507f9f MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  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_t len = PyString_GET_SIZE(self);
  1869. char *sep = PyString_AS_STRING(sepobj);
  1870. Py_ssize_t seplen = PyString_GET_SIZE(sepobj);
  1871. Py_ssize_t i, j;
  1872. i = 0;
  1873. if (striptype != RIGHTSTRIP) {
  1874. while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) {
  1875. i++;
  1876. }
  1877. }
  1878. j = len;
  1879. if (striptype != LEFTSTRIP) {
  1880. do {
  1881. j--;
  1882. } while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen));
  1883. j++;
  1884. }
  1885. if (i == 0 && j == len && PyString_CheckExact(self)) {
  1886. Py_INCREF(self);
  1887. return (PyObject*)self;
  1888. }
  1889. else
  1890. return PyString_FromStringAndSize(s+i, j-i);
  1891. }
  1892. Py_LOCAL_INLINE(PyObject *)
  1893. do_strip(PyStringObject *self, int striptype)
  1894. {
  1895. char *s = PyString_AS_STRING(self);
  1896. Py_ssize_t len = PyString_GET_SIZE(self), i, j;
  1897. i = 0;
  1898. if (striptype != RIGHTSTRIP) {
  1899. while (i < len && isspace(Py_CHARMASK(s[i]))) {
  1900. i++;
  1901. }
  1902. }
  1903. j = len;
  1904. if (striptype != LEFTSTRIP) {
  1905. do {
  1906. j--;
  1907. } while (j >= i && isspace(Py_CHARMASK(s[j])));
  1908. j++;
  1909. }
  1910. if (i == 0 && j == len && PyString_CheckExact(self)) {
  1911. Py_INCREF(self);
  1912. return (PyObject*)self;
  1913. }
  1914. else
  1915. return PyString_FromStringAndSize(s+i, j-i);
  1916. }
  1917. Py_LOCAL_INLINE(PyObject *)
  1918. do_argstrip(PyStringObject *self, int striptype, PyObject *args)
  1919. {
  1920. PyObject *sep = NULL;
  1921. if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
  1922. return NULL;
  1923. if (sep != NULL && sep != Py_None) {
  1924. if (PyString_Check(sep))
  1925. return do_xstrip(self, striptype, sep);
  1926. #ifdef Py_USING_UNICODE
  1927. else if (PyUnicode_Check(sep)) {
  1928. PyObject *uniself = PyUnicode_FromObject((PyObject *)self);
  1929. PyObject *res;
  1930. if (uniself==NULL)
  1931. return NULL;
  1932. res = _PyUnicode_XStrip((PyUnicodeObject *)uniself,
  1933. striptype, sep);
  1934. Py_DECREF(uniself);
  1935. return res;
  1936. }
  1937. #endif
  1938. PyErr_Format(PyExc_TypeError,
  1939. #ifdef Py_USING_UNICODE
  1940. "%s arg must be None, str or unicode",
  1941. #else
  1942. "%s arg must be None or str",
  1943. #endif
  1944. STRIPNAME(striptype));
  1945. return NULL;
  1946. }
  1947. return do_strip(self, striptype);
  1948. }
  1949. PyDoc_STRVAR(strip__doc__,
  1950. "S.strip([chars]) -> string or unicode\n\
  1951. \n\
  1952. Return a copy of the string S with leading and trailing\n\
  1953. whitespace removed.\n\
  1954. If chars is given and not None, remove characters in chars instead.\n\
  1955. If chars is unicode, S will be converted to unicode before stripping");
  1956. static PyObject *
  1957. string_strip(PyStringObject *self, PyObject *args)
  1958. {
  1959. if (PyTuple_GET_SIZE(args) == 0)
  1960. return do_strip(self, BOTHSTRIP); /* Common case */
  1961. else
  1962. return do_argstrip(self, BOTHSTRIP, args);
  1963. }
  1964. PyDoc_STRVAR(lstrip__doc__,
  1965. "S.lstrip([chars]) -> string or unicode\n\
  1966. \n\
  1967. Return a copy of the string S with leading whitespace removed.\n\
  1968. If chars is given and not None, remove characters in chars instead.\n\
  1969. If chars is unicode, S will be converted to unicode before stripping");
  1970. static PyObject *
  1971. string_lstrip(PyStringObject *self, PyObject *args)
  1972. {
  1973. if (PyTuple_GET_SIZE(args) == 0)
  1974. return do_strip(self, LEFTSTRIP); /* Common case */
  1975. else
  1976. return do_argstrip(self, LEFTSTRIP, args);
  1977. }
  1978. PyDoc_STRVAR(rstrip__doc__,
  1979. "S.rstrip([chars]) -> string or unicode\n\
  1980. \n\
  1981. Return a copy of the string S with trailing whitespace removed.\n\
  1982. If chars is given and not None, remove characters in chars instead.\n\
  1983. If chars is unicode, S will be converted to unicode before stripping");
  1984. static PyObject *
  1985. string_rstrip(PyStringObject *self, PyObject *args)
  1986. {
  1987. if (PyTuple_GET_SIZE(args) == 0)
  1988. return do_strip(self, RIGHTSTRIP); /* Common case */
  1989. else
  1990. return do_argstrip(self, RIGHTSTRIP, args);
  1991. }
  1992. PyDoc_STRVAR(lower__doc__,
  1993. "S.lower() -> string\n\
  1994. \n\
  1995. Return a copy of the string S converted to lowercase.");
  1996. /* _tolower and _toupper are defined by SUSv2, but they're not ISO C */
  1997. #ifndef _tolower
  1998. #define _tolower tolower
  1999. #endif
  2000. static PyObject *
  2001. string_lower(PyStringObject *self)
  2002. {
  2003. char *s;
  2004. Py_ssize_t i, n = PyString_GET_SIZE(self);
  2005. PyObject *newobj;
  2006. newobj = PyString_FromStringAndSize(NULL, n);
  2007. if (!newobj)
  2008. return NULL;
  2009. s = PyString_AS_STRING(newobj);
  2010. Py_MEMCPY(s, PyString_AS_STRING(self), n);
  2011. for (i = 0; i < n; i++) {
  2012. int c = Py_CHARMASK(s[i]);
  2013. if (isupper(c))
  2014. s[i] = _tolower(c);
  2015. }
  2016. return newobj;
  2017. }
  2018. PyDoc_STRVAR(upper__doc__,
  2019. "S.upper() -> string\n\
  2020. \n\
  2021. Return a copy of the string S converted to uppercase.");
  2022. #ifndef _toupper
  2023. #define _toupper toupper
  2024. #endif
  2025. static PyObject *
  2026. string_upper(PyStringObject *self)
  2027. {
  2028. char *s;
  2029. Py_ssize_t i, n = PyString_GET_SIZE(self);
  2030. PyObject *newobj;
  2031. newobj = PyString_FromStringAndSize(NULL, n);
  2032. if (!newobj)
  2033. return NULL;
  2034. s = PyString_AS_STRING(newobj);
  2035. Py_MEMCPY(s, PyString_AS_STRING(self), n);
  2036. for (i = 0; i < n; i++) {
  2037. int c = Py_CHARMASK(s[i]);
  2038. if (islower(c))
  2039. s[i] = _toupper(c);
  2040. }
  2041. return newobj;
  2042. }
  2043. PyDoc_STRVAR(title__doc__,
  2044. "S.title() -> string\n\
  2045. \n\
  2046. Return a titlecased version of S, i.e. words start with uppercase\n\
  2047. characters, all remaining cased characters have lowercase.");
  2048. static PyObject*
  2049. string_title(PyStringObject *self)
  2050. {
  2051. char *s = PyString_AS_STRING(self), *s_new;
  2052. Py_ssize_t i, n = PyString_GET_SIZE(self);
  2053. int previous_is_cased = 0;
  2054. PyObject *newobj;
  2055. newobj = PyString_FromStringAndSize(NULL, n);
  2056. if (newobj == NULL)
  2057. return NULL;
  2058. s_new = PyString_AsString(newobj);
  2059. for (i = 0; i < n; i++) {
  2060. int c = Py_CHARMASK(*s++);
  2061. if (islower(c)) {
  2062. if (!previous_is_cased)
  2063. c = toupper(c);
  2064. previous_is_cased = 1;
  2065. } else if (isupper(c)) {
  2066. if (previous_is_cased)
  2067. c = tolower(c);
  2068. previous_is_cased = 1;
  2069. } else
  2070. previous_is_cased = 0;
  2071. *s_new++ = c;
  2072. }
  2073. return newobj;
  2074. }
  2075. PyDoc_STRVAR(capitalize__doc__,
  2076. "S.capitalize() -> string\n\
  2077. \n\
  2078. Return a copy of the string S with only its first character\n\
  2079. capitalized.");
  2080. static PyObject *
  2081. string_capitalize(PyStringObject *self)
  2082. {
  2083. char *s = PyString_AS_STRING(self), *s_new;
  2084. Py_ssize_t i, n = PyString_GET_SIZE(self);
  2085. PyObject *newobj;
  2086. newobj = PyString_FromStringAndSize(NULL, n);
  2087. if (newobj == NULL)
  2088. return NULL;
  2089. s_new = PyString_AsString(newobj);
  2090. if (0 < n) {
  2091. int c = Py_CHARMASK(*s++);
  2092. if (islower(c))
  2093. *s_new = toupper(c);
  2094. else
  2095. *s_new = c;
  2096. s_new++;
  2097. }
  2098. for (i = 1; i < n; i++) {
  2099. int c = Py_CHARMASK(*s++);
  2100. if (isupper(c))
  2101. *s_new = tolower(c);
  2102. else
  2103. *s_new = c;
  2104. s_new++;
  2105. }
  2106. return newobj;
  2107. }
  2108. PyDoc_STRVAR(count__doc__,
  2109. "S.count(sub[, start[, end]]) -> int\n\
  2110. \n\
  2111. Return the number of non-overlapping occurrences of substring sub in\n\
  2112. string S[start:end]. Optional arguments start and end are interpreted\n\
  2113. as in slice notation.");
  2114. static PyObject *
  2115. string_count(PyStringObject *self, PyObject *args)
  2116. {
  2117. PyObject *sub_obj;
  2118. const char *str = PyString_AS_STRING(self), *sub;
  2119. Py_ssize_t sub_len;
  2120. Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
  2121. if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj,
  2122. _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
  2123. return NULL;
  2124. if (PyString_Check(sub_obj)) {
  2125. sub = PyString_AS_STRING(sub_obj);
  2126. sub_len = PyString_GET_SIZE(sub_obj);
  2127. }
  2128. #ifdef Py_USING_UNICODE
  2129. else if (PyUnicode_Check(sub_obj)) {
  2130. Py_ssize_t count;
  2131. count = PyUnicode_Count((PyObject *)self, sub_obj, start, end);
  2132. if (count == -1)
  2133. return NULL;
  2134. else
  2135. return PyInt_FromSsize_t(count);
  2136. }
  2137. #endif
  2138. else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len))
  2139. return NULL;
  2140. string_adjust_indices(&start, &end, PyString_GET_SIZE(self));
  2141. return PyInt_FromSsize_t(
  2142. stringlib_count(str + start, end - start, sub, sub_len)
  2143. );
  2144. }
  2145. PyDoc_STRVAR(swapcase__doc__,
  2146. "S.swapcase() -> string\n\
  2147. \n\
  2148. Return a copy of the string S with uppercase characters\n\
  2149. converted to lowercase and vice versa.");
  2150. static PyObject *
  2151. string_swapcase(PyStringObject *self)
  2152. {
  2153. char *s = PyString_AS_STRING(self), *s_new;
  2154. Py_ssize_t i, n = PyString_GET_SIZE(self);
  2155. PyObject *newobj;
  2156. newobj = PyString_FromStringAndSize(NULL, n);
  2157. if (newobj == NULL)
  2158. return NULL;
  2159. s_new = PyString_AsString(newobj);
  2160. for (i = 0; i < n; i++) {
  2161. int c = Py_CHARMASK(*s++);
  2162. if (islower(c)) {
  2163. *s_new = toupper(c);
  2164. }
  2165. else if (isupper(c)) {
  2166. *s_new = tolower(c);
  2167. }
  2168. else
  2169. *s_new = c;
  2170. s_new++;
  2171. }
  2172. return newobj;
  2173. }
  2174. PyDoc_STRVAR(translate__doc__,
  2175. "S.translate(table [,deletechars]) -> string\n\
  2176. \n\
  2177. Return a copy of the string S, where all characters occurring\n\
  2178. in the optional argument deletechars are removed, and the\n\
  2179. remaining characters have been mapped through the given\n\
  2180. translation table, which must be a string of length 256.");
  2181. static PyObject *
  2182. string_translate(PyStringObject *self, PyObject *args)
  2183. {
  2184. register char *input, *output;
  2185. const char *table;
  2186. register Py_ssize_t i, c, changed = 0;
  2187. PyObject *input_obj = (PyObject*)self;
  2188. const char *output_start, *del_table=NULL;
  2189. Py_ssize_t inlen, tablen, dellen = 0;
  2190. PyObject *result;
  2191. int trans_table[256];
  2192. PyObject *tableobj, *delobj = NULL;
  2193. if (!PyArg_UnpackTuple(args, "translate", 1, 2,
  2194. &tableobj, &delobj))
  2195. return NULL;
  2196. if (PyString_Check(tableobj)) {
  2197. table = PyString_AS_STRING(tableobj);
  2198. tablen = PyString_GET_SIZE(tableobj);
  2199. }
  2200. else if (tableobj == Py_None) {
  2201. table = NULL;
  2202. tablen = 256;
  2203. }
  2204. #ifdef Py_USING_UNICODE
  2205. else if (PyUnicode_Check(tableobj)) {
  2206. /* Unicode .translate() does not support the deletechars
  2207. parameter; instead a mapping to None will cause characters
  2208. to be deleted. */
  2209. if (delobj != NULL) {
  2210. PyErr_SetString(PyExc_TypeError,
  2211. "deletions are implemented differently for unicode");
  2212. return NULL;
  2213. }
  2214. return PyUnicode_Translate((PyObject *)self, tableobj, NULL);
  2215. }
  2216. #endif
  2217. else if (PyObject_AsCharBuffer(tableobj, &table, &tablen))
  2218. return NULL;
  2219. if (tablen != 256) {
  2220. PyErr_SetString(PyExc_ValueError,
  2221. "translation table must be 256 characters long");
  2222. return NULL;
  2223. }
  2224. if (delobj != NULL) {
  2225. if (PyString_Check(delobj)) {
  2226. del_table = PyString_AS_STRING(delobj);
  2227. dellen = PyString_GET_SIZE(delobj);
  2228. }
  2229. #ifdef Py_USING_UNICODE
  2230. else if (PyUnicode_Check(delobj)) {
  2231. PyErr_SetString(PyExc_TypeError,
  2232. "deletions are implemented differently for unicode");
  2233. return NULL;
  2234. }
  2235. #endif
  2236. else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen))
  2237. return NULL;
  2238. }
  2239. else {
  2240. del_table = NULL;
  2241. dellen = 0;
  2242. }
  2243. inlen = PyString_GET_SIZE(input_obj);
  2244. result = PyString_FromStringAndSize((char *)NULL, inlen);
  2245. if (result == NULL)
  2246. return NULL;
  2247. output_start = output = PyString_AsString(result);
  2248. input = PyString_AS_STRING(input_obj);
  2249. if (dellen == 0 && table != NULL) {
  2250. /* If no deletions are required, use faster code */
  2251. for (i = inlen; --i >= 0; ) {
  2252. c = Py_CHARMASK(*input++);
  2253. if (Py_CHARMASK((*output++ = table[c])) != c)
  2254. changed = 1;
  2255. }
  2256. if (changed || !PyString_CheckExact(input_obj))
  2257. return result;
  2258. Py_DECREF(result);
  2259. Py_INCREF(input_obj);
  2260. return input_obj;
  2261. }
  2262. if (table == NULL) {
  2263. for (i = 0; i < 256; i++)
  2264. trans_table[i] = Py_CHARMASK(i);
  2265. } else {
  2266. for (i = 0; i < 256; i++)
  2267. trans_table[i] = Py_CHARMASK(table[i]);
  2268. }
  2269. for (i = 0; i < dellen; i++)
  2270. trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
  2271. for (i = inlen; --i >= 0; ) {
  2272. c = Py_CHARMASK(*input++);
  2273. if (trans_table[c] != -1)
  2274. if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
  2275. continue;
  2276. changed = 1;
  2277. }
  2278. if (!changed && PyString_CheckExact(input_obj)) {
  2279. Py_DECREF(result);
  2280. Py_INCREF(input_obj);
  2281. return input_obj;
  2282. }
  2283. /* Fix the size of the resulting string */
  2284. if (inlen > 0)
  2285. _PyString_Resize(&result, output - output_start);
  2286. return result;
  2287. }
  2288. #define FORWARD 1
  2289. #define REVERSE -1
  2290. /* find and count characters and substrings */
  2291. #define findchar(target, target_len, c) \
  2292. ((char *)memchr((const void *)(target), c, target_len))
  2293. /* String ops must return a string. */
  2294. /* If the object is subclass of string, create a copy */
  2295. Py_LOCAL(PyStringObject *)
  2296. return_self(PyStringObject *self)
  2297. {
  2298. if (PyString_CheckExact(self)) {
  2299. Py_INCREF(self);
  2300. return self;
  2301. }
  2302. return (PyStringObject *)PyString_FromStringAndSize(
  2303. PyString_AS_STRING(self),
  2304. PyString_GET_SIZE(self));
  2305. }
  2306. Py_LOCAL_INLINE(Py_ssize_t)
  2307. countchar(const char *target, int target_len, char c, Py_ssize_t maxcount)
  2308. {
  2309. Py_ssize_t count=0;
  2310. const char *start=target;
  2311. const char *end=target+target_len;
  2312. while ( (start=findchar(start, end-start, c)) != NULL ) {
  2313. count++;
  2314. if (count >= maxcount)
  2315. break;
  2316. start += 1;
  2317. }
  2318. return count;
  2319. }
  2320. Py_LOCAL(Py_ssize_t)
  2321. findstring(const char *target, Py_ssize_t target_len,
  2322. const char *pattern, Py_ssize_t pattern_len,
  2323. Py_ssize_t start,
  2324. Py_ssize_t end,
  2325. int direction)
  2326. {
  2327. if (start < 0) {
  2328. start += target_len;
  2329. if (start < 0)
  2330. start = 0;
  2331. }
  2332. if (end > target_len) {
  2333. end = target_len;
  2334. } else if (end < 0) {
  2335. end += target_len;
  2336. if (end < 0)
  2337. end = 0;
  2338. }
  2339. /* zero-length substrings always match at the first attempt */
  2340. if (pattern_len == 0)
  2341. return (direction > 0) ? start : end;
  2342. end -= pattern_len;
  2343. if (direction < 0) {
  2344. for (; end >= start; end--)
  2345. if (Py_STRING_MATCH(target, end, pattern, pattern_len))
  2346. return end;
  2347. } else {
  2348. for (; start <= end; start++)
  2349. if (Py_STRING_MATCH(target, start, pattern, pattern_len))
  2350. return start;
  2351. }
  2352. return -1;
  2353. }
  2354. Py_LOCAL_INLINE(Py_ssize_t)
  2355. countstring(const char *target, Py_ssize_t target_len,
  2356. const char *pattern, Py_ssize_t pattern_len,
  2357. Py_ssize_t start,
  2358. Py_ssize_t end,
  2359. int direction, Py_ssize_t maxcount)
  2360. {
  2361. Py_ssize_t count=0;
  2362. if (start < 0) {
  2363. start += target_len;
  2364. if (start < 0)
  2365. start = 0;
  2366. }
  2367. if (end > target_len) {
  2368. end = target_len;
  2369. } else if (end < 0) {
  2370. end += target_len;
  2371. if (end < 0)
  2372. end = 0;
  2373. }
  2374. /* zero-length substrings match everywhere */
  2375. if (pattern_len == 0 || maxcount == 0) {
  2376. if (target_len+1 < maxcount)
  2377. return target_len+1;
  2378. return maxcount;
  2379. }
  2380. end -= pattern_len;
  2381. if (direction < 0) {
  2382. for (; (end >= start); end--)
  2383. if (Py_STRING_MATCH(target, end, pattern, pattern_len)) {
  2384. count++;
  2385. if (--maxcount <= 0) break;
  2386. end -= pattern_len-1;
  2387. }
  2388. } else {
  2389. for (; (start <= end); start++)
  2390. if (Py_STRING_MATCH(target, start, pattern, pattern_len)) {
  2391. count++;
  2392. if (--maxcount <= 0)
  2393. break;
  2394. start += pattern_len-1;
  2395. }
  2396. }
  2397. return count;
  2398. }
  2399. /* Algorithms for different cases of string replacement */
  2400. /* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
  2401. Py_LOCAL(PyStringObject *)
  2402. replace_interleave(PyStringObject *self,
  2403. const char *to_s, Py_ssize_t to_len,
  2404. Py_ssize_t maxcount)
  2405. {
  2406. char *self_s, *result_s;
  2407. Py_ssize_t self_len, result_len;
  2408. Py_ssize_t count, i, product;
  2409. PyStringObject *result;
  2410. self_len = PyString_GET_SIZE(self);
  2411. /* 1 at the end plus 1 after every character */
  2412. count = self_len+1;
  2413. if (maxcount < count)
  2414. count = maxcount;
  2415. /* Check for overflow */
  2416. /* result_len = count * to_len + self_len; */
  2417. product = count * to_len;
  2418. if (product / to_len != count) {
  2419. PyErr_SetString(PyExc_OverflowError,
  2420. "replace string is too long");
  2421. return NULL;
  2422. }
  2423. result_len = product + self_len;
  2424. if (result_len < 0) {
  2425. PyErr_SetString(PyExc_OverflowError,
  2426. "replace string is too long");
  2427. return NULL;
  2428. }
  2429. if (! (result = (PyStringObject *)
  2430. PyString_FromStringAndSize(NULL, result_len)) )
  2431. return NULL;
  2432. self_s = PyString_AS_STRING(self);
  2433. result_s = PyString_AS_STRING(result);
  2434. /* TODO: special case single character, which doesn't need memcpy */
  2435. /* Lay the first one down (guaranteed this will occur) */
  2436. Py_MEMCPY(result_s, to_s, to_len);
  2437. result_s += to_len;
  2438. count -= 1;
  2439. for (i=0; i<count; i++) {
  2440. *result_s++ = *self_s++;
  2441. Py_MEMCPY(result_s, to_s, to_len);
  2442. result_s += to_len;
  2443. }
  2444. /* Copy the rest of the original string */
  2445. Py_MEMCPY(result_s, self_s, self_len-i);
  2446. return result;
  2447. }
  2448. /* Special case for deleting a single character */
  2449. /* len(self)>=1, len(from)==1, to="", maxcount>=1 */
  2450. Py_LOCAL(PyStringObject *)
  2451. replace_delete_single_character(PyStringObject *self,
  2452. char from_c, Py_ssize_t maxcount)
  2453. {
  2454. char *self_s, *result_s;
  2455. char *start, *next, *end;
  2456. Py_ssize_t self_len, result_len;
  2457. Py_ssize_t count;
  2458. PyStringObject *result;
  2459. self_len = PyString_GET_SIZE(self);
  2460. self_s = PyString_AS_STRING(self);
  2461. count = countchar(self_s, self_len, from_c, maxcount);
  2462. if (count == 0) {
  2463. return return_self(self);
  2464. }
  2465. result_len = self_len - count; /* from_len == 1 */
  2466. assert(result_len>=0);
  2467. if ( (result = (PyStringObject *)
  2468. PyString_FromStringAndSize(NULL, result_len)) == NULL)
  2469. return NULL;
  2470. result_s = PyString_AS_STRING(result);
  2471. start = self_s;
  2472. end = self_s + self_len;
  2473. while (count-- > 0) {
  2474. next = findchar(start, end-start, from_c);
  2475. if (next == NULL)
  2476. break;
  2477. Py_MEMCPY(result_s, start, next-start);
  2478. result_s += (next-start);
  2479. start = next+1;
  2480. }
  2481. Py_MEMCPY(result_s, start, end-start);
  2482. return result;
  2483. }
  2484. /* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
  2485. Py_LOCAL(PyStringObject *)
  2486. replace_delete_substring(PyStringObject *self,
  2487. const char *from_s, Py_ssize_t from_len,
  2488. Py_ssize_t maxcount) {
  2489. char *self_s, *result_s;
  2490. char *start, *next, *end;
  2491. Py_ssize_t self_len, result_len;
  2492. Py_ssize_t count, offset;
  2493. PyStringObject *result;
  2494. self_len = PyString_GET_SIZE(self);
  2495. self_s = PyString_AS_STRING(self);
  2496. count = countstring(self_s, self_len,
  2497. from_s, from_len,
  2498. 0, self_len, 1,
  2499. maxcount);
  2500. if (count == 0) {
  2501. /* no matches */
  2502. return return_self(self);
  2503. }
  2504. result_len = self_len - (count * from_len);
  2505. assert (result_len>=0);
  2506. if ( (result = (PyStringObject *)
  2507. PyString_FromStringAndSize(NULL, result_len)) == NULL )
  2508. return NULL;
  2509. result_s = PyString_AS_STRING(result);
  2510. start = self_s;
  2511. end = self_s + self_len;
  2512. while (count-- > 0) {
  2513. offset = findstring(start, end-start,
  2514. from_s, from_len,
  2515. 0, end-start, FORWARD);
  2516. if (offset == -1)
  2517. break;
  2518. next = start + offset;
  2519. Py_MEMCPY(result_s, start, next-start);
  2520. result_s += (next-start);
  2521. start = next+from_len;
  2522. }
  2523. Py_MEMCPY(result_s, start, end-start);
  2524. return result;
  2525. }
  2526. /* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
  2527. Py_LOCAL(PyStringObject *)
  2528. replace_single_character_in_place(PyStringObject *self,
  2529. char from_c, char to_c,
  2530. Py_ssize_t maxcount)
  2531. {
  2532. char *self_s, *result_s, *start, *end, *next;
  2533. Py_ssize_t self_len;
  2534. PyStringObject *result;
  2535. /* The result string will be the same size */
  2536. self_s = PyString_AS_STRING(self);
  2537. self_len = PyString_GET_SIZE(self);
  2538. next = findchar(self_s, self_len, from_c);
  2539. if (next == NULL) {
  2540. /* No matches; return the original string */
  2541. return return_self(self);
  2542. }
  2543. /* Need to make a new string */
  2544. result = (PyStringObject *) PyString_FromStringAndSize(NULL, self_len);
  2545. if (result == NULL)
  2546. return NULL;
  2547. result_s = PyString_AS_STRING(result);
  2548. Py_MEMCPY(result_s, self_s, self_len);
  2549. /* change everything in-place, starting with this one */
  2550. start = result_s + (next-self_s);
  2551. *start = to_c;
  2552. start++;
  2553. end = result_s + self_len;
  2554. while (--maxcount > 0) {
  2555. next = findchar(start, end-start, from_c);
  2556. if (next == NULL)
  2557. break;
  2558. *next = to_c;
  2559. start = next+1;
  2560. }
  2561. return result;
  2562. }
  2563. /* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
  2564. Py_LOCAL(PyStringObject *)
  2565. replace_substring_in_place(PyStringObject *self,
  2566. const char *from_s, Py_ssize_t from_len,
  2567. const char *to_s, Py_ssize_t to_len,
  2568. Py_ssize_t maxcount)
  2569. {
  2570. char *result_s, *start, *end;
  2571. char *self_s;
  2572. Py_ssize_t self_len, offset;
  2573. PyStringObject *result;
  2574. /* The result string will be the same size */
  2575. self_s = PyString_AS_STRING(self);
  2576. self_len = PyString_GET_SIZE(self);
  2577. offset = findstring(self_s, self_len,
  2578. from_s, from_len,
  2579. 0, self_len, FORWARD);
  2580. if (offset == -1) {
  2581. /* No matches; return the original string */
  2582. return return_self(self);
  2583. }
  2584. /* Need to make a new string */
  2585. result = (PyStringObject *) PyString_FromStringAndSize(NULL, self_len);
  2586. if (result == NULL)
  2587. return NULL;
  2588. result_s = PyString_AS_STRING(result);
  2589. Py_MEMCPY(result_s, self_s, self_len);
  2590. /* change everything in-place, starting with this one */
  2591. start = result_s + offset;
  2592. Py_MEMCPY(start, to_s, from_len);
  2593. start += from_len;
  2594. end = result_s + self_len;
  2595. while ( --maxcount > 0) {
  2596. offset = findstring(start, end-start,
  2597. from_s, from_len,
  2598. 0, end-start, FORWARD);
  2599. if (offset==-1)
  2600. break;
  2601. Py_MEMCPY(start+offset, to_s, from_len);
  2602. start += offset+from_len;
  2603. }
  2604. return result;
  2605. }
  2606. /* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
  2607. Py_LOCAL(PyStringObject *)
  2608. replace_single_character(PyStringObject *self,
  2609. char from_c,
  2610. const char *to_s, Py_ssize_t to_len,
  2611. Py_ssize_t maxcount)
  2612. {
  2613. char *self_s, *result_s;
  2614. char *start, *next, *end;
  2615. Py_ssize_t self_len, result_len;
  2616. Py_ssize_t count, product;
  2617. PyStringObject *result;
  2618. self_s = PyString_AS_STRING(self);
  2619. self_len = PyString_GET_SIZE(self);
  2620. count = countchar(self_s, self_len, from_c, maxcount);
  2621. if (count == 0) {
  2622. /* no matches, return unchanged */
  2623. return return_self(self);
  2624. }
  2625. /* use the difference between current and new, hence the "-1" */
  2626. /* result_len = self_len + count * (to_len-1) */
  2627. product = count * (to_len-1);
  2628. if (product / (to_len-1) != count) {
  2629. PyErr_SetString(PyExc_OverflowError, "replace string is too long");
  2630. return NULL;
  2631. }
  2632. result_len = self_len + product;
  2633. if (result_len < 0) {
  2634. PyErr_SetString(PyExc_OverflowError, "replace string is too long");
  2635. return NULL;
  2636. }
  2637. if ( (result = (PyStringObject *)
  2638. PyString_FromStringAndSize(NULL, result_len)) == NULL)
  2639. return NULL;
  2640. result_s = PyString_AS_STRING(result);
  2641. start = self_s;
  2642. end = self_s + self_len;
  2643. while (count-- > 0) {
  2644. next = findchar(start, end-start, from_c);
  2645. if (next == NULL)
  2646. break;
  2647. if (next == start) {
  2648. /* replace with the 'to' */
  2649. Py_MEMCPY(result_s, to_s, to_len);
  2650. result_s += to_len;
  2651. start += 1;
  2652. } else {
  2653. /* copy the unchanged old then the 'to' */
  2654. Py_MEMCPY(result_s, start, next-start);
  2655. result_s += (next-start);
  2656. Py_MEMCPY(result_s, to_s, to_len);
  2657. result_s += to_len;
  2658. start = next+1;
  2659. }
  2660. }
  2661. /* Copy the remainder of the remaining string */
  2662. Py_MEMCPY(result_s, start, end-start);
  2663. return result;
  2664. }
  2665. /* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
  2666. Py_LOCAL(PyStringObject *)
  2667. replace_substring(PyStringObject *self,
  2668. const char *from_s, Py_ssize_t from_len,
  2669. const char *to_s, Py_ssize_t to_len,
  2670. Py_ssize_t maxcount) {
  2671. char *self_s, *result_s;
  2672. char *start, *next, *end;
  2673. Py_ssize_t self_len, result_len;
  2674. Py_ssize_t count, offset, product;
  2675. PyStringObject *result;
  2676. self_s = PyString_AS_STRING(self);
  2677. self_len = PyString_GET_SIZE(self);
  2678. count = countstring(self_s, self_len,
  2679. from_s, from_len,
  2680. 0, self_len, FORWARD, maxcount);
  2681. if (count == 0) {
  2682. /* no matches, return unchanged */
  2683. return return_self(self);
  2684. }
  2685. /* Check for overflow */
  2686. /* result_len = self_len + count * (to_len-from_len) */
  2687. product = count * (to_len-from_len);
  2688. if (product / (to_len-from_len) != count) {
  2689. PyErr_SetString(PyExc_OverflowError, "replace string is too long");
  2690. return NULL;
  2691. }
  2692. result_len = self_len + product;
  2693. if (result_len < 0) {
  2694. PyErr_SetString(PyExc_OverflowError, "replace string is too long");
  2695. return NULL;
  2696. }
  2697. if ( (result = (PyStringObject *)
  2698. PyString_FromStringAndSize(NULL, result_len)) == NULL)
  2699. return NULL;
  2700. result_s = PyString_AS_STRING(result);
  2701. start = self_s;
  2702. end = self_s + self_len;
  2703. while (count-- > 0) {
  2704. offset = findstring(start, end-start,
  2705. from_s, from_len,
  2706. 0, end-start, FORWARD);
  2707. if (offset == -1)
  2708. break;
  2709. next = start+offset;
  2710. if (next == start) {
  2711. /* replace with the 'to' */
  2712. Py_MEMCPY(result_s, to_s, to_len);
  2713. result_s += to_len;
  2714. start += from_len;
  2715. } else {
  2716. /* copy the unchanged old then the 'to' */
  2717. Py_MEMCPY(result_s, start, next-start);
  2718. result_s += (next-start);
  2719. Py_MEMCPY(result_s, to_s, to_len);
  2720. result_s += to_len;
  2721. start = next+from_len;
  2722. }
  2723. }
  2724. /* Copy the remainder of the remaining string */
  2725. Py_MEMCPY(result_s, start, end-start);
  2726. return result;
  2727. }
  2728. Py_LOCAL(PyStringObject *)
  2729. replace(PyStringObject *self,
  2730. const char *from_s, Py_ssize_t from_len,
  2731. const char *to_s, Py_ssize_t to_len,
  2732. Py_ssize_t maxcount)
  2733. {
  2734. if (maxcount < 0) {
  2735. maxcount = PY_SSIZE_T_MAX;
  2736. } else if (maxcount == 0 || PyString_GET_SIZE(self) == 0) {
  2737. /* nothing to do; return the original string */
  2738. return return_self(self);
  2739. }
  2740. if (maxcount == 0 ||
  2741. (from_len == 0 && to_len == 0)) {
  2742. /* nothing to do; return the original string */
  2743. return return_self(self);
  2744. }
  2745. /* Handle zero-length special cases */
  2746. if (from_len == 0) {
  2747. /* insert the 'to' string everywhere. */
  2748. /* >>> "Python".replace("", ".") */
  2749. /* '.P.y.t.h.o.n.' */
  2750. return replace_interleave(self, to_s, to_len, maxcount);
  2751. }
  2752. /* Except for "".replace("", "A") == "A" there is no way beyond this */
  2753. /* point for an empty self string to generate a non-empty string */
  2754. /* Special case so the remaining code always gets a non-empty string */
  2755. if (PyString_GET_SIZE(self) == 0) {
  2756. return return_self(self);
  2757. }
  2758. if (to_len == 0) {
  2759. /* delete all occurances of 'from' string */
  2760. if (from_len == 1) {
  2761. return replace_delete_single_character(
  2762. self, from_s[0], maxcount);
  2763. } else {
  2764. return replace_delete_substring(self, from_s, from_len, maxcount);
  2765. }
  2766. }
  2767. /* Handle special case where both strings have the same length */
  2768. if (from_len == to_len) {
  2769. if (from_len == 1) {
  2770. return replace_single_character_in_place(
  2771. self,
  2772. from_s[0],
  2773. to_s[0],
  2774. maxcount);
  2775. } else {
  2776. return replace_substring_in_place(
  2777. self, from_s, from_len, to_s, to_len, maxcount);
  2778. }
  2779. }
  2780. /* Otherwise use the more generic algorithms */
  2781. if (from_len == 1) {
  2782. return replace_single_character(self, from_s[0],
  2783. to_s, to_len, maxcount);
  2784. } else {
  2785. /* len('from')>=2, len('to')>=1 */
  2786. return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
  2787. }
  2788. }
  2789. PyDoc_STRVAR(replace__doc__,
  2790. "S.replace (old, new[, count]) -> string\n\
  2791. \n\
  2792. Return a copy of string S with all occurrences of substring\n\
  2793. old replaced by new. If the optional argument count is\n\
  2794. given, only the first count occurrences are replaced.");
  2795. static PyObject *
  2796. string_replace(PyStringObject *self, PyObject *args)
  2797. {
  2798. Py_ssize_t count = -1;
  2799. PyObject *from, *to;
  2800. const char *from_s, *to_s;
  2801. Py_ssize_t from_len, to_len;
  2802. if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
  2803. return NULL;
  2804. if (PyString_Check(from)) {
  2805. from_s = PyString_AS_STRING(from);
  2806. from_len = PyString_GET_SIZE(from);
  2807. }
  2808. #ifdef Py_USING_UNICODE
  2809. if (PyUnicode_Check(from))
  2810. return PyUnicode_Replace((PyObject *)self,
  2811. from, to, count);
  2812. #endif
  2813. else if (PyObject_AsCharBuffer(from, &from_s, &from_len))
  2814. return NULL;
  2815. if (PyString_Check(to)) {
  2816. to_s = PyString_AS_STRING(to);
  2817. to_len = PyString_GET_SIZE(to);
  2818. }
  2819. #ifdef Py_USING_UNICODE
  2820. else if (PyUnicode_Check(to))
  2821. return PyUnicode_Replace((PyObject *)self,
  2822. from, to, count);
  2823. #endif
  2824. else if (PyObject_AsCharBuffer(to, &to_s, &to_len))
  2825. return NULL;
  2826. return (PyObject *)replace((PyStringObject *) self,
  2827. from_s, from_len,
  2828. to_s, to_len, count);
  2829. }
  2830. /** End DALKE **/
  2831. /* Matches the end (direction >= 0) or start (direction < 0) of self
  2832. * against substr, using the start and end arguments. Returns
  2833. * -1 on error, 0 if not found and 1 if found.
  2834. */
  2835. Py_LOCAL(int)
  2836. _string_tailmatch(PyStringObject *self, PyObject *substr, Py_ssize_t start,
  2837. Py_ssize_t end, int direction)
  2838. {
  2839. Py_ssize_t len = PyString_GET_SIZE(self);
  2840. Py_ssize_t slen;
  2841. const char* sub;
  2842. const char* str;
  2843. if (PyString_Check(substr)) {
  2844. sub = PyString_AS_STRING(substr);
  2845. slen = PyString_GET_SIZE(substr);
  2846. }
  2847. #ifdef Py_USING_UNICODE
  2848. else if (PyUnicode_Check(substr))
  2849. return PyUnicode_Tailmatch((PyObject *)self,
  2850. substr, start, end, direction);
  2851. #endif
  2852. else if (PyObject_AsCharBuffer(substr, &sub, &slen))
  2853. return -1;
  2854. str = PyString_AS_STRING(self);
  2855. string_adjust_indices(&start, &end, len);
  2856. if (direction < 0) {
  2857. /* startswith */
  2858. if (start+slen > len)
  2859. return 0;
  2860. } else {
  2861. /* endswith */
  2862. if (end-start < slen || start > len)
  2863. return 0;
  2864. if (end-slen > start)
  2865. start = end - slen;
  2866. }
  2867. if (end-start >= slen)
  2868. return ! memcmp(str+start, sub, slen);
  2869. return 0;
  2870. }
  2871. PyDoc_STRVAR(startswith__doc__,
  2872. "S.startswith(prefix[, start[, end]]) -> bool\n\
  2873. \n\
  2874. Return True if S starts with the specified prefix, False otherwise.\n\
  2875. With optional start, test S beginning at that position.\n\
  2876. With optional end, stop comparing S at that position.\n\
  2877. prefix can also be a tuple of strings to try.");
  2878. static PyObject *
  2879. string_startswith(PyStringObject *self, PyObject *args)
  2880. {
  2881. Py_ssize_t start = 0;
  2882. Py_ssize_t end = PY_SSIZE_T_MAX;
  2883. PyObject *subobj;
  2884. int result;
  2885. if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
  2886. _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
  2887. return NULL;
  2888. if (PyTuple_Check(subobj)) {
  2889. Py_ssize_t i;
  2890. for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
  2891. result = _string_tailmatch(self,
  2892. PyTuple_GET_ITEM(subobj, i),
  2893. start, end, -1);
  2894. if (result == -1)
  2895. return NULL;
  2896. else if (result) {
  2897. Py_RETURN_TRUE;
  2898. }
  2899. }
  2900. Py_RETURN_FALSE;
  2901. }
  2902. result = _string_tailmatch(self, subobj, start, end, -1);
  2903. if (result == -1)
  2904. return NULL;
  2905. else
  2906. return PyBool_FromLong(result);
  2907. }
  2908. PyDoc_STRVAR(endswith__doc__,
  2909. "S.endswith(suffix[, start[, end]]) -> bool\n\
  2910. \n\
  2911. Return True if S ends with the specified suffix, False otherwise.\n\
  2912. With optional start, test S beginning at that position.\n\
  2913. With optional end, stop comparing S at that position.\n\
  2914. suffix can also be a tuple of strings to try.");
  2915. static PyObject *
  2916. string_endswith(PyStringObject *self, PyObject *args)
  2917. {
  2918. Py_ssize_t start = 0;
  2919. Py_ssize_t end = PY_SSIZE_T_MAX;
  2920. PyObject *subobj;
  2921. int result;
  2922. if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
  2923. _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
  2924. return NULL;
  2925. if (PyTuple_Check(subobj)) {
  2926. Py_ssize_t i;
  2927. for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
  2928. result = _string_tailmatch(self,
  2929. PyTuple_GET_ITEM(subobj, i),
  2930. start, end, +1);
  2931. if (result == -1)
  2932. return NULL;
  2933. else if (result) {
  2934. Py_RETURN_TRUE;
  2935. }
  2936. }
  2937. Py_RETURN_FALSE;
  2938. }
  2939. result = _string_tailmatch(self, subobj, start, end, +1);
  2940. if (result == -1)
  2941. return NULL;
  2942. else
  2943. return PyBool_FromLong(result);
  2944. }
  2945. PyDoc_STRVAR(encode__doc__,
  2946. "S.encode([encoding[,errors]]) -> object\n\
  2947. \n\
  2948. Encodes S using the codec registered for encoding. encoding defaults\n\
  2949. to the default encoding. errors may be given to set a different error\n\
  2950. handling scheme. Default is 'strict' meaning that encoding errors raise\n\
  2951. a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
  2952. 'xmlcharrefreplace' as well as any other name registered with\n\
  2953. codecs.register_error that is able to handle UnicodeEncodeErrors.");
  2954. static PyObject *
  2955. string_encode(PyStringObject *self, PyObject *args)
  2956. {
  2957. char *encoding = NULL;
  2958. char *errors = NULL;
  2959. PyObject *v;
  2960. if (!PyArg_ParseTuple(args, "|ss:encode", &encoding, &errors))
  2961. return NULL;
  2962. v = PyString_AsEncodedObject((PyObject *)self, encoding, errors);
  2963. if (v == NULL)
  2964. goto onError;
  2965. if (!PyString_Check(v) && !PyUnicode_Check(v)) {
  2966. PyErr_Format(PyExc_TypeError,
  2967. "encoder did not return a string/unicode object "
  2968. "(type=%.400s)",
  2969. Py_TYPE(v)->tp_name);
  2970. Py_DECREF(v);
  2971. return NULL;
  2972. }
  2973. return v;
  2974. onError:
  2975. return NULL;
  2976. }
  2977. PyDoc_STRVAR(decode__doc__,
  2978. "S.decode([encoding[,errors]]) -> object\n\
  2979. \n\
  2980. Decodes S using the codec registered for encoding. encoding defaults\n\
  2981. to the default encoding. errors may be given to set a different error\n\
  2982. handling scheme. Default is 'strict' meaning that encoding errors raise\n\
  2983. a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
  2984. as well as any other name registered with codecs.register_error that is\n\
  2985. able to handle UnicodeDecodeErrors.");
  2986. static PyObject *
  2987. string_decode(PyStringObject *self, PyObject *args)
  2988. {
  2989. char *encoding = NULL;
  2990. char *errors = NULL;
  2991. PyObject *v;
  2992. if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
  2993. return NULL;
  2994. v = PyString_AsDecodedObject((PyObject *)self, encoding, errors);
  2995. if (v == NULL)
  2996. goto onError;
  2997. if (!PyString_Check(v) && !PyUnicode_Check(v)) {
  2998. PyErr_Format(PyExc_TypeError,
  2999. "decoder did not return a string/unicode object "
  3000. "(type=%.400s)",
  3001. Py_TYPE(v)->tp_name);
  3002. Py_DECREF(v);
  3003. return NULL;
  3004. }
  3005. return v;
  3006. onError:
  3007. return NULL;
  3008. }
  3009. PyDoc_STRVAR(expandtabs__doc__,
  3010. "S.expandtabs([tabsize]) -> string\n\
  3011. \n\
  3012. Return a copy of S where all tab characters are expanded using spaces.\n\
  3013. If tabsize is not given, a tab size of 8 characters is assumed.");
  3014. static PyObject*
  3015. string_expandtabs(PyStringObject *self, PyObject *args)
  3016. {
  3017. const char *e, *p, *qe;
  3018. char *q;
  3019. Py_ssize_t i, j, incr;
  3020. PyObject *u;
  3021. int tabsize = 8;
  3022. if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
  3023. return NULL;
  3024. /* First pass: determine size of output string */
  3025. i = 0; /* chars up to and including most recent \n or \r */
  3026. j = 0; /* chars since most recent \n or \r (use in tab calculations) */
  3027. e = PyString_AS_STRING(self) + PyString_GET_SIZE(self); /* end of input */
  3028. for (p = PyString_AS_STRING(self); p < e; p++)
  3029. if (*p == '\t') {
  3030. if (tabsize > 0) {
  3031. incr = tabsize - (j % tabsize);
  3032. if (j > PY_SSIZE_T_MAX - incr)
  3033. goto overflow1;
  3034. j += incr;
  3035. }
  3036. }
  3037. else {
  3038. if (j > PY_SSIZE_T_MAX - 1)
  3039. goto overflow1;
  3040. j++;
  3041. if (*p == '\n' || *p == '\r') {
  3042. if (i > PY_SSIZE_T_MAX - j)
  3043. goto overflow1;
  3044. i += j;
  3045. j = 0;
  3046. }
  3047. }
  3048. if (i > PY_SSIZE_T_MAX - j)
  3049. goto overflow1;
  3050. /* Second pass: create output string and fill it */
  3051. u = PyString_FromStringAndSize(NULL, i + j);
  3052. if (!u)
  3053. return NULL;
  3054. j = 0; /* same as in first pass */
  3055. q = PyString_AS_STRING(u); /* next output char */
  3056. qe = PyString_AS_STRING(u) + PyString_GET_SIZE(u); /* end of output */
  3057. for (p = PyString_AS_STRING(self); p < e; p++)
  3058. if (*p == '\t') {
  3059. if (tabsize > 0) {
  3060. i = tabsize - (j % tabsize);
  3061. j += i;
  3062. while (i--) {
  3063. if (q >= qe)
  3064. goto overflow2;
  3065. *q++ = ' ';
  3066. }
  3067. }
  3068. }
  3069. else {
  3070. if (q >= qe)
  3071. goto overflow2;
  3072. *q++ = *p;
  3073. j++;
  3074. if (*p == '\n' || *p == '\r')
  3075. j = 0;
  3076. }
  3077. return u;
  3078. overflow2:
  3079. Py_DECREF(u);
  3080. overflow1:
  3081. PyErr_SetString(PyExc_OverflowError, "new string is too long");
  3082. return NULL;
  3083. }
  3084. Py_LOCAL_INLINE(PyObject *)
  3085. pad(PyStringObject *self, Py_ssize_t left, Py_ssize_t right, char fill)
  3086. {
  3087. PyObject *u;
  3088. if (left < 0)
  3089. left = 0;
  3090. if (right < 0)
  3091. right = 0;
  3092. if (left == 0 && right == 0 && PyString_CheckExact(self)) {
  3093. Py_INCREF(self);
  3094. return (PyObject *)self;
  3095. }
  3096. u = PyString_FromStringAndSize(NULL,
  3097. left + PyString_GET_SIZE(self) + right);
  3098. if (u) {
  3099. if (left)
  3100. memset(PyString_AS_STRING(u), fill, left);
  3101. Py_MEMCPY(PyString_AS_STRING(u) + left,
  3102. PyString_AS_STRING(self),
  3103. PyString_GET_SIZE(self));
  3104. if (right)
  3105. memset(PyString_AS_STRING(u) + left + PyString_GET_SIZE(self),
  3106. fill, right);
  3107. }
  3108. return u;
  3109. }
  3110. PyDoc_STRVAR(ljust__doc__,
  3111. "S.ljust(width[, fillchar]) -> string\n"
  3112. "\n"
  3113. "Return S left-justified in a string of length width. Padding is\n"
  3114. "done using the specified fill character (default is a space).");
  3115. static PyObject *
  3116. string_ljust(PyStringObject *self, PyObject *args)
  3117. {
  3118. Py_ssize_t width;
  3119. char fillchar = ' ';
  3120. if (!PyArg_ParseTuple(args, "n|c:ljust", &width, &fillchar))
  3121. return NULL;
  3122. if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
  3123. Py_INCREF(self);
  3124. return (PyObject*) self;
  3125. }
  3126. return pad(self, 0, width - PyString_GET_SIZE(self), fillchar);
  3127. }
  3128. PyDoc_STRVAR(rjust__doc__,
  3129. "S.rjust(width[, fillchar]) -> string\n"
  3130. "\n"
  3131. "Return S right-justified in a string of length width. Padding is\n"
  3132. "done using the specified fill character (default is a space)");
  3133. static PyObject *
  3134. string_rjust(PyStringObject *self, PyObject *args)
  3135. {
  3136. Py_ssize_t width;
  3137. char fillchar = ' ';
  3138. if (!PyArg_ParseTuple(args, "n|c:rjust", &width, &fillchar))
  3139. return NULL;
  3140. if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
  3141. Py_INCREF(self);
  3142. return (PyObject*) self;
  3143. }
  3144. return pad(self, width - PyString_GET_SIZE(self), 0, fillchar);
  3145. }
  3146. PyDoc_STRVAR(center__doc__,
  3147. "S.center(width[, fillchar]) -> string\n"
  3148. "\n"
  3149. "Return S centered in a string of length width. Padding is\n"
  3150. "done using the specified fill character (default is a space)");
  3151. static PyObject *
  3152. string_center(PyStringObject *self, PyObject *args)
  3153. {
  3154. Py_ssize_t marg, left;
  3155. Py_ssize_t width;
  3156. char fillchar = ' ';
  3157. if (!PyArg_ParseTuple(args, "n|c:center", &width, &fillchar))
  3158. return NULL;
  3159. if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
  3160. Py_INCREF(self);
  3161. return (PyObject*) self;
  3162. }
  3163. marg = width - PyString_GET_SIZE(self);
  3164. left = marg / 2 + (marg & width & 1);
  3165. return pad(self, left, marg - left, fillchar);
  3166. }
  3167. PyDoc_STRVAR(zfill__doc__,
  3168. "S.zfill(width) -> string\n"
  3169. "\n"
  3170. "Pad a numeric string S with zeros on the left, to fill a field\n"
  3171. "of the specified width. The string S is never truncated.");
  3172. static PyObject *
  3173. string_zfill(PyStringObject *self, PyObject *args)
  3174. {
  3175. Py_ssize_t fill;
  3176. PyObject *s;
  3177. char *p;
  3178. Py_ssize_t width;
  3179. if (!PyArg_ParseTuple(args, "n:zfill", &width))
  3180. return NULL;
  3181. if (PyString_GET_SIZE(self) >= width) {
  3182. if (PyString_CheckExact(self)) {
  3183. Py_INCREF(self);
  3184. return (PyObject*) self;
  3185. }
  3186. else
  3187. return PyString_FromStringAndSize(
  3188. PyString_AS_STRING(self),
  3189. PyString_GET_SIZE(self)
  3190. );
  3191. }
  3192. fill = width - PyString_GET_SIZE(self);
  3193. s = pad(self, fill, 0, '0');
  3194. if (s == NULL)
  3195. return NULL;
  3196. p = PyString_AS_STRING(s);
  3197. if (p[fill] == '+' || p[fill] == '-') {
  3198. /* move sign to beginning of string */
  3199. p[0] = p[fill];
  3200. p[fill] = '0';
  3201. }
  3202. return (PyObject*) s;
  3203. }
  3204. PyDoc_STRVAR(isspace__doc__,
  3205. "S.isspace() -> bool\n\
  3206. \n\
  3207. Return True if all characters in S are whitespace\n\
  3208. and there is at least one character in S, False otherwise.");
  3209. static PyObject*
  3210. string_isspace(PyStringObject *self)
  3211. {
  3212. register const unsigned char *p
  3213. = (unsigned char *) PyString_AS_STRING(self);
  3214. register const unsigned char *e;
  3215. /* Shortcut for single character strings */
  3216. if (PyString_GET_SIZE(self) == 1 &&
  3217. isspace(*p))
  3218. return PyBool_FromLong(1);
  3219. /* Special case for empty strings */
  3220. if (PyString_GET_SIZE(self) == 0)
  3221. return PyBool_FromLong(0);
  3222. e = p + PyString_GET_SIZE(self);
  3223. for (; p < e; p++) {
  3224. if (!isspace(*p))
  3225. return PyBool_FromLong(0);
  3226. }
  3227. return PyBool_FromLong(1);
  3228. }
  3229. PyDoc_STRVAR(isalpha__doc__,
  3230. "S.isalpha() -> bool\n\
  3231. \n\
  3232. Return True if all characters in S are alphabetic\n\
  3233. and there is at least one character in S, False otherwise.");
  3234. static PyObject*
  3235. string_isalpha(PyStringObject *self)
  3236. {
  3237. register const unsigned char *p
  3238. = (unsigned char *) PyString_AS_STRING(self);
  3239. register const unsigned char *e;
  3240. /* Shortcut for single character strings */
  3241. if (PyString_GET_SIZE(self) == 1 &&
  3242. isalpha(*p))
  3243. return PyBool_FromLong(1);
  3244. /* Special case for empty strings */
  3245. if (PyString_GET_SIZE(self) == 0)
  3246. return PyBool_FromLong(0);
  3247. e = p + PyString_GET_SIZE(self);
  3248. for (; p < e; p++) {
  3249. if (!isalpha(*p))
  3250. return PyBool_FromLong(0);
  3251. }
  3252. return PyBool_FromLong(1);
  3253. }
  3254. PyDoc_STRVAR(isalnum__doc__,
  3255. "S.isalnum() -> bool\n\
  3256. \n\
  3257. Return True if all characters in S are alphanumeric\n\
  3258. and there is at least one character in S, False otherwise.");
  3259. static PyObject*
  3260. string_isalnum(PyStringObject *self)
  3261. {
  3262. register const unsigned char *p
  3263. = (unsigned char *) PyString_AS_STRING(self);
  3264. register const unsigned char *e;
  3265. /* Shortcut for single character strings */
  3266. if (PyString_GET_SIZE(self) == 1 &&
  3267. isalnum(*p))
  3268. return PyBool_FromLong(1);
  3269. /* Special case for empty strings */
  3270. if (PyString_GET_SIZE(self) == 0)
  3271. return PyBool_FromLong(0);
  3272. e = p + PyString_GET_SIZE(self);
  3273. for (; p < e; p++) {
  3274. if (!isalnum(*p))
  3275. return PyBool_FromLong(0);
  3276. }
  3277. return PyBool_FromLong(1);
  3278. }
  3279. PyDoc_STRVAR(isdigit__doc__,
  3280. "S.isdigit() -> bool\n\
  3281. \n\
  3282. Return True if all characters in S are digits\n\
  3283. and there is at least one character in S, False otherwise.");
  3284. static PyObject*
  3285. string_isdigit(PyStringObject *self)
  3286. {
  3287. register const unsigned char *p
  3288. = (unsigned char *) PyString_AS_STRING(self);
  3289. register const unsigned char *e;
  3290. /* Shortcut for single character strings */
  3291. if (PyString_GET_SIZE(self) == 1 &&
  3292. isdigit(*p))
  3293. return PyBool_FromLong(1);
  3294. /* Special case for empty strings */
  3295. if (PyString_GET_SIZE(self) == 0)
  3296. return PyBool_FromLong(0);
  3297. e = p + PyString_GET_SIZE(self);
  3298. for (; p < e; p++) {
  3299. if (!isdigit(*p))
  3300. return PyBool_FromLong(0);
  3301. }
  3302. return PyBool_FromLong(1);
  3303. }
  3304. PyDoc_STRVAR(islower__doc__,
  3305. "S.islower() -> bool\n\
  3306. \n\
  3307. Return True if all cased characters in S are lowercase and there is\n\
  3308. at least one cased character in S, False otherwise.");
  3309. static PyObject*
  3310. string_islower(PyStringObject *self)
  3311. {
  3312. register const unsigned char *p
  3313. = (unsigned char *) PyString_AS_STRING(self);
  3314. register const unsigned char *e;
  3315. int cased;
  3316. /* Shortcut for single character strings */
  3317. if (PyString_GET_SIZE(self) == 1)
  3318. return PyBool_FromLong(islower(*p) != 0);
  3319. /* Special case for empty strings */
  3320. if (PyString_GET_SIZE(self) == 0)
  3321. return PyBool_FromLong(0);
  3322. e = p + PyString_GET_SIZE(self);
  3323. cased = 0;
  3324. for (; p < e; p++) {
  3325. if (isupper(*p))
  3326. return PyBool_FromLong(0);
  3327. else if (!cased && islower(*p))
  3328. cased = 1;
  3329. }
  3330. return PyBool_FromLong(cased);
  3331. }
  3332. PyDoc_STRVAR(isupper__doc__,
  3333. "S.isupper() -> bool\n\
  3334. \n\
  3335. Return True if all cased characters in S are uppercase and there is\n\
  3336. at least one cased character in S, False otherwise.");
  3337. static PyObject*
  3338. string_isupper(PyStringObject *self)
  3339. {
  3340. register const unsigned char *p
  3341. = (unsigned char *) PyString_AS_STRING(self);
  3342. register const unsigned char *e;
  3343. int cased;
  3344. /* Shortcut for single character strings */
  3345. if (PyString_GET_SIZE(self) == 1)
  3346. return PyBool_FromLong(isupper(*p) != 0);
  3347. /* Special case for empty strings */
  3348. if (PyString_GET_SIZE(self) == 0)
  3349. return PyBool_FromLong(0);
  3350. e = p + PyString_GET_SIZE(self);
  3351. cased = 0;
  3352. for (; p < e; p++) {
  3353. if (islower(*p))
  3354. return PyBool_FromLong(0);
  3355. else if (!cased && isupper(*p))
  3356. cased = 1;
  3357. }
  3358. return PyBool_FromLong(cased);
  3359. }
  3360. PyDoc_STRVAR(istitle__doc__,
  3361. "S.istitle() -> bool\n\
  3362. \n\
  3363. Return True if S is a titlecased string and there is at least one\n\
  3364. character in S, i.e. uppercase characters may only follow uncased\n\
  3365. characters and lowercase characters only cased ones. Return False\n\
  3366. otherwise.");
  3367. static PyObject*
  3368. string_istitle(PyStringObject *self, PyObject *uncased)
  3369. {
  3370. register const unsigned char *p
  3371. = (unsigned char *) PyString_AS_STRING(self);
  3372. register const unsigned char *e;
  3373. int cased, previous_is_cased;
  3374. /* Shortcut for single character strings */
  3375. if (PyString_GET_SIZE(self) == 1)
  3376. return PyBool_FromLong(isupper(*p) != 0);
  3377. /* Special case for empty strings */
  3378. if (PyString_GET_SIZE(self) == 0)
  3379. return PyBool_FromLong(0);
  3380. e = p + PyString_GET_SIZE(self);
  3381. cased = 0;
  3382. previous_is_cased = 0;
  3383. for (; p < e; p++) {
  3384. register const unsigned char ch = *p;
  3385. if (isupper(ch)) {
  3386. if (previous_is_cased)
  3387. return PyBool_FromLong(0);
  3388. previous_is_cased = 1;
  3389. cased = 1;
  3390. }
  3391. else if (islower(ch)) {
  3392. if (!previous_is_cased)
  3393. return PyBool_FromLong(0);
  3394. previous_is_cased = 1;
  3395. cased = 1;
  3396. }
  3397. else
  3398. previous_is_cased = 0;
  3399. }
  3400. return PyBool_FromLong(cased);
  3401. }
  3402. PyDoc_STRVAR(splitlines__doc__,
  3403. "S.splitlines([keepends]) -> list of strings\n\
  3404. \n\
  3405. Return a list of the lines in S, breaking at line boundaries.\n\
  3406. Line breaks are not included in the resulting list unless keepends\n\
  3407. is given and true.");
  3408. static PyObject*
  3409. string_splitlines(PyStringObject *self, PyObject *args)
  3410. {
  3411. register Py_ssize_t i;
  3412. register Py_ssize_t j;
  3413. Py_ssize_t len;
  3414. int keepends = 0;
  3415. PyObject *list;
  3416. PyObject *str;
  3417. char *data;
  3418. if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
  3419. return NULL;
  3420. data = PyString_AS_STRING(self);
  3421. len = PyString_GET_SIZE(self);
  3422. /* This does not use the preallocated list because splitlines is
  3423. usually run with hundreds of newlines. The overhead of
  3424. switching between PyList_SET_ITEM and append causes about a
  3425. 2-3% slowdown for that common case. A smarter implementation
  3426. could move the if check out, so the SET_ITEMs are done first
  3427. and the appends only done when the prealloc buffer is full.
  3428. That's too much work for little gain.*/
  3429. list = PyList_New(0);
  3430. if (!list)
  3431. goto onError;
  3432. for (i = j = 0; i < len; ) {
  3433. Py_ssize_t eol;
  3434. /* Find a line and append it */
  3435. while (i < len && data[i] != '\n' && data[i] != '\r')
  3436. i++;
  3437. /* Skip the line break reading CRLF as one line break */
  3438. eol = i;
  3439. if (i < len) {
  3440. if (data[i] == '\r' && i + 1 < len &&
  3441. data[i+1] == '\n')
  3442. i += 2;
  3443. else
  3444. i++;
  3445. if (keepends)
  3446. eol = i;
  3447. }
  3448. SPLIT_APPEND(data, j, eol);
  3449. j = i;
  3450. }
  3451. if (j < len) {
  3452. SPLIT_APPEND(data, j, len);
  3453. }
  3454. return list;
  3455. onError:
  3456. Py_XDECREF(list);
  3457. return NULL;
  3458. }
  3459. PyDoc_STRVAR(sizeof__doc__,
  3460. "S.__sizeof__() -> size of S in memory, in bytes");
  3461. static PyObject *
  3462. string_sizeof(PyStringObject *v)
  3463. {
  3464. Py_ssize_t res;
  3465. res = sizeof(PyStringObject) + v->ob_size * v->ob_type->tp_itemsize;
  3466. return PyInt_FromSsize_t(res);
  3467. }
  3468. #undef SPLIT_APPEND
  3469. #undef SPLIT_ADD
  3470. #undef MAX_PREALLOC
  3471. #undef PREALLOC_SIZE
  3472. static PyObject *
  3473. string_getnewargs(PyStringObject *v)
  3474. {
  3475. return Py_BuildValue("(s#)", v->ob_sval, Py_SIZE(v));
  3476. }
  3477. #include "stringlib/string_format.h"
  3478. PyDoc_STRVAR(format__doc__,
  3479. "S.format(*args, **kwargs) -> unicode\n\
  3480. \n\
  3481. ");
  3482. static PyObject *
  3483. string__format__(PyObject* self, PyObject* args)
  3484. {
  3485. PyObject *format_spec;
  3486. PyObject *result = NULL;
  3487. PyObject *tmp = NULL;
  3488. /* If 2.x, convert format_spec to the same type as value */
  3489. /* This is to allow things like u''.format('') */
  3490. if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
  3491. goto done;
  3492. if (!(PyString_Check(format_spec) || PyUnicode_Check(format_spec))) {
  3493. PyErr_Format(PyExc_TypeError, "__format__ arg must be str "
  3494. "or unicode, not %s", Py_TYPE(format_spec)->tp_name);
  3495. goto done;
  3496. }
  3497. tmp = PyObject_Str(format_spec);
  3498. if (tmp == NULL)
  3499. goto done;
  3500. format_spec = tmp;
  3501. result = _PyBytes_FormatAdvanced(self,
  3502. PyString_AS_STRING(format_spec),
  3503. PyString_GET_SIZE(format_spec));
  3504. done:
  3505. Py_XDECREF(tmp);
  3506. return result;
  3507. }
  3508. PyDoc_STRVAR(p_format__doc__,
  3509. "S.__format__(format_spec) -> unicode\n\
  3510. \n\
  3511. ");
  3512. static PyMethodDef
  3513. string_methods[] = {
  3514. /* Counterparts of the obsolete stropmodule functions; except
  3515. string.maketrans(). */
  3516. {"join", (PyCFunction)string_join, METH_O, join__doc__},
  3517. {"split", (PyCFunction)string_split, METH_VARARGS, split__doc__},
  3518. {"rsplit", (PyCFunction)string_rsplit, METH_VARARGS, rsplit__doc__},
  3519. {"lower", (PyCFunction)string_lower, METH_NOARGS, lower__doc__},
  3520. {"upper", (PyCFunction)string_upper, METH_NOARGS, upper__doc__},
  3521. {"islower", (PyCFunction)string_islower, METH_NOARGS, islower__doc__},
  3522. {"isupper", (PyCFunction)string_isupper, METH_NOARGS, isupper__doc__},
  3523. {"isspace", (PyCFunction)string_isspace, METH_NOARGS, isspace__doc__},
  3524. {"isdigit", (PyCFunction)string_isdigit, METH_NOARGS, isdigit__doc__},
  3525. {"istitle", (PyCFunction)string_istitle, METH_NOARGS, istitle__doc__},
  3526. {"isalpha", (PyCFunction)string_isalpha, METH_NOARGS, isalpha__doc__},
  3527. {"isalnum", (PyCFunction)string_isalnum, METH_NOARGS, isalnum__doc__},
  3528. {"capitalize", (PyCFunction)string_capitalize, METH_NOARGS,
  3529. capitalize__doc__},
  3530. {"count", (PyCFunction)string_count, METH_VARARGS, count__doc__},
  3531. {"endswith", (PyCFunction)string_endswith, METH_VARARGS,
  3532. endswith__doc__},
  3533. {"partition", (PyCFunction)string_partition, METH_O, partition__doc__},
  3534. {"find", (PyCFunction)string_find, METH_VARARGS, find__doc__},
  3535. {"index", (PyCFunction)string_index, METH_VARARGS, index__doc__},
  3536. {"lstrip", (PyCFunction)string_lstrip, METH_VARARGS, lstrip__doc__},
  3537. {"replace", (PyCFunction)string_replace, METH_VARARGS, replace__doc__},
  3538. {"rfind", (PyCFunction)string_rfind, METH_VARARGS, rfind__doc__},
  3539. {"rindex", (PyCFunction)string_rindex, METH_VARARGS, rindex__doc__},
  3540. {"rstrip", (PyCFunction)string_rstrip, METH_VARARGS, rstrip__doc__},
  3541. {"rpartition", (PyCFunction)string_rpartition, METH_O,
  3542. rpartition__doc__},
  3543. {"startswith", (PyCFunction)string_startswith, METH_VARARGS,
  3544. startswith__doc__},
  3545. {"strip", (PyCFunction)string_strip, METH_VARARGS, strip__doc__},
  3546. {"swapcase", (PyCFunction)string_swapcase, METH_NOARGS,
  3547. swapcase__doc__},
  3548. {"translate", (PyCFunction)string_translate, METH_VARARGS,
  3549. translate__doc__},
  3550. {"title", (PyCFunction)string_title, METH_NOARGS, title__doc__},
  3551. {"ljust", (PyCFunction)string_ljust, METH_VARARGS, ljust__doc__},
  3552. {"rjust", (PyCFunction)string_rjust, METH_VARARGS, rjust__doc__},
  3553. {"center", (PyCFunction)string_center, METH_VARARGS, center__doc__},
  3554. {"zfill", (PyCFunction)string_zfill, METH_VARARGS, zfill__doc__},
  3555. {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
  3556. {"__format__", (PyCFunction) string__format__, METH_VARARGS, p_format__doc__},
  3557. {"_formatter_field_name_split", (PyCFunction) formatter_field_name_split, METH_NOARGS},
  3558. {"_formatter_parser", (PyCFunction) formatter_parser, METH_NOARGS},
  3559. {"encode", (PyCFunction)string_encode, METH_VARARGS, encode__doc__},
  3560. {"decode", (PyCFunction)string_decode, METH_VARARGS, decode__doc__},
  3561. {"expandtabs", (PyCFunction)string_expandtabs, METH_VARARGS,
  3562. expandtabs__doc__},
  3563. {"splitlines", (PyCFunction)string_splitlines, METH_VARARGS,
  3564. splitlines__doc__},
  3565. {"__sizeof__", (PyCFunction)string_sizeof, METH_NOARGS,
  3566. sizeof__doc__},
  3567. {"__getnewargs__", (PyCFunction)string_getnewargs, METH_NOARGS},
  3568. {NULL, NULL} /* sentinel */
  3569. };
  3570. static PyObject *
  3571. str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
  3572. static PyObject *
  3573. string_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  3574. {
  3575. PyObject *x = NULL;
  3576. static char *kwlist[] = {"object", 0};
  3577. if (type != &PyString_Type)
  3578. return str_subtype_new(type, args, kwds);
  3579. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:str", kwlist, &x))
  3580. return NULL;
  3581. if (x == NULL)
  3582. return PyString_FromString("");
  3583. return PyObject_Str(x);
  3584. }
  3585. static PyObject *
  3586. str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  3587. {
  3588. PyObject *tmp, *pnew;
  3589. Py_ssize_t n;
  3590. assert(PyType_IsSubtype(type, &PyString_Type));
  3591. tmp = string_new(&PyString_Type, args, kwds);
  3592. if (tmp == NULL)
  3593. return NULL;
  3594. assert(PyString_CheckExact(tmp));
  3595. n = PyString_GET_SIZE(tmp);
  3596. pnew = type->tp_alloc(type, n);
  3597. if (pnew != NULL) {
  3598. Py_MEMCPY(PyString_AS_STRING(pnew), PyString_AS_STRING(tmp), n+1);
  3599. ((PyStringObject *)pnew)->ob_shash =
  3600. ((PyStringObject *)tmp)->ob_shash;
  3601. ((PyStringObject *)pnew)->ob_sstate = SSTATE_NOT_INTERNED;
  3602. }
  3603. Py_DECREF(tmp);
  3604. return pnew;
  3605. }
  3606. static PyObject *
  3607. basestring_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  3608. {
  3609. PyErr_SetString(PyExc_TypeError,
  3610. "The basestring type cannot be instantiated");
  3611. return NULL;
  3612. }
  3613. static PyObject *
  3614. string_mod(PyObject *v, PyObject *w)
  3615. {
  3616. if (!PyString_Check(v)) {
  3617. Py_INCREF(Py_NotImplemented);
  3618. return Py_NotImplemented;
  3619. }
  3620. return PyString_Format(v, w);
  3621. }
  3622. PyDoc_STRVAR(basestring_doc,
  3623. "Type basestring cannot be instantiated; it is the base for str and unicode.");
  3624. static PyNumberMethods string_as_number = {
  3625. 0, /*nb_add*/
  3626. 0, /*nb_subtract*/
  3627. 0, /*nb_multiply*/
  3628. 0, /*nb_divide*/
  3629. string_mod, /*nb_remainder*/
  3630. };
  3631. PyTypeObject PyBaseString_Type = {
  3632. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  3633. "basestring",
  3634. 0,
  3635. 0,
  3636. 0, /* tp_dealloc */
  3637. 0, /* tp_print */
  3638. 0, /* tp_getattr */
  3639. 0, /* tp_setattr */
  3640. 0, /* tp_compare */
  3641. 0, /* tp_repr */
  3642. 0, /* tp_as_number */
  3643. 0, /* tp_as_sequence */
  3644. 0, /* tp_as_mapping */
  3645. 0, /* tp_hash */
  3646. 0, /* tp_call */
  3647. 0, /* tp_str */
  3648. 0, /* tp_getattro */
  3649. 0, /* tp_setattro */
  3650. 0, /* tp_as_buffer */
  3651. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  3652. basestring_doc, /* tp_doc */
  3653. 0, /* tp_traverse */
  3654. 0, /* tp_clear */
  3655. 0, /* tp_richcompare */
  3656. 0, /* tp_weaklistoffset */
  3657. 0, /* tp_iter */
  3658. 0, /* tp_iternext */
  3659. 0, /* tp_methods */
  3660. 0, /* tp_members */
  3661. 0, /* tp_getset */
  3662. &PyBaseObject_Type, /* tp_base */
  3663. 0, /* tp_dict */
  3664. 0, /* tp_descr_get */
  3665. 0, /* tp_descr_set */
  3666. 0, /* tp_dictoffset */
  3667. 0, /* tp_init */
  3668. 0, /* tp_alloc */
  3669. basestring_new, /* tp_new */
  3670. 0, /* tp_free */
  3671. };
  3672. PyDoc_STRVAR(string_doc,
  3673. "str(object) -> string\n\
  3674. \n\
  3675. Return a nice string representation of the object.\n\
  3676. If the argument is a string, the return value is the same object.");
  3677. PyTypeObject PyString_Type = {
  3678. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  3679. "str",
  3680. sizeof(PyStringObject),
  3681. sizeof(char),
  3682. string_dealloc, /* tp_dealloc */
  3683. (printfunc)string_print, /* tp_print */
  3684. 0, /* tp_getattr */
  3685. 0, /* tp_setattr */
  3686. 0, /* tp_compare */
  3687. string_repr, /* tp_repr */
  3688. &string_as_number, /* tp_as_number */
  3689. &string_as_sequence, /* tp_as_sequence */
  3690. &string_as_mapping, /* tp_as_mapping */
  3691. (hashfunc)string_hash, /* tp_hash */
  3692. 0, /* tp_call */
  3693. string_str, /* tp_str */
  3694. PyObject_GenericGetAttr, /* tp_getattro */
  3695. 0, /* tp_setattro */
  3696. &string_as_buffer, /* tp_as_buffer */
  3697. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
  3698. Py_TPFLAGS_BASETYPE | Py_TPFLAGS_STRING_SUBCLASS |
  3699. Py_TPFLAGS_HAVE_NEWBUFFER, /* tp_flags */
  3700. string_doc, /* tp_doc */
  3701. 0, /* tp_traverse */
  3702. 0, /* tp_clear */
  3703. (richcmpfunc)string_richcompare, /* tp_richcompare */
  3704. 0, /* tp_weaklistoffset */
  3705. 0, /* tp_iter */
  3706. 0, /* tp_iternext */
  3707. string_methods, /* tp_methods */
  3708. 0, /* tp_members */
  3709. 0, /* tp_getset */
  3710. &PyBaseString_Type, /* tp_base */
  3711. 0, /* tp_dict */
  3712. 0, /* tp_descr_get */
  3713. 0, /* tp_descr_set */
  3714. 0, /* tp_dictoffset */
  3715. 0, /* tp_init */
  3716. 0, /* tp_alloc */
  3717. string_new, /* tp_new */
  3718. PyObject_Del, /* tp_free */
  3719. };
  3720. void
  3721. PyString_Concat(register PyObject **pv, register PyObject *w)
  3722. {
  3723. register PyObject *v;
  3724. if (*pv == NULL)
  3725. return;
  3726. if (w == NULL || !PyString_Check(*pv)) {
  3727. Py_DECREF(*pv);
  3728. *pv = NULL;
  3729. return;
  3730. }
  3731. v = string_concat((PyStringObject *) *pv, w);
  3732. Py_DECREF(*pv);
  3733. *pv = v;
  3734. }
  3735. void
  3736. PyString_ConcatAndDel(register PyObject **pv, register PyObject *w)
  3737. {
  3738. PyString_Concat(pv, w);
  3739. Py_XDECREF(w);
  3740. }
  3741. /* The following function breaks the notion that strings are immutable:
  3742. it changes the size of a string. We get away with this only if there
  3743. is only one module referencing the object. You can also think of it
  3744. as creating a new string object and destroying the old one, only
  3745. more efficiently. In any case, don't use this if the string may
  3746. already be known to some other part of the code...
  3747. Note that if there's not enough memory to resize the string, the original
  3748. string object at *pv is deallocated, *pv is set to NULL, an "out of
  3749. memory" exception is set, and -1 is returned. Else (on success) 0 is
  3750. returned, and the value in *pv may or may not be the same as on input.
  3751. As always, an extra byte is allocated for a trailing \0 byte (newsize
  3752. does *not* include that), and a trailing \0 byte is stored.
  3753. */
  3754. int
  3755. _PyString_Resize(PyObject **pv, Py_ssize_t newsize)
  3756. {
  3757. register PyObject *v;
  3758. register PyStringObject *sv;
  3759. v = *pv;
  3760. if (!PyString_Check(v) || Py_REFCNT(v) != 1 || newsize < 0 ||
  3761. PyString_CHECK_INTERNED(v)) {
  3762. *pv = 0;
  3763. Py_DECREF(v);
  3764. PyErr_BadInternalCall();
  3765. return -1;
  3766. }
  3767. /* XXX UNREF/NEWREF interface should be more symmetrical */
  3768. _Py_DEC_REFTOTAL;
  3769. _Py_ForgetReference(v);
  3770. *pv = (PyObject *)
  3771. PyObject_REALLOC((char *)v, sizeof(PyStringObject) + newsize);
  3772. if (*pv == NULL) {
  3773. PyObject_Del(v);
  3774. PyErr_NoMemory();
  3775. return -1;
  3776. }
  3777. _Py_NewReference(*pv);
  3778. sv = (PyStringObject *) *pv;
  3779. Py_SIZE(sv) = newsize;
  3780. sv->ob_sval[newsize] = '\0';
  3781. sv->ob_shash = -1; /* invalidate cached hash value */
  3782. return 0;
  3783. }
  3784. /* Helpers for formatstring */
  3785. Py_LOCAL_INLINE(PyObject *)
  3786. getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
  3787. {
  3788. Py_ssize_t argidx = *p_argidx;
  3789. if (argidx < arglen) {
  3790. (*p_argidx)++;
  3791. if (arglen < 0)
  3792. return args;
  3793. else
  3794. return PyTuple_GetItem(args, argidx);
  3795. }
  3796. PyErr_SetString(PyExc_TypeError,
  3797. "not enough arguments for format string");
  3798. return NULL;
  3799. }
  3800. /* Format codes
  3801. * F_LJUST '-'
  3802. * F_SIGN '+'
  3803. * F_BLANK ' '
  3804. * F_ALT '#'
  3805. * F_ZERO '0'
  3806. */
  3807. #define F_LJUST (1<<0)
  3808. #define F_SIGN (1<<1)
  3809. #define F_BLANK (1<<2)
  3810. #define F_ALT (1<<3)
  3811. #define F_ZERO (1<<4)
  3812. Py_LOCAL_INLINE(int)
  3813. formatfloat(char *buf, size_t buflen, int flags,
  3814. int prec, int type, PyObject *v)
  3815. {
  3816. /* fmt = '%#.' + `prec` + `type`
  3817. worst case length = 3 + 10 (len of INT_MAX) + 1 = 14 (use 20)*/
  3818. char fmt[20];
  3819. double x;
  3820. x = PyFloat_AsDouble(v);
  3821. if (x == -1.0 && PyErr_Occurred()) {
  3822. PyErr_Format(PyExc_TypeError, "float argument required, "
  3823. "not %.200s", Py_TYPE(v)->tp_name);
  3824. return -1;
  3825. }
  3826. if (prec < 0)
  3827. prec = 6;
  3828. #if SIZEOF_INT > 4
  3829. /* make sure that the decimal representation of precision really does
  3830. need at most 10 digits: platforms with sizeof(int) == 8 exist! */
  3831. if (prec > 0x7fffffff) {
  3832. PyErr_SetString(PyExc_OverflowError,
  3833. "outrageously large precision "
  3834. "for formatted float");
  3835. return -1;
  3836. }
  3837. #endif
  3838. if (type == 'f' && fabs(x) >= 1e50)
  3839. type = 'g';
  3840. /* Worst case length calc to ensure no buffer overrun:
  3841. 'g' formats:
  3842. fmt = %#.<prec>g
  3843. buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
  3844. for any double rep.)
  3845. len = 1 + prec + 1 + 2 + 5 = 9 + prec
  3846. 'f' formats:
  3847. buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50)
  3848. len = 1 + 50 + 1 + prec = 52 + prec
  3849. If prec=0 the effective precision is 1 (the leading digit is
  3850. always given), therefore increase the length by one.
  3851. */
  3852. if (((type == 'g' || type == 'G') &&
  3853. buflen <= (size_t)10 + (size_t)prec) ||
  3854. (type == 'f' && buflen <= (size_t)53 + (size_t)prec)) {
  3855. PyErr_SetString(PyExc_OverflowError,
  3856. "formatted float is too long (precision too large?)");
  3857. return -1;
  3858. }
  3859. PyOS_snprintf(fmt, sizeof(fmt), "%%%s.%d%c",
  3860. (flags&F_ALT) ? "#" : "",
  3861. prec, type);
  3862. PyOS_ascii_formatd(buf, buflen, fmt, x);
  3863. return (int)strlen(buf);
  3864. }
  3865. /* _PyString_FormatLong emulates the format codes d, u, o, x and X, and
  3866. * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
  3867. * Python's regular ints.
  3868. * Return value: a new PyString*, or NULL if error.
  3869. * . *pbuf is set to point into it,
  3870. * *plen set to the # of chars following that.
  3871. * Caller must decref it when done using pbuf.
  3872. * The string starting at *pbuf is of the form
  3873. * "-"? ("0x" | "0X")? digit+
  3874. * "0x"/"0X" are present only for x and X conversions, with F_ALT
  3875. * set in flags. The case of hex digits will be correct,
  3876. * There will be at least prec digits, zero-filled on the left if
  3877. * necessary to get that many.
  3878. * val object to be converted
  3879. * flags bitmask of format flags; only F_ALT is looked at
  3880. * prec minimum number of digits; 0-fill on left if needed
  3881. * type a character in [duoxX]; u acts the same as d
  3882. *
  3883. * CAUTION: o, x and X conversions on regular ints can never
  3884. * produce a '-' sign, but can for Python's unbounded ints.
  3885. */
  3886. PyObject*
  3887. _PyString_FormatLong(PyObject *val, int flags, int prec, int type,
  3888. char **pbuf, int *plen)
  3889. {
  3890. PyObject *result = NULL;
  3891. char *buf;
  3892. Py_ssize_t i;
  3893. int sign; /* 1 if '-', else 0 */
  3894. int len; /* number of characters */
  3895. Py_ssize_t llen;
  3896. int numdigits; /* len == numnondigits + numdigits */
  3897. int numnondigits = 0;
  3898. switch (type) {
  3899. case 'd':
  3900. case 'u':
  3901. result = Py_TYPE(val)->tp_str(val);
  3902. break;
  3903. case 'o':
  3904. result = Py_TYPE(val)->tp_as_number->nb_oct(val);
  3905. break;
  3906. case 'x':
  3907. case 'X':
  3908. numnondigits = 2;
  3909. result = Py_TYPE(val)->tp_as_number->nb_hex(val);
  3910. break;
  3911. default:
  3912. assert(!"'type' not in [duoxX]");
  3913. }
  3914. if (!result)
  3915. return NULL;
  3916. buf = PyString_AsString(result);
  3917. if (!buf) {
  3918. Py_DECREF(result);
  3919. return NULL;
  3920. }
  3921. /* To modify the string in-place, there can only be one reference. */
  3922. if (Py_REFCNT(result) != 1) {
  3923. PyErr_BadInternalCall();
  3924. return NULL;
  3925. }
  3926. llen = PyString_Size(result);
  3927. if (llen > INT_MAX) {
  3928. PyErr_SetString(PyExc_ValueError, "string too large in _PyString_FormatLong");
  3929. return NULL;
  3930. }
  3931. len = (int)llen;
  3932. if (buf[len-1] == 'L') {
  3933. --len;
  3934. buf[len] = '\0';
  3935. }
  3936. sign = buf[0] == '-';
  3937. numnondigits += sign;
  3938. numdigits = len - numnondigits;
  3939. assert(numdigits > 0);
  3940. /* Get rid of base marker unless F_ALT */
  3941. if ((flags & F_ALT) == 0) {
  3942. /* Need to skip 0x, 0X or 0. */
  3943. int skipped = 0;
  3944. switch (type) {
  3945. case 'o':
  3946. assert(buf[sign] == '0');
  3947. /* If 0 is only digit, leave it alone. */
  3948. if (numdigits > 1) {
  3949. skipped = 1;
  3950. --numdigits;
  3951. }
  3952. break;
  3953. case 'x':
  3954. case 'X':
  3955. assert(buf[sign] == '0');
  3956. assert(buf[sign + 1] == 'x');
  3957. skipped = 2;
  3958. numnondigits -= 2;
  3959. break;
  3960. }
  3961. if (skipped) {
  3962. buf += skipped;
  3963. len -= skipped;
  3964. if (sign)
  3965. buf[0] = '-';
  3966. }
  3967. assert(len == numnondigits + numdigits);
  3968. assert(numdigits > 0);
  3969. }
  3970. /* Fill with leading zeroes to meet minimum width. */
  3971. if (prec > numdigits) {
  3972. PyObject *r1 = PyString_FromStringAndSize(NULL,
  3973. numnondigits + prec);
  3974. char *b1;
  3975. if (!r1) {
  3976. Py_DECREF(result);
  3977. return NULL;
  3978. }
  3979. b1 = PyString_AS_STRING(r1);
  3980. for (i = 0; i < numnondigits; ++i)
  3981. *b1++ = *buf++;
  3982. for (i = 0; i < prec - numdigits; i++)
  3983. *b1++ = '0';
  3984. for (i = 0; i < numdigits; i++)
  3985. *b1++ = *buf++;
  3986. *b1 = '\0';
  3987. Py_DECREF(result);
  3988. result = r1;
  3989. buf = PyString_AS_STRING(result);
  3990. len = numnondigits + prec;
  3991. }
  3992. /* Fix up case for hex conversions. */
  3993. if (type == 'X') {
  3994. /* Need to convert all lower case letters to upper case.
  3995. and need to convert 0x to 0X (and -0x to -0X). */
  3996. for (i = 0; i < len; i++)
  3997. if (buf[i] >= 'a' && buf[i] <= 'x')
  3998. buf[i] -= 'a'-'A';
  3999. }
  4000. *pbuf = buf;
  4001. *plen = len;
  4002. return result;
  4003. }
  4004. Py_LOCAL_INLINE(int)
  4005. formatint(char *buf, size_t buflen, int flags,
  4006. int prec, int type, PyObject *v)
  4007. {
  4008. /* fmt = '%#.' + `prec` + 'l' + `type`
  4009. worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine)
  4010. + 1 + 1 = 24 */
  4011. char fmt[64]; /* plenty big enough! */
  4012. char *sign;
  4013. long x;
  4014. x = PyInt_AsLong(v);
  4015. if (x == -1 && PyErr_Occurred()) {
  4016. PyErr_Format(PyExc_TypeError, "int argument required, not %.200s",
  4017. Py_TYPE(v)->tp_name);
  4018. return -1;
  4019. }
  4020. if (x < 0 && type == 'u') {
  4021. type = 'd';
  4022. }
  4023. if (x < 0 && (type == 'x' || type == 'X' || type == 'o'))
  4024. sign = "-";
  4025. else
  4026. sign = "";
  4027. if (prec < 0)
  4028. prec = 1;
  4029. if ((flags & F_ALT) &&
  4030. (type == 'x' || type == 'X')) {
  4031. /* When converting under %#x or %#X, there are a number
  4032. * of issues that cause pain:
  4033. * - when 0 is being converted, the C standard leaves off
  4034. * the '0x' or '0X', which is inconsistent with other
  4035. * %#x/%#X conversions and inconsistent with Python's
  4036. * hex() function
  4037. * - there are platforms that violate the standard and
  4038. * convert 0 with the '0x' or '0X'
  4039. * (Metrowerks, Compaq Tru64)
  4040. * - there are platforms that give '0x' when converting
  4041. * under %#X, but convert 0 in accordance with the
  4042. * standard (OS/2 EMX)
  4043. *
  4044. * We can achieve the desired consistency by inserting our
  4045. * own '0x' or '0X' prefix, and substituting %x/%X in place
  4046. * of %#x/%#X.
  4047. *
  4048. * Note that this is the same approach as used in
  4049. * formatint() in unicodeobject.c
  4050. */
  4051. PyOS_snprintf(fmt, sizeof(fmt), "%s0%c%%.%dl%c",
  4052. sign, type, prec, type);
  4053. }
  4054. else {
  4055. PyOS_snprintf(fmt, sizeof(fmt), "%s%%%s.%dl%c",
  4056. sign, (flags&F_ALT) ? "#" : "",
  4057. prec, type);
  4058. }
  4059. /* buf = '+'/'-'/'' + '0'/'0x'/'' + '[0-9]'*max(prec, len(x in octal))
  4060. * worst case buf = '-0x' + [0-9]*prec, where prec >= 11
  4061. */
  4062. if (buflen <= 14 || buflen <= (size_t)3 + (size_t)prec) {
  4063. PyErr_SetString(PyExc_OverflowError,
  4064. "formatted integer is too long (precision too large?)");
  4065. return -1;
  4066. }
  4067. if (sign[0])
  4068. PyOS_snprintf(buf, buflen, fmt, -x);
  4069. else
  4070. PyOS_snprintf(buf, buflen, fmt, x);
  4071. return (int)strlen(buf);
  4072. }
  4073. Py_LOCAL_INLINE(int)
  4074. formatchar(char *buf, size_t buflen, PyObject *v)
  4075. {
  4076. /* presume that the buffer is at least 2 characters long */
  4077. if (PyString_Check(v)) {
  4078. if (!PyArg_Parse(v, "c;%c requires int or char", &buf[0]))
  4079. return -1;
  4080. }
  4081. else {
  4082. if (!PyArg_Parse(v, "b;%c requires int or char", &buf[0]))
  4083. return -1;
  4084. }
  4085. buf[1] = '\0';
  4086. return 1;
  4087. }
  4088. /* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
  4089. FORMATBUFLEN is the length of the buffer in which the floats, ints, &
  4090. chars are formatted. XXX This is a magic number. Each formatting
  4091. routine does bounds checking to ensure no overflow, but a better
  4092. solution may be to malloc a buffer of appropriate size for each
  4093. format. For now, the current solution is sufficient.
  4094. */
  4095. #define FORMATBUFLEN (size_t)120
  4096. PyObject *
  4097. PyString_Format(PyObject *format, PyObject *args)
  4098. {
  4099. char *fmt, *res;
  4100. Py_ssize_t arglen, argidx;
  4101. Py_ssize_t reslen, rescnt, fmtcnt;
  4102. int args_owned = 0;
  4103. PyObject *result, *orig_args;
  4104. #ifdef Py_USING_UNICODE
  4105. PyObject *v, *w;
  4106. #endif
  4107. PyObject *dict = NULL;
  4108. if (format == NULL || !PyString_Check(format) || args == NULL) {
  4109. PyErr_BadInternalCall();
  4110. return NULL;
  4111. }
  4112. orig_args = args;
  4113. fmt = PyString_AS_STRING(format);
  4114. fmtcnt = PyString_GET_SIZE(format);
  4115. reslen = rescnt = fmtcnt + 100;
  4116. result = PyString_FromStringAndSize((char *)NULL, reslen);
  4117. if (result == NULL)
  4118. return NULL;
  4119. res = PyString_AsString(result);
  4120. if (PyTuple_Check(args)) {
  4121. arglen = PyTuple_GET_SIZE(args);
  4122. argidx = 0;
  4123. }
  4124. else {
  4125. arglen = -1;
  4126. argidx = -2;
  4127. }
  4128. if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
  4129. !PyObject_TypeCheck(args, &PyBaseString_Type))
  4130. dict = args;
  4131. while (--fmtcnt >= 0) {
  4132. if (*fmt != '%') {
  4133. if (--rescnt < 0) {
  4134. rescnt = fmtcnt + 100;
  4135. reslen += rescnt;
  4136. if (_PyString_Resize(&result, reslen) < 0)
  4137. return NULL;
  4138. res = PyString_AS_STRING(result)
  4139. + reslen - rescnt;
  4140. --rescnt;
  4141. }
  4142. *res++ = *fmt++;
  4143. }
  4144. else {
  4145. /* Got a format specifier */
  4146. int flags = 0;
  4147. Py_ssize_t width = -1;
  4148. int prec = -1;
  4149. int c = '\0';
  4150. int fill;
  4151. int isnumok;
  4152. PyObject *v = NULL;
  4153. PyObject *temp = NULL;
  4154. char *pbuf;
  4155. int sign;
  4156. Py_ssize_t len;
  4157. char formatbuf[FORMATBUFLEN];
  4158. /* For format{float,int,char}() */
  4159. #ifdef Py_USING_UNICODE
  4160. char *fmt_start = fmt;
  4161. Py_ssize_t argidx_start = argidx;
  4162. #endif
  4163. fmt++;
  4164. if (*fmt == '(') {
  4165. char *keystart;
  4166. Py_ssize_t keylen;
  4167. PyObject *key;
  4168. int pcount = 1;
  4169. if (dict == NULL) {
  4170. PyErr_SetString(PyExc_TypeError,
  4171. "format requires a mapping");
  4172. goto error;
  4173. }
  4174. ++fmt;
  4175. --fmtcnt;
  4176. keystart = fmt;
  4177. /* Skip over balanced parentheses */
  4178. while (pcount > 0 && --fmtcnt >= 0) {
  4179. if (*fmt == ')')
  4180. --pcount;
  4181. else if (*fmt == '(')
  4182. ++pcount;
  4183. fmt++;
  4184. }
  4185. keylen = fmt - keystart - 1;
  4186. if (fmtcnt < 0 || pcount > 0) {
  4187. PyErr_SetString(PyExc_ValueError,
  4188. "incomplete format key");
  4189. goto error;
  4190. }
  4191. key = PyString_FromStringAndSize(keystart,
  4192. keylen);
  4193. if (key == NULL)
  4194. goto error;
  4195. if (args_owned) {
  4196. Py_DECREF(args);
  4197. args_owned = 0;
  4198. }
  4199. args = PyObject_GetItem(dict, key);
  4200. Py_DECREF(key);
  4201. if (args == NULL) {
  4202. goto error;
  4203. }
  4204. args_owned = 1;
  4205. arglen = -1;
  4206. argidx = -2;
  4207. }
  4208. while (--fmtcnt >= 0) {
  4209. switch (c = *fmt++) {
  4210. case '-': flags |= F_LJUST; continue;
  4211. case '+': flags |= F_SIGN; continue;
  4212. case ' ': flags |= F_BLANK; continue;
  4213. case '#': flags |= F_ALT; continue;
  4214. case '0': flags |= F_ZERO; continue;
  4215. }
  4216. break;
  4217. }
  4218. if (c == '*') {
  4219. v = getnextarg(args, arglen, &argidx);
  4220. if (v == NULL)
  4221. goto error;
  4222. if (!PyInt_Check(v)) {
  4223. PyErr_SetString(PyExc_TypeError,
  4224. "* wants int");
  4225. goto error;
  4226. }
  4227. width = PyInt_AsLong(v);
  4228. if (width < 0) {
  4229. flags |= F_LJUST;
  4230. width = -width;
  4231. }
  4232. if (--fmtcnt >= 0)
  4233. c = *fmt++;
  4234. }
  4235. else if (c >= 0 && isdigit(c)) {
  4236. width = c - '0';
  4237. while (--fmtcnt >= 0) {
  4238. c = Py_CHARMASK(*fmt++);
  4239. if (!isdigit(c))
  4240. break;
  4241. if ((width*10) / 10 != width) {
  4242. PyErr_SetString(
  4243. PyExc_ValueError,
  4244. "width too big");
  4245. goto error;
  4246. }
  4247. width = width*10 + (c - '0');
  4248. }
  4249. }
  4250. if (c == '.') {
  4251. prec = 0;
  4252. if (--fmtcnt >= 0)
  4253. c = *fmt++;
  4254. if (c == '*') {
  4255. v = getnextarg(args, arglen, &argidx);
  4256. if (v == NULL)
  4257. goto error;
  4258. if (!PyInt_Check(v)) {
  4259. PyErr_SetString(
  4260. PyExc_TypeError,
  4261. "* wants int");
  4262. goto error;
  4263. }
  4264. prec = PyInt_AsLong(v);
  4265. if (prec < 0)
  4266. prec = 0;
  4267. if (--fmtcnt >= 0)
  4268. c = *fmt++;
  4269. }
  4270. else if (c >= 0 && isdigit(c)) {
  4271. prec = c - '0';
  4272. while (--fmtcnt >= 0) {
  4273. c = Py_CHARMASK(*fmt++);
  4274. if (!isdigit(c))
  4275. break;
  4276. if ((prec*10) / 10 != prec) {
  4277. PyErr_SetString(
  4278. PyExc_ValueError,
  4279. "prec too big");
  4280. goto error;
  4281. }
  4282. prec = prec*10 + (c - '0');
  4283. }
  4284. }
  4285. } /* prec */
  4286. if (fmtcnt >= 0) {
  4287. if (c == 'h' || c == 'l' || c == 'L') {
  4288. if (--fmtcnt >= 0)
  4289. c = *fmt++;
  4290. }
  4291. }
  4292. if (fmtcnt < 0) {
  4293. PyErr_SetString(PyExc_ValueError,
  4294. "incomplete format");
  4295. goto error;
  4296. }
  4297. if (c != '%') {
  4298. v = getnextarg(args, arglen, &argidx);
  4299. if (v == NULL)
  4300. goto error;
  4301. }
  4302. sign = 0;
  4303. fill = ' ';
  4304. switch (c) {
  4305. case '%':
  4306. pbuf = "%";
  4307. len = 1;
  4308. break;
  4309. case 's':
  4310. #ifdef Py_USING_UNICODE
  4311. if (PyUnicode_Check(v)) {
  4312. fmt = fmt_start;
  4313. argidx = argidx_start;
  4314. goto unicode;
  4315. }
  4316. #endif
  4317. temp = _PyObject_Str(v);
  4318. #ifdef Py_USING_UNICODE
  4319. if (temp != NULL && PyUnicode_Check(temp)) {
  4320. Py_DECREF(temp);
  4321. fmt = fmt_start;
  4322. argidx = argidx_start;
  4323. goto unicode;
  4324. }
  4325. #endif
  4326. /* Fall through */
  4327. case 'r':
  4328. if (c == 'r')
  4329. temp = PyObject_Repr(v);
  4330. if (temp == NULL)
  4331. goto error;
  4332. if (!PyString_Check(temp)) {
  4333. PyErr_SetString(PyExc_TypeError,
  4334. "%s argument has non-string str()");
  4335. Py_DECREF(temp);
  4336. goto error;
  4337. }
  4338. pbuf = PyString_AS_STRING(temp);
  4339. len = PyString_GET_SIZE(temp);
  4340. if (prec >= 0 && len > prec)
  4341. len = prec;
  4342. break;
  4343. case 'i':
  4344. case 'd':
  4345. case 'u':
  4346. case 'o':
  4347. case 'x':
  4348. case 'X':
  4349. if (c == 'i')
  4350. c = 'd';
  4351. isnumok = 0;
  4352. if (PyNumber_Check(v)) {
  4353. PyObject *iobj=NULL;
  4354. if (PyInt_Check(v) || (PyLong_Check(v))) {
  4355. iobj = v;
  4356. Py_INCREF(iobj);
  4357. }
  4358. else {
  4359. iobj = PyNumber_Int(v);
  4360. if (iobj==NULL) iobj = PyNumber_Long(v);
  4361. }
  4362. if (iobj!=NULL) {
  4363. if (PyInt_Check(iobj)) {
  4364. isnumok = 1;
  4365. pbuf = formatbuf;
  4366. len = formatint(pbuf,
  4367. sizeof(formatbuf),
  4368. flags, prec, c, iobj);
  4369. Py_DECREF(iobj);
  4370. if (len < 0)
  4371. goto error;
  4372. sign = 1;
  4373. }
  4374. else if (PyLong_Check(iobj)) {
  4375. int ilen;
  4376. isnumok = 1;
  4377. temp = _PyString_FormatLong(iobj, flags,
  4378. prec, c, &pbuf, &ilen);
  4379. Py_DECREF(iobj);
  4380. len = ilen;
  4381. if (!temp)
  4382. goto error;
  4383. sign = 1;
  4384. }
  4385. else {
  4386. Py_DECREF(iobj);
  4387. }
  4388. }
  4389. }
  4390. if (!isnumok) {
  4391. PyErr_Format(PyExc_TypeError,
  4392. "%%%c format: a number is required, "
  4393. "not %.200s", c, Py_TYPE(v)->tp_name);
  4394. goto error;
  4395. }
  4396. if (flags & F_ZERO)
  4397. fill = '0';
  4398. break;
  4399. case 'e':
  4400. case 'E':
  4401. case 'f':
  4402. case 'F':
  4403. case 'g':
  4404. case 'G':
  4405. if (c == 'F')
  4406. c = 'f';
  4407. pbuf = formatbuf;
  4408. len = formatfloat(pbuf, sizeof(formatbuf),
  4409. flags, prec, c, v);
  4410. if (len < 0)
  4411. goto error;
  4412. sign = 1;
  4413. if (flags & F_ZERO)
  4414. fill = '0';
  4415. break;
  4416. case 'c':
  4417. #ifdef Py_USING_UNICODE
  4418. if (PyUnicode_Check(v)) {
  4419. fmt = fmt_start;
  4420. argidx = argidx_start;
  4421. goto unicode;
  4422. }
  4423. #endif
  4424. pbuf = formatbuf;
  4425. len = formatchar(pbuf, sizeof(formatbuf), v);
  4426. if (len < 0)
  4427. goto error;
  4428. break;
  4429. default:
  4430. PyErr_Format(PyExc_ValueError,
  4431. "unsupported format character '%c' (0x%x) "
  4432. "at index %zd",
  4433. c, c,
  4434. (Py_ssize_t)(fmt - 1 -
  4435. PyString_AsString(format)));
  4436. goto error;
  4437. }
  4438. if (sign) {
  4439. if (*pbuf == '-' || *pbuf == '+') {
  4440. sign = *pbuf++;
  4441. len--;
  4442. }
  4443. else if (flags & F_SIGN)
  4444. sign = '+';
  4445. else if (flags & F_BLANK)
  4446. sign = ' ';
  4447. else
  4448. sign = 0;
  4449. }
  4450. if (width < len)
  4451. width = len;
  4452. if (rescnt - (sign != 0) < width) {
  4453. reslen -= rescnt;
  4454. rescnt = width + fmtcnt + 100;
  4455. reslen += rescnt;
  4456. if (reslen < 0) {
  4457. Py_DECREF(result);
  4458. Py_XDECREF(temp);
  4459. return PyErr_NoMemory();
  4460. }
  4461. if (_PyString_Resize(&result, reslen) < 0) {
  4462. Py_XDECREF(temp);
  4463. return NULL;
  4464. }
  4465. res = PyString_AS_STRING(result)
  4466. + reslen - rescnt;
  4467. }
  4468. if (sign) {
  4469. if (fill != ' ')
  4470. *res++ = sign;
  4471. rescnt--;
  4472. if (width > len)
  4473. width--;
  4474. }
  4475. if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
  4476. assert(pbuf[0] == '0');
  4477. assert(pbuf[1] == c);
  4478. if (fill != ' ') {
  4479. *res++ = *pbuf++;
  4480. *res++ = *pbuf++;
  4481. }
  4482. rescnt -= 2;
  4483. width -= 2;
  4484. if (width < 0)
  4485. width = 0;
  4486. len -= 2;
  4487. }
  4488. if (width > len && !(flags & F_LJUST)) {
  4489. do {
  4490. --rescnt;
  4491. *res++ = fill;
  4492. } while (--width > len);
  4493. }
  4494. if (fill == ' ') {
  4495. if (sign)
  4496. *res++ = sign;
  4497. if ((flags & F_ALT) &&
  4498. (c == 'x' || c == 'X')) {
  4499. assert(pbuf[0] == '0');
  4500. assert(pbuf[1] == c);
  4501. *res++ = *pbuf++;
  4502. *res++ = *pbuf++;
  4503. }
  4504. }
  4505. Py_MEMCPY(res, pbuf, len);
  4506. res += len;
  4507. rescnt -= len;
  4508. while (--width >= len) {
  4509. --rescnt;
  4510. *res++ = ' ';
  4511. }
  4512. if (dict && (argidx < arglen) && c != '%') {
  4513. PyErr_SetString(PyExc_TypeError,
  4514. "not all arguments converted during string formatting");
  4515. Py_XDECREF(temp);
  4516. goto error;
  4517. }
  4518. Py_XDECREF(temp);
  4519. } /* '%' */
  4520. } /* until end */
  4521. if (argidx < arglen && !dict) {
  4522. PyErr_SetString(PyExc_TypeError,
  4523. "not all arguments converted during string formatting");
  4524. goto error;
  4525. }
  4526. if (args_owned) {
  4527. Py_DECREF(args);
  4528. }
  4529. _PyString_Resize(&result, reslen - rescnt);
  4530. return result;
  4531. #ifdef Py_USING_UNICODE
  4532. unicode:
  4533. if (args_owned) {
  4534. Py_DECREF(args);
  4535. args_owned = 0;
  4536. }
  4537. /* Fiddle args right (remove the first argidx arguments) */
  4538. if (PyTuple_Check(orig_args) && argidx > 0) {
  4539. PyObject *v;
  4540. Py_ssize_t n = PyTuple_GET_SIZE(orig_args) - argidx;
  4541. v = PyTuple_New(n);
  4542. if (v == NULL)
  4543. goto error;
  4544. while (--n >= 0) {
  4545. PyObject *w = PyTuple_GET_ITEM(orig_args, n + argidx);
  4546. Py_INCREF(w);
  4547. PyTuple_SET_ITEM(v, n, w);
  4548. }
  4549. args = v;
  4550. } else {
  4551. Py_INCREF(orig_args);
  4552. args = orig_args;
  4553. }
  4554. args_owned = 1;
  4555. /* Take what we have of the result and let the Unicode formatting
  4556. function format the rest of the input. */
  4557. rescnt = res - PyString_AS_STRING(result);
  4558. if (_PyString_Resize(&result, rescnt))
  4559. goto error;
  4560. fmtcnt = PyString_GET_SIZE(format) - \
  4561. (fmt - PyString_AS_STRING(format));
  4562. format = PyUnicode_Decode(fmt, fmtcnt, NULL, NULL);
  4563. if (format == NULL)
  4564. goto error;
  4565. v = PyUnicode_Format(format, args);
  4566. Py_DECREF(format);
  4567. if (v == NULL)
  4568. goto error;
  4569. /* Paste what we have (result) to what the Unicode formatting
  4570. function returned (v) and return the result (or error) */
  4571. w = PyUnicode_Concat(result, v);
  4572. Py_DECREF(result);
  4573. Py_DECREF(v);
  4574. Py_DECREF(args);
  4575. return w;
  4576. #endif /* Py_USING_UNICODE */
  4577. error:
  4578. Py_DECREF(result);
  4579. if (args_owned) {
  4580. Py_DECREF(args);
  4581. }
  4582. return NULL;
  4583. }
  4584. void
  4585. PyString_InternInPlace(PyObject **p)
  4586. {
  4587. register PyStringObject *s = (PyStringObject *)(*p);
  4588. PyObject *t;
  4589. if (s == NULL || !PyString_Check(s))
  4590. Py_FatalError("PyString_InternInPlace: strings only please!");
  4591. /* If it's a string subclass, we don't really know what putting
  4592. it in the interned dict might do. */
  4593. if (!PyString_CheckExact(s))
  4594. return;
  4595. if (PyString_CHECK_INTERNED(s))
  4596. return;
  4597. if (interned == NULL) {
  4598. interned = PyDict_New();
  4599. if (interned == NULL) {
  4600. PyErr_Clear(); /* Don't leave an exception */
  4601. return;
  4602. }
  4603. }
  4604. t = PyDict_GetItem(interned, (PyObject *)s);
  4605. if (t) {
  4606. Py_INCREF(t);
  4607. Py_DECREF(*p);
  4608. *p = t;
  4609. return;
  4610. }
  4611. if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
  4612. PyErr_Clear();
  4613. return;
  4614. }
  4615. /* The two references in interned are not counted by refcnt.
  4616. The string deallocator will take care of this */
  4617. Py_REFCNT(s) -= 2;
  4618. PyString_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
  4619. }
  4620. void
  4621. PyString_InternImmortal(PyObject **p)
  4622. {
  4623. PyString_InternInPlace(p);
  4624. if (PyString_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
  4625. PyString_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
  4626. Py_INCREF(*p);
  4627. }
  4628. }
  4629. PyObject *
  4630. PyString_InternFromString(const char *cp)
  4631. {
  4632. PyObject *s = PyString_FromString(cp);
  4633. if (s == NULL)
  4634. return NULL;
  4635. PyString_InternInPlace(&s);
  4636. return s;
  4637. }
  4638. void
  4639. PyString_Fini(void)
  4640. {
  4641. int i;
  4642. for (i = 0; i < UCHAR_MAX + 1; i++) {
  4643. Py_XDECREF(characters[i]);
  4644. characters[i] = NULL;
  4645. }
  4646. Py_XDECREF(nullstring);
  4647. nullstring = NULL;
  4648. }
  4649. void _Py_ReleaseInternedStrings(void)
  4650. {
  4651. PyObject *keys;
  4652. PyStringObject *s;
  4653. Py_ssize_t i, n;
  4654. Py_ssize_t immortal_size = 0, mortal_size = 0;
  4655. if (interned == NULL || !PyDict_Check(interned))
  4656. return;
  4657. keys = PyDict_Keys(interned);
  4658. if (keys == NULL || !PyList_Check(keys)) {
  4659. PyErr_Clear();
  4660. return;
  4661. }
  4662. /* Since _Py_ReleaseInternedStrings() is intended to help a leak
  4663. detector, interned strings are not forcibly deallocated; rather, we
  4664. give them their stolen references back, and then clear and DECREF
  4665. the interned dict. */
  4666. n = PyList_GET_SIZE(keys);
  4667. fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
  4668. n);
  4669. for (i = 0; i < n; i++) {
  4670. s = (PyStringObject *) PyList_GET_ITEM(keys, i);
  4671. switch (s->ob_sstate) {
  4672. case SSTATE_NOT_INTERNED:
  4673. /* XXX Shouldn't happen */
  4674. break;
  4675. case SSTATE_INTERNED_IMMORTAL:
  4676. Py_REFCNT(s) += 1;
  4677. immortal_size += Py_SIZE(s);
  4678. break;
  4679. case SSTATE_INTERNED_MORTAL:
  4680. Py_REFCNT(s) += 2;
  4681. mortal_size += Py_SIZE(s);
  4682. break;
  4683. default:
  4684. Py_FatalError("Inconsistent interned string state.");
  4685. }
  4686. s->ob_sstate = SSTATE_NOT_INTERNED;
  4687. }
  4688. fprintf(stderr, "total size of all interned strings: "
  4689. "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
  4690. "mortal/immortal\n", mortal_size, immortal_size);
  4691. Py_DECREF(keys);
  4692. PyDict_Clear(interned);
  4693. Py_DECREF(interned);
  4694. interned = NULL;
  4695. }