PageRenderTime 89ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 1ms

/Objects/unicodeobject.c

http://unladen-swallow.googlecode.com/
C | 9106 lines | 7348 code | 957 blank | 801 comment | 1905 complexity | 9db69b4d6a66f4afb0d8ed2b2d32eecc MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. /*
  2. Unicode implementation based on original code by Fredrik Lundh,
  3. modified by Marc-Andre Lemburg <mal@lemburg.com> according to the
  4. Unicode Integration Proposal (see file Misc/unicode.txt).
  5. Major speed upgrades to the method implementations at the Reykjavik
  6. NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
  7. Copyright (c) Corporation for National Research Initiatives.
  8. --------------------------------------------------------------------
  9. The original string type implementation is:
  10. Copyright (c) 1999 by Secret Labs AB
  11. Copyright (c) 1999 by Fredrik Lundh
  12. By obtaining, using, and/or copying this software and/or its
  13. associated documentation, you agree that you have read, understood,
  14. and will comply with the following terms and conditions:
  15. Permission to use, copy, modify, and distribute this software and its
  16. associated documentation for any purpose and without fee is hereby
  17. granted, provided that the above copyright notice appears in all
  18. copies, and that both that copyright notice and this permission notice
  19. appear in supporting documentation, and that the name of Secret Labs
  20. AB or the author not be used in advertising or publicity pertaining to
  21. distribution of the software without specific, written prior
  22. permission.
  23. SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
  24. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  25. FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
  26. ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  27. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  28. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  29. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  30. --------------------------------------------------------------------
  31. */
  32. #define PY_SSIZE_T_CLEAN
  33. #include "Python.h"
  34. #include "unicodeobject.h"
  35. #include "ucnhash.h"
  36. #ifdef MS_WINDOWS
  37. #include <windows.h>
  38. #endif
  39. /* Limit for the Unicode object free list */
  40. #define PyUnicode_MAXFREELIST 1024
  41. /* Limit for the Unicode object free list stay alive optimization.
  42. The implementation will keep allocated Unicode memory intact for
  43. all objects on the free list having a size less than this
  44. limit. This reduces malloc() overhead for small Unicode objects.
  45. At worst this will result in PyUnicode_MAXFREELIST *
  46. (sizeof(PyUnicodeObject) + KEEPALIVE_SIZE_LIMIT +
  47. malloc()-overhead) bytes of unused garbage.
  48. Setting the limit to 0 effectively turns the feature off.
  49. Note: This is an experimental feature ! If you get core dumps when
  50. using Unicode objects, turn this feature off.
  51. */
  52. #define KEEPALIVE_SIZE_LIMIT 9
  53. /* Endianness switches; defaults to little endian */
  54. #ifdef WORDS_BIGENDIAN
  55. # define BYTEORDER_IS_BIG_ENDIAN
  56. #else
  57. # define BYTEORDER_IS_LITTLE_ENDIAN
  58. #endif
  59. /* --- Globals ------------------------------------------------------------
  60. The globals are initialized by the _PyUnicode_Init() API and should
  61. not be used before calling that API.
  62. */
  63. #ifdef __cplusplus
  64. extern "C" {
  65. #endif
  66. /* Free list for Unicode objects */
  67. static PyUnicodeObject *free_list;
  68. static int numfree;
  69. /* The empty Unicode object is shared to improve performance. */
  70. static PyUnicodeObject *unicode_empty;
  71. /* Single character Unicode strings in the Latin-1 range are being
  72. shared as well. */
  73. static PyUnicodeObject *unicode_latin1[256];
  74. /* Default encoding to use and assume when NULL is passed as encoding
  75. parameter; it is initialized by _PyUnicode_Init().
  76. Always use the PyUnicode_SetDefaultEncoding() and
  77. PyUnicode_GetDefaultEncoding() APIs to access this global.
  78. */
  79. static char unicode_default_encoding[100];
  80. /* Fast detection of the most frequent whitespace characters */
  81. const unsigned char _Py_ascii_whitespace[] = {
  82. 0, 0, 0, 0, 0, 0, 0, 0,
  83. /* case 0x0009: * HORIZONTAL TABULATION */
  84. /* case 0x000A: * LINE FEED */
  85. /* case 0x000B: * VERTICAL TABULATION */
  86. /* case 0x000C: * FORM FEED */
  87. /* case 0x000D: * CARRIAGE RETURN */
  88. 0, 1, 1, 1, 1, 1, 0, 0,
  89. 0, 0, 0, 0, 0, 0, 0, 0,
  90. /* case 0x001C: * FILE SEPARATOR */
  91. /* case 0x001D: * GROUP SEPARATOR */
  92. /* case 0x001E: * RECORD SEPARATOR */
  93. /* case 0x001F: * UNIT SEPARATOR */
  94. 0, 0, 0, 0, 1, 1, 1, 1,
  95. /* case 0x0020: * SPACE */
  96. 1, 0, 0, 0, 0, 0, 0, 0,
  97. 0, 0, 0, 0, 0, 0, 0, 0,
  98. 0, 0, 0, 0, 0, 0, 0, 0,
  99. 0, 0, 0, 0, 0, 0, 0, 0,
  100. 0, 0, 0, 0, 0, 0, 0, 0,
  101. 0, 0, 0, 0, 0, 0, 0, 0,
  102. 0, 0, 0, 0, 0, 0, 0, 0,
  103. 0, 0, 0, 0, 0, 0, 0, 0,
  104. 0, 0, 0, 0, 0, 0, 0, 0,
  105. 0, 0, 0, 0, 0, 0, 0, 0,
  106. 0, 0, 0, 0, 0, 0, 0, 0,
  107. 0, 0, 0, 0, 0, 0, 0, 0
  108. };
  109. /* Same for linebreaks */
  110. static unsigned char ascii_linebreak[] = {
  111. 0, 0, 0, 0, 0, 0, 0, 0,
  112. /* 0x000A, * LINE FEED */
  113. /* 0x000D, * CARRIAGE RETURN */
  114. 0, 0, 1, 0, 0, 1, 0, 0,
  115. 0, 0, 0, 0, 0, 0, 0, 0,
  116. /* 0x001C, * FILE SEPARATOR */
  117. /* 0x001D, * GROUP SEPARATOR */
  118. /* 0x001E, * RECORD SEPARATOR */
  119. 0, 0, 0, 0, 1, 1, 1, 0,
  120. 0, 0, 0, 0, 0, 0, 0, 0,
  121. 0, 0, 0, 0, 0, 0, 0, 0,
  122. 0, 0, 0, 0, 0, 0, 0, 0,
  123. 0, 0, 0, 0, 0, 0, 0, 0,
  124. 0, 0, 0, 0, 0, 0, 0, 0,
  125. 0, 0, 0, 0, 0, 0, 0, 0,
  126. 0, 0, 0, 0, 0, 0, 0, 0,
  127. 0, 0, 0, 0, 0, 0, 0, 0,
  128. 0, 0, 0, 0, 0, 0, 0, 0,
  129. 0, 0, 0, 0, 0, 0, 0, 0,
  130. 0, 0, 0, 0, 0, 0, 0, 0,
  131. 0, 0, 0, 0, 0, 0, 0, 0
  132. };
  133. Py_UNICODE
  134. PyUnicode_GetMax(void)
  135. {
  136. #ifdef Py_UNICODE_WIDE
  137. return 0x10FFFF;
  138. #else
  139. /* This is actually an illegal character, so it should
  140. not be passed to unichr. */
  141. return 0xFFFF;
  142. #endif
  143. }
  144. /* --- Bloom Filters ----------------------------------------------------- */
  145. /* stuff to implement simple "bloom filters" for Unicode characters.
  146. to keep things simple, we use a single bitmask, using the least 5
  147. bits from each unicode characters as the bit index. */
  148. /* the linebreak mask is set up by Unicode_Init below */
  149. #define BLOOM_MASK unsigned long
  150. static BLOOM_MASK bloom_linebreak;
  151. #define BLOOM(mask, ch) ((mask & (1 << ((ch) & 0x1F))))
  152. #define BLOOM_LINEBREAK(ch) \
  153. ((ch) < 128U ? ascii_linebreak[(ch)] : \
  154. (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
  155. Py_LOCAL_INLINE(BLOOM_MASK) make_bloom_mask(Py_UNICODE* ptr, Py_ssize_t len)
  156. {
  157. /* calculate simple bloom-style bitmask for a given unicode string */
  158. long mask;
  159. Py_ssize_t i;
  160. mask = 0;
  161. for (i = 0; i < len; i++)
  162. mask |= (1 << (ptr[i] & 0x1F));
  163. return mask;
  164. }
  165. Py_LOCAL_INLINE(int) unicode_member(Py_UNICODE chr, Py_UNICODE* set, Py_ssize_t setlen)
  166. {
  167. Py_ssize_t i;
  168. for (i = 0; i < setlen; i++)
  169. if (set[i] == chr)
  170. return 1;
  171. return 0;
  172. }
  173. #define BLOOM_MEMBER(mask, chr, set, setlen) \
  174. BLOOM(mask, chr) && unicode_member(chr, set, setlen)
  175. /* --- Unicode Object ----------------------------------------------------- */
  176. static
  177. int unicode_resize(register PyUnicodeObject *unicode,
  178. Py_ssize_t length)
  179. {
  180. void *oldstr;
  181. /* Shortcut if there's nothing much to do. */
  182. if (unicode->length == length)
  183. goto reset;
  184. /* Resizing shared object (unicode_empty or single character
  185. objects) in-place is not allowed. Use PyUnicode_Resize()
  186. instead ! */
  187. if (unicode == unicode_empty ||
  188. (unicode->length == 1 &&
  189. unicode->str[0] < 256U &&
  190. unicode_latin1[unicode->str[0]] == unicode)) {
  191. PyErr_SetString(PyExc_SystemError,
  192. "can't resize shared unicode objects");
  193. return -1;
  194. }
  195. /* We allocate one more byte to make sure the string is Ux0000 terminated.
  196. The overallocation is also used by fastsearch, which assumes that it's
  197. safe to look at str[length] (without making any assumptions about what
  198. it contains). */
  199. oldstr = unicode->str;
  200. unicode->str = PyObject_REALLOC(unicode->str,
  201. sizeof(Py_UNICODE) * (length + 1));
  202. if (!unicode->str) {
  203. unicode->str = (Py_UNICODE *)oldstr;
  204. PyErr_NoMemory();
  205. return -1;
  206. }
  207. unicode->str[length] = 0;
  208. unicode->length = length;
  209. reset:
  210. /* Reset the object caches */
  211. if (unicode->defenc) {
  212. Py_DECREF(unicode->defenc);
  213. unicode->defenc = NULL;
  214. }
  215. unicode->hash = -1;
  216. return 0;
  217. }
  218. /* We allocate one more byte to make sure the string is
  219. Ux0000 terminated -- XXX is this needed ?
  220. XXX This allocator could further be enhanced by assuring that the
  221. free list never reduces its size below 1.
  222. */
  223. static
  224. PyUnicodeObject *_PyUnicode_New(Py_ssize_t length)
  225. {
  226. register PyUnicodeObject *unicode;
  227. /* Optimization for empty strings */
  228. if (length == 0 && unicode_empty != NULL) {
  229. Py_INCREF(unicode_empty);
  230. return unicode_empty;
  231. }
  232. /* Ensure we won't overflow the size. */
  233. if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
  234. return (PyUnicodeObject *)PyErr_NoMemory();
  235. }
  236. /* Unicode freelist & memory allocation */
  237. if (free_list) {
  238. unicode = free_list;
  239. free_list = *(PyUnicodeObject **)unicode;
  240. numfree--;
  241. if (unicode->str) {
  242. /* Keep-Alive optimization: we only upsize the buffer,
  243. never downsize it. */
  244. if ((unicode->length < length) &&
  245. unicode_resize(unicode, length) < 0) {
  246. PyObject_DEL(unicode->str);
  247. unicode->str = NULL;
  248. }
  249. }
  250. else {
  251. size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
  252. unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
  253. }
  254. PyObject_INIT(unicode, &PyUnicode_Type);
  255. }
  256. else {
  257. size_t new_size;
  258. unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
  259. if (unicode == NULL)
  260. return NULL;
  261. new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
  262. unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
  263. }
  264. if (!unicode->str) {
  265. PyErr_NoMemory();
  266. goto onError;
  267. }
  268. /* Initialize the first element to guard against cases where
  269. * the caller fails before initializing str -- unicode_resize()
  270. * reads str[0], and the Keep-Alive optimization can keep memory
  271. * allocated for str alive across a call to unicode_dealloc(unicode).
  272. * We don't want unicode_resize to read uninitialized memory in
  273. * that case.
  274. */
  275. unicode->str[0] = 0;
  276. unicode->str[length] = 0;
  277. unicode->length = length;
  278. unicode->hash = -1;
  279. unicode->defenc = NULL;
  280. return unicode;
  281. onError:
  282. /* XXX UNREF/NEWREF interface should be more symmetrical */
  283. _Py_DEC_REFTOTAL;
  284. _Py_ForgetReference((PyObject *)unicode);
  285. PyObject_Del(unicode);
  286. return NULL;
  287. }
  288. static
  289. void unicode_dealloc(register PyUnicodeObject *unicode)
  290. {
  291. if (PyUnicode_CheckExact(unicode) &&
  292. numfree < PyUnicode_MAXFREELIST) {
  293. /* Keep-Alive optimization */
  294. if (unicode->length >= KEEPALIVE_SIZE_LIMIT) {
  295. PyObject_DEL(unicode->str);
  296. unicode->str = NULL;
  297. unicode->length = 0;
  298. }
  299. if (unicode->defenc) {
  300. Py_DECREF(unicode->defenc);
  301. unicode->defenc = NULL;
  302. }
  303. /* Add to free list */
  304. *(PyUnicodeObject **)unicode = free_list;
  305. free_list = unicode;
  306. numfree++;
  307. }
  308. else {
  309. PyObject_DEL(unicode->str);
  310. Py_XDECREF(unicode->defenc);
  311. Py_TYPE(unicode)->tp_free((PyObject *)unicode);
  312. }
  313. }
  314. static
  315. int _PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
  316. {
  317. register PyUnicodeObject *v;
  318. /* Argument checks */
  319. if (unicode == NULL) {
  320. PyErr_BadInternalCall();
  321. return -1;
  322. }
  323. v = *unicode;
  324. if (v == NULL || !PyUnicode_Check(v) || Py_REFCNT(v) != 1 || length < 0) {
  325. PyErr_BadInternalCall();
  326. return -1;
  327. }
  328. /* Resizing unicode_empty and single character objects is not
  329. possible since these are being shared. We simply return a fresh
  330. copy with the same Unicode content. */
  331. if (v->length != length &&
  332. (v == unicode_empty || v->length == 1)) {
  333. PyUnicodeObject *w = _PyUnicode_New(length);
  334. if (w == NULL)
  335. return -1;
  336. Py_UNICODE_COPY(w->str, v->str,
  337. length < v->length ? length : v->length);
  338. Py_DECREF(*unicode);
  339. *unicode = w;
  340. return 0;
  341. }
  342. /* Note that we don't have to modify *unicode for unshared Unicode
  343. objects, since we can modify them in-place. */
  344. return unicode_resize(v, length);
  345. }
  346. int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
  347. {
  348. return _PyUnicode_Resize((PyUnicodeObject **)unicode, length);
  349. }
  350. PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u,
  351. Py_ssize_t size)
  352. {
  353. PyUnicodeObject *unicode;
  354. /* If the Unicode data is known at construction time, we can apply
  355. some optimizations which share commonly used objects. */
  356. if (u != NULL) {
  357. /* Optimization for empty strings */
  358. if (size == 0 && unicode_empty != NULL) {
  359. Py_INCREF(unicode_empty);
  360. return (PyObject *)unicode_empty;
  361. }
  362. /* Single character Unicode objects in the Latin-1 range are
  363. shared when using this constructor */
  364. if (size == 1 && *u < 256) {
  365. unicode = unicode_latin1[*u];
  366. if (!unicode) {
  367. unicode = _PyUnicode_New(1);
  368. if (!unicode)
  369. return NULL;
  370. unicode->str[0] = *u;
  371. unicode_latin1[*u] = unicode;
  372. }
  373. Py_INCREF(unicode);
  374. return (PyObject *)unicode;
  375. }
  376. }
  377. unicode = _PyUnicode_New(size);
  378. if (!unicode)
  379. return NULL;
  380. /* Copy the Unicode data into the new object */
  381. if (u != NULL)
  382. Py_UNICODE_COPY(unicode->str, u, size);
  383. return (PyObject *)unicode;
  384. }
  385. PyObject *PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
  386. {
  387. PyUnicodeObject *unicode;
  388. if (size < 0) {
  389. PyErr_SetString(PyExc_SystemError,
  390. "Negative size passed to PyUnicode_FromStringAndSize");
  391. return NULL;
  392. }
  393. /* If the Unicode data is known at construction time, we can apply
  394. some optimizations which share commonly used objects.
  395. Also, this means the input must be UTF-8, so fall back to the
  396. UTF-8 decoder at the end. */
  397. if (u != NULL) {
  398. /* Optimization for empty strings */
  399. if (size == 0 && unicode_empty != NULL) {
  400. Py_INCREF(unicode_empty);
  401. return (PyObject *)unicode_empty;
  402. }
  403. /* Single characters are shared when using this constructor.
  404. Restrict to ASCII, since the input must be UTF-8. */
  405. if (size == 1 && Py_CHARMASK(*u) < 128) {
  406. unicode = unicode_latin1[Py_CHARMASK(*u)];
  407. if (!unicode) {
  408. unicode = _PyUnicode_New(1);
  409. if (!unicode)
  410. return NULL;
  411. unicode->str[0] = Py_CHARMASK(*u);
  412. unicode_latin1[Py_CHARMASK(*u)] = unicode;
  413. }
  414. Py_INCREF(unicode);
  415. return (PyObject *)unicode;
  416. }
  417. return PyUnicode_DecodeUTF8(u, size, NULL);
  418. }
  419. unicode = _PyUnicode_New(size);
  420. if (!unicode)
  421. return NULL;
  422. return (PyObject *)unicode;
  423. }
  424. PyObject *PyUnicode_FromString(const char *u)
  425. {
  426. size_t size = strlen(u);
  427. if (size > PY_SSIZE_T_MAX) {
  428. PyErr_SetString(PyExc_OverflowError, "input too long");
  429. return NULL;
  430. }
  431. return PyUnicode_FromStringAndSize(u, size);
  432. }
  433. #ifdef HAVE_WCHAR_H
  434. PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
  435. Py_ssize_t size)
  436. {
  437. PyUnicodeObject *unicode;
  438. if (w == NULL) {
  439. PyErr_BadInternalCall();
  440. return NULL;
  441. }
  442. unicode = _PyUnicode_New(size);
  443. if (!unicode)
  444. return NULL;
  445. /* Copy the wchar_t data into the new object */
  446. #ifdef HAVE_USABLE_WCHAR_T
  447. memcpy(unicode->str, w, size * sizeof(wchar_t));
  448. #else
  449. {
  450. register Py_UNICODE *u;
  451. register Py_ssize_t i;
  452. u = PyUnicode_AS_UNICODE(unicode);
  453. for (i = size; i > 0; i--)
  454. *u++ = *w++;
  455. }
  456. #endif
  457. return (PyObject *)unicode;
  458. }
  459. static void
  460. makefmt(char *fmt, int longflag, int size_tflag, int zeropad, int width, int precision, char c)
  461. {
  462. *fmt++ = '%';
  463. if (width) {
  464. if (zeropad)
  465. *fmt++ = '0';
  466. fmt += sprintf(fmt, "%d", width);
  467. }
  468. if (precision)
  469. fmt += sprintf(fmt, ".%d", precision);
  470. if (longflag)
  471. *fmt++ = 'l';
  472. else if (size_tflag) {
  473. char *f = PY_FORMAT_SIZE_T;
  474. while (*f)
  475. *fmt++ = *f++;
  476. }
  477. *fmt++ = c;
  478. *fmt = '\0';
  479. }
  480. #define appendstring(string) {for (copy = string;*copy;) *s++ = *copy++;}
  481. PyObject *
  482. PyUnicode_FromFormatV(const char *format, va_list vargs)
  483. {
  484. va_list count;
  485. Py_ssize_t callcount = 0;
  486. PyObject **callresults = NULL;
  487. PyObject **callresult = NULL;
  488. Py_ssize_t n = 0;
  489. int width = 0;
  490. int precision = 0;
  491. int zeropad;
  492. const char* f;
  493. Py_UNICODE *s;
  494. PyObject *string;
  495. /* used by sprintf */
  496. char buffer[21];
  497. /* use abuffer instead of buffer, if we need more space
  498. * (which can happen if there's a format specifier with width). */
  499. char *abuffer = NULL;
  500. char *realbuffer;
  501. Py_ssize_t abuffersize = 0;
  502. char fmt[60]; /* should be enough for %0width.precisionld */
  503. const char *copy;
  504. #ifdef VA_LIST_IS_ARRAY
  505. Py_MEMCPY(count, vargs, sizeof(va_list));
  506. #else
  507. #ifdef __va_copy
  508. __va_copy(count, vargs);
  509. #else
  510. count = vargs;
  511. #endif
  512. #endif
  513. /* step 1: count the number of %S/%R/%s format specifications
  514. * (we call PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() for these
  515. * objects once during step 3 and put the result in an array) */
  516. for (f = format; *f; f++) {
  517. if (*f == '%') {
  518. if (*(f+1)=='%')
  519. continue;
  520. if (*(f+1)=='S' || *(f+1)=='R')
  521. ++callcount;
  522. while (isdigit((unsigned)*f))
  523. width = (width*10) + *f++ - '0';
  524. while (*++f && *f != '%' && !isalpha((unsigned)*f))
  525. ;
  526. if (*f == 's')
  527. ++callcount;
  528. }
  529. }
  530. /* step 2: allocate memory for the results of
  531. * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
  532. if (callcount) {
  533. callresults = PyObject_Malloc(sizeof(PyObject *)*callcount);
  534. if (!callresults) {
  535. PyErr_NoMemory();
  536. return NULL;
  537. }
  538. callresult = callresults;
  539. }
  540. /* step 3: figure out how large a buffer we need */
  541. for (f = format; *f; f++) {
  542. if (*f == '%') {
  543. const char* p = f;
  544. width = 0;
  545. while (isdigit((unsigned)*f))
  546. width = (width*10) + *f++ - '0';
  547. while (*++f && *f != '%' && !isalpha((unsigned)*f))
  548. ;
  549. /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
  550. * they don't affect the amount of space we reserve.
  551. */
  552. if ((*f == 'l' || *f == 'z') &&
  553. (f[1] == 'd' || f[1] == 'u'))
  554. ++f;
  555. switch (*f) {
  556. case 'c':
  557. (void)va_arg(count, int);
  558. /* fall through... */
  559. case '%':
  560. n++;
  561. break;
  562. case 'd': case 'u': case 'i': case 'x':
  563. (void) va_arg(count, int);
  564. /* 20 bytes is enough to hold a 64-bit
  565. integer. Decimal takes the most space.
  566. This isn't enough for octal.
  567. If a width is specified we need more
  568. (which we allocate later). */
  569. if (width < 20)
  570. width = 20;
  571. n += width;
  572. if (abuffersize < width)
  573. abuffersize = width;
  574. break;
  575. case 's':
  576. {
  577. /* UTF-8 */
  578. unsigned char *s = va_arg(count, unsigned char*);
  579. PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
  580. if (!str)
  581. goto fail;
  582. n += PyUnicode_GET_SIZE(str);
  583. /* Remember the str and switch to the next slot */
  584. *callresult++ = str;
  585. break;
  586. }
  587. case 'U':
  588. {
  589. PyObject *obj = va_arg(count, PyObject *);
  590. assert(obj && PyUnicode_Check(obj));
  591. n += PyUnicode_GET_SIZE(obj);
  592. break;
  593. }
  594. case 'V':
  595. {
  596. PyObject *obj = va_arg(count, PyObject *);
  597. const char *str = va_arg(count, const char *);
  598. assert(obj || str);
  599. assert(!obj || PyUnicode_Check(obj));
  600. if (obj)
  601. n += PyUnicode_GET_SIZE(obj);
  602. else
  603. n += strlen(str);
  604. break;
  605. }
  606. case 'S':
  607. {
  608. PyObject *obj = va_arg(count, PyObject *);
  609. PyObject *str;
  610. assert(obj);
  611. str = PyObject_Str(obj);
  612. if (!str)
  613. goto fail;
  614. n += PyUnicode_GET_SIZE(str);
  615. /* Remember the str and switch to the next slot */
  616. *callresult++ = str;
  617. break;
  618. }
  619. case 'R':
  620. {
  621. PyObject *obj = va_arg(count, PyObject *);
  622. PyObject *repr;
  623. assert(obj);
  624. repr = PyObject_Repr(obj);
  625. if (!repr)
  626. goto fail;
  627. n += PyUnicode_GET_SIZE(repr);
  628. /* Remember the repr and switch to the next slot */
  629. *callresult++ = repr;
  630. break;
  631. }
  632. case 'p':
  633. (void) va_arg(count, int);
  634. /* maximum 64-bit pointer representation:
  635. * 0xffffffffffffffff
  636. * so 19 characters is enough.
  637. * XXX I count 18 -- what's the extra for?
  638. */
  639. n += 19;
  640. break;
  641. default:
  642. /* if we stumble upon an unknown
  643. formatting code, copy the rest of
  644. the format string to the output
  645. string. (we cannot just skip the
  646. code, since there's no way to know
  647. what's in the argument list) */
  648. n += strlen(p);
  649. goto expand;
  650. }
  651. } else
  652. n++;
  653. }
  654. expand:
  655. if (abuffersize > 20) {
  656. abuffer = PyObject_Malloc(abuffersize);
  657. if (!abuffer) {
  658. PyErr_NoMemory();
  659. goto fail;
  660. }
  661. realbuffer = abuffer;
  662. }
  663. else
  664. realbuffer = buffer;
  665. /* step 4: fill the buffer */
  666. /* Since we've analyzed how much space we need for the worst case,
  667. we don't have to resize the string.
  668. There can be no errors beyond this point. */
  669. string = PyUnicode_FromUnicode(NULL, n);
  670. if (!string)
  671. goto fail;
  672. s = PyUnicode_AS_UNICODE(string);
  673. callresult = callresults;
  674. for (f = format; *f; f++) {
  675. if (*f == '%') {
  676. const char* p = f++;
  677. int longflag = 0;
  678. int size_tflag = 0;
  679. zeropad = (*f == '0');
  680. /* parse the width.precision part */
  681. width = 0;
  682. while (isdigit((unsigned)*f))
  683. width = (width*10) + *f++ - '0';
  684. precision = 0;
  685. if (*f == '.') {
  686. f++;
  687. while (isdigit((unsigned)*f))
  688. precision = (precision*10) + *f++ - '0';
  689. }
  690. /* handle the long flag, but only for %ld and %lu.
  691. others can be added when necessary. */
  692. if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
  693. longflag = 1;
  694. ++f;
  695. }
  696. /* handle the size_t flag. */
  697. if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
  698. size_tflag = 1;
  699. ++f;
  700. }
  701. switch (*f) {
  702. case 'c':
  703. *s++ = va_arg(vargs, int);
  704. break;
  705. case 'd':
  706. makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'd');
  707. if (longflag)
  708. sprintf(realbuffer, fmt, va_arg(vargs, long));
  709. else if (size_tflag)
  710. sprintf(realbuffer, fmt, va_arg(vargs, Py_ssize_t));
  711. else
  712. sprintf(realbuffer, fmt, va_arg(vargs, int));
  713. appendstring(realbuffer);
  714. break;
  715. case 'u':
  716. makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'u');
  717. if (longflag)
  718. sprintf(realbuffer, fmt, va_arg(vargs, unsigned long));
  719. else if (size_tflag)
  720. sprintf(realbuffer, fmt, va_arg(vargs, size_t));
  721. else
  722. sprintf(realbuffer, fmt, va_arg(vargs, unsigned int));
  723. appendstring(realbuffer);
  724. break;
  725. case 'i':
  726. makefmt(fmt, 0, 0, zeropad, width, precision, 'i');
  727. sprintf(realbuffer, fmt, va_arg(vargs, int));
  728. appendstring(realbuffer);
  729. break;
  730. case 'x':
  731. makefmt(fmt, 0, 0, zeropad, width, precision, 'x');
  732. sprintf(realbuffer, fmt, va_arg(vargs, int));
  733. appendstring(realbuffer);
  734. break;
  735. case 's':
  736. {
  737. /* unused, since we already have the result */
  738. (void) va_arg(vargs, char *);
  739. Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(*callresult),
  740. PyUnicode_GET_SIZE(*callresult));
  741. s += PyUnicode_GET_SIZE(*callresult);
  742. /* We're done with the unicode()/repr() => forget it */
  743. Py_DECREF(*callresult);
  744. /* switch to next unicode()/repr() result */
  745. ++callresult;
  746. break;
  747. }
  748. case 'U':
  749. {
  750. PyObject *obj = va_arg(vargs, PyObject *);
  751. Py_ssize_t size = PyUnicode_GET_SIZE(obj);
  752. Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
  753. s += size;
  754. break;
  755. }
  756. case 'V':
  757. {
  758. PyObject *obj = va_arg(vargs, PyObject *);
  759. const char *str = va_arg(vargs, const char *);
  760. if (obj) {
  761. Py_ssize_t size = PyUnicode_GET_SIZE(obj);
  762. Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
  763. s += size;
  764. } else {
  765. appendstring(str);
  766. }
  767. break;
  768. }
  769. case 'S':
  770. case 'R':
  771. {
  772. Py_UNICODE *ucopy;
  773. Py_ssize_t usize;
  774. Py_ssize_t upos;
  775. /* unused, since we already have the result */
  776. (void) va_arg(vargs, PyObject *);
  777. ucopy = PyUnicode_AS_UNICODE(*callresult);
  778. usize = PyUnicode_GET_SIZE(*callresult);
  779. for (upos = 0; upos<usize;)
  780. *s++ = ucopy[upos++];
  781. /* We're done with the unicode()/repr() => forget it */
  782. Py_DECREF(*callresult);
  783. /* switch to next unicode()/repr() result */
  784. ++callresult;
  785. break;
  786. }
  787. case 'p':
  788. sprintf(buffer, "%p", va_arg(vargs, void*));
  789. /* %p is ill-defined: ensure leading 0x. */
  790. if (buffer[1] == 'X')
  791. buffer[1] = 'x';
  792. else if (buffer[1] != 'x') {
  793. memmove(buffer+2, buffer, strlen(buffer)+1);
  794. buffer[0] = '0';
  795. buffer[1] = 'x';
  796. }
  797. appendstring(buffer);
  798. break;
  799. case '%':
  800. *s++ = '%';
  801. break;
  802. default:
  803. appendstring(p);
  804. goto end;
  805. }
  806. } else
  807. *s++ = *f;
  808. }
  809. end:
  810. if (callresults)
  811. PyObject_Free(callresults);
  812. if (abuffer)
  813. PyObject_Free(abuffer);
  814. PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string));
  815. return string;
  816. fail:
  817. if (callresults) {
  818. PyObject **callresult2 = callresults;
  819. while (callresult2 < callresult) {
  820. Py_DECREF(*callresult2);
  821. ++callresult2;
  822. }
  823. PyObject_Free(callresults);
  824. }
  825. if (abuffer)
  826. PyObject_Free(abuffer);
  827. return NULL;
  828. }
  829. #undef appendstring
  830. PyObject *
  831. PyUnicode_FromFormat(const char *format, ...)
  832. {
  833. PyObject* ret;
  834. va_list vargs;
  835. #ifdef HAVE_STDARG_PROTOTYPES
  836. va_start(vargs, format);
  837. #else
  838. va_start(vargs);
  839. #endif
  840. ret = PyUnicode_FromFormatV(format, vargs);
  841. va_end(vargs);
  842. return ret;
  843. }
  844. Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode,
  845. wchar_t *w,
  846. Py_ssize_t size)
  847. {
  848. if (unicode == NULL) {
  849. PyErr_BadInternalCall();
  850. return -1;
  851. }
  852. /* If possible, try to copy the 0-termination as well */
  853. if (size > PyUnicode_GET_SIZE(unicode))
  854. size = PyUnicode_GET_SIZE(unicode) + 1;
  855. #ifdef HAVE_USABLE_WCHAR_T
  856. memcpy(w, unicode->str, size * sizeof(wchar_t));
  857. #else
  858. {
  859. register Py_UNICODE *u;
  860. register Py_ssize_t i;
  861. u = PyUnicode_AS_UNICODE(unicode);
  862. for (i = size; i > 0; i--)
  863. *w++ = *u++;
  864. }
  865. #endif
  866. if (size > PyUnicode_GET_SIZE(unicode))
  867. return PyUnicode_GET_SIZE(unicode);
  868. else
  869. return size;
  870. }
  871. #endif
  872. PyObject *PyUnicode_FromOrdinal(int ordinal)
  873. {
  874. Py_UNICODE s[1];
  875. #ifdef Py_UNICODE_WIDE
  876. if (ordinal < 0 || ordinal > 0x10ffff) {
  877. PyErr_SetString(PyExc_ValueError,
  878. "unichr() arg not in range(0x110000) "
  879. "(wide Python build)");
  880. return NULL;
  881. }
  882. #else
  883. if (ordinal < 0 || ordinal > 0xffff) {
  884. PyErr_SetString(PyExc_ValueError,
  885. "unichr() arg not in range(0x10000) "
  886. "(narrow Python build)");
  887. return NULL;
  888. }
  889. #endif
  890. s[0] = (Py_UNICODE)ordinal;
  891. return PyUnicode_FromUnicode(s, 1);
  892. }
  893. PyObject *PyUnicode_FromObject(register PyObject *obj)
  894. {
  895. /* XXX Perhaps we should make this API an alias of
  896. PyObject_Unicode() instead ?! */
  897. if (PyUnicode_CheckExact(obj)) {
  898. Py_INCREF(obj);
  899. return obj;
  900. }
  901. if (PyUnicode_Check(obj)) {
  902. /* For a Unicode subtype that's not a Unicode object,
  903. return a true Unicode object with the same data. */
  904. return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj),
  905. PyUnicode_GET_SIZE(obj));
  906. }
  907. return PyUnicode_FromEncodedObject(obj, NULL, "strict");
  908. }
  909. PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
  910. const char *encoding,
  911. const char *errors)
  912. {
  913. const char *s = NULL;
  914. Py_ssize_t len;
  915. PyObject *v;
  916. if (obj == NULL) {
  917. PyErr_BadInternalCall();
  918. return NULL;
  919. }
  920. #if 0
  921. /* For b/w compatibility we also accept Unicode objects provided
  922. that no encodings is given and then redirect to
  923. PyObject_Unicode() which then applies the additional logic for
  924. Unicode subclasses.
  925. NOTE: This API should really only be used for object which
  926. represent *encoded* Unicode !
  927. */
  928. if (PyUnicode_Check(obj)) {
  929. if (encoding) {
  930. PyErr_SetString(PyExc_TypeError,
  931. "decoding Unicode is not supported");
  932. return NULL;
  933. }
  934. return PyObject_Unicode(obj);
  935. }
  936. #else
  937. if (PyUnicode_Check(obj)) {
  938. PyErr_SetString(PyExc_TypeError,
  939. "decoding Unicode is not supported");
  940. return NULL;
  941. }
  942. #endif
  943. /* Coerce object */
  944. if (PyString_Check(obj)) {
  945. s = PyString_AS_STRING(obj);
  946. len = PyString_GET_SIZE(obj);
  947. }
  948. else if (PyByteArray_Check(obj)) {
  949. /* Python 2.x specific */
  950. PyErr_Format(PyExc_TypeError,
  951. "decoding bytearray is not supported");
  952. return NULL;
  953. }
  954. else if (PyObject_AsCharBuffer(obj, &s, &len)) {
  955. /* Overwrite the error message with something more useful in
  956. case of a TypeError. */
  957. if (PyErr_ExceptionMatches(PyExc_TypeError))
  958. PyErr_Format(PyExc_TypeError,
  959. "coercing to Unicode: need string or buffer, "
  960. "%.80s found",
  961. Py_TYPE(obj)->tp_name);
  962. goto onError;
  963. }
  964. /* Convert to Unicode */
  965. if (len == 0) {
  966. Py_INCREF(unicode_empty);
  967. v = (PyObject *)unicode_empty;
  968. }
  969. else
  970. v = PyUnicode_Decode(s, len, encoding, errors);
  971. return v;
  972. onError:
  973. return NULL;
  974. }
  975. PyObject *PyUnicode_Decode(const char *s,
  976. Py_ssize_t size,
  977. const char *encoding,
  978. const char *errors)
  979. {
  980. PyObject *buffer = NULL, *unicode;
  981. if (encoding == NULL)
  982. encoding = PyUnicode_GetDefaultEncoding();
  983. /* Shortcuts for common default encodings */
  984. if (strcmp(encoding, "utf-8") == 0)
  985. return PyUnicode_DecodeUTF8(s, size, errors);
  986. else if (strcmp(encoding, "latin-1") == 0)
  987. return PyUnicode_DecodeLatin1(s, size, errors);
  988. #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
  989. else if (strcmp(encoding, "mbcs") == 0)
  990. return PyUnicode_DecodeMBCS(s, size, errors);
  991. #endif
  992. else if (strcmp(encoding, "ascii") == 0)
  993. return PyUnicode_DecodeASCII(s, size, errors);
  994. /* Decode via the codec registry */
  995. buffer = PyBuffer_FromMemory((void *)s, size);
  996. if (buffer == NULL)
  997. goto onError;
  998. unicode = PyCodec_Decode(buffer, encoding, errors);
  999. if (unicode == NULL)
  1000. goto onError;
  1001. if (!PyUnicode_Check(unicode)) {
  1002. PyErr_Format(PyExc_TypeError,
  1003. "decoder did not return an unicode object (type=%.400s)",
  1004. Py_TYPE(unicode)->tp_name);
  1005. Py_DECREF(unicode);
  1006. goto onError;
  1007. }
  1008. Py_DECREF(buffer);
  1009. return unicode;
  1010. onError:
  1011. Py_XDECREF(buffer);
  1012. return NULL;
  1013. }
  1014. PyObject *PyUnicode_AsDecodedObject(PyObject *unicode,
  1015. const char *encoding,
  1016. const char *errors)
  1017. {
  1018. PyObject *v;
  1019. if (!PyUnicode_Check(unicode)) {
  1020. PyErr_BadArgument();
  1021. goto onError;
  1022. }
  1023. if (encoding == NULL)
  1024. encoding = PyUnicode_GetDefaultEncoding();
  1025. /* Decode via the codec registry */
  1026. v = PyCodec_Decode(unicode, encoding, errors);
  1027. if (v == NULL)
  1028. goto onError;
  1029. return v;
  1030. onError:
  1031. return NULL;
  1032. }
  1033. PyObject *PyUnicode_Encode(const Py_UNICODE *s,
  1034. Py_ssize_t size,
  1035. const char *encoding,
  1036. const char *errors)
  1037. {
  1038. PyObject *v, *unicode;
  1039. unicode = PyUnicode_FromUnicode(s, size);
  1040. if (unicode == NULL)
  1041. return NULL;
  1042. v = PyUnicode_AsEncodedString(unicode, encoding, errors);
  1043. Py_DECREF(unicode);
  1044. return v;
  1045. }
  1046. PyObject *PyUnicode_AsEncodedObject(PyObject *unicode,
  1047. const char *encoding,
  1048. const char *errors)
  1049. {
  1050. PyObject *v;
  1051. if (!PyUnicode_Check(unicode)) {
  1052. PyErr_BadArgument();
  1053. goto onError;
  1054. }
  1055. if (encoding == NULL)
  1056. encoding = PyUnicode_GetDefaultEncoding();
  1057. /* Encode via the codec registry */
  1058. v = PyCodec_Encode(unicode, encoding, errors);
  1059. if (v == NULL)
  1060. goto onError;
  1061. return v;
  1062. onError:
  1063. return NULL;
  1064. }
  1065. PyObject *PyUnicode_AsEncodedString(PyObject *unicode,
  1066. const char *encoding,
  1067. const char *errors)
  1068. {
  1069. PyObject *v;
  1070. if (!PyUnicode_Check(unicode)) {
  1071. PyErr_BadArgument();
  1072. goto onError;
  1073. }
  1074. if (encoding == NULL)
  1075. encoding = PyUnicode_GetDefaultEncoding();
  1076. /* Shortcuts for common default encodings */
  1077. if (errors == NULL) {
  1078. if (strcmp(encoding, "utf-8") == 0)
  1079. return PyUnicode_AsUTF8String(unicode);
  1080. else if (strcmp(encoding, "latin-1") == 0)
  1081. return PyUnicode_AsLatin1String(unicode);
  1082. #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
  1083. else if (strcmp(encoding, "mbcs") == 0)
  1084. return PyUnicode_AsMBCSString(unicode);
  1085. #endif
  1086. else if (strcmp(encoding, "ascii") == 0)
  1087. return PyUnicode_AsASCIIString(unicode);
  1088. }
  1089. /* Encode via the codec registry */
  1090. v = PyCodec_Encode(unicode, encoding, errors);
  1091. if (v == NULL)
  1092. goto onError;
  1093. if (!PyString_Check(v)) {
  1094. PyErr_Format(PyExc_TypeError,
  1095. "encoder did not return a string object (type=%.400s)",
  1096. Py_TYPE(v)->tp_name);
  1097. Py_DECREF(v);
  1098. goto onError;
  1099. }
  1100. return v;
  1101. onError:
  1102. return NULL;
  1103. }
  1104. PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
  1105. const char *errors)
  1106. {
  1107. PyObject *v = ((PyUnicodeObject *)unicode)->defenc;
  1108. if (v)
  1109. return v;
  1110. v = PyUnicode_AsEncodedString(unicode, NULL, errors);
  1111. if (v && errors == NULL)
  1112. ((PyUnicodeObject *)unicode)->defenc = v;
  1113. return v;
  1114. }
  1115. Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)
  1116. {
  1117. if (!PyUnicode_Check(unicode)) {
  1118. PyErr_BadArgument();
  1119. goto onError;
  1120. }
  1121. return PyUnicode_AS_UNICODE(unicode);
  1122. onError:
  1123. return NULL;
  1124. }
  1125. Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
  1126. {
  1127. if (!PyUnicode_Check(unicode)) {
  1128. PyErr_BadArgument();
  1129. goto onError;
  1130. }
  1131. return PyUnicode_GET_SIZE(unicode);
  1132. onError:
  1133. return -1;
  1134. }
  1135. const char *PyUnicode_GetDefaultEncoding(void)
  1136. {
  1137. return unicode_default_encoding;
  1138. }
  1139. int PyUnicode_SetDefaultEncoding(const char *encoding)
  1140. {
  1141. PyObject *v;
  1142. /* Make sure the encoding is valid. As side effect, this also
  1143. loads the encoding into the codec registry cache. */
  1144. v = _PyCodec_Lookup(encoding);
  1145. if (v == NULL)
  1146. goto onError;
  1147. Py_DECREF(v);
  1148. strncpy(unicode_default_encoding,
  1149. encoding,
  1150. sizeof(unicode_default_encoding));
  1151. return 0;
  1152. onError:
  1153. return -1;
  1154. }
  1155. /* error handling callback helper:
  1156. build arguments, call the callback and check the arguments,
  1157. if no exception occurred, copy the replacement to the output
  1158. and adjust various state variables.
  1159. return 0 on success, -1 on error
  1160. */
  1161. static
  1162. int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
  1163. const char *encoding, const char *reason,
  1164. const char *input, Py_ssize_t insize, Py_ssize_t *startinpos,
  1165. Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
  1166. PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
  1167. {
  1168. static char *argparse = "O!n;decoding error handler must return (unicode, int) tuple";
  1169. PyObject *restuple = NULL;
  1170. PyObject *repunicode = NULL;
  1171. Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
  1172. Py_ssize_t requiredsize;
  1173. Py_ssize_t newpos;
  1174. Py_UNICODE *repptr;
  1175. Py_ssize_t repsize;
  1176. int res = -1;
  1177. if (*errorHandler == NULL) {
  1178. *errorHandler = PyCodec_LookupError(errors);
  1179. if (*errorHandler == NULL)
  1180. goto onError;
  1181. }
  1182. if (*exceptionObject == NULL) {
  1183. *exceptionObject = PyUnicodeDecodeError_Create(
  1184. encoding, input, insize, *startinpos, *endinpos, reason);
  1185. if (*exceptionObject == NULL)
  1186. goto onError;
  1187. }
  1188. else {
  1189. if (PyUnicodeDecodeError_SetStart(*exceptionObject, *startinpos))
  1190. goto onError;
  1191. if (PyUnicodeDecodeError_SetEnd(*exceptionObject, *endinpos))
  1192. goto onError;
  1193. if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
  1194. goto onError;
  1195. }
  1196. restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
  1197. if (restuple == NULL)
  1198. goto onError;
  1199. if (!PyTuple_Check(restuple)) {
  1200. PyErr_SetString(PyExc_TypeError, &argparse[4]);
  1201. goto onError;
  1202. }
  1203. if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
  1204. goto onError;
  1205. if (newpos<0)
  1206. newpos = insize+newpos;
  1207. if (newpos<0 || newpos>insize) {
  1208. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
  1209. goto onError;
  1210. }
  1211. /* need more space? (at least enough for what we
  1212. have+the replacement+the rest of the string (starting
  1213. at the new input position), so we won't have to check space
  1214. when there are no errors in the rest of the string) */
  1215. repptr = PyUnicode_AS_UNICODE(repunicode);
  1216. repsize = PyUnicode_GET_SIZE(repunicode);
  1217. requiredsize = *outpos + repsize + insize-newpos;
  1218. if (requiredsize > outsize) {
  1219. if (requiredsize<2*outsize)
  1220. requiredsize = 2*outsize;
  1221. if (_PyUnicode_Resize(output, requiredsize) < 0)
  1222. goto onError;
  1223. *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
  1224. }
  1225. *endinpos = newpos;
  1226. *inptr = input + newpos;
  1227. Py_UNICODE_COPY(*outptr, repptr, repsize);
  1228. *outptr += repsize;
  1229. *outpos += repsize;
  1230. /* we made it! */
  1231. res = 0;
  1232. onError:
  1233. Py_XDECREF(restuple);
  1234. return res;
  1235. }
  1236. /* --- UTF-7 Codec -------------------------------------------------------- */
  1237. /* see RFC2152 for details */
  1238. static
  1239. char utf7_special[128] = {
  1240. /* indicate whether a UTF-7 character is special i.e. cannot be directly
  1241. encoded:
  1242. 0 - not special
  1243. 1 - special
  1244. 2 - whitespace (optional)
  1245. 3 - RFC2152 Set O (optional) */
  1246. 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 2, 1, 1,
  1247. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1248. 2, 3, 3, 3, 3, 3, 3, 0, 0, 0, 3, 1, 0, 0, 0, 1,
  1249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 0,
  1250. 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 3, 3, 3,
  1252. 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 1, 1,
  1254. };
  1255. /* Note: The comparison (c) <= 0 is a trick to work-around gcc
  1256. warnings about the comparison always being false; since
  1257. utf7_special[0] is 1, we can safely make that one comparison
  1258. true */
  1259. #define SPECIAL(c, encodeO, encodeWS) \
  1260. ((c) > 127 || (c) <= 0 || utf7_special[(c)] == 1 || \
  1261. (encodeWS && (utf7_special[(c)] == 2)) || \
  1262. (encodeO && (utf7_special[(c)] == 3)))
  1263. #define B64(n) \
  1264. ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
  1265. #define B64CHAR(c) \
  1266. (isalnum(c) || (c) == '+' || (c) == '/')
  1267. #define UB64(c) \
  1268. ((c) == '+' ? 62 : (c) == '/' ? 63 : (c) >= 'a' ? \
  1269. (c) - 71 : (c) >= 'A' ? (c) - 65 : (c) + 4 )
  1270. #define ENCODE(out, ch, bits) \
  1271. while (bits >= 6) { \
  1272. *out++ = B64(ch >> (bits-6)); \
  1273. bits -= 6; \
  1274. }
  1275. #define DECODE(out, ch, bits, surrogate) \
  1276. while (bits >= 16) { \
  1277. Py_UNICODE outCh = (Py_UNICODE) ((ch >> (bits-16)) & 0xffff); \
  1278. bits -= 16; \
  1279. if (surrogate) { \
  1280. /* We have already generated an error for the high surrogate \
  1281. so let's not bother seeing if the low surrogate is correct or not */ \
  1282. surrogate = 0; \
  1283. } else if (0xDC00 <= outCh && outCh <= 0xDFFF) { \
  1284. /* This is a surrogate pair. Unfortunately we can't represent \
  1285. it in a 16-bit character */ \
  1286. surrogate = 1; \
  1287. errmsg = "code pairs are not supported"; \
  1288. goto utf7Error; \
  1289. } else { \
  1290. *out++ = outCh; \
  1291. } \
  1292. }
  1293. PyObject *PyUnicode_DecodeUTF7(const char *s,
  1294. Py_ssize_t size,
  1295. const char *errors)
  1296. {
  1297. return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
  1298. }
  1299. PyObject *PyUnicode_DecodeUTF7Stateful(const char *s,
  1300. Py_ssize_t size,
  1301. const char *errors,
  1302. Py_ssize_t *consumed)
  1303. {
  1304. const char *starts = s;
  1305. Py_ssize_t startinpos;
  1306. Py_ssize_t endinpos;
  1307. Py_ssize_t outpos;
  1308. const char *e;
  1309. PyUnicodeObject *unicode;
  1310. Py_UNICODE *p;
  1311. const char *errmsg = "";
  1312. int inShift = 0;
  1313. unsigned int bitsleft = 0;
  1314. unsigned long charsleft = 0;
  1315. int surrogate = 0;
  1316. PyObject *errorHandler = NULL;
  1317. PyObject *exc = NULL;
  1318. unicode = _PyUnicode_New(size);
  1319. if (!unicode)
  1320. return NULL;
  1321. if (size == 0) {
  1322. if (consumed)
  1323. *consumed = 0;
  1324. return (PyObject *)unicode;
  1325. }
  1326. p = unicode->str;
  1327. e = s + size;
  1328. while (s < e) {
  1329. Py_UNICODE ch;
  1330. restart:
  1331. ch = (unsigned char) *s;
  1332. if (inShift) {
  1333. if ((ch == '-') || !B64CHAR(ch)) {
  1334. inShift = 0;
  1335. s++;
  1336. /* p, charsleft, bitsleft, surrogate = */ DECODE(p, charsleft, bitsleft, surrogate);
  1337. if (bitsleft >= 6) {
  1338. /* The shift sequence has a partial character in it. If
  1339. bitsleft < 6 then we could just classify it as padding
  1340. but that is not the case here */
  1341. errmsg = "partial character in shift sequence";
  1342. goto utf7Error;
  1343. }
  1344. /* According to RFC2152 the remaining bits should be zero. We
  1345. choose to signal an error/insert a replacement character
  1346. here so indicate the potential of a misencoded character. */
  1347. /* On x86, a << b == a << (b%32) so make sure that bitsleft != 0 */
  1348. if (bitsleft && charsleft << (sizeof(charsleft) * 8 - bitsleft)) {
  1349. errmsg = "non-zero padding bits in shift sequence";
  1350. goto utf7Error;
  1351. }
  1352. if (ch == '-') {
  1353. if ((s < e) && (*(s) == '-')) {
  1354. *p++ = '-';
  1355. inShift = 1;
  1356. }
  1357. } else if (SPECIAL(ch,0,0)) {
  1358. errmsg = "unexpected special character";
  1359. goto utf7Error;
  1360. } else {
  1361. *p++ = ch;
  1362. }
  1363. } else {
  1364. charsleft = (charsleft << 6) | UB64(ch);
  1365. bitsleft += 6;
  1366. s++;
  1367. /* p, charsleft, bitsleft, surrogate = */ DECODE(p, charsleft, bitsleft, surrogate);
  1368. }
  1369. }
  1370. else if ( ch == '+' ) {
  1371. startinpos = s-starts;
  1372. s++;
  1373. if (s < e && *s == '-') {
  1374. s++;
  1375. *p++ = '+';
  1376. } else
  1377. {
  1378. inShift = 1;
  1379. bitsleft = 0;
  1380. }
  1381. }
  1382. else if (SPECIAL(ch,0,0)) {
  1383. startinpos = s-starts;
  1384. errmsg = "unexpected special character";
  1385. s++;
  1386. goto utf7Error;
  1387. }
  1388. else {
  1389. *p++ = ch;
  1390. s++;
  1391. }
  1392. continue;
  1393. utf7Error:
  1394. outpos = p-PyUnicode_AS_UNICODE(unicode);
  1395. endinpos = s-starts;
  1396. if (unicode_decode_call_errorhandler(
  1397. errors, &errorHandler,
  1398. "utf7", errmsg,
  1399. starts, size, &startinpos, &endinpos, &exc, &s,
  1400. &unicode, &outpos, &p))
  1401. goto onError;
  1402. }
  1403. if (inShift && !consumed) {
  1404. outpos = p-PyUnicode_AS_UNICODE(unicode);
  1405. endinpos = size;
  1406. if (unicode_decode_call_errorhandler(
  1407. errors, &errorHandler,
  1408. "utf7", "unterminated shift sequence",
  1409. starts, size, &startinpos, &endinpos, &exc, &s,
  1410. &unicode, &outpos, &p))
  1411. goto onError;
  1412. if (s < e)
  1413. goto restart;
  1414. }
  1415. if (consumed) {
  1416. if(inShift)
  1417. *consumed = startinpos;
  1418. else
  1419. *consumed = s-starts;
  1420. }
  1421. if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
  1422. goto onError;
  1423. Py_XDECREF(errorHandler);
  1424. Py_XDECREF(exc);
  1425. return (PyObject *)unicode;
  1426. onError:
  1427. Py_XDECREF(errorHandler);
  1428. Py_XDECREF(exc);
  1429. Py_DECREF(unicode);
  1430. return NULL;
  1431. }
  1432. PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s,
  1433. Py_ssize_t size,
  1434. int encodeSetO,
  1435. int encodeWhiteSpace,
  1436. const char *errors)
  1437. {
  1438. PyObject *v;
  1439. /* It might be possible to tighten this worst case */
  1440. Py_ssize_t cbAllocated = 5 * size;
  1441. int inShift = 0;
  1442. Py_ssize_t i = 0;
  1443. unsigned int bitsleft = 0;
  1444. unsigned long charsleft = 0;
  1445. char * out;
  1446. char * start;
  1447. if (cbAllocated / 5 != size)
  1448. return PyErr_NoMemory();
  1449. if (size == 0)
  1450. return PyString_FromStringAndSize(NULL, 0);
  1451. v = PyString_FromStringAndSize(NULL, cbAllocated);
  1452. if (v == NULL)
  1453. return NULL;
  1454. start = out = PyString_AS_STRING(v);
  1455. for (;i < size; ++i) {
  1456. Py_UNICODE ch = s[i];
  1457. if (!inShift) {
  1458. if (ch == '+') {
  1459. *out++ = '+';
  1460. *out++ = '-';
  1461. } else if (SPECIAL(ch, encodeSetO, encodeWhiteSpace)) {
  1462. charsleft = ch;
  1463. bitsleft = 16;
  1464. *out++ = '+';
  1465. /* out, charsleft, bitsleft = */ ENCODE(out, charsleft, bitsleft);
  1466. inShift = bitsleft > 0;
  1467. } else {
  1468. *out++ = (char) ch;
  1469. }
  1470. } else {
  1471. if (!SPECIAL(ch, encodeSetO, encodeWhiteSpace)) {
  1472. *out++ = B64(charsleft << (6-bitsleft));
  1473. charsleft = 0;
  1474. bitsleft = 0;
  1475. /* Characters not in the BASE64 set implicitly unshift the sequence
  1476. so no '-' is required, except if the character is itself a '-' */
  1477. if (B64CHAR(ch) || ch == '-') {
  1478. *out++ = '-';
  1479. }
  1480. inShift = 0;
  1481. *out++ = (char) ch;
  1482. } else {
  1483. bitsleft += 16;
  1484. charsleft = (charsleft << 16) | ch;
  1485. /* out, charsleft, bitsleft = */ ENCODE(out, charsleft, bitsleft);
  1486. /* If the next character is special then we don't need to terminate
  1487. the shift sequence. If the next character is not a BASE64 character
  1488. or '-' then the shift sequence will be terminated implicitly and we
  1489. don't have to insert a '-'. */
  1490. if (bitsleft == 0) {
  1491. if (i + 1 < size) {
  1492. Py_UNICODE ch2 = s[i+1];
  1493. if (SPECIAL(ch2, encodeSetO, encodeWhiteSpace)) {
  1494. } else if (B64CHAR(ch2) || ch2 == '-') {
  1495. *out++ = '-';
  1496. inShift = 0;
  1497. } else {
  1498. inShift = 0;
  1499. }
  1500. }
  1501. else {
  1502. *out++ = '-';
  1503. inShift = 0;
  1504. }
  1505. }
  1506. }
  1507. }
  1508. }
  1509. if (bitsleft) {
  1510. *out++= B64(charsleft << (6-bitsleft) );
  1511. *out++ = '-';
  1512. }
  1513. _PyString_Resize(&v, out - start);
  1514. return v;
  1515. }
  1516. #undef SPECIAL
  1517. #undef B64
  1518. #undef B64CHAR
  1519. #undef UB64
  1520. #undef ENCODE
  1521. #undef DECODE
  1522. /* --- UTF-8 Codec -------------------------------------------------------- */
  1523. static
  1524. char utf8_code_length[256] = {
  1525. /* Map UTF-8 encoded prefix byte to sequence length. zero means
  1526. illegal prefix. see RFC 2279 for details */
  1527. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1528. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1529. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1530. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1531. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1532. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1533. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1534. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1539. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  1540. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  1541. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  1542. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0
  1543. };
  1544. PyObject *PyUnicode_DecodeUTF8(const char *s,
  1545. Py_ssize_t size,
  1546. const char *errors)
  1547. {
  1548. return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
  1549. }
  1550. PyObject *PyUnicode_DecodeUTF8Stateful(const char *s,
  1551. Py_ssize_t size,
  1552. const char *errors,
  1553. Py_ssize_t *consumed)
  1554. {
  1555. const char *starts = s;
  1556. int n;
  1557. Py_ssize_t startinpos;
  1558. Py_ssize_t endinpos;
  1559. Py_ssize_t outpos;
  1560. const char *e;
  1561. PyUnicodeObject *unicode;
  1562. Py_UNICODE *p;
  1563. const char *errmsg = "";
  1564. PyObject *errorHandler = NULL;
  1565. PyObject *exc = NULL;
  1566. /* Note: size will always be longer than the resulting Unicode
  1567. character count */
  1568. unicode = _PyUnicode_New(size);
  1569. if (!unicode)
  1570. return NULL;
  1571. if (size == 0) {
  1572. if (consumed)
  1573. *consumed = 0;
  1574. return (PyObject *)unicode;
  1575. }
  1576. /* Unpack UTF-8 encoded data */
  1577. p = unicode->str;
  1578. e = s + size;
  1579. while (s < e) {
  1580. Py_UCS4 ch = (unsigned char)*s;
  1581. if (ch < 0x80) {
  1582. *p++ = (Py_UNICODE)ch;
  1583. s++;
  1584. continue;
  1585. }
  1586. n = utf8_code_length[ch];
  1587. if (s + n > e) {
  1588. if (consumed)
  1589. break;
  1590. else {
  1591. errmsg = "unexpected end of data";
  1592. startinpos = s-starts;
  1593. endinpos = size;
  1594. goto utf8Error;
  1595. }
  1596. }
  1597. switch (n) {
  1598. case 0:
  1599. errmsg = "unexpected code byte";
  1600. startinpos = s-starts;
  1601. endinpos = startinpos+1;
  1602. goto utf8Error;
  1603. case 1:
  1604. errmsg = "internal error";
  1605. startinpos = s-starts;
  1606. endinpos = startinpos+1;
  1607. goto utf8Error;
  1608. case 2:
  1609. if ((s[1] & 0xc0) != 0x80) {
  1610. errmsg = "invalid data";
  1611. startinpos = s-starts;
  1612. endinpos = startinpos+2;
  1613. goto utf8Error;
  1614. }
  1615. ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
  1616. if (ch < 0x80) {
  1617. startinpos = s-starts;
  1618. endinpos = startinpos+2;
  1619. errmsg = "illegal encoding";
  1620. goto utf8Error;
  1621. }
  1622. else
  1623. *p++ = (Py_UNICODE)ch;
  1624. break;
  1625. case 3:
  1626. if ((s[1] & 0xc0) != 0x80 ||
  1627. (s[2] & 0xc0) != 0x80) {
  1628. errmsg = "invalid data";
  1629. startinpos = s-starts;
  1630. endinpos = startinpos+3;
  1631. goto utf8Error;
  1632. }
  1633. ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
  1634. if (ch < 0x0800) {
  1635. /* Note: UTF-8 encodings of surrogates are considered
  1636. legal UTF-8 sequences;
  1637. XXX For wide builds (UCS-4) we should probably try
  1638. to recombine the surrogates into a single code
  1639. unit.
  1640. */
  1641. errmsg = "illegal encoding";
  1642. startinpos = s-starts;
  1643. endinpos = startinpos+3;
  1644. goto utf8Error;
  1645. }
  1646. else
  1647. *p++ = (Py_UNICODE)ch;
  1648. break;
  1649. case 4:
  1650. if ((s[1] & 0xc0) != 0x80 ||
  1651. (s[2] & 0xc0) != 0x80 ||
  1652. (s[3] & 0xc0) != 0x80) {
  1653. errmsg = "invalid data";
  1654. startinpos = s-starts;
  1655. endinpos = startinpos+4;
  1656. goto utf8Error;
  1657. }
  1658. ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
  1659. ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
  1660. /* validate and convert to UTF-16 */
  1661. if ((ch < 0x10000) /* minimum value allowed for 4
  1662. byte encoding */
  1663. || (ch > 0x10ffff)) /* maximum value allowed for
  1664. UTF-16 */
  1665. {
  1666. errmsg = "illegal encoding";
  1667. startinpos = s-starts;
  1668. endinpos = startinpos+4;
  1669. goto utf8Error;
  1670. }
  1671. #ifdef Py_UNICODE_WIDE
  1672. *p++ = (Py_UNICODE)ch;
  1673. #else
  1674. /* compute and append the two surrogates: */
  1675. /* translate from 10000..10FFFF to 0..FFFF */
  1676. ch -= 0x10000;
  1677. /* high surrogate = top 10 bits added to D800 */
  1678. *p++ = (Py_UNICODE)(0xD800 + (ch >> 10));
  1679. /* low surrogate = bottom 10 bits added to DC00 */
  1680. *p++ = (Py_UNICODE)(0xDC00 + (ch & 0x03FF));
  1681. #endif
  1682. break;
  1683. default:
  1684. /* Other sizes are only needed for UCS-4 */
  1685. errmsg = "unsupported Unicode code range";
  1686. startinpos = s-starts;
  1687. endinpos = startinpos+n;
  1688. goto utf8Error;
  1689. }
  1690. s += n;
  1691. continue;
  1692. utf8Error:
  1693. outpos = p-PyUnicode_AS_UNICODE(unicode);
  1694. if (unicode_decode_call_errorhandler(
  1695. errors, &errorHandler,
  1696. "utf8", errmsg,
  1697. starts, size, &startinpos, &endinpos, &exc, &s,
  1698. &unicode, &outpos, &p))
  1699. goto onError;
  1700. }
  1701. if (consumed)
  1702. *consumed = s-starts;
  1703. /* Adjust length */
  1704. if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
  1705. goto onError;
  1706. Py_XDECREF(errorHandler);
  1707. Py_XDECREF(exc);
  1708. return (PyObject *)unicode;
  1709. onError:
  1710. Py_XDECREF(errorHandler);
  1711. Py_XDECREF(exc);
  1712. Py_DECREF(unicode);
  1713. return NULL;
  1714. }
  1715. /* Allocation strategy: if the string is short, convert into a stack buffer
  1716. and allocate exactly as much space needed at the end. Else allocate the
  1717. maximum possible needed (4 result bytes per Unicode character), and return
  1718. the excess memory at the end.
  1719. */
  1720. PyObject *
  1721. PyUnicode_EncodeUTF8(const Py_UNICODE *s,
  1722. Py_ssize_t size,
  1723. const char *errors)
  1724. {
  1725. #define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
  1726. Py_ssize_t i; /* index into s of next input byte */
  1727. PyObject *v; /* result string object */
  1728. char *p; /* next free byte in output buffer */
  1729. Py_ssize_t nallocated; /* number of result bytes allocated */
  1730. Py_ssize_t nneeded; /* number of result bytes needed */
  1731. char stackbuf[MAX_SHORT_UNICHARS * 4];
  1732. assert(s != NULL);
  1733. assert(size >= 0);
  1734. if (size <= MAX_SHORT_UNICHARS) {
  1735. /* Write into the stack buffer; nallocated can't overflow.
  1736. * At the end, we'll allocate exactly as much heap space as it
  1737. * turns out we need.
  1738. */
  1739. nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
  1740. v = NULL; /* will allocate after we're done */
  1741. p = stackbuf;
  1742. }
  1743. else {
  1744. /* Overallocate on the heap, and give the excess back at the end. */
  1745. nallocated = size * 4;
  1746. if (nallocated / 4 != size) /* overflow! */
  1747. return PyErr_NoMemory();
  1748. v = PyString_FromStringAndSize(NULL, nallocated);
  1749. if (v == NULL)
  1750. return NULL;
  1751. p = PyString_AS_STRING(v);
  1752. }
  1753. for (i = 0; i < size;) {
  1754. Py_UCS4 ch = s[i++];
  1755. if (ch < 0x80)
  1756. /* Encode ASCII */
  1757. *p++ = (char) ch;
  1758. else if (ch < 0x0800) {
  1759. /* Encode Latin-1 */
  1760. *p++ = (char)(0xc0 | (ch >> 6));
  1761. *p++ = (char)(0x80 | (ch & 0x3f));
  1762. }
  1763. else {
  1764. /* Encode UCS2 Unicode ordinals */
  1765. if (ch < 0x10000) {
  1766. /* Special case: check for high surrogate */
  1767. if (0xD800 <= ch && ch <= 0xDBFF && i != size) {
  1768. Py_UCS4 ch2 = s[i];
  1769. /* Check for low surrogate and combine the two to
  1770. form a UCS4 value */
  1771. if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
  1772. ch = ((ch - 0xD800) << 10 | (ch2 - 0xDC00)) + 0x10000;
  1773. i++;
  1774. goto encodeUCS4;
  1775. }
  1776. /* Fall through: handles isolated high surrogates */
  1777. }
  1778. *p++ = (char)(0xe0 | (ch >> 12));
  1779. *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
  1780. *p++ = (char)(0x80 | (ch & 0x3f));
  1781. continue;
  1782. }
  1783. encodeUCS4:
  1784. /* Encode UCS4 Unicode ordinals */
  1785. *p++ = (char)(0xf0 | (ch >> 18));
  1786. *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
  1787. *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
  1788. *p++ = (char)(0x80 | (ch & 0x3f));
  1789. }
  1790. }
  1791. if (v == NULL) {
  1792. /* This was stack allocated. */
  1793. nneeded = p - stackbuf;
  1794. assert(nneeded <= nallocated);
  1795. v = PyString_FromStringAndSize(stackbuf, nneeded);
  1796. }
  1797. else {
  1798. /* Cut back to size actually needed. */
  1799. nneeded = p - PyString_AS_STRING(v);
  1800. assert(nneeded <= nallocated);
  1801. _PyString_Resize(&v, nneeded);
  1802. }
  1803. return v;
  1804. #undef MAX_SHORT_UNICHARS
  1805. }
  1806. PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
  1807. {
  1808. if (!PyUnicode_Check(unicode)) {
  1809. PyErr_BadArgument();
  1810. return NULL;
  1811. }
  1812. return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
  1813. PyUnicode_GET_SIZE(unicode),
  1814. NULL);
  1815. }
  1816. /* --- UTF-32 Codec ------------------------------------------------------- */
  1817. PyObject *
  1818. PyUnicode_DecodeUTF32(const char *s,
  1819. Py_ssize_t size,
  1820. const char *errors,
  1821. int *byteorder)
  1822. {
  1823. return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
  1824. }
  1825. PyObject *
  1826. PyUnicode_DecodeUTF32Stateful(const char *s,
  1827. Py_ssize_t size,
  1828. const char *errors,
  1829. int *byteorder,
  1830. Py_ssize_t *consumed)
  1831. {
  1832. const char *starts = s;
  1833. Py_ssize_t startinpos;
  1834. Py_ssize_t endinpos;
  1835. Py_ssize_t outpos;
  1836. PyUnicodeObject *unicode;
  1837. Py_UNICODE *p;
  1838. #ifndef Py_UNICODE_WIDE
  1839. int i, pairs;
  1840. #else
  1841. const int pairs = 0;
  1842. #endif
  1843. const unsigned char *q, *e;
  1844. int bo = 0; /* assume native ordering by default */
  1845. const char *errmsg = "";
  1846. /* Offsets from q for retrieving bytes in the right order. */
  1847. #ifdef BYTEORDER_IS_LITTLE_ENDIAN
  1848. int iorder[] = {0, 1, 2, 3};
  1849. #else
  1850. int iorder[] = {3, 2, 1, 0};
  1851. #endif
  1852. PyObject *errorHandler = NULL;
  1853. PyObject *exc = NULL;
  1854. /* On narrow builds we split characters outside the BMP into two
  1855. codepoints => count how much extra space we need. */
  1856. #ifndef Py_UNICODE_WIDE
  1857. for (i = pairs = 0; i < size/4; i++)
  1858. if (((Py_UCS4 *)s)[i] >= 0x10000)
  1859. pairs++;
  1860. #endif
  1861. /* This might be one to much, because of a BOM */
  1862. unicode = _PyUnicode_New((size+3)/4+pairs);
  1863. if (!unicode)
  1864. return NULL;
  1865. if (size == 0)
  1866. return (PyObject *)unicode;
  1867. /* Unpack UTF-32 encoded data */
  1868. p = unicode->str;
  1869. q = (unsigned char *)s;
  1870. e = q + size;
  1871. if (byteorder)
  1872. bo = *byteorder;
  1873. /* Check for BOM marks (U+FEFF) in the input and adjust current
  1874. byte order setting accordingly. In native mode, the leading BOM
  1875. mark is skipped, in all other modes, it is copied to the output
  1876. stream as-is (giving a ZWNBSP character). */
  1877. if (bo == 0) {
  1878. if (size >= 4) {
  1879. const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
  1880. (q[iorder[1]] << 8) | q[iorder[0]];
  1881. #ifdef BYTEORDER_IS_LITTLE_ENDIAN
  1882. if (bom == 0x0000FEFF) {
  1883. q += 4;
  1884. bo = -1;
  1885. }
  1886. else if (bom == 0xFFFE0000) {
  1887. q += 4;
  1888. bo = 1;
  1889. }
  1890. #else
  1891. if (bom == 0x0000FEFF) {
  1892. q += 4;
  1893. bo = 1;
  1894. }
  1895. else if (bom == 0xFFFE0000) {
  1896. q += 4;
  1897. bo = -1;
  1898. }
  1899. #endif
  1900. }
  1901. }
  1902. if (bo == -1) {
  1903. /* force LE */
  1904. iorder[0] = 0;
  1905. iorder[1] = 1;
  1906. iorder[2] = 2;
  1907. iorder[3] = 3;
  1908. }
  1909. else if (bo == 1) {
  1910. /* force BE */
  1911. iorder[0] = 3;
  1912. iorder[1] = 2;
  1913. iorder[2] = 1;
  1914. iorder[3] = 0;
  1915. }
  1916. while (q < e) {
  1917. Py_UCS4 ch;
  1918. /* remaining bytes at the end? (size should be divisible by 4) */
  1919. if (e-q<4) {
  1920. if (consumed)
  1921. break;
  1922. errmsg = "truncated data";
  1923. startinpos = ((const char *)q)-starts;
  1924. endinpos = ((const char *)e)-starts;
  1925. goto utf32Error;
  1926. /* The remaining input chars are ignored if the callback
  1927. chooses to skip the input */
  1928. }
  1929. ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
  1930. (q[iorder[1]] << 8) | q[iorder[0]];
  1931. if (ch >= 0x110000)
  1932. {
  1933. errmsg = "codepoint not in range(0x110000)";
  1934. startinpos = ((const char *)q)-starts;
  1935. endinpos = startinpos+4;
  1936. goto utf32Error;
  1937. }
  1938. #ifndef Py_UNICODE_WIDE
  1939. if (ch >= 0x10000)
  1940. {
  1941. *p++ = 0xD800 | ((ch-0x10000) >> 10);
  1942. *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
  1943. }
  1944. else
  1945. #endif
  1946. *p++ = ch;
  1947. q += 4;
  1948. continue;
  1949. utf32Error:
  1950. outpos = p-PyUnicode_AS_UNICODE(unicode);
  1951. if (unicode_decode_call_errorhandler(
  1952. errors, &errorHandler,
  1953. "utf32", errmsg,
  1954. starts, size, &startinpos, &endinpos, &exc, (const char **)&q,
  1955. &unicode, &outpos, &p))
  1956. goto onError;
  1957. }
  1958. if (byteorder)
  1959. *byteorder = bo;
  1960. if (consumed)
  1961. *consumed = (const char *)q-starts;
  1962. /* Adjust length */
  1963. if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
  1964. goto onError;
  1965. Py_XDECREF(errorHandler);
  1966. Py_XDECREF(exc);
  1967. return (PyObject *)unicode;
  1968. onError:
  1969. Py_DECREF(unicode);
  1970. Py_XDECREF(errorHandler);
  1971. Py_XDECREF(exc);
  1972. return NULL;
  1973. }
  1974. PyObject *
  1975. PyUnicode_EncodeUTF32(const Py_UNICODE *s,
  1976. Py_ssize_t size,
  1977. const char *errors,
  1978. int byteorder)
  1979. {
  1980. PyObject *v;
  1981. unsigned char *p;
  1982. Py_ssize_t nsize, bytesize;
  1983. #ifndef Py_UNICODE_WIDE
  1984. Py_ssize_t i, pairs;
  1985. #else
  1986. const int pairs = 0;
  1987. #endif
  1988. /* Offsets from p for storing byte pairs in the right order. */
  1989. #ifdef BYTEORDER_IS_LITTLE_ENDIAN
  1990. int iorder[] = {0, 1, 2, 3};
  1991. #else
  1992. int iorder[] = {3, 2, 1, 0};
  1993. #endif
  1994. #define STORECHAR(CH) \
  1995. do { \
  1996. p[iorder[3]] = ((CH) >> 24) & 0xff; \
  1997. p[iorder[2]] = ((CH) >> 16) & 0xff; \
  1998. p[iorder[1]] = ((CH) >> 8) & 0xff; \
  1999. p[iorder[0]] = (CH) & 0xff; \
  2000. p += 4; \
  2001. } while(0)
  2002. /* In narrow builds we can output surrogate pairs as one codepoint,
  2003. so we need less space. */
  2004. #ifndef Py_UNICODE_WIDE
  2005. for (i = pairs = 0; i < size-1; i++)
  2006. if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
  2007. 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
  2008. pairs++;
  2009. #endif
  2010. nsize = (size - pairs + (byteorder == 0));
  2011. bytesize = nsize * 4;
  2012. if (bytesize / 4 != nsize)
  2013. return PyErr_NoMemory();
  2014. v = PyString_FromStringAndSize(NULL, bytesize);
  2015. if (v == NULL)
  2016. return NULL;
  2017. p = (unsigned char *)PyString_AS_STRING(v);
  2018. if (byteorder == 0)
  2019. STORECHAR(0xFEFF);
  2020. if (size == 0)
  2021. return v;
  2022. if (byteorder == -1) {
  2023. /* force LE */
  2024. iorder[0] = 0;
  2025. iorder[1] = 1;
  2026. iorder[2] = 2;
  2027. iorder[3] = 3;
  2028. }
  2029. else if (byteorder == 1) {
  2030. /* force BE */
  2031. iorder[0] = 3;
  2032. iorder[1] = 2;
  2033. iorder[2] = 1;
  2034. iorder[3] = 0;
  2035. }
  2036. while (size-- > 0) {
  2037. Py_UCS4 ch = *s++;
  2038. #ifndef Py_UNICODE_WIDE
  2039. if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
  2040. Py_UCS4 ch2 = *s;
  2041. if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
  2042. ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
  2043. s++;
  2044. size--;
  2045. }
  2046. }
  2047. #endif
  2048. STORECHAR(ch);
  2049. }
  2050. return v;
  2051. #undef STORECHAR
  2052. }
  2053. PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
  2054. {
  2055. if (!PyUnicode_Check(unicode)) {
  2056. PyErr_BadArgument();
  2057. return NULL;
  2058. }
  2059. return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
  2060. PyUnicode_GET_SIZE(unicode),
  2061. NULL,
  2062. 0);
  2063. }
  2064. /* --- UTF-16 Codec ------------------------------------------------------- */
  2065. PyObject *
  2066. PyUnicode_DecodeUTF16(const char *s,
  2067. Py_ssize_t size,
  2068. const char *errors,
  2069. int *byteorder)
  2070. {
  2071. return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
  2072. }
  2073. PyObject *
  2074. PyUnicode_DecodeUTF16Stateful(const char *s,
  2075. Py_ssize_t size,
  2076. const char *errors,
  2077. int *byteorder,
  2078. Py_ssize_t *consumed)
  2079. {
  2080. const char *starts = s;
  2081. Py_ssize_t startinpos;
  2082. Py_ssize_t endinpos;
  2083. Py_ssize_t outpos;
  2084. PyUnicodeObject *unicode;
  2085. Py_UNICODE *p;
  2086. const unsigned char *q, *e;
  2087. int bo = 0; /* assume native ordering by default */
  2088. const char *errmsg = "";
  2089. /* Offsets from q for retrieving byte pairs in the right order. */
  2090. #ifdef BYTEORDER_IS_LITTLE_ENDIAN
  2091. int ihi = 1, ilo = 0;
  2092. #else
  2093. int ihi = 0, ilo = 1;
  2094. #endif
  2095. PyObject *errorHandler = NULL;
  2096. PyObject *exc = NULL;
  2097. /* Note: size will always be longer than the resulting Unicode
  2098. character count */
  2099. unicode = _PyUnicode_New(size);
  2100. if (!unicode)
  2101. return NULL;
  2102. if (size == 0)
  2103. return (PyObject *)unicode;
  2104. /* Unpack UTF-16 encoded data */
  2105. p = unicode->str;
  2106. q = (unsigned char *)s;
  2107. e = q + size;
  2108. if (byteorder)
  2109. bo = *byteorder;
  2110. /* Check for BOM marks (U+FEFF) in the input and adjust current
  2111. byte order setting accordingly. In native mode, the leading BOM
  2112. mark is skipped, in all other modes, it is copied to the output
  2113. stream as-is (giving a ZWNBSP character). */
  2114. if (bo == 0) {
  2115. if (size >= 2) {
  2116. const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
  2117. #ifdef BYTEORDER_IS_LITTLE_ENDIAN
  2118. if (bom == 0xFEFF) {
  2119. q += 2;
  2120. bo = -1;
  2121. }
  2122. else if (bom == 0xFFFE) {
  2123. q += 2;
  2124. bo = 1;
  2125. }
  2126. #else
  2127. if (bom == 0xFEFF) {
  2128. q += 2;
  2129. bo = 1;
  2130. }
  2131. else if (bom == 0xFFFE) {
  2132. q += 2;
  2133. bo = -1;
  2134. }
  2135. #endif
  2136. }
  2137. }
  2138. if (bo == -1) {
  2139. /* force LE */
  2140. ihi = 1;
  2141. ilo = 0;
  2142. }
  2143. else if (bo == 1) {
  2144. /* force BE */
  2145. ihi = 0;
  2146. ilo = 1;
  2147. }
  2148. while (q < e) {
  2149. Py_UNICODE ch;
  2150. /* remaining bytes at the end? (size should be even) */
  2151. if (e-q<2) {
  2152. if (consumed)
  2153. break;
  2154. errmsg = "truncated data";
  2155. startinpos = ((const char *)q)-starts;
  2156. endinpos = ((const char *)e)-starts;
  2157. goto utf16Error;
  2158. /* The remaining input chars are ignored if the callback
  2159. chooses to skip the input */
  2160. }
  2161. ch = (q[ihi] << 8) | q[ilo];
  2162. q += 2;
  2163. if (ch < 0xD800 || ch > 0xDFFF) {
  2164. *p++ = ch;
  2165. continue;
  2166. }
  2167. /* UTF-16 code pair: */
  2168. if (q >= e) {
  2169. errmsg = "unexpected end of data";
  2170. startinpos = (((const char *)q)-2)-starts;
  2171. endinpos = ((const char *)e)-starts;
  2172. goto utf16Error;
  2173. }
  2174. if (0xD800 <= ch && ch <= 0xDBFF) {
  2175. Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
  2176. q += 2;
  2177. if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
  2178. #ifndef Py_UNICODE_WIDE
  2179. *p++ = ch;
  2180. *p++ = ch2;
  2181. #else
  2182. *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
  2183. #endif
  2184. continue;
  2185. }
  2186. else {
  2187. errmsg = "illegal UTF-16 surrogate";
  2188. startinpos = (((const char *)q)-4)-starts;
  2189. endinpos = startinpos+2;
  2190. goto utf16Error;
  2191. }
  2192. }
  2193. errmsg = "illegal encoding";
  2194. startinpos = (((const char *)q)-2)-starts;
  2195. endinpos = startinpos+2;
  2196. /* Fall through to report the error */
  2197. utf16Error:
  2198. outpos = p-PyUnicode_AS_UNICODE(unicode);
  2199. if (unicode_decode_call_errorhandler(
  2200. errors, &errorHandler,
  2201. "utf16", errmsg,
  2202. starts, size, &startinpos, &endinpos, &exc, (const char **)&q,
  2203. &unicode, &outpos, &p))
  2204. goto onError;
  2205. }
  2206. if (byteorder)
  2207. *byteorder = bo;
  2208. if (consumed)
  2209. *consumed = (const char *)q-starts;
  2210. /* Adjust length */
  2211. if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
  2212. goto onError;
  2213. Py_XDECREF(errorHandler);
  2214. Py_XDECREF(exc);
  2215. return (PyObject *)unicode;
  2216. onError:
  2217. Py_DECREF(unicode);
  2218. Py_XDECREF(errorHandler);
  2219. Py_XDECREF(exc);
  2220. return NULL;
  2221. }
  2222. PyObject *
  2223. PyUnicode_EncodeUTF16(const Py_UNICODE *s,
  2224. Py_ssize_t size,
  2225. const char *errors,
  2226. int byteorder)
  2227. {
  2228. PyObject *v;
  2229. unsigned char *p;
  2230. Py_ssize_t nsize, bytesize;
  2231. #ifdef Py_UNICODE_WIDE
  2232. Py_ssize_t i, pairs;
  2233. #else
  2234. const int pairs = 0;
  2235. #endif
  2236. /* Offsets from p for storing byte pairs in the right order. */
  2237. #ifdef BYTEORDER_IS_LITTLE_ENDIAN
  2238. int ihi = 1, ilo = 0;
  2239. #else
  2240. int ihi = 0, ilo = 1;
  2241. #endif
  2242. #define STORECHAR(CH) \
  2243. do { \
  2244. p[ihi] = ((CH) >> 8) & 0xff; \
  2245. p[ilo] = (CH) & 0xff; \
  2246. p += 2; \
  2247. } while(0)
  2248. #ifdef Py_UNICODE_WIDE
  2249. for (i = pairs = 0; i < size; i++)
  2250. if (s[i] >= 0x10000)
  2251. pairs++;
  2252. #endif
  2253. /* 2 * (size + pairs + (byteorder == 0)) */
  2254. if (size > PY_SSIZE_T_MAX ||
  2255. size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
  2256. return PyErr_NoMemory();
  2257. nsize = size + pairs + (byteorder == 0);
  2258. bytesize = nsize * 2;
  2259. if (bytesize / 2 != nsize)
  2260. return PyErr_NoMemory();
  2261. v = PyString_FromStringAndSize(NULL, bytesize);
  2262. if (v == NULL)
  2263. return NULL;
  2264. p = (unsigned char *)PyString_AS_STRING(v);
  2265. if (byteorder == 0)
  2266. STORECHAR(0xFEFF);
  2267. if (size == 0)
  2268. return v;
  2269. if (byteorder == -1) {
  2270. /* force LE */
  2271. ihi = 1;
  2272. ilo = 0;
  2273. }
  2274. else if (byteorder == 1) {
  2275. /* force BE */
  2276. ihi = 0;
  2277. ilo = 1;
  2278. }
  2279. while (size-- > 0) {
  2280. Py_UNICODE ch = *s++;
  2281. Py_UNICODE ch2 = 0;
  2282. #ifdef Py_UNICODE_WIDE
  2283. if (ch >= 0x10000) {
  2284. ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
  2285. ch = 0xD800 | ((ch-0x10000) >> 10);
  2286. }
  2287. #endif
  2288. STORECHAR(ch);
  2289. if (ch2)
  2290. STORECHAR(ch2);
  2291. }
  2292. return v;
  2293. #undef STORECHAR
  2294. }
  2295. PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
  2296. {
  2297. if (!PyUnicode_Check(unicode)) {
  2298. PyErr_BadArgument();
  2299. return NULL;
  2300. }
  2301. return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
  2302. PyUnicode_GET_SIZE(unicode),
  2303. NULL,
  2304. 0);
  2305. }
  2306. /* --- Unicode Escape Codec ----------------------------------------------- */
  2307. static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
  2308. PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
  2309. Py_ssize_t size,
  2310. const char *errors)
  2311. {
  2312. const char *starts = s;
  2313. Py_ssize_t startinpos;
  2314. Py_ssize_t endinpos;
  2315. Py_ssize_t outpos;
  2316. int i;
  2317. PyUnicodeObject *v;
  2318. Py_UNICODE *p;
  2319. const char *end;
  2320. char* message;
  2321. Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
  2322. PyObject *errorHandler = NULL;
  2323. PyObject *exc = NULL;
  2324. /* Escaped strings will always be longer than the resulting
  2325. Unicode string, so we start with size here and then reduce the
  2326. length after conversion to the true value.
  2327. (but if the error callback returns a long replacement string
  2328. we'll have to allocate more space) */
  2329. v = _PyUnicode_New(size);
  2330. if (v == NULL)
  2331. goto onError;
  2332. if (size == 0)
  2333. return (PyObject *)v;
  2334. p = PyUnicode_AS_UNICODE(v);
  2335. end = s + size;
  2336. while (s < end) {
  2337. unsigned char c;
  2338. Py_UNICODE x;
  2339. int digits;
  2340. /* Non-escape characters are interpreted as Unicode ordinals */
  2341. if (*s != '\\') {
  2342. *p++ = (unsigned char) *s++;
  2343. continue;
  2344. }
  2345. startinpos = s-starts;
  2346. /* \ - Escapes */
  2347. s++;
  2348. c = *s++;
  2349. if (s > end)
  2350. c = '\0'; /* Invalid after \ */
  2351. switch (c) {
  2352. /* \x escapes */
  2353. case '\n': break;
  2354. case '\\': *p++ = '\\'; break;
  2355. case '\'': *p++ = '\''; break;
  2356. case '\"': *p++ = '\"'; break;
  2357. case 'b': *p++ = '\b'; break;
  2358. case 'f': *p++ = '\014'; break; /* FF */
  2359. case 't': *p++ = '\t'; break;
  2360. case 'n': *p++ = '\n'; break;
  2361. case 'r': *p++ = '\r'; break;
  2362. case 'v': *p++ = '\013'; break; /* VT */
  2363. case 'a': *p++ = '\007'; break; /* BEL, not classic C */
  2364. /* \OOO (octal) escapes */
  2365. case '0': case '1': case '2': case '3':
  2366. case '4': case '5': case '6': case '7':
  2367. x = s[-1] - '0';
  2368. if (s < end && '0' <= *s && *s <= '7') {
  2369. x = (x<<3) + *s++ - '0';
  2370. if (s < end && '0' <= *s && *s <= '7')
  2371. x = (x<<3) + *s++ - '0';
  2372. }
  2373. *p++ = x;
  2374. break;
  2375. /* hex escapes */
  2376. /* \xXX */
  2377. case 'x':
  2378. digits = 2;
  2379. message = "truncated \\xXX escape";
  2380. goto hexescape;
  2381. /* \uXXXX */
  2382. case 'u':
  2383. digits = 4;
  2384. message = "truncated \\uXXXX escape";
  2385. goto hexescape;
  2386. /* \UXXXXXXXX */
  2387. case 'U':
  2388. digits = 8;
  2389. message = "truncated \\UXXXXXXXX escape";
  2390. hexescape:
  2391. chr = 0;
  2392. outpos = p-PyUnicode_AS_UNICODE(v);
  2393. if (s+digits>end) {
  2394. endinpos = size;
  2395. if (unicode_decode_call_errorhandler(
  2396. errors, &errorHandler,
  2397. "unicodeescape", "end of string in escape sequence",
  2398. starts, size, &startinpos, &endinpos, &exc, &s,
  2399. &v, &outpos, &p))
  2400. goto onError;
  2401. goto nextByte;
  2402. }
  2403. for (i = 0; i < digits; ++i) {
  2404. c = (unsigned char) s[i];
  2405. if (!isxdigit(c)) {
  2406. endinpos = (s+i+1)-starts;
  2407. if (unicode_decode_call_errorhandler(
  2408. errors, &errorHandler,
  2409. "unicodeescape", message,
  2410. starts, size, &startinpos, &endinpos, &exc, &s,
  2411. &v, &outpos, &p))
  2412. goto onError;
  2413. goto nextByte;
  2414. }
  2415. chr = (chr<<4) & ~0xF;
  2416. if (c >= '0' && c <= '9')
  2417. chr += c - '0';
  2418. else if (c >= 'a' && c <= 'f')
  2419. chr += 10 + c - 'a';
  2420. else
  2421. chr += 10 + c - 'A';
  2422. }
  2423. s += i;
  2424. if (chr == 0xffffffff && PyErr_Occurred())
  2425. /* _decoding_error will have already written into the
  2426. target buffer. */
  2427. break;
  2428. store:
  2429. /* when we get here, chr is a 32-bit unicode character */
  2430. if (chr <= 0xffff)
  2431. /* UCS-2 character */
  2432. *p++ = (Py_UNICODE) chr;
  2433. else if (chr <= 0x10ffff) {
  2434. /* UCS-4 character. Either store directly, or as
  2435. surrogate pair. */
  2436. #ifdef Py_UNICODE_WIDE
  2437. *p++ = chr;
  2438. #else
  2439. chr -= 0x10000L;
  2440. *p++ = 0xD800 + (Py_UNICODE) (chr >> 10);
  2441. *p++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
  2442. #endif
  2443. } else {
  2444. endinpos = s-starts;
  2445. outpos = p-PyUnicode_AS_UNICODE(v);
  2446. if (unicode_decode_call_errorhandler(
  2447. errors, &errorHandler,
  2448. "unicodeescape", "illegal Unicode character",
  2449. starts, size, &startinpos, &endinpos, &exc, &s,
  2450. &v, &outpos, &p))
  2451. goto onError;
  2452. }
  2453. break;
  2454. /* \N{name} */
  2455. case 'N':
  2456. message = "malformed \\N character escape";
  2457. if (ucnhash_CAPI == NULL) {
  2458. /* load the unicode data module */
  2459. PyObject *m, *api;
  2460. m = PyImport_ImportModuleNoBlock("unicodedata");
  2461. if (m == NULL)
  2462. goto ucnhashError;
  2463. api = PyObject_GetAttrString(m, "ucnhash_CAPI");
  2464. Py_DECREF(m);
  2465. if (api == NULL)
  2466. goto ucnhashError;
  2467. ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCObject_AsVoidPtr(api);
  2468. Py_DECREF(api);
  2469. if (ucnhash_CAPI == NULL)
  2470. goto ucnhashError;
  2471. }
  2472. if (*s == '{') {
  2473. const char *start = s+1;
  2474. /* look for the closing brace */
  2475. while (*s != '}' && s < end)
  2476. s++;
  2477. if (s > start && s < end && *s == '}') {
  2478. /* found a name. look it up in the unicode database */
  2479. message = "unknown Unicode character name";
  2480. s++;
  2481. if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1), &chr))
  2482. goto store;
  2483. }
  2484. }
  2485. endinpos = s-starts;
  2486. outpos = p-PyUnicode_AS_UNICODE(v);
  2487. if (unicode_decode_call_errorhandler(
  2488. errors, &errorHandler,
  2489. "unicodeescape", message,
  2490. starts, size, &startinpos, &endinpos, &exc, &s,
  2491. &v, &outpos, &p))
  2492. goto onError;
  2493. break;
  2494. default:
  2495. if (s > end) {
  2496. message = "\\ at end of string";
  2497. s--;
  2498. endinpos = s-starts;
  2499. outpos = p-PyUnicode_AS_UNICODE(v);
  2500. if (unicode_decode_call_errorhandler(
  2501. errors, &errorHandler,
  2502. "unicodeescape", message,
  2503. starts, size, &startinpos, &endinpos, &exc, &s,
  2504. &v, &outpos, &p))
  2505. goto onError;
  2506. }
  2507. else {
  2508. *p++ = '\\';
  2509. *p++ = (unsigned char)s[-1];
  2510. }
  2511. break;
  2512. }
  2513. nextByte:
  2514. ;
  2515. }
  2516. if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
  2517. goto onError;
  2518. Py_XDECREF(errorHandler);
  2519. Py_XDECREF(exc);
  2520. return (PyObject *)v;
  2521. ucnhashError:
  2522. PyErr_SetString(
  2523. PyExc_UnicodeError,
  2524. "\\N escapes not supported (can't load unicodedata module)"
  2525. );
  2526. Py_XDECREF(v);
  2527. Py_XDECREF(errorHandler);
  2528. Py_XDECREF(exc);
  2529. return NULL;
  2530. onError:
  2531. Py_XDECREF(v);
  2532. Py_XDECREF(errorHandler);
  2533. Py_XDECREF(exc);
  2534. return NULL;
  2535. }
  2536. /* Return a Unicode-Escape string version of the Unicode object.
  2537. If quotes is true, the string is enclosed in u"" or u'' quotes as
  2538. appropriate.
  2539. */
  2540. Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s,
  2541. Py_ssize_t size,
  2542. Py_UNICODE ch)
  2543. {
  2544. /* like wcschr, but doesn't stop at NULL characters */
  2545. while (size-- > 0) {
  2546. if (*s == ch)
  2547. return s;
  2548. s++;
  2549. }
  2550. return NULL;
  2551. }
  2552. static
  2553. PyObject *unicodeescape_string(const Py_UNICODE *s,
  2554. Py_ssize_t size,
  2555. int quotes)
  2556. {
  2557. PyObject *repr;
  2558. char *p;
  2559. static const char *hexdigit = "0123456789abcdef";
  2560. #ifdef Py_UNICODE_WIDE
  2561. const Py_ssize_t expandsize = 10;
  2562. #else
  2563. const Py_ssize_t expandsize = 6;
  2564. #endif
  2565. /* XXX(nnorwitz): rather than over-allocating, it would be
  2566. better to choose a different scheme. Perhaps scan the
  2567. first N-chars of the string and allocate based on that size.
  2568. */
  2569. /* Initial allocation is based on the longest-possible unichr
  2570. escape.
  2571. In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
  2572. unichr, so in this case it's the longest unichr escape. In
  2573. narrow (UTF-16) builds this is five chars per source unichr
  2574. since there are two unichrs in the surrogate pair, so in narrow
  2575. (UTF-16) builds it's not the longest unichr escape.
  2576. In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
  2577. so in the narrow (UTF-16) build case it's the longest unichr
  2578. escape.
  2579. */
  2580. if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
  2581. return PyErr_NoMemory();
  2582. repr = PyString_FromStringAndSize(NULL,
  2583. 2
  2584. + expandsize*size
  2585. + 1);
  2586. if (repr == NULL)
  2587. return NULL;
  2588. p = PyString_AS_STRING(repr);
  2589. if (quotes) {
  2590. *p++ = 'u';
  2591. *p++ = (findchar(s, size, '\'') &&
  2592. !findchar(s, size, '"')) ? '"' : '\'';
  2593. }
  2594. while (size-- > 0) {
  2595. Py_UNICODE ch = *s++;
  2596. /* Escape quotes and backslashes */
  2597. if ((quotes &&
  2598. ch == (Py_UNICODE) PyString_AS_STRING(repr)[1]) || ch == '\\') {
  2599. *p++ = '\\';
  2600. *p++ = (char) ch;
  2601. continue;
  2602. }
  2603. #ifdef Py_UNICODE_WIDE
  2604. /* Map 21-bit characters to '\U00xxxxxx' */
  2605. else if (ch >= 0x10000) {
  2606. *p++ = '\\';
  2607. *p++ = 'U';
  2608. *p++ = hexdigit[(ch >> 28) & 0x0000000F];
  2609. *p++ = hexdigit[(ch >> 24) & 0x0000000F];
  2610. *p++ = hexdigit[(ch >> 20) & 0x0000000F];
  2611. *p++ = hexdigit[(ch >> 16) & 0x0000000F];
  2612. *p++ = hexdigit[(ch >> 12) & 0x0000000F];
  2613. *p++ = hexdigit[(ch >> 8) & 0x0000000F];
  2614. *p++ = hexdigit[(ch >> 4) & 0x0000000F];
  2615. *p++ = hexdigit[ch & 0x0000000F];
  2616. continue;
  2617. }
  2618. #else
  2619. /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
  2620. else if (ch >= 0xD800 && ch < 0xDC00) {
  2621. Py_UNICODE ch2;
  2622. Py_UCS4 ucs;
  2623. ch2 = *s++;
  2624. size--;
  2625. if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
  2626. ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
  2627. *p++ = '\\';
  2628. *p++ = 'U';
  2629. *p++ = hexdigit[(ucs >> 28) & 0x0000000F];
  2630. *p++ = hexdigit[(ucs >> 24) & 0x0000000F];
  2631. *p++ = hexdigit[(ucs >> 20) & 0x0000000F];
  2632. *p++ = hexdigit[(ucs >> 16) & 0x0000000F];
  2633. *p++ = hexdigit[(ucs >> 12) & 0x0000000F];
  2634. *p++ = hexdigit[(ucs >> 8) & 0x0000000F];
  2635. *p++ = hexdigit[(ucs >> 4) & 0x0000000F];
  2636. *p++ = hexdigit[ucs & 0x0000000F];
  2637. continue;
  2638. }
  2639. /* Fall through: isolated surrogates are copied as-is */
  2640. s--;
  2641. size++;
  2642. }
  2643. #endif
  2644. /* Map 16-bit characters to '\uxxxx' */
  2645. if (ch >= 256) {
  2646. *p++ = '\\';
  2647. *p++ = 'u';
  2648. *p++ = hexdigit[(ch >> 12) & 0x000F];
  2649. *p++ = hexdigit[(ch >> 8) & 0x000F];
  2650. *p++ = hexdigit[(ch >> 4) & 0x000F];
  2651. *p++ = hexdigit[ch & 0x000F];
  2652. }
  2653. /* Map special whitespace to '\t', \n', '\r' */
  2654. else if (ch == '\t') {
  2655. *p++ = '\\';
  2656. *p++ = 't';
  2657. }
  2658. else if (ch == '\n') {
  2659. *p++ = '\\';
  2660. *p++ = 'n';
  2661. }
  2662. else if (ch == '\r') {
  2663. *p++ = '\\';
  2664. *p++ = 'r';
  2665. }
  2666. /* Map non-printable US ASCII to '\xhh' */
  2667. else if (ch < ' ' || ch >= 0x7F) {
  2668. *p++ = '\\';
  2669. *p++ = 'x';
  2670. *p++ = hexdigit[(ch >> 4) & 0x000F];
  2671. *p++ = hexdigit[ch & 0x000F];
  2672. }
  2673. /* Copy everything else as-is */
  2674. else
  2675. *p++ = (char) ch;
  2676. }
  2677. if (quotes)
  2678. *p++ = PyString_AS_STRING(repr)[1];
  2679. *p = '\0';
  2680. _PyString_Resize(&repr, p - PyString_AS_STRING(repr));
  2681. return repr;
  2682. }
  2683. PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
  2684. Py_ssize_t size)
  2685. {
  2686. return unicodeescape_string(s, size, 0);
  2687. }
  2688. PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
  2689. {
  2690. if (!PyUnicode_Check(unicode)) {
  2691. PyErr_BadArgument();
  2692. return NULL;
  2693. }
  2694. return PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
  2695. PyUnicode_GET_SIZE(unicode));
  2696. }
  2697. /* --- Raw Unicode Escape Codec ------------------------------------------- */
  2698. PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
  2699. Py_ssize_t size,
  2700. const char *errors)
  2701. {
  2702. const char *starts = s;
  2703. Py_ssize_t startinpos;
  2704. Py_ssize_t endinpos;
  2705. Py_ssize_t outpos;
  2706. PyUnicodeObject *v;
  2707. Py_UNICODE *p;
  2708. const char *end;
  2709. const char *bs;
  2710. PyObject *errorHandler = NULL;
  2711. PyObject *exc = NULL;
  2712. /* Escaped strings will always be longer than the resulting
  2713. Unicode string, so we start with size here and then reduce the
  2714. length after conversion to the true value. (But decoding error
  2715. handler might have to resize the string) */
  2716. v = _PyUnicode_New(size);
  2717. if (v == NULL)
  2718. goto onError;
  2719. if (size == 0)
  2720. return (PyObject *)v;
  2721. p = PyUnicode_AS_UNICODE(v);
  2722. end = s + size;
  2723. while (s < end) {
  2724. unsigned char c;
  2725. Py_UCS4 x;
  2726. int i;
  2727. int count;
  2728. /* Non-escape characters are interpreted as Unicode ordinals */
  2729. if (*s != '\\') {
  2730. *p++ = (unsigned char)*s++;
  2731. continue;
  2732. }
  2733. startinpos = s-starts;
  2734. /* \u-escapes are only interpreted iff the number of leading
  2735. backslashes if odd */
  2736. bs = s;
  2737. for (;s < end;) {
  2738. if (*s != '\\')
  2739. break;
  2740. *p++ = (unsigned char)*s++;
  2741. }
  2742. if (((s - bs) & 1) == 0 ||
  2743. s >= end ||
  2744. (*s != 'u' && *s != 'U')) {
  2745. continue;
  2746. }
  2747. p--;
  2748. count = *s=='u' ? 4 : 8;
  2749. s++;
  2750. /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
  2751. outpos = p-PyUnicode_AS_UNICODE(v);
  2752. for (x = 0, i = 0; i < count; ++i, ++s) {
  2753. c = (unsigned char)*s;
  2754. if (!isxdigit(c)) {
  2755. endinpos = s-starts;
  2756. if (unicode_decode_call_errorhandler(
  2757. errors, &errorHandler,
  2758. "rawunicodeescape", "truncated \\uXXXX",
  2759. starts, size, &startinpos, &endinpos, &exc, &s,
  2760. &v, &outpos, &p))
  2761. goto onError;
  2762. goto nextByte;
  2763. }
  2764. x = (x<<4) & ~0xF;
  2765. if (c >= '0' && c <= '9')
  2766. x += c - '0';
  2767. else if (c >= 'a' && c <= 'f')
  2768. x += 10 + c - 'a';
  2769. else
  2770. x += 10 + c - 'A';
  2771. }
  2772. if (x <= 0xffff)
  2773. /* UCS-2 character */
  2774. *p++ = (Py_UNICODE) x;
  2775. else if (x <= 0x10ffff) {
  2776. /* UCS-4 character. Either store directly, or as
  2777. surrogate pair. */
  2778. #ifdef Py_UNICODE_WIDE
  2779. *p++ = (Py_UNICODE) x;
  2780. #else
  2781. x -= 0x10000L;
  2782. *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
  2783. *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
  2784. #endif
  2785. } else {
  2786. endinpos = s-starts;
  2787. outpos = p-PyUnicode_AS_UNICODE(v);
  2788. if (unicode_decode_call_errorhandler(
  2789. errors, &errorHandler,
  2790. "rawunicodeescape", "\\Uxxxxxxxx out of range",
  2791. starts, size, &startinpos, &endinpos, &exc, &s,
  2792. &v, &outpos, &p))
  2793. goto onError;
  2794. }
  2795. nextByte:
  2796. ;
  2797. }
  2798. if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
  2799. goto onError;
  2800. Py_XDECREF(errorHandler);
  2801. Py_XDECREF(exc);
  2802. return (PyObject *)v;
  2803. onError:
  2804. Py_XDECREF(v);
  2805. Py_XDECREF(errorHandler);
  2806. Py_XDECREF(exc);
  2807. return NULL;
  2808. }
  2809. PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
  2810. Py_ssize_t size)
  2811. {
  2812. PyObject *repr;
  2813. char *p;
  2814. char *q;
  2815. static const char *hexdigit = "0123456789abcdef";
  2816. #ifdef Py_UNICODE_WIDE
  2817. const Py_ssize_t expandsize = 10;
  2818. #else
  2819. const Py_ssize_t expandsize = 6;
  2820. #endif
  2821. if (size > PY_SSIZE_T_MAX / expandsize)
  2822. return PyErr_NoMemory();
  2823. repr = PyString_FromStringAndSize(NULL, expandsize * size);
  2824. if (repr == NULL)
  2825. return NULL;
  2826. if (size == 0)
  2827. return repr;
  2828. p = q = PyString_AS_STRING(repr);
  2829. while (size-- > 0) {
  2830. Py_UNICODE ch = *s++;
  2831. #ifdef Py_UNICODE_WIDE
  2832. /* Map 32-bit characters to '\Uxxxxxxxx' */
  2833. if (ch >= 0x10000) {
  2834. *p++ = '\\';
  2835. *p++ = 'U';
  2836. *p++ = hexdigit[(ch >> 28) & 0xf];
  2837. *p++ = hexdigit[(ch >> 24) & 0xf];
  2838. *p++ = hexdigit[(ch >> 20) & 0xf];
  2839. *p++ = hexdigit[(ch >> 16) & 0xf];
  2840. *p++ = hexdigit[(ch >> 12) & 0xf];
  2841. *p++ = hexdigit[(ch >> 8) & 0xf];
  2842. *p++ = hexdigit[(ch >> 4) & 0xf];
  2843. *p++ = hexdigit[ch & 15];
  2844. }
  2845. else
  2846. #else
  2847. /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
  2848. if (ch >= 0xD800 && ch < 0xDC00) {
  2849. Py_UNICODE ch2;
  2850. Py_UCS4 ucs;
  2851. ch2 = *s++;
  2852. size--;
  2853. if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
  2854. ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
  2855. *p++ = '\\';
  2856. *p++ = 'U';
  2857. *p++ = hexdigit[(ucs >> 28) & 0xf];
  2858. *p++ = hexdigit[(ucs >> 24) & 0xf];
  2859. *p++ = hexdigit[(ucs >> 20) & 0xf];
  2860. *p++ = hexdigit[(ucs >> 16) & 0xf];
  2861. *p++ = hexdigit[(ucs >> 12) & 0xf];
  2862. *p++ = hexdigit[(ucs >> 8) & 0xf];
  2863. *p++ = hexdigit[(ucs >> 4) & 0xf];
  2864. *p++ = hexdigit[ucs & 0xf];
  2865. continue;
  2866. }
  2867. /* Fall through: isolated surrogates are copied as-is */
  2868. s--;
  2869. size++;
  2870. }
  2871. #endif
  2872. /* Map 16-bit characters to '\uxxxx' */
  2873. if (ch >= 256) {
  2874. *p++ = '\\';
  2875. *p++ = 'u';
  2876. *p++ = hexdigit[(ch >> 12) & 0xf];
  2877. *p++ = hexdigit[(ch >> 8) & 0xf];
  2878. *p++ = hexdigit[(ch >> 4) & 0xf];
  2879. *p++ = hexdigit[ch & 15];
  2880. }
  2881. /* Copy everything else as-is */
  2882. else
  2883. *p++ = (char) ch;
  2884. }
  2885. *p = '\0';
  2886. _PyString_Resize(&repr, p - q);
  2887. return repr;
  2888. }
  2889. PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
  2890. {
  2891. if (!PyUnicode_Check(unicode)) {
  2892. PyErr_BadArgument();
  2893. return NULL;
  2894. }
  2895. return PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
  2896. PyUnicode_GET_SIZE(unicode));
  2897. }
  2898. /* --- Unicode Internal Codec ------------------------------------------- */
  2899. PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s,
  2900. Py_ssize_t size,
  2901. const char *errors)
  2902. {
  2903. const char *starts = s;
  2904. Py_ssize_t startinpos;
  2905. Py_ssize_t endinpos;
  2906. Py_ssize_t outpos;
  2907. PyUnicodeObject *v;
  2908. Py_UNICODE *p;
  2909. const char *end;
  2910. const char *reason;
  2911. PyObject *errorHandler = NULL;
  2912. PyObject *exc = NULL;
  2913. #ifdef Py_UNICODE_WIDE
  2914. Py_UNICODE unimax = PyUnicode_GetMax();
  2915. #endif
  2916. /* XXX overflow detection missing */
  2917. v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
  2918. if (v == NULL)
  2919. goto onError;
  2920. if (PyUnicode_GetSize((PyObject *)v) == 0)
  2921. return (PyObject *)v;
  2922. p = PyUnicode_AS_UNICODE(v);
  2923. end = s + size;
  2924. while (s < end) {
  2925. memcpy(p, s, sizeof(Py_UNICODE));
  2926. /* We have to sanity check the raw data, otherwise doom looms for
  2927. some malformed UCS-4 data. */
  2928. if (
  2929. #ifdef Py_UNICODE_WIDE
  2930. *p > unimax || *p < 0 ||
  2931. #endif
  2932. end-s < Py_UNICODE_SIZE
  2933. )
  2934. {
  2935. startinpos = s - starts;
  2936. if (end-s < Py_UNICODE_SIZE) {
  2937. endinpos = end-starts;
  2938. reason = "truncated input";
  2939. }
  2940. else {
  2941. endinpos = s - starts + Py_UNICODE_SIZE;
  2942. reason = "illegal code point (> 0x10FFFF)";
  2943. }
  2944. outpos = p - PyUnicode_AS_UNICODE(v);
  2945. if (unicode_decode_call_errorhandler(
  2946. errors, &errorHandler,
  2947. "unicode_internal", reason,
  2948. starts, size, &startinpos, &endinpos, &exc, &s,
  2949. &v, &outpos, &p)) {
  2950. goto onError;
  2951. }
  2952. }
  2953. else {
  2954. p++;
  2955. s += Py_UNICODE_SIZE;
  2956. }
  2957. }
  2958. if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
  2959. goto onError;
  2960. Py_XDECREF(errorHandler);
  2961. Py_XDECREF(exc);
  2962. return (PyObject *)v;
  2963. onError:
  2964. Py_XDECREF(v);
  2965. Py_XDECREF(errorHandler);
  2966. Py_XDECREF(exc);
  2967. return NULL;
  2968. }
  2969. /* --- Latin-1 Codec ------------------------------------------------------ */
  2970. PyObject *PyUnicode_DecodeLatin1(const char *s,
  2971. Py_ssize_t size,
  2972. const char *errors)
  2973. {
  2974. PyUnicodeObject *v;
  2975. Py_UNICODE *p;
  2976. /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
  2977. if (size == 1) {
  2978. Py_UNICODE r = *(unsigned char*)s;
  2979. return PyUnicode_FromUnicode(&r, 1);
  2980. }
  2981. v = _PyUnicode_New(size);
  2982. if (v == NULL)
  2983. goto onError;
  2984. if (size == 0)
  2985. return (PyObject *)v;
  2986. p = PyUnicode_AS_UNICODE(v);
  2987. while (size-- > 0)
  2988. *p++ = (unsigned char)*s++;
  2989. return (PyObject *)v;
  2990. onError:
  2991. Py_XDECREF(v);
  2992. return NULL;
  2993. }
  2994. /* create or adjust a UnicodeEncodeError */
  2995. static void make_encode_exception(PyObject **exceptionObject,
  2996. const char *encoding,
  2997. const Py_UNICODE *unicode, Py_ssize_t size,
  2998. Py_ssize_t startpos, Py_ssize_t endpos,
  2999. const char *reason)
  3000. {
  3001. if (*exceptionObject == NULL) {
  3002. *exceptionObject = PyUnicodeEncodeError_Create(
  3003. encoding, unicode, size, startpos, endpos, reason);
  3004. }
  3005. else {
  3006. if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
  3007. goto onError;
  3008. if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
  3009. goto onError;
  3010. if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
  3011. goto onError;
  3012. return;
  3013. onError:
  3014. Py_DECREF(*exceptionObject);
  3015. *exceptionObject = NULL;
  3016. }
  3017. }
  3018. /* raises a UnicodeEncodeError */
  3019. static void raise_encode_exception(PyObject **exceptionObject,
  3020. const char *encoding,
  3021. const Py_UNICODE *unicode, Py_ssize_t size,
  3022. Py_ssize_t startpos, Py_ssize_t endpos,
  3023. const char *reason)
  3024. {
  3025. make_encode_exception(exceptionObject,
  3026. encoding, unicode, size, startpos, endpos, reason);
  3027. if (*exceptionObject != NULL)
  3028. PyCodec_StrictErrors(*exceptionObject);
  3029. }
  3030. /* error handling callback helper:
  3031. build arguments, call the callback and check the arguments,
  3032. put the result into newpos and return the replacement string, which
  3033. has to be freed by the caller */
  3034. static PyObject *unicode_encode_call_errorhandler(const char *errors,
  3035. PyObject **errorHandler,
  3036. const char *encoding, const char *reason,
  3037. const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
  3038. Py_ssize_t startpos, Py_ssize_t endpos,
  3039. Py_ssize_t *newpos)
  3040. {
  3041. static char *argparse = "O!n;encoding error handler must return (unicode, int) tuple";
  3042. PyObject *restuple;
  3043. PyObject *resunicode;
  3044. if (*errorHandler == NULL) {
  3045. *errorHandler = PyCodec_LookupError(errors);
  3046. if (*errorHandler == NULL)
  3047. return NULL;
  3048. }
  3049. make_encode_exception(exceptionObject,
  3050. encoding, unicode, size, startpos, endpos, reason);
  3051. if (*exceptionObject == NULL)
  3052. return NULL;
  3053. restuple = PyObject_CallFunctionObjArgs(
  3054. *errorHandler, *exceptionObject, NULL);
  3055. if (restuple == NULL)
  3056. return NULL;
  3057. if (!PyTuple_Check(restuple)) {
  3058. PyErr_SetString(PyExc_TypeError, &argparse[4]);
  3059. Py_DECREF(restuple);
  3060. return NULL;
  3061. }
  3062. if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
  3063. &resunicode, newpos)) {
  3064. Py_DECREF(restuple);
  3065. return NULL;
  3066. }
  3067. if (*newpos<0)
  3068. *newpos = size+*newpos;
  3069. if (*newpos<0 || *newpos>size) {
  3070. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
  3071. Py_DECREF(restuple);
  3072. return NULL;
  3073. }
  3074. Py_INCREF(resunicode);
  3075. Py_DECREF(restuple);
  3076. return resunicode;
  3077. }
  3078. static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
  3079. Py_ssize_t size,
  3080. const char *errors,
  3081. int limit)
  3082. {
  3083. /* output object */
  3084. PyObject *res;
  3085. /* pointers to the beginning and end+1 of input */
  3086. const Py_UNICODE *startp = p;
  3087. const Py_UNICODE *endp = p + size;
  3088. /* pointer to the beginning of the unencodable characters */
  3089. /* const Py_UNICODE *badp = NULL; */
  3090. /* pointer into the output */
  3091. char *str;
  3092. /* current output position */
  3093. Py_ssize_t respos = 0;
  3094. Py_ssize_t ressize;
  3095. const char *encoding = (limit == 256) ? "latin-1" : "ascii";
  3096. const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
  3097. PyObject *errorHandler = NULL;
  3098. PyObject *exc = NULL;
  3099. /* the following variable is used for caching string comparisons
  3100. * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
  3101. int known_errorHandler = -1;
  3102. /* allocate enough for a simple encoding without
  3103. replacements, if we need more, we'll resize */
  3104. res = PyString_FromStringAndSize(NULL, size);
  3105. if (res == NULL)
  3106. goto onError;
  3107. if (size == 0)
  3108. return res;
  3109. str = PyString_AS_STRING(res);
  3110. ressize = size;
  3111. while (p<endp) {
  3112. Py_UNICODE c = *p;
  3113. /* can we encode this? */
  3114. if (c<limit) {
  3115. /* no overflow check, because we know that the space is enough */
  3116. *str++ = (char)c;
  3117. ++p;
  3118. }
  3119. else {
  3120. Py_ssize_t unicodepos = p-startp;
  3121. Py_ssize_t requiredsize;
  3122. PyObject *repunicode;
  3123. Py_ssize_t repsize;
  3124. Py_ssize_t newpos;
  3125. Py_ssize_t respos;
  3126. Py_UNICODE *uni2;
  3127. /* startpos for collecting unencodable chars */
  3128. const Py_UNICODE *collstart = p;
  3129. const Py_UNICODE *collend = p;
  3130. /* find all unecodable characters */
  3131. while ((collend < endp) && ((*collend)>=limit))
  3132. ++collend;
  3133. /* cache callback name lookup (if not done yet, i.e. it's the first error) */
  3134. if (known_errorHandler==-1) {
  3135. if ((errors==NULL) || (!strcmp(errors, "strict")))
  3136. known_errorHandler = 1;
  3137. else if (!strcmp(errors, "replace"))
  3138. known_errorHandler = 2;
  3139. else if (!strcmp(errors, "ignore"))
  3140. known_errorHandler = 3;
  3141. else if (!strcmp(errors, "xmlcharrefreplace"))
  3142. known_errorHandler = 4;
  3143. else
  3144. known_errorHandler = 0;
  3145. }
  3146. switch (known_errorHandler) {
  3147. case 1: /* strict */
  3148. raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
  3149. goto onError;
  3150. case 2: /* replace */
  3151. while (collstart++<collend)
  3152. *str++ = '?'; /* fall through */
  3153. case 3: /* ignore */
  3154. p = collend;
  3155. break;
  3156. case 4: /* xmlcharrefreplace */
  3157. respos = str-PyString_AS_STRING(res);
  3158. /* determine replacement size (temporarily (mis)uses p) */
  3159. for (p = collstart, repsize = 0; p < collend; ++p) {
  3160. if (*p<10)
  3161. repsize += 2+1+1;
  3162. else if (*p<100)
  3163. repsize += 2+2+1;
  3164. else if (*p<1000)
  3165. repsize += 2+3+1;
  3166. else if (*p<10000)
  3167. repsize += 2+4+1;
  3168. #ifndef Py_UNICODE_WIDE
  3169. else
  3170. repsize += 2+5+1;
  3171. #else
  3172. else if (*p<100000)
  3173. repsize += 2+5+1;
  3174. else if (*p<1000000)
  3175. repsize += 2+6+1;
  3176. else
  3177. repsize += 2+7+1;
  3178. #endif
  3179. }
  3180. requiredsize = respos+repsize+(endp-collend);
  3181. if (requiredsize > ressize) {
  3182. if (requiredsize<2*ressize)
  3183. requiredsize = 2*ressize;
  3184. if (_PyString_Resize(&res, requiredsize))
  3185. goto onError;
  3186. str = PyString_AS_STRING(res) + respos;
  3187. ressize = requiredsize;
  3188. }
  3189. /* generate replacement (temporarily (mis)uses p) */
  3190. for (p = collstart; p < collend; ++p) {
  3191. str += sprintf(str, "&#%d;", (int)*p);
  3192. }
  3193. p = collend;
  3194. break;
  3195. default:
  3196. repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
  3197. encoding, reason, startp, size, &exc,
  3198. collstart-startp, collend-startp, &newpos);
  3199. if (repunicode == NULL)
  3200. goto onError;
  3201. /* need more space? (at least enough for what we
  3202. have+the replacement+the rest of the string, so
  3203. we won't have to check space for encodable characters) */
  3204. respos = str-PyString_AS_STRING(res);
  3205. repsize = PyUnicode_GET_SIZE(repunicode);
  3206. requiredsize = respos+repsize+(endp-collend);
  3207. if (requiredsize > ressize) {
  3208. if (requiredsize<2*ressize)
  3209. requiredsize = 2*ressize;
  3210. if (_PyString_Resize(&res, requiredsize)) {
  3211. Py_DECREF(repunicode);
  3212. goto onError;
  3213. }
  3214. str = PyString_AS_STRING(res) + respos;
  3215. ressize = requiredsize;
  3216. }
  3217. /* check if there is anything unencodable in the replacement
  3218. and copy it to the output */
  3219. for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
  3220. c = *uni2;
  3221. if (c >= limit) {
  3222. raise_encode_exception(&exc, encoding, startp, size,
  3223. unicodepos, unicodepos+1, reason);
  3224. Py_DECREF(repunicode);
  3225. goto onError;
  3226. }
  3227. *str = (char)c;
  3228. }
  3229. p = startp + newpos;
  3230. Py_DECREF(repunicode);
  3231. }
  3232. }
  3233. }
  3234. /* Resize if we allocated to much */
  3235. respos = str-PyString_AS_STRING(res);
  3236. if (respos<ressize)
  3237. /* If this falls res will be NULL */
  3238. _PyString_Resize(&res, respos);
  3239. Py_XDECREF(errorHandler);
  3240. Py_XDECREF(exc);
  3241. return res;
  3242. onError:
  3243. Py_XDECREF(res);
  3244. Py_XDECREF(errorHandler);
  3245. Py_XDECREF(exc);
  3246. return NULL;
  3247. }
  3248. PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
  3249. Py_ssize_t size,
  3250. const char *errors)
  3251. {
  3252. return unicode_encode_ucs1(p, size, errors, 256);
  3253. }
  3254. PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
  3255. {
  3256. if (!PyUnicode_Check(unicode)) {
  3257. PyErr_BadArgument();
  3258. return NULL;
  3259. }
  3260. return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
  3261. PyUnicode_GET_SIZE(unicode),
  3262. NULL);
  3263. }
  3264. /* --- 7-bit ASCII Codec -------------------------------------------------- */
  3265. PyObject *PyUnicode_DecodeASCII(const char *s,
  3266. Py_ssize_t size,
  3267. const char *errors)
  3268. {
  3269. const char *starts = s;
  3270. PyUnicodeObject *v;
  3271. Py_UNICODE *p;
  3272. Py_ssize_t startinpos;
  3273. Py_ssize_t endinpos;
  3274. Py_ssize_t outpos;
  3275. const char *e;
  3276. PyObject *errorHandler = NULL;
  3277. PyObject *exc = NULL;
  3278. /* ASCII is equivalent to the first 128 ordinals in Unicode. */
  3279. if (size == 1 && *(unsigned char*)s < 128) {
  3280. Py_UNICODE r = *(unsigned char*)s;
  3281. return PyUnicode_FromUnicode(&r, 1);
  3282. }
  3283. v = _PyUnicode_New(size);
  3284. if (v == NULL)
  3285. goto onError;
  3286. if (size == 0)
  3287. return (PyObject *)v;
  3288. p = PyUnicode_AS_UNICODE(v);
  3289. e = s + size;
  3290. while (s < e) {
  3291. register unsigned char c = (unsigned char)*s;
  3292. if (c < 128) {
  3293. *p++ = c;
  3294. ++s;
  3295. }
  3296. else {
  3297. startinpos = s-starts;
  3298. endinpos = startinpos + 1;
  3299. outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
  3300. if (unicode_decode_call_errorhandler(
  3301. errors, &errorHandler,
  3302. "ascii", "ordinal not in range(128)",
  3303. starts, size, &startinpos, &endinpos, &exc, &s,
  3304. &v, &outpos, &p))
  3305. goto onError;
  3306. }
  3307. }
  3308. if (p - PyUnicode_AS_UNICODE(v) < PyString_GET_SIZE(v))
  3309. if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
  3310. goto onError;
  3311. Py_XDECREF(errorHandler);
  3312. Py_XDECREF(exc);
  3313. return (PyObject *)v;
  3314. onError:
  3315. Py_XDECREF(v);
  3316. Py_XDECREF(errorHandler);
  3317. Py_XDECREF(exc);
  3318. return NULL;
  3319. }
  3320. PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
  3321. Py_ssize_t size,
  3322. const char *errors)
  3323. {
  3324. return unicode_encode_ucs1(p, size, errors, 128);
  3325. }
  3326. PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
  3327. {
  3328. if (!PyUnicode_Check(unicode)) {
  3329. PyErr_BadArgument();
  3330. return NULL;
  3331. }
  3332. return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
  3333. PyUnicode_GET_SIZE(unicode),
  3334. NULL);
  3335. }
  3336. #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
  3337. /* --- MBCS codecs for Windows -------------------------------------------- */
  3338. #if SIZEOF_INT < SIZEOF_SIZE_T
  3339. #define NEED_RETRY
  3340. #endif
  3341. /* XXX This code is limited to "true" double-byte encodings, as
  3342. a) it assumes an incomplete character consists of a single byte, and
  3343. b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
  3344. encodings, see IsDBCSLeadByteEx documentation. */
  3345. static int is_dbcs_lead_byte(const char *s, int offset)
  3346. {
  3347. const char *curr = s + offset;
  3348. if (IsDBCSLeadByte(*curr)) {
  3349. const char *prev = CharPrev(s, curr);
  3350. return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
  3351. }
  3352. return 0;
  3353. }
  3354. /*
  3355. * Decode MBCS string into unicode object. If 'final' is set, converts
  3356. * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
  3357. */
  3358. static int decode_mbcs(PyUnicodeObject **v,
  3359. const char *s, /* MBCS string */
  3360. int size, /* sizeof MBCS string */
  3361. int final)
  3362. {
  3363. Py_UNICODE *p;
  3364. Py_ssize_t n = 0;
  3365. int usize = 0;
  3366. assert(size >= 0);
  3367. /* Skip trailing lead-byte unless 'final' is set */
  3368. if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
  3369. --size;
  3370. /* First get the size of the result */
  3371. if (size > 0) {
  3372. usize = MultiByteToWideChar(CP_ACP, 0, s, size, NULL, 0);
  3373. if (usize == 0) {
  3374. PyErr_SetFromWindowsErrWithFilename(0, NULL);
  3375. return -1;
  3376. }
  3377. }
  3378. if (*v == NULL) {
  3379. /* Create unicode object */
  3380. *v = _PyUnicode_New(usize);
  3381. if (*v == NULL)
  3382. return -1;
  3383. }
  3384. else {
  3385. /* Extend unicode object */
  3386. n = PyUnicode_GET_SIZE(*v);
  3387. if (_PyUnicode_Resize(v, n + usize) < 0)
  3388. return -1;
  3389. }
  3390. /* Do the conversion */
  3391. if (size > 0) {
  3392. p = PyUnicode_AS_UNICODE(*v) + n;
  3393. if (0 == MultiByteToWideChar(CP_ACP, 0, s, size, p, usize)) {
  3394. PyErr_SetFromWindowsErrWithFilename(0, NULL);
  3395. return -1;
  3396. }
  3397. }
  3398. return size;
  3399. }
  3400. PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
  3401. Py_ssize_t size,
  3402. const char *errors,
  3403. Py_ssize_t *consumed)
  3404. {
  3405. PyUnicodeObject *v = NULL;
  3406. int done;
  3407. if (consumed)
  3408. *consumed = 0;
  3409. #ifdef NEED_RETRY
  3410. retry:
  3411. if (size > INT_MAX)
  3412. done = decode_mbcs(&v, s, INT_MAX, 0);
  3413. else
  3414. #endif
  3415. done = decode_mbcs(&v, s, (int)size, !consumed);
  3416. if (done < 0) {
  3417. Py_XDECREF(v);
  3418. return NULL;
  3419. }
  3420. if (consumed)
  3421. *consumed += done;
  3422. #ifdef NEED_RETRY
  3423. if (size > INT_MAX) {
  3424. s += done;
  3425. size -= done;
  3426. goto retry;
  3427. }
  3428. #endif
  3429. return (PyObject *)v;
  3430. }
  3431. PyObject *PyUnicode_DecodeMBCS(const char *s,
  3432. Py_ssize_t size,
  3433. const char *errors)
  3434. {
  3435. return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
  3436. }
  3437. /*
  3438. * Convert unicode into string object (MBCS).
  3439. * Returns 0 if succeed, -1 otherwise.
  3440. */
  3441. static int encode_mbcs(PyObject **repr,
  3442. const Py_UNICODE *p, /* unicode */
  3443. int size) /* size of unicode */
  3444. {
  3445. int mbcssize = 0;
  3446. Py_ssize_t n = 0;
  3447. assert(size >= 0);
  3448. /* First get the size of the result */
  3449. if (size > 0) {
  3450. mbcssize = WideCharToMultiByte(CP_ACP, 0, p, size, NULL, 0, NULL, NULL);
  3451. if (mbcssize == 0) {
  3452. PyErr_SetFromWindowsErrWithFilename(0, NULL);
  3453. return -1;
  3454. }
  3455. }
  3456. if (*repr == NULL) {
  3457. /* Create string object */
  3458. *repr = PyString_FromStringAndSize(NULL, mbcssize);
  3459. if (*repr == NULL)
  3460. return -1;
  3461. }
  3462. else {
  3463. /* Extend string object */
  3464. n = PyString_Size(*repr);
  3465. if (_PyString_Resize(repr, n + mbcssize) < 0)
  3466. return -1;
  3467. }
  3468. /* Do the conversion */
  3469. if (size > 0) {
  3470. char *s = PyString_AS_STRING(*repr) + n;
  3471. if (0 == WideCharToMultiByte(CP_ACP, 0, p, size, s, mbcssize, NULL, NULL)) {
  3472. PyErr_SetFromWindowsErrWithFilename(0, NULL);
  3473. return -1;
  3474. }
  3475. }
  3476. return 0;
  3477. }
  3478. PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
  3479. Py_ssize_t size,
  3480. const char *errors)
  3481. {
  3482. PyObject *repr = NULL;
  3483. int ret;
  3484. #ifdef NEED_RETRY
  3485. retry:
  3486. if (size > INT_MAX)
  3487. ret = encode_mbcs(&repr, p, INT_MAX);
  3488. else
  3489. #endif
  3490. ret = encode_mbcs(&repr, p, (int)size);
  3491. if (ret < 0) {
  3492. Py_XDECREF(repr);
  3493. return NULL;
  3494. }
  3495. #ifdef NEED_RETRY
  3496. if (size > INT_MAX) {
  3497. p += INT_MAX;
  3498. size -= INT_MAX;
  3499. goto retry;
  3500. }
  3501. #endif
  3502. return repr;
  3503. }
  3504. PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
  3505. {
  3506. if (!PyUnicode_Check(unicode)) {
  3507. PyErr_BadArgument();
  3508. return NULL;
  3509. }
  3510. return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
  3511. PyUnicode_GET_SIZE(unicode),
  3512. NULL);
  3513. }
  3514. #undef NEED_RETRY
  3515. #endif /* MS_WINDOWS */
  3516. /* --- Character Mapping Codec -------------------------------------------- */
  3517. PyObject *PyUnicode_DecodeCharmap(const char *s,
  3518. Py_ssize_t size,
  3519. PyObject *mapping,
  3520. const char *errors)
  3521. {
  3522. const char *starts = s;
  3523. Py_ssize_t startinpos;
  3524. Py_ssize_t endinpos;
  3525. Py_ssize_t outpos;
  3526. const char *e;
  3527. PyUnicodeObject *v;
  3528. Py_UNICODE *p;
  3529. Py_ssize_t extrachars = 0;
  3530. PyObject *errorHandler = NULL;
  3531. PyObject *exc = NULL;
  3532. Py_UNICODE *mapstring = NULL;
  3533. Py_ssize_t maplen = 0;
  3534. /* Default to Latin-1 */
  3535. if (mapping == NULL)
  3536. return PyUnicode_DecodeLatin1(s, size, errors);
  3537. v = _PyUnicode_New(size);
  3538. if (v == NULL)
  3539. goto onError;
  3540. if (size == 0)
  3541. return (PyObject *)v;
  3542. p = PyUnicode_AS_UNICODE(v);
  3543. e = s + size;
  3544. if (PyUnicode_CheckExact(mapping)) {
  3545. mapstring = PyUnicode_AS_UNICODE(mapping);
  3546. maplen = PyUnicode_GET_SIZE(mapping);
  3547. while (s < e) {
  3548. unsigned char ch = *s;
  3549. Py_UNICODE x = 0xfffe; /* illegal value */
  3550. if (ch < maplen)
  3551. x = mapstring[ch];
  3552. if (x == 0xfffe) {
  3553. /* undefined mapping */
  3554. outpos = p-PyUnicode_AS_UNICODE(v);
  3555. startinpos = s-starts;
  3556. endinpos = startinpos+1;
  3557. if (unicode_decode_call_errorhandler(
  3558. errors, &errorHandler,
  3559. "charmap", "character maps to <undefined>",
  3560. starts, size, &startinpos, &endinpos, &exc, &s,
  3561. &v, &outpos, &p)) {
  3562. goto onError;
  3563. }
  3564. continue;
  3565. }
  3566. *p++ = x;
  3567. ++s;
  3568. }
  3569. }
  3570. else {
  3571. while (s < e) {
  3572. unsigned char ch = *s;
  3573. PyObject *w, *x;
  3574. /* Get mapping (char ordinal -> integer, Unicode char or None) */
  3575. w = PyInt_FromLong((long)ch);
  3576. if (w == NULL)
  3577. goto onError;
  3578. x = PyObject_GetItem(mapping, w);
  3579. Py_DECREF(w);
  3580. if (x == NULL) {
  3581. if (PyErr_ExceptionMatches(PyExc_LookupError)) {
  3582. /* No mapping found means: mapping is undefined. */
  3583. PyErr_Clear();
  3584. x = Py_None;
  3585. Py_INCREF(x);
  3586. } else
  3587. goto onError;
  3588. }
  3589. /* Apply mapping */
  3590. if (PyInt_Check(x)) {
  3591. long value = PyInt_AS_LONG(x);
  3592. if (value < 0 || value > 65535) {
  3593. PyErr_SetString(PyExc_TypeError,
  3594. "character mapping must be in range(65536)");
  3595. Py_DECREF(x);
  3596. goto onError;
  3597. }
  3598. *p++ = (Py_UNICODE)value;
  3599. }
  3600. else if (x == Py_None) {
  3601. /* undefined mapping */
  3602. outpos = p-PyUnicode_AS_UNICODE(v);
  3603. startinpos = s-starts;
  3604. endinpos = startinpos+1;
  3605. if (unicode_decode_call_errorhandler(
  3606. errors, &errorHandler,
  3607. "charmap", "character maps to <undefined>",
  3608. starts, size, &startinpos, &endinpos, &exc, &s,
  3609. &v, &outpos, &p)) {
  3610. Py_DECREF(x);
  3611. goto onError;
  3612. }
  3613. Py_DECREF(x);
  3614. continue;
  3615. }
  3616. else if (PyUnicode_Check(x)) {
  3617. Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
  3618. if (targetsize == 1)
  3619. /* 1-1 mapping */
  3620. *p++ = *PyUnicode_AS_UNICODE(x);
  3621. else if (targetsize > 1) {
  3622. /* 1-n mapping */
  3623. if (targetsize > extrachars) {
  3624. /* resize first */
  3625. Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
  3626. Py_ssize_t needed = (targetsize - extrachars) + \
  3627. (targetsize << 2);
  3628. extrachars += needed;
  3629. /* XXX overflow detection missing */
  3630. if (_PyUnicode_Resize(&v,
  3631. PyUnicode_GET_SIZE(v) + needed) < 0) {
  3632. Py_DECREF(x);
  3633. goto onError;
  3634. }
  3635. p = PyUnicode_AS_UNICODE(v) + oldpos;
  3636. }
  3637. Py_UNICODE_COPY(p,
  3638. PyUnicode_AS_UNICODE(x),
  3639. targetsize);
  3640. p += targetsize;
  3641. extrachars -= targetsize;
  3642. }
  3643. /* 1-0 mapping: skip the character */
  3644. }
  3645. else {
  3646. /* wrong return value */
  3647. PyErr_SetString(PyExc_TypeError,
  3648. "character mapping must return integer, None or unicode");
  3649. Py_DECREF(x);
  3650. goto onError;
  3651. }
  3652. Py_DECREF(x);
  3653. ++s;
  3654. }
  3655. }
  3656. if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
  3657. if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
  3658. goto onError;
  3659. Py_XDECREF(errorHandler);
  3660. Py_XDECREF(exc);
  3661. return (PyObject *)v;
  3662. onError:
  3663. Py_XDECREF(errorHandler);
  3664. Py_XDECREF(exc);
  3665. Py_XDECREF(v);
  3666. return NULL;
  3667. }
  3668. /* Charmap encoding: the lookup table */
  3669. struct encoding_map{
  3670. PyObject_HEAD
  3671. unsigned char level1[32];
  3672. int count2, count3;
  3673. unsigned char level23[1];
  3674. };
  3675. static PyObject*
  3676. encoding_map_size(PyObject *obj, PyObject* args)
  3677. {
  3678. struct encoding_map *map = (struct encoding_map*)obj;
  3679. return PyInt_FromLong(sizeof(*map) - 1 + 16*map->count2 +
  3680. 128*map->count3);
  3681. }
  3682. static PyMethodDef encoding_map_methods[] = {
  3683. {"size", encoding_map_size, METH_NOARGS,
  3684. PyDoc_STR("Return the size (in bytes) of this object") },
  3685. { 0 }
  3686. };
  3687. static void
  3688. encoding_map_dealloc(PyObject* o)
  3689. {
  3690. PyObject_FREE(o);
  3691. }
  3692. static PyTypeObject EncodingMapType = {
  3693. PyVarObject_HEAD_INIT(NULL, 0)
  3694. "EncodingMap", /*tp_name*/
  3695. sizeof(struct encoding_map), /*tp_basicsize*/
  3696. 0, /*tp_itemsize*/
  3697. /* methods */
  3698. encoding_map_dealloc, /*tp_dealloc*/
  3699. 0, /*tp_print*/
  3700. 0, /*tp_getattr*/
  3701. 0, /*tp_setattr*/
  3702. 0, /*tp_compare*/
  3703. 0, /*tp_repr*/
  3704. 0, /*tp_as_number*/
  3705. 0, /*tp_as_sequence*/
  3706. 0, /*tp_as_mapping*/
  3707. 0, /*tp_hash*/
  3708. 0, /*tp_call*/
  3709. 0, /*tp_str*/
  3710. 0, /*tp_getattro*/
  3711. 0, /*tp_setattro*/
  3712. 0, /*tp_as_buffer*/
  3713. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  3714. 0, /*tp_doc*/
  3715. 0, /*tp_traverse*/
  3716. 0, /*tp_clear*/
  3717. 0, /*tp_richcompare*/
  3718. 0, /*tp_weaklistoffset*/
  3719. 0, /*tp_iter*/
  3720. 0, /*tp_iternext*/
  3721. encoding_map_methods, /*tp_methods*/
  3722. 0, /*tp_members*/
  3723. 0, /*tp_getset*/
  3724. 0, /*tp_base*/
  3725. 0, /*tp_dict*/
  3726. 0, /*tp_descr_get*/
  3727. 0, /*tp_descr_set*/
  3728. 0, /*tp_dictoffset*/
  3729. 0, /*tp_init*/
  3730. 0, /*tp_alloc*/
  3731. 0, /*tp_new*/
  3732. 0, /*tp_free*/
  3733. 0, /*tp_is_gc*/
  3734. };
  3735. PyObject*
  3736. PyUnicode_BuildEncodingMap(PyObject* string)
  3737. {
  3738. Py_UNICODE *decode;
  3739. PyObject *result;
  3740. struct encoding_map *mresult;
  3741. int i;
  3742. int need_dict = 0;
  3743. unsigned char level1[32];
  3744. unsigned char level2[512];
  3745. unsigned char *mlevel1, *mlevel2, *mlevel3;
  3746. int count2 = 0, count3 = 0;
  3747. if (!PyUnicode_Check(string) || PyUnicode_GetSize(string) != 256) {
  3748. PyErr_BadArgument();
  3749. return NULL;
  3750. }
  3751. decode = PyUnicode_AS_UNICODE(string);
  3752. memset(level1, 0xFF, sizeof level1);
  3753. memset(level2, 0xFF, sizeof level2);
  3754. /* If there isn't a one-to-one mapping of NULL to \0,
  3755. or if there are non-BMP characters, we need to use
  3756. a mapping dictionary. */
  3757. if (decode[0] != 0)
  3758. need_dict = 1;
  3759. for (i = 1; i < 256; i++) {
  3760. int l1, l2;
  3761. if (decode[i] == 0
  3762. #ifdef Py_UNICODE_WIDE
  3763. || decode[i] > 0xFFFF
  3764. #endif
  3765. ) {
  3766. need_dict = 1;
  3767. break;
  3768. }
  3769. if (decode[i] == 0xFFFE)
  3770. /* unmapped character */
  3771. continue;
  3772. l1 = decode[i] >> 11;
  3773. l2 = decode[i] >> 7;
  3774. if (level1[l1] == 0xFF)
  3775. level1[l1] = count2++;
  3776. if (level2[l2] == 0xFF)
  3777. level2[l2] = count3++;
  3778. }
  3779. if (count2 >= 0xFF || count3 >= 0xFF)
  3780. need_dict = 1;
  3781. if (need_dict) {
  3782. PyObject *result = PyDict_New();
  3783. PyObject *key, *value;
  3784. if (!result)
  3785. return NULL;
  3786. for (i = 0; i < 256; i++) {
  3787. key = value = NULL;
  3788. key = PyInt_FromLong(decode[i]);
  3789. value = PyInt_FromLong(i);
  3790. if (!key || !value)
  3791. goto failed1;
  3792. if (PyDict_SetItem(result, key, value) == -1)
  3793. goto failed1;
  3794. Py_DECREF(key);
  3795. Py_DECREF(value);
  3796. }
  3797. return result;
  3798. failed1:
  3799. Py_XDECREF(key);
  3800. Py_XDECREF(value);
  3801. Py_DECREF(result);
  3802. return NULL;
  3803. }
  3804. /* Create a three-level trie */
  3805. result = PyObject_MALLOC(sizeof(struct encoding_map) +
  3806. 16*count2 + 128*count3 - 1);
  3807. if (!result)
  3808. return PyErr_NoMemory();
  3809. PyObject_Init(result, &EncodingMapType);
  3810. mresult = (struct encoding_map*)result;
  3811. mresult->count2 = count2;
  3812. mresult->count3 = count3;
  3813. mlevel1 = mresult->level1;
  3814. mlevel2 = mresult->level23;
  3815. mlevel3 = mresult->level23 + 16*count2;
  3816. memcpy(mlevel1, level1, 32);
  3817. memset(mlevel2, 0xFF, 16*count2);
  3818. memset(mlevel3, 0, 128*count3);
  3819. count3 = 0;
  3820. for (i = 1; i < 256; i++) {
  3821. int o1, o2, o3, i2, i3;
  3822. if (decode[i] == 0xFFFE)
  3823. /* unmapped character */
  3824. continue;
  3825. o1 = decode[i]>>11;
  3826. o2 = (decode[i]>>7) & 0xF;
  3827. i2 = 16*mlevel1[o1] + o2;
  3828. if (mlevel2[i2] == 0xFF)
  3829. mlevel2[i2] = count3++;
  3830. o3 = decode[i] & 0x7F;
  3831. i3 = 128*mlevel2[i2] + o3;
  3832. mlevel3[i3] = i;
  3833. }
  3834. return result;
  3835. }
  3836. static int
  3837. encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
  3838. {
  3839. struct encoding_map *map = (struct encoding_map*)mapping;
  3840. int l1 = c>>11;
  3841. int l2 = (c>>7) & 0xF;
  3842. int l3 = c & 0x7F;
  3843. int i;
  3844. #ifdef Py_UNICODE_WIDE
  3845. if (c > 0xFFFF) {
  3846. return -1;
  3847. }
  3848. #endif
  3849. if (c == 0)
  3850. return 0;
  3851. /* level 1*/
  3852. i = map->level1[l1];
  3853. if (i == 0xFF) {
  3854. return -1;
  3855. }
  3856. /* level 2*/
  3857. i = map->level23[16*i+l2];
  3858. if (i == 0xFF) {
  3859. return -1;
  3860. }
  3861. /* level 3 */
  3862. i = map->level23[16*map->count2 + 128*i + l3];
  3863. if (i == 0) {
  3864. return -1;
  3865. }
  3866. return i;
  3867. }
  3868. /* Lookup the character ch in the mapping. If the character
  3869. can't be found, Py_None is returned (or NULL, if another
  3870. error occurred). */
  3871. static PyObject *charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
  3872. {
  3873. PyObject *w = PyInt_FromLong((long)c);
  3874. PyObject *x;
  3875. if (w == NULL)
  3876. return NULL;
  3877. x = PyObject_GetItem(mapping, w);
  3878. Py_DECREF(w);
  3879. if (x == NULL) {
  3880. if (PyErr_ExceptionMatches(PyExc_LookupError)) {
  3881. /* No mapping found means: mapping is undefined. */
  3882. PyErr_Clear();
  3883. x = Py_None;
  3884. Py_INCREF(x);
  3885. return x;
  3886. } else
  3887. return NULL;
  3888. }
  3889. else if (x == Py_None)
  3890. return x;
  3891. else if (PyInt_Check(x)) {
  3892. long value = PyInt_AS_LONG(x);
  3893. if (value < 0 || value > 255) {
  3894. PyErr_SetString(PyExc_TypeError,
  3895. "character mapping must be in range(256)");
  3896. Py_DECREF(x);
  3897. return NULL;
  3898. }
  3899. return x;
  3900. }
  3901. else if (PyString_Check(x))
  3902. return x;
  3903. else {
  3904. /* wrong return value */
  3905. PyErr_SetString(PyExc_TypeError,
  3906. "character mapping must return integer, None or str");
  3907. Py_DECREF(x);
  3908. return NULL;
  3909. }
  3910. }
  3911. static int
  3912. charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
  3913. {
  3914. Py_ssize_t outsize = PyString_GET_SIZE(*outobj);
  3915. /* exponentially overallocate to minimize reallocations */
  3916. if (requiredsize < 2*outsize)
  3917. requiredsize = 2*outsize;
  3918. if (_PyString_Resize(outobj, requiredsize)) {
  3919. return 0;
  3920. }
  3921. return 1;
  3922. }
  3923. typedef enum charmapencode_result {
  3924. enc_SUCCESS, enc_FAILED, enc_EXCEPTION
  3925. }charmapencode_result;
  3926. /* lookup the character, put the result in the output string and adjust
  3927. various state variables. Reallocate the output string if not enough
  3928. space is available. Return a new reference to the object that
  3929. was put in the output buffer, or Py_None, if the mapping was undefined
  3930. (in which case no character was written) or NULL, if a
  3931. reallocation error occurred. The caller must decref the result */
  3932. static
  3933. charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping,
  3934. PyObject **outobj, Py_ssize_t *outpos)
  3935. {
  3936. PyObject *rep;
  3937. char *outstart;
  3938. Py_ssize_t outsize = PyString_GET_SIZE(*outobj);
  3939. if (Py_TYPE(mapping) == &EncodingMapType) {
  3940. int res = encoding_map_lookup(c, mapping);
  3941. Py_ssize_t requiredsize = *outpos+1;
  3942. if (res == -1)
  3943. return enc_FAILED;
  3944. if (outsize<requiredsize)
  3945. if (!charmapencode_resize(outobj, outpos, requiredsize))
  3946. return enc_EXCEPTION;
  3947. outstart = PyString_AS_STRING(*outobj);
  3948. outstart[(*outpos)++] = (char)res;
  3949. return enc_SUCCESS;
  3950. }
  3951. rep = charmapencode_lookup(c, mapping);
  3952. if (rep==NULL)
  3953. return enc_EXCEPTION;
  3954. else if (rep==Py_None) {
  3955. Py_DECREF(rep);
  3956. return enc_FAILED;
  3957. } else {
  3958. if (PyInt_Check(rep)) {
  3959. Py_ssize_t requiredsize = *outpos+1;
  3960. if (outsize<requiredsize)
  3961. if (!charmapencode_resize(outobj, outpos, requiredsize)) {
  3962. Py_DECREF(rep);
  3963. return enc_EXCEPTION;
  3964. }
  3965. outstart = PyString_AS_STRING(*outobj);
  3966. outstart[(*outpos)++] = (char)PyInt_AS_LONG(rep);
  3967. }
  3968. else {
  3969. const char *repchars = PyString_AS_STRING(rep);
  3970. Py_ssize_t repsize = PyString_GET_SIZE(rep);
  3971. Py_ssize_t requiredsize = *outpos+repsize;
  3972. if (outsize<requiredsize)
  3973. if (!charmapencode_resize(outobj, outpos, requiredsize)) {
  3974. Py_DECREF(rep);
  3975. return enc_EXCEPTION;
  3976. }
  3977. outstart = PyString_AS_STRING(*outobj);
  3978. memcpy(outstart + *outpos, repchars, repsize);
  3979. *outpos += repsize;
  3980. }
  3981. }
  3982. Py_DECREF(rep);
  3983. return enc_SUCCESS;
  3984. }
  3985. /* handle an error in PyUnicode_EncodeCharmap
  3986. Return 0 on success, -1 on error */
  3987. static
  3988. int charmap_encoding_error(
  3989. const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
  3990. PyObject **exceptionObject,
  3991. int *known_errorHandler, PyObject **errorHandler, const char *errors,
  3992. PyObject **res, Py_ssize_t *respos)
  3993. {
  3994. PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
  3995. Py_ssize_t repsize;
  3996. Py_ssize_t newpos;
  3997. Py_UNICODE *uni2;
  3998. /* startpos for collecting unencodable chars */
  3999. Py_ssize_t collstartpos = *inpos;
  4000. Py_ssize_t collendpos = *inpos+1;
  4001. Py_ssize_t collpos;
  4002. char *encoding = "charmap";
  4003. char *reason = "character maps to <undefined>";
  4004. charmapencode_result x;
  4005. /* find all unencodable characters */
  4006. while (collendpos < size) {
  4007. PyObject *rep;
  4008. if (Py_TYPE(mapping) == &EncodingMapType) {
  4009. int res = encoding_map_lookup(p[collendpos], mapping);
  4010. if (res != -1)
  4011. break;
  4012. ++collendpos;
  4013. continue;
  4014. }
  4015. rep = charmapencode_lookup(p[collendpos], mapping);
  4016. if (rep==NULL)
  4017. return -1;
  4018. else if (rep!=Py_None) {
  4019. Py_DECREF(rep);
  4020. break;
  4021. }
  4022. Py_DECREF(rep);
  4023. ++collendpos;
  4024. }
  4025. /* cache callback name lookup
  4026. * (if not done yet, i.e. it's the first error) */
  4027. if (*known_errorHandler==-1) {
  4028. if ((errors==NULL) || (!strcmp(errors, "strict")))
  4029. *known_errorHandler = 1;
  4030. else if (!strcmp(errors, "replace"))
  4031. *known_errorHandler = 2;
  4032. else if (!strcmp(errors, "ignore"))
  4033. *known_errorHandler = 3;
  4034. else if (!strcmp(errors, "xmlcharrefreplace"))
  4035. *known_errorHandler = 4;
  4036. else
  4037. *known_errorHandler = 0;
  4038. }
  4039. switch (*known_errorHandler) {
  4040. case 1: /* strict */
  4041. raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
  4042. return -1;
  4043. case 2: /* replace */
  4044. for (collpos = collstartpos; collpos<collendpos; ++collpos) {
  4045. x = charmapencode_output('?', mapping, res, respos);
  4046. if (x==enc_EXCEPTION) {
  4047. return -1;
  4048. }
  4049. else if (x==enc_FAILED) {
  4050. raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
  4051. return -1;
  4052. }
  4053. }
  4054. /* fall through */
  4055. case 3: /* ignore */
  4056. *inpos = collendpos;
  4057. break;
  4058. case 4: /* xmlcharrefreplace */
  4059. /* generate replacement (temporarily (mis)uses p) */
  4060. for (collpos = collstartpos; collpos < collendpos; ++collpos) {
  4061. char buffer[2+29+1+1];
  4062. char *cp;
  4063. sprintf(buffer, "&#%d;", (int)p[collpos]);
  4064. for (cp = buffer; *cp; ++cp) {
  4065. x = charmapencode_output(*cp, mapping, res, respos);
  4066. if (x==enc_EXCEPTION)
  4067. return -1;
  4068. else if (x==enc_FAILED) {
  4069. raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
  4070. return -1;
  4071. }
  4072. }
  4073. }
  4074. *inpos = collendpos;
  4075. break;
  4076. default:
  4077. repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
  4078. encoding, reason, p, size, exceptionObject,
  4079. collstartpos, collendpos, &newpos);
  4080. if (repunicode == NULL)
  4081. return -1;
  4082. /* generate replacement */
  4083. repsize = PyUnicode_GET_SIZE(repunicode);
  4084. for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
  4085. x = charmapencode_output(*uni2, mapping, res, respos);
  4086. if (x==enc_EXCEPTION) {
  4087. return -1;
  4088. }
  4089. else if (x==enc_FAILED) {
  4090. Py_DECREF(repunicode);
  4091. raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
  4092. return -1;
  4093. }
  4094. }
  4095. *inpos = newpos;
  4096. Py_DECREF(repunicode);
  4097. }
  4098. return 0;
  4099. }
  4100. PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
  4101. Py_ssize_t size,
  4102. PyObject *mapping,
  4103. const char *errors)
  4104. {
  4105. /* output object */
  4106. PyObject *res = NULL;
  4107. /* current input position */
  4108. Py_ssize_t inpos = 0;
  4109. /* current output position */
  4110. Py_ssize_t respos = 0;
  4111. PyObject *errorHandler = NULL;
  4112. PyObject *exc = NULL;
  4113. /* the following variable is used for caching string comparisons
  4114. * -1=not initialized, 0=unknown, 1=strict, 2=replace,
  4115. * 3=ignore, 4=xmlcharrefreplace */
  4116. int known_errorHandler = -1;
  4117. /* Default to Latin-1 */
  4118. if (mapping == NULL)
  4119. return PyUnicode_EncodeLatin1(p, size, errors);
  4120. /* allocate enough for a simple encoding without
  4121. replacements, if we need more, we'll resize */
  4122. res = PyString_FromStringAndSize(NULL, size);
  4123. if (res == NULL)
  4124. goto onError;
  4125. if (size == 0)
  4126. return res;
  4127. while (inpos<size) {
  4128. /* try to encode it */
  4129. charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
  4130. if (x==enc_EXCEPTION) /* error */
  4131. goto onError;
  4132. if (x==enc_FAILED) { /* unencodable character */
  4133. if (charmap_encoding_error(p, size, &inpos, mapping,
  4134. &exc,
  4135. &known_errorHandler, &errorHandler, errors,
  4136. &res, &respos)) {
  4137. goto onError;
  4138. }
  4139. }
  4140. else
  4141. /* done with this character => adjust input position */
  4142. ++inpos;
  4143. }
  4144. /* Resize if we allocated to much */
  4145. if (respos<PyString_GET_SIZE(res)) {
  4146. if (_PyString_Resize(&res, respos))
  4147. goto onError;
  4148. }
  4149. Py_XDECREF(exc);
  4150. Py_XDECREF(errorHandler);
  4151. return res;
  4152. onError:
  4153. Py_XDECREF(res);
  4154. Py_XDECREF(exc);
  4155. Py_XDECREF(errorHandler);
  4156. return NULL;
  4157. }
  4158. PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
  4159. PyObject *mapping)
  4160. {
  4161. if (!PyUnicode_Check(unicode) || mapping == NULL) {
  4162. PyErr_BadArgument();
  4163. return NULL;
  4164. }
  4165. return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
  4166. PyUnicode_GET_SIZE(unicode),
  4167. mapping,
  4168. NULL);
  4169. }
  4170. /* create or adjust a UnicodeTranslateError */
  4171. static void make_translate_exception(PyObject **exceptionObject,
  4172. const Py_UNICODE *unicode, Py_ssize_t size,
  4173. Py_ssize_t startpos, Py_ssize_t endpos,
  4174. const char *reason)
  4175. {
  4176. if (*exceptionObject == NULL) {
  4177. *exceptionObject = PyUnicodeTranslateError_Create(
  4178. unicode, size, startpos, endpos, reason);
  4179. }
  4180. else {
  4181. if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
  4182. goto onError;
  4183. if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
  4184. goto onError;
  4185. if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
  4186. goto onError;
  4187. return;
  4188. onError:
  4189. Py_DECREF(*exceptionObject);
  4190. *exceptionObject = NULL;
  4191. }
  4192. }
  4193. /* raises a UnicodeTranslateError */
  4194. static void raise_translate_exception(PyObject **exceptionObject,
  4195. const Py_UNICODE *unicode, Py_ssize_t size,
  4196. Py_ssize_t startpos, Py_ssize_t endpos,
  4197. const char *reason)
  4198. {
  4199. make_translate_exception(exceptionObject,
  4200. unicode, size, startpos, endpos, reason);
  4201. if (*exceptionObject != NULL)
  4202. PyCodec_StrictErrors(*exceptionObject);
  4203. }
  4204. /* error handling callback helper:
  4205. build arguments, call the callback and check the arguments,
  4206. put the result into newpos and return the replacement string, which
  4207. has to be freed by the caller */
  4208. static PyObject *unicode_translate_call_errorhandler(const char *errors,
  4209. PyObject **errorHandler,
  4210. const char *reason,
  4211. const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
  4212. Py_ssize_t startpos, Py_ssize_t endpos,
  4213. Py_ssize_t *newpos)
  4214. {
  4215. static char *argparse = "O!n;translating error handler must return (unicode, int) tuple";
  4216. Py_ssize_t i_newpos;
  4217. PyObject *restuple;
  4218. PyObject *resunicode;
  4219. if (*errorHandler == NULL) {
  4220. *errorHandler = PyCodec_LookupError(errors);
  4221. if (*errorHandler == NULL)
  4222. return NULL;
  4223. }
  4224. make_translate_exception(exceptionObject,
  4225. unicode, size, startpos, endpos, reason);
  4226. if (*exceptionObject == NULL)
  4227. return NULL;
  4228. restuple = PyObject_CallFunctionObjArgs(
  4229. *errorHandler, *exceptionObject, NULL);
  4230. if (restuple == NULL)
  4231. return NULL;
  4232. if (!PyTuple_Check(restuple)) {
  4233. PyErr_SetString(PyExc_TypeError, &argparse[4]);
  4234. Py_DECREF(restuple);
  4235. return NULL;
  4236. }
  4237. if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
  4238. &resunicode, &i_newpos)) {
  4239. Py_DECREF(restuple);
  4240. return NULL;
  4241. }
  4242. if (i_newpos<0)
  4243. *newpos = size+i_newpos;
  4244. else
  4245. *newpos = i_newpos;
  4246. if (*newpos<0 || *newpos>size) {
  4247. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
  4248. Py_DECREF(restuple);
  4249. return NULL;
  4250. }
  4251. Py_INCREF(resunicode);
  4252. Py_DECREF(restuple);
  4253. return resunicode;
  4254. }
  4255. /* Lookup the character ch in the mapping and put the result in result,
  4256. which must be decrefed by the caller.
  4257. Return 0 on success, -1 on error */
  4258. static
  4259. int charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
  4260. {
  4261. PyObject *w = PyInt_FromLong((long)c);
  4262. PyObject *x;
  4263. if (w == NULL)
  4264. return -1;
  4265. x = PyObject_GetItem(mapping, w);
  4266. Py_DECREF(w);
  4267. if (x == NULL) {
  4268. if (PyErr_ExceptionMatches(PyExc_LookupError)) {
  4269. /* No mapping found means: use 1:1 mapping. */
  4270. PyErr_Clear();
  4271. *result = NULL;
  4272. return 0;
  4273. } else
  4274. return -1;
  4275. }
  4276. else if (x == Py_None) {
  4277. *result = x;
  4278. return 0;
  4279. }
  4280. else if (PyInt_Check(x)) {
  4281. long value = PyInt_AS_LONG(x);
  4282. long max = PyUnicode_GetMax();
  4283. if (value < 0 || value > max) {
  4284. PyErr_Format(PyExc_TypeError,
  4285. "character mapping must be in range(0x%lx)", max+1);
  4286. Py_DECREF(x);
  4287. return -1;
  4288. }
  4289. *result = x;
  4290. return 0;
  4291. }
  4292. else if (PyUnicode_Check(x)) {
  4293. *result = x;
  4294. return 0;
  4295. }
  4296. else {
  4297. /* wrong return value */
  4298. PyErr_SetString(PyExc_TypeError,
  4299. "character mapping must return integer, None or unicode");
  4300. Py_DECREF(x);
  4301. return -1;
  4302. }
  4303. }
  4304. /* ensure that *outobj is at least requiredsize characters long,
  4305. if not reallocate and adjust various state variables.
  4306. Return 0 on success, -1 on error */
  4307. static
  4308. int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
  4309. Py_ssize_t requiredsize)
  4310. {
  4311. Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj);
  4312. if (requiredsize > oldsize) {
  4313. /* remember old output position */
  4314. Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
  4315. /* exponentially overallocate to minimize reallocations */
  4316. if (requiredsize < 2 * oldsize)
  4317. requiredsize = 2 * oldsize;
  4318. if (PyUnicode_Resize(outobj, requiredsize) < 0)
  4319. return -1;
  4320. *outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
  4321. }
  4322. return 0;
  4323. }
  4324. /* lookup the character, put the result in the output string and adjust
  4325. various state variables. Return a new reference to the object that
  4326. was put in the output buffer in *result, or Py_None, if the mapping was
  4327. undefined (in which case no character was written).
  4328. The called must decref result.
  4329. Return 0 on success, -1 on error. */
  4330. static
  4331. int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
  4332. Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
  4333. PyObject **res)
  4334. {
  4335. if (charmaptranslate_lookup(*curinp, mapping, res))
  4336. return -1;
  4337. if (*res==NULL) {
  4338. /* not found => default to 1:1 mapping */
  4339. *(*outp)++ = *curinp;
  4340. }
  4341. else if (*res==Py_None)
  4342. ;
  4343. else if (PyInt_Check(*res)) {
  4344. /* no overflow check, because we know that the space is enough */
  4345. *(*outp)++ = (Py_UNICODE)PyInt_AS_LONG(*res);
  4346. }
  4347. else if (PyUnicode_Check(*res)) {
  4348. Py_ssize_t repsize = PyUnicode_GET_SIZE(*res);
  4349. if (repsize==1) {
  4350. /* no overflow check, because we know that the space is enough */
  4351. *(*outp)++ = *PyUnicode_AS_UNICODE(*res);
  4352. }
  4353. else if (repsize!=0) {
  4354. /* more than one character */
  4355. Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
  4356. (insize - (curinp-startinp)) +
  4357. repsize - 1;
  4358. if (charmaptranslate_makespace(outobj, outp, requiredsize))
  4359. return -1;
  4360. memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
  4361. *outp += repsize;
  4362. }
  4363. }
  4364. else
  4365. return -1;
  4366. return 0;
  4367. }
  4368. PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
  4369. Py_ssize_t size,
  4370. PyObject *mapping,
  4371. const char *errors)
  4372. {
  4373. /* output object */
  4374. PyObject *res = NULL;
  4375. /* pointers to the beginning and end+1 of input */
  4376. const Py_UNICODE *startp = p;
  4377. const Py_UNICODE *endp = p + size;
  4378. /* pointer into the output */
  4379. Py_UNICODE *str;
  4380. /* current output position */
  4381. Py_ssize_t respos = 0;
  4382. char *reason = "character maps to <undefined>";
  4383. PyObject *errorHandler = NULL;
  4384. PyObject *exc = NULL;
  4385. /* the following variable is used for caching string comparisons
  4386. * -1=not initialized, 0=unknown, 1=strict, 2=replace,
  4387. * 3=ignore, 4=xmlcharrefreplace */
  4388. int known_errorHandler = -1;
  4389. if (mapping == NULL) {
  4390. PyErr_BadArgument();
  4391. return NULL;
  4392. }
  4393. /* allocate enough for a simple 1:1 translation without
  4394. replacements, if we need more, we'll resize */
  4395. res = PyUnicode_FromUnicode(NULL, size);
  4396. if (res == NULL)
  4397. goto onError;
  4398. if (size == 0)
  4399. return res;
  4400. str = PyUnicode_AS_UNICODE(res);
  4401. while (p<endp) {
  4402. /* try to encode it */
  4403. PyObject *x = NULL;
  4404. if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
  4405. Py_XDECREF(x);
  4406. goto onError;
  4407. }
  4408. Py_XDECREF(x);
  4409. if (x!=Py_None) /* it worked => adjust input pointer */
  4410. ++p;
  4411. else { /* untranslatable character */
  4412. PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
  4413. Py_ssize_t repsize;
  4414. Py_ssize_t newpos;
  4415. Py_UNICODE *uni2;
  4416. /* startpos for collecting untranslatable chars */
  4417. const Py_UNICODE *collstart = p;
  4418. const Py_UNICODE *collend = p+1;
  4419. const Py_UNICODE *coll;
  4420. /* find all untranslatable characters */
  4421. while (collend < endp) {
  4422. if (charmaptranslate_lookup(*collend, mapping, &x))
  4423. goto onError;
  4424. Py_XDECREF(x);
  4425. if (x!=Py_None)
  4426. break;
  4427. ++collend;
  4428. }
  4429. /* cache callback name lookup
  4430. * (if not done yet, i.e. it's the first error) */
  4431. if (known_errorHandler==-1) {
  4432. if ((errors==NULL) || (!strcmp(errors, "strict")))
  4433. known_errorHandler = 1;
  4434. else if (!strcmp(errors, "replace"))
  4435. known_errorHandler = 2;
  4436. else if (!strcmp(errors, "ignore"))
  4437. known_errorHandler = 3;
  4438. else if (!strcmp(errors, "xmlcharrefreplace"))
  4439. known_errorHandler = 4;
  4440. else
  4441. known_errorHandler = 0;
  4442. }
  4443. switch (known_errorHandler) {
  4444. case 1: /* strict */
  4445. raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
  4446. goto onError;
  4447. case 2: /* replace */
  4448. /* No need to check for space, this is a 1:1 replacement */
  4449. for (coll = collstart; coll<collend; ++coll)
  4450. *str++ = '?';
  4451. /* fall through */
  4452. case 3: /* ignore */
  4453. p = collend;
  4454. break;
  4455. case 4: /* xmlcharrefreplace */
  4456. /* generate replacement (temporarily (mis)uses p) */
  4457. for (p = collstart; p < collend; ++p) {
  4458. char buffer[2+29+1+1];
  4459. char *cp;
  4460. sprintf(buffer, "&#%d;", (int)*p);
  4461. if (charmaptranslate_makespace(&res, &str,
  4462. (str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
  4463. goto onError;
  4464. for (cp = buffer; *cp; ++cp)
  4465. *str++ = *cp;
  4466. }
  4467. p = collend;
  4468. break;
  4469. default:
  4470. repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
  4471. reason, startp, size, &exc,
  4472. collstart-startp, collend-startp, &newpos);
  4473. if (repunicode == NULL)
  4474. goto onError;
  4475. /* generate replacement */
  4476. repsize = PyUnicode_GET_SIZE(repunicode);
  4477. if (charmaptranslate_makespace(&res, &str,
  4478. (str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
  4479. Py_DECREF(repunicode);
  4480. goto onError;
  4481. }
  4482. for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
  4483. *str++ = *uni2;
  4484. p = startp + newpos;
  4485. Py_DECREF(repunicode);
  4486. }
  4487. }
  4488. }
  4489. /* Resize if we allocated to much */
  4490. respos = str-PyUnicode_AS_UNICODE(res);
  4491. if (respos<PyUnicode_GET_SIZE(res)) {
  4492. if (PyUnicode_Resize(&res, respos) < 0)
  4493. goto onError;
  4494. }
  4495. Py_XDECREF(exc);
  4496. Py_XDECREF(errorHandler);
  4497. return res;
  4498. onError:
  4499. Py_XDECREF(res);
  4500. Py_XDECREF(exc);
  4501. Py_XDECREF(errorHandler);
  4502. return NULL;
  4503. }
  4504. PyObject *PyUnicode_Translate(PyObject *str,
  4505. PyObject *mapping,
  4506. const char *errors)
  4507. {
  4508. PyObject *result;
  4509. str = PyUnicode_FromObject(str);
  4510. if (str == NULL)
  4511. goto onError;
  4512. result = PyUnicode_TranslateCharmap(PyUnicode_AS_UNICODE(str),
  4513. PyUnicode_GET_SIZE(str),
  4514. mapping,
  4515. errors);
  4516. Py_DECREF(str);
  4517. return result;
  4518. onError:
  4519. Py_XDECREF(str);
  4520. return NULL;
  4521. }
  4522. /* --- Decimal Encoder ---------------------------------------------------- */
  4523. int PyUnicode_EncodeDecimal(Py_UNICODE *s,
  4524. Py_ssize_t length,
  4525. char *output,
  4526. const char *errors)
  4527. {
  4528. Py_UNICODE *p, *end;
  4529. PyObject *errorHandler = NULL;
  4530. PyObject *exc = NULL;
  4531. const char *encoding = "decimal";
  4532. const char *reason = "invalid decimal Unicode string";
  4533. /* the following variable is used for caching string comparisons
  4534. * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
  4535. int known_errorHandler = -1;
  4536. if (output == NULL) {
  4537. PyErr_BadArgument();
  4538. return -1;
  4539. }
  4540. p = s;
  4541. end = s + length;
  4542. while (p < end) {
  4543. register Py_UNICODE ch = *p;
  4544. int decimal;
  4545. PyObject *repunicode;
  4546. Py_ssize_t repsize;
  4547. Py_ssize_t newpos;
  4548. Py_UNICODE *uni2;
  4549. Py_UNICODE *collstart;
  4550. Py_UNICODE *collend;
  4551. if (Py_UNICODE_ISSPACE(ch)) {
  4552. *output++ = ' ';
  4553. ++p;
  4554. continue;
  4555. }
  4556. decimal = Py_UNICODE_TODECIMAL(ch);
  4557. if (decimal >= 0) {
  4558. *output++ = '0' + decimal;
  4559. ++p;
  4560. continue;
  4561. }
  4562. if (0 < ch && ch < 256) {
  4563. *output++ = (char)ch;
  4564. ++p;
  4565. continue;
  4566. }
  4567. /* All other characters are considered unencodable */
  4568. collstart = p;
  4569. collend = p+1;
  4570. while (collend < end) {
  4571. if ((0 < *collend && *collend < 256) ||
  4572. !Py_UNICODE_ISSPACE(*collend) ||
  4573. Py_UNICODE_TODECIMAL(*collend))
  4574. break;
  4575. }
  4576. /* cache callback name lookup
  4577. * (if not done yet, i.e. it's the first error) */
  4578. if (known_errorHandler==-1) {
  4579. if ((errors==NULL) || (!strcmp(errors, "strict")))
  4580. known_errorHandler = 1;
  4581. else if (!strcmp(errors, "replace"))
  4582. known_errorHandler = 2;
  4583. else if (!strcmp(errors, "ignore"))
  4584. known_errorHandler = 3;
  4585. else if (!strcmp(errors, "xmlcharrefreplace"))
  4586. known_errorHandler = 4;
  4587. else
  4588. known_errorHandler = 0;
  4589. }
  4590. switch (known_errorHandler) {
  4591. case 1: /* strict */
  4592. raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
  4593. goto onError;
  4594. case 2: /* replace */
  4595. for (p = collstart; p < collend; ++p)
  4596. *output++ = '?';
  4597. /* fall through */
  4598. case 3: /* ignore */
  4599. p = collend;
  4600. break;
  4601. case 4: /* xmlcharrefreplace */
  4602. /* generate replacement (temporarily (mis)uses p) */
  4603. for (p = collstart; p < collend; ++p)
  4604. output += sprintf(output, "&#%d;", (int)*p);
  4605. p = collend;
  4606. break;
  4607. default:
  4608. repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
  4609. encoding, reason, s, length, &exc,
  4610. collstart-s, collend-s, &newpos);
  4611. if (repunicode == NULL)
  4612. goto onError;
  4613. /* generate replacement */
  4614. repsize = PyUnicode_GET_SIZE(repunicode);
  4615. for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
  4616. Py_UNICODE ch = *uni2;
  4617. if (Py_UNICODE_ISSPACE(ch))
  4618. *output++ = ' ';
  4619. else {
  4620. decimal = Py_UNICODE_TODECIMAL(ch);
  4621. if (decimal >= 0)
  4622. *output++ = '0' + decimal;
  4623. else if (0 < ch && ch < 256)
  4624. *output++ = (char)ch;
  4625. else {
  4626. Py_DECREF(repunicode);
  4627. raise_encode_exception(&exc, encoding,
  4628. s, length, collstart-s, collend-s, reason);
  4629. goto onError;
  4630. }
  4631. }
  4632. }
  4633. p = s + newpos;
  4634. Py_DECREF(repunicode);
  4635. }
  4636. }
  4637. /* 0-terminate the output string */
  4638. *output++ = '\0';
  4639. Py_XDECREF(exc);
  4640. Py_XDECREF(errorHandler);
  4641. return 0;
  4642. onError:
  4643. Py_XDECREF(exc);
  4644. Py_XDECREF(errorHandler);
  4645. return -1;
  4646. }
  4647. /* --- Helpers ------------------------------------------------------------ */
  4648. #include "stringlib/unicodedefs.h"
  4649. #define FROM_UNICODE
  4650. #include "stringlib/fastsearch.h"
  4651. #include "stringlib/count.h"
  4652. #include "stringlib/find.h"
  4653. #include "stringlib/partition.h"
  4654. /* helper macro to fixup start/end slice values */
  4655. #define FIX_START_END(obj) \
  4656. if (start < 0) \
  4657. start += (obj)->length; \
  4658. if (start < 0) \
  4659. start = 0; \
  4660. if (end > (obj)->length) \
  4661. end = (obj)->length; \
  4662. if (end < 0) \
  4663. end += (obj)->length; \
  4664. if (end < 0) \
  4665. end = 0;
  4666. Py_ssize_t PyUnicode_Count(PyObject *str,
  4667. PyObject *substr,
  4668. Py_ssize_t start,
  4669. Py_ssize_t end)
  4670. {
  4671. Py_ssize_t result;
  4672. PyUnicodeObject* str_obj;
  4673. PyUnicodeObject* sub_obj;
  4674. str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
  4675. if (!str_obj)
  4676. return -1;
  4677. sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
  4678. if (!sub_obj) {
  4679. Py_DECREF(str_obj);
  4680. return -1;
  4681. }
  4682. FIX_START_END(str_obj);
  4683. result = stringlib_count(
  4684. str_obj->str + start, end - start, sub_obj->str, sub_obj->length
  4685. );
  4686. Py_DECREF(sub_obj);
  4687. Py_DECREF(str_obj);
  4688. return result;
  4689. }
  4690. Py_ssize_t PyUnicode_Find(PyObject *str,
  4691. PyObject *sub,
  4692. Py_ssize_t start,
  4693. Py_ssize_t end,
  4694. int direction)
  4695. {
  4696. Py_ssize_t result;
  4697. str = PyUnicode_FromObject(str);
  4698. if (!str)
  4699. return -2;
  4700. sub = PyUnicode_FromObject(sub);
  4701. if (!sub) {
  4702. Py_DECREF(str);
  4703. return -2;
  4704. }
  4705. if (direction > 0)
  4706. result = stringlib_find_slice(
  4707. PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
  4708. PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
  4709. start, end
  4710. );
  4711. else
  4712. result = stringlib_rfind_slice(
  4713. PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
  4714. PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
  4715. start, end
  4716. );
  4717. Py_DECREF(str);
  4718. Py_DECREF(sub);
  4719. return result;
  4720. }
  4721. static
  4722. int tailmatch(PyUnicodeObject *self,
  4723. PyUnicodeObject *substring,
  4724. Py_ssize_t start,
  4725. Py_ssize_t end,
  4726. int direction)
  4727. {
  4728. if (substring->length == 0)
  4729. return 1;
  4730. FIX_START_END(self);
  4731. end -= substring->length;
  4732. if (end < start)
  4733. return 0;
  4734. if (direction > 0) {
  4735. if (Py_UNICODE_MATCH(self, end, substring))
  4736. return 1;
  4737. } else {
  4738. if (Py_UNICODE_MATCH(self, start, substring))
  4739. return 1;
  4740. }
  4741. return 0;
  4742. }
  4743. Py_ssize_t PyUnicode_Tailmatch(PyObject *str,
  4744. PyObject *substr,
  4745. Py_ssize_t start,
  4746. Py_ssize_t end,
  4747. int direction)
  4748. {
  4749. Py_ssize_t result;
  4750. str = PyUnicode_FromObject(str);
  4751. if (str == NULL)
  4752. return -1;
  4753. substr = PyUnicode_FromObject(substr);
  4754. if (substr == NULL) {
  4755. Py_DECREF(str);
  4756. return -1;
  4757. }
  4758. result = tailmatch((PyUnicodeObject *)str,
  4759. (PyUnicodeObject *)substr,
  4760. start, end, direction);
  4761. Py_DECREF(str);
  4762. Py_DECREF(substr);
  4763. return result;
  4764. }
  4765. /* Apply fixfct filter to the Unicode object self and return a
  4766. reference to the modified object */
  4767. static
  4768. PyObject *fixup(PyUnicodeObject *self,
  4769. int (*fixfct)(PyUnicodeObject *s))
  4770. {
  4771. PyUnicodeObject *u;
  4772. u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
  4773. if (u == NULL)
  4774. return NULL;
  4775. Py_UNICODE_COPY(u->str, self->str, self->length);
  4776. if (!fixfct(u) && PyUnicode_CheckExact(self)) {
  4777. /* fixfct should return TRUE if it modified the buffer. If
  4778. FALSE, return a reference to the original buffer instead
  4779. (to save space, not time) */
  4780. Py_INCREF(self);
  4781. Py_DECREF(u);
  4782. return (PyObject*) self;
  4783. }
  4784. return (PyObject*) u;
  4785. }
  4786. static
  4787. int fixupper(PyUnicodeObject *self)
  4788. {
  4789. Py_ssize_t len = self->length;
  4790. Py_UNICODE *s = self->str;
  4791. int status = 0;
  4792. while (len-- > 0) {
  4793. register Py_UNICODE ch;
  4794. ch = Py_UNICODE_TOUPPER(*s);
  4795. if (ch != *s) {
  4796. status = 1;
  4797. *s = ch;
  4798. }
  4799. s++;
  4800. }
  4801. return status;
  4802. }
  4803. static
  4804. int fixlower(PyUnicodeObject *self)
  4805. {
  4806. Py_ssize_t len = self->length;
  4807. Py_UNICODE *s = self->str;
  4808. int status = 0;
  4809. while (len-- > 0) {
  4810. register Py_UNICODE ch;
  4811. ch = Py_UNICODE_TOLOWER(*s);
  4812. if (ch != *s) {
  4813. status = 1;
  4814. *s = ch;
  4815. }
  4816. s++;
  4817. }
  4818. return status;
  4819. }
  4820. static
  4821. int fixswapcase(PyUnicodeObject *self)
  4822. {
  4823. Py_ssize_t len = self->length;
  4824. Py_UNICODE *s = self->str;
  4825. int status = 0;
  4826. while (len-- > 0) {
  4827. if (Py_UNICODE_ISUPPER(*s)) {
  4828. *s = Py_UNICODE_TOLOWER(*s);
  4829. status = 1;
  4830. } else if (Py_UNICODE_ISLOWER(*s)) {
  4831. *s = Py_UNICODE_TOUPPER(*s);
  4832. status = 1;
  4833. }
  4834. s++;
  4835. }
  4836. return status;
  4837. }
  4838. static
  4839. int fixcapitalize(PyUnicodeObject *self)
  4840. {
  4841. Py_ssize_t len = self->length;
  4842. Py_UNICODE *s = self->str;
  4843. int status = 0;
  4844. if (len == 0)
  4845. return 0;
  4846. if (Py_UNICODE_ISLOWER(*s)) {
  4847. *s = Py_UNICODE_TOUPPER(*s);
  4848. status = 1;
  4849. }
  4850. s++;
  4851. while (--len > 0) {
  4852. if (Py_UNICODE_ISUPPER(*s)) {
  4853. *s = Py_UNICODE_TOLOWER(*s);
  4854. status = 1;
  4855. }
  4856. s++;
  4857. }
  4858. return status;
  4859. }
  4860. static
  4861. int fixtitle(PyUnicodeObject *self)
  4862. {
  4863. register Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
  4864. register Py_UNICODE *e;
  4865. int previous_is_cased;
  4866. /* Shortcut for single character strings */
  4867. if (PyUnicode_GET_SIZE(self) == 1) {
  4868. Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
  4869. if (*p != ch) {
  4870. *p = ch;
  4871. return 1;
  4872. }
  4873. else
  4874. return 0;
  4875. }
  4876. e = p + PyUnicode_GET_SIZE(self);
  4877. previous_is_cased = 0;
  4878. for (; p < e; p++) {
  4879. register const Py_UNICODE ch = *p;
  4880. if (previous_is_cased)
  4881. *p = Py_UNICODE_TOLOWER(ch);
  4882. else
  4883. *p = Py_UNICODE_TOTITLE(ch);
  4884. if (Py_UNICODE_ISLOWER(ch) ||
  4885. Py_UNICODE_ISUPPER(ch) ||
  4886. Py_UNICODE_ISTITLE(ch))
  4887. previous_is_cased = 1;
  4888. else
  4889. previous_is_cased = 0;
  4890. }
  4891. return 1;
  4892. }
  4893. PyObject *
  4894. PyUnicode_Join(PyObject *separator, PyObject *seq)
  4895. {
  4896. PyObject *internal_separator = NULL;
  4897. const Py_UNICODE blank = ' ';
  4898. const Py_UNICODE *sep = &blank;
  4899. Py_ssize_t seplen = 1;
  4900. PyUnicodeObject *res = NULL; /* the result */
  4901. Py_ssize_t res_alloc = 100; /* # allocated bytes for string in res */
  4902. Py_ssize_t res_used; /* # used bytes */
  4903. Py_UNICODE *res_p; /* pointer to free byte in res's string area */
  4904. PyObject *fseq; /* PySequence_Fast(seq) */
  4905. Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
  4906. PyObject *item;
  4907. Py_ssize_t i;
  4908. fseq = PySequence_Fast(seq, "");
  4909. if (fseq == NULL) {
  4910. return NULL;
  4911. }
  4912. /* Grrrr. A codec may be invoked to convert str objects to
  4913. * Unicode, and so it's possible to call back into Python code
  4914. * during PyUnicode_FromObject(), and so it's possible for a sick
  4915. * codec to change the size of fseq (if seq is a list). Therefore
  4916. * we have to keep refetching the size -- can't assume seqlen
  4917. * is invariant.
  4918. */
  4919. seqlen = PySequence_Fast_GET_SIZE(fseq);
  4920. /* If empty sequence, return u"". */
  4921. if (seqlen == 0) {
  4922. res = _PyUnicode_New(0); /* empty sequence; return u"" */
  4923. goto Done;
  4924. }
  4925. /* If singleton sequence with an exact Unicode, return that. */
  4926. if (seqlen == 1) {
  4927. item = PySequence_Fast_GET_ITEM(fseq, 0);
  4928. if (PyUnicode_CheckExact(item)) {
  4929. Py_INCREF(item);
  4930. res = (PyUnicodeObject *)item;
  4931. goto Done;
  4932. }
  4933. }
  4934. /* At least two items to join, or one that isn't exact Unicode. */
  4935. if (seqlen > 1) {
  4936. /* Set up sep and seplen -- they're needed. */
  4937. if (separator == NULL) {
  4938. sep = &blank;
  4939. seplen = 1;
  4940. }
  4941. else {
  4942. internal_separator = PyUnicode_FromObject(separator);
  4943. if (internal_separator == NULL)
  4944. goto onError;
  4945. sep = PyUnicode_AS_UNICODE(internal_separator);
  4946. seplen = PyUnicode_GET_SIZE(internal_separator);
  4947. /* In case PyUnicode_FromObject() mutated seq. */
  4948. seqlen = PySequence_Fast_GET_SIZE(fseq);
  4949. }
  4950. }
  4951. /* Get space. */
  4952. res = _PyUnicode_New(res_alloc);
  4953. if (res == NULL)
  4954. goto onError;
  4955. res_p = PyUnicode_AS_UNICODE(res);
  4956. res_used = 0;
  4957. for (i = 0; i < seqlen; ++i) {
  4958. Py_ssize_t itemlen;
  4959. Py_ssize_t new_res_used;
  4960. item = PySequence_Fast_GET_ITEM(fseq, i);
  4961. /* Convert item to Unicode. */
  4962. if (! PyUnicode_Check(item) && ! PyString_Check(item)) {
  4963. PyErr_Format(PyExc_TypeError,
  4964. "sequence item %zd: expected string or Unicode,"
  4965. " %.80s found",
  4966. i, Py_TYPE(item)->tp_name);
  4967. goto onError;
  4968. }
  4969. item = PyUnicode_FromObject(item);
  4970. if (item == NULL)
  4971. goto onError;
  4972. /* We own a reference to item from here on. */
  4973. /* In case PyUnicode_FromObject() mutated seq. */
  4974. seqlen = PySequence_Fast_GET_SIZE(fseq);
  4975. /* Make sure we have enough space for the separator and the item. */
  4976. itemlen = PyUnicode_GET_SIZE(item);
  4977. new_res_used = res_used + itemlen;
  4978. if (new_res_used < 0)
  4979. goto Overflow;
  4980. if (i < seqlen - 1) {
  4981. new_res_used += seplen;
  4982. if (new_res_used < 0)
  4983. goto Overflow;
  4984. }
  4985. if (new_res_used > res_alloc) {
  4986. /* double allocated size until it's big enough */
  4987. do {
  4988. res_alloc += res_alloc;
  4989. if (res_alloc <= 0)
  4990. goto Overflow;
  4991. } while (new_res_used > res_alloc);
  4992. if (_PyUnicode_Resize(&res, res_alloc) < 0) {
  4993. Py_DECREF(item);
  4994. goto onError;
  4995. }
  4996. res_p = PyUnicode_AS_UNICODE(res) + res_used;
  4997. }
  4998. /* Copy item, and maybe the separator. */
  4999. Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen);
  5000. res_p += itemlen;
  5001. if (i < seqlen - 1) {
  5002. Py_UNICODE_COPY(res_p, sep, seplen);
  5003. res_p += seplen;
  5004. }
  5005. Py_DECREF(item);
  5006. res_used = new_res_used;
  5007. }
  5008. /* Shrink res to match the used area; this probably can't fail,
  5009. * but it's cheap to check.
  5010. */
  5011. if (_PyUnicode_Resize(&res, res_used) < 0)
  5012. goto onError;
  5013. Done:
  5014. Py_XDECREF(internal_separator);
  5015. Py_DECREF(fseq);
  5016. return (PyObject *)res;
  5017. Overflow:
  5018. PyErr_SetString(PyExc_OverflowError,
  5019. "join() result is too long for a Python string");
  5020. Py_DECREF(item);
  5021. /* fall through */
  5022. onError:
  5023. Py_XDECREF(internal_separator);
  5024. Py_DECREF(fseq);
  5025. Py_XDECREF(res);
  5026. return NULL;
  5027. }
  5028. static
  5029. PyUnicodeObject *pad(PyUnicodeObject *self,
  5030. Py_ssize_t left,
  5031. Py_ssize_t right,
  5032. Py_UNICODE fill)
  5033. {
  5034. PyUnicodeObject *u;
  5035. if (left < 0)
  5036. left = 0;
  5037. if (right < 0)
  5038. right = 0;
  5039. if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
  5040. Py_INCREF(self);
  5041. return self;
  5042. }
  5043. if (left > PY_SSIZE_T_MAX - self->length ||
  5044. right > PY_SSIZE_T_MAX - (left + self->length)) {
  5045. PyErr_SetString(PyExc_OverflowError, "padded string is too long");
  5046. return NULL;
  5047. }
  5048. u = _PyUnicode_New(left + self->length + right);
  5049. if (u) {
  5050. if (left)
  5051. Py_UNICODE_FILL(u->str, fill, left);
  5052. Py_UNICODE_COPY(u->str + left, self->str, self->length);
  5053. if (right)
  5054. Py_UNICODE_FILL(u->str + left + self->length, fill, right);
  5055. }
  5056. return u;
  5057. }
  5058. #define SPLIT_APPEND(data, left, right) \
  5059. str = PyUnicode_FromUnicode((data) + (left), (right) - (left)); \
  5060. if (!str) \
  5061. goto onError; \
  5062. if (PyList_Append(list, str)) { \
  5063. Py_DECREF(str); \
  5064. goto onError; \
  5065. } \
  5066. else \
  5067. Py_DECREF(str);
  5068. static
  5069. PyObject *split_whitespace(PyUnicodeObject *self,
  5070. PyObject *list,
  5071. Py_ssize_t maxcount)
  5072. {
  5073. register Py_ssize_t i;
  5074. register Py_ssize_t j;
  5075. Py_ssize_t len = self->length;
  5076. PyObject *str;
  5077. register const Py_UNICODE *buf = self->str;
  5078. for (i = j = 0; i < len; ) {
  5079. /* find a token */
  5080. while (i < len && Py_UNICODE_ISSPACE(buf[i]))
  5081. i++;
  5082. j = i;
  5083. while (i < len && !Py_UNICODE_ISSPACE(buf[i]))
  5084. i++;
  5085. if (j < i) {
  5086. if (maxcount-- <= 0)
  5087. break;
  5088. SPLIT_APPEND(buf, j, i);
  5089. while (i < len && Py_UNICODE_ISSPACE(buf[i]))
  5090. i++;
  5091. j = i;
  5092. }
  5093. }
  5094. if (j < len) {
  5095. SPLIT_APPEND(buf, j, len);
  5096. }
  5097. return list;
  5098. onError:
  5099. Py_DECREF(list);
  5100. return NULL;
  5101. }
  5102. PyObject *PyUnicode_Splitlines(PyObject *string,
  5103. int keepends)
  5104. {
  5105. register Py_ssize_t i;
  5106. register Py_ssize_t j;
  5107. Py_ssize_t len;
  5108. PyObject *list;
  5109. PyObject *str;
  5110. Py_UNICODE *data;
  5111. string = PyUnicode_FromObject(string);
  5112. if (string == NULL)
  5113. return NULL;
  5114. data = PyUnicode_AS_UNICODE(string);
  5115. len = PyUnicode_GET_SIZE(string);
  5116. list = PyList_New(0);
  5117. if (!list)
  5118. goto onError;
  5119. for (i = j = 0; i < len; ) {
  5120. Py_ssize_t eol;
  5121. /* Find a line and append it */
  5122. while (i < len && !BLOOM_LINEBREAK(data[i]))
  5123. i++;
  5124. /* Skip the line break reading CRLF as one line break */
  5125. eol = i;
  5126. if (i < len) {
  5127. if (data[i] == '\r' && i + 1 < len &&
  5128. data[i+1] == '\n')
  5129. i += 2;
  5130. else
  5131. i++;
  5132. if (keepends)
  5133. eol = i;
  5134. }
  5135. SPLIT_APPEND(data, j, eol);
  5136. j = i;
  5137. }
  5138. if (j < len) {
  5139. SPLIT_APPEND(data, j, len);
  5140. }
  5141. Py_DECREF(string);
  5142. return list;
  5143. onError:
  5144. Py_XDECREF(list);
  5145. Py_DECREF(string);
  5146. return NULL;
  5147. }
  5148. static
  5149. PyObject *split_char(PyUnicodeObject *self,
  5150. PyObject *list,
  5151. Py_UNICODE ch,
  5152. Py_ssize_t maxcount)
  5153. {
  5154. register Py_ssize_t i;
  5155. register Py_ssize_t j;
  5156. Py_ssize_t len = self->length;
  5157. PyObject *str;
  5158. register const Py_UNICODE *buf = self->str;
  5159. for (i = j = 0; i < len; ) {
  5160. if (buf[i] == ch) {
  5161. if (maxcount-- <= 0)
  5162. break;
  5163. SPLIT_APPEND(buf, j, i);
  5164. i = j = i + 1;
  5165. } else
  5166. i++;
  5167. }
  5168. if (j <= len) {
  5169. SPLIT_APPEND(buf, j, len);
  5170. }
  5171. return list;
  5172. onError:
  5173. Py_DECREF(list);
  5174. return NULL;
  5175. }
  5176. static
  5177. PyObject *split_substring(PyUnicodeObject *self,
  5178. PyObject *list,
  5179. PyUnicodeObject *substring,
  5180. Py_ssize_t maxcount)
  5181. {
  5182. register Py_ssize_t i;
  5183. register Py_ssize_t j;
  5184. Py_ssize_t len = self->length;
  5185. Py_ssize_t sublen = substring->length;
  5186. PyObject *str;
  5187. for (i = j = 0; i <= len - sublen; ) {
  5188. if (Py_UNICODE_MATCH(self, i, substring)) {
  5189. if (maxcount-- <= 0)
  5190. break;
  5191. SPLIT_APPEND(self->str, j, i);
  5192. i = j = i + sublen;
  5193. } else
  5194. i++;
  5195. }
  5196. if (j <= len) {
  5197. SPLIT_APPEND(self->str, j, len);
  5198. }
  5199. return list;
  5200. onError:
  5201. Py_DECREF(list);
  5202. return NULL;
  5203. }
  5204. static
  5205. PyObject *rsplit_whitespace(PyUnicodeObject *self,
  5206. PyObject *list,
  5207. Py_ssize_t maxcount)
  5208. {
  5209. register Py_ssize_t i;
  5210. register Py_ssize_t j;
  5211. Py_ssize_t len = self->length;
  5212. PyObject *str;
  5213. register const Py_UNICODE *buf = self->str;
  5214. for (i = j = len - 1; i >= 0; ) {
  5215. /* find a token */
  5216. while (i >= 0 && Py_UNICODE_ISSPACE(buf[i]))
  5217. i--;
  5218. j = i;
  5219. while (i >= 0 && !Py_UNICODE_ISSPACE(buf[i]))
  5220. i--;
  5221. if (j > i) {
  5222. if (maxcount-- <= 0)
  5223. break;
  5224. SPLIT_APPEND(buf, i + 1, j + 1);
  5225. while (i >= 0 && Py_UNICODE_ISSPACE(buf[i]))
  5226. i--;
  5227. j = i;
  5228. }
  5229. }
  5230. if (j >= 0) {
  5231. SPLIT_APPEND(buf, 0, j + 1);
  5232. }
  5233. if (PyList_Reverse(list) < 0)
  5234. goto onError;
  5235. return list;
  5236. onError:
  5237. Py_DECREF(list);
  5238. return NULL;
  5239. }
  5240. static
  5241. PyObject *rsplit_char(PyUnicodeObject *self,
  5242. PyObject *list,
  5243. Py_UNICODE ch,
  5244. Py_ssize_t maxcount)
  5245. {
  5246. register Py_ssize_t i;
  5247. register Py_ssize_t j;
  5248. Py_ssize_t len = self->length;
  5249. PyObject *str;
  5250. register const Py_UNICODE *buf = self->str;
  5251. for (i = j = len - 1; i >= 0; ) {
  5252. if (buf[i] == ch) {
  5253. if (maxcount-- <= 0)
  5254. break;
  5255. SPLIT_APPEND(buf, i + 1, j + 1);
  5256. j = i = i - 1;
  5257. } else
  5258. i--;
  5259. }
  5260. if (j >= -1) {
  5261. SPLIT_APPEND(buf, 0, j + 1);
  5262. }
  5263. if (PyList_Reverse(list) < 0)
  5264. goto onError;
  5265. return list;
  5266. onError:
  5267. Py_DECREF(list);
  5268. return NULL;
  5269. }
  5270. static
  5271. PyObject *rsplit_substring(PyUnicodeObject *self,
  5272. PyObject *list,
  5273. PyUnicodeObject *substring,
  5274. Py_ssize_t maxcount)
  5275. {
  5276. register Py_ssize_t i;
  5277. register Py_ssize_t j;
  5278. Py_ssize_t len = self->length;
  5279. Py_ssize_t sublen = substring->length;
  5280. PyObject *str;
  5281. for (i = len - sublen, j = len; i >= 0; ) {
  5282. if (Py_UNICODE_MATCH(self, i, substring)) {
  5283. if (maxcount-- <= 0)
  5284. break;
  5285. SPLIT_APPEND(self->str, i + sublen, j);
  5286. j = i;
  5287. i -= sublen;
  5288. } else
  5289. i--;
  5290. }
  5291. if (j >= 0) {
  5292. SPLIT_APPEND(self->str, 0, j);
  5293. }
  5294. if (PyList_Reverse(list) < 0)
  5295. goto onError;
  5296. return list;
  5297. onError:
  5298. Py_DECREF(list);
  5299. return NULL;
  5300. }
  5301. #undef SPLIT_APPEND
  5302. static
  5303. PyObject *split(PyUnicodeObject *self,
  5304. PyUnicodeObject *substring,
  5305. Py_ssize_t maxcount)
  5306. {
  5307. PyObject *list;
  5308. if (maxcount < 0)
  5309. maxcount = PY_SSIZE_T_MAX;
  5310. list = PyList_New(0);
  5311. if (!list)
  5312. return NULL;
  5313. if (substring == NULL)
  5314. return split_whitespace(self,list,maxcount);
  5315. else if (substring->length == 1)
  5316. return split_char(self,list,substring->str[0],maxcount);
  5317. else if (substring->length == 0) {
  5318. Py_DECREF(list);
  5319. PyErr_SetString(PyExc_ValueError, "empty separator");
  5320. return NULL;
  5321. }
  5322. else
  5323. return split_substring(self,list,substring,maxcount);
  5324. }
  5325. static
  5326. PyObject *rsplit(PyUnicodeObject *self,
  5327. PyUnicodeObject *substring,
  5328. Py_ssize_t maxcount)
  5329. {
  5330. PyObject *list;
  5331. if (maxcount < 0)
  5332. maxcount = PY_SSIZE_T_MAX;
  5333. list = PyList_New(0);
  5334. if (!list)
  5335. return NULL;
  5336. if (substring == NULL)
  5337. return rsplit_whitespace(self,list,maxcount);
  5338. else if (substring->length == 1)
  5339. return rsplit_char(self,list,substring->str[0],maxcount);
  5340. else if (substring->length == 0) {
  5341. Py_DECREF(list);
  5342. PyErr_SetString(PyExc_ValueError, "empty separator");
  5343. return NULL;
  5344. }
  5345. else
  5346. return rsplit_substring(self,list,substring,maxcount);
  5347. }
  5348. static
  5349. PyObject *replace(PyUnicodeObject *self,
  5350. PyUnicodeObject *str1,
  5351. PyUnicodeObject *str2,
  5352. Py_ssize_t maxcount)
  5353. {
  5354. PyUnicodeObject *u;
  5355. if (maxcount < 0)
  5356. maxcount = PY_SSIZE_T_MAX;
  5357. if (str1->length == str2->length) {
  5358. /* same length */
  5359. Py_ssize_t i;
  5360. if (str1->length == 1) {
  5361. /* replace characters */
  5362. Py_UNICODE u1, u2;
  5363. if (!findchar(self->str, self->length, str1->str[0]))
  5364. goto nothing;
  5365. u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
  5366. if (!u)
  5367. return NULL;
  5368. Py_UNICODE_COPY(u->str, self->str, self->length);
  5369. u1 = str1->str[0];
  5370. u2 = str2->str[0];
  5371. for (i = 0; i < u->length; i++)
  5372. if (u->str[i] == u1) {
  5373. if (--maxcount < 0)
  5374. break;
  5375. u->str[i] = u2;
  5376. }
  5377. } else {
  5378. i = fastsearch(
  5379. self->str, self->length, str1->str, str1->length, FAST_SEARCH
  5380. );
  5381. if (i < 0)
  5382. goto nothing;
  5383. u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
  5384. if (!u)
  5385. return NULL;
  5386. Py_UNICODE_COPY(u->str, self->str, self->length);
  5387. while (i <= self->length - str1->length)
  5388. if (Py_UNICODE_MATCH(self, i, str1)) {
  5389. if (--maxcount < 0)
  5390. break;
  5391. Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
  5392. i += str1->length;
  5393. } else
  5394. i++;
  5395. }
  5396. } else {
  5397. Py_ssize_t n, i, j, e;
  5398. Py_ssize_t product, new_size, delta;
  5399. Py_UNICODE *p;
  5400. /* replace strings */
  5401. n = stringlib_count(self->str, self->length, str1->str, str1->length);
  5402. if (n > maxcount)
  5403. n = maxcount;
  5404. if (n == 0)
  5405. goto nothing;
  5406. /* new_size = self->length + n * (str2->length - str1->length)); */
  5407. delta = (str2->length - str1->length);
  5408. if (delta == 0) {
  5409. new_size = self->length;
  5410. } else {
  5411. product = n * (str2->length - str1->length);
  5412. if ((product / (str2->length - str1->length)) != n) {
  5413. PyErr_SetString(PyExc_OverflowError,
  5414. "replace string is too long");
  5415. return NULL;
  5416. }
  5417. new_size = self->length + product;
  5418. if (new_size < 0) {
  5419. PyErr_SetString(PyExc_OverflowError,
  5420. "replace string is too long");
  5421. return NULL;
  5422. }
  5423. }
  5424. u = _PyUnicode_New(new_size);
  5425. if (!u)
  5426. return NULL;
  5427. i = 0;
  5428. p = u->str;
  5429. e = self->length - str1->length;
  5430. if (str1->length > 0) {
  5431. while (n-- > 0) {
  5432. /* look for next match */
  5433. j = i;
  5434. while (j <= e) {
  5435. if (Py_UNICODE_MATCH(self, j, str1))
  5436. break;
  5437. j++;
  5438. }
  5439. if (j > i) {
  5440. if (j > e)
  5441. break;
  5442. /* copy unchanged part [i:j] */
  5443. Py_UNICODE_COPY(p, self->str+i, j-i);
  5444. p += j - i;
  5445. }
  5446. /* copy substitution string */
  5447. if (str2->length > 0) {
  5448. Py_UNICODE_COPY(p, str2->str, str2->length);
  5449. p += str2->length;
  5450. }
  5451. i = j + str1->length;
  5452. }
  5453. if (i < self->length)
  5454. /* copy tail [i:] */
  5455. Py_UNICODE_COPY(p, self->str+i, self->length-i);
  5456. } else {
  5457. /* interleave */
  5458. while (n > 0) {
  5459. Py_UNICODE_COPY(p, str2->str, str2->length);
  5460. p += str2->length;
  5461. if (--n <= 0)
  5462. break;
  5463. *p++ = self->str[i++];
  5464. }
  5465. Py_UNICODE_COPY(p, self->str+i, self->length-i);
  5466. }
  5467. }
  5468. return (PyObject *) u;
  5469. nothing:
  5470. /* nothing to replace; return original string (when possible) */
  5471. if (PyUnicode_CheckExact(self)) {
  5472. Py_INCREF(self);
  5473. return (PyObject *) self;
  5474. }
  5475. return PyUnicode_FromUnicode(self->str, self->length);
  5476. }
  5477. /* --- Unicode Object Methods --------------------------------------------- */
  5478. PyDoc_STRVAR(title__doc__,
  5479. "S.title() -> unicode\n\
  5480. \n\
  5481. Return a titlecased version of S, i.e. words start with title case\n\
  5482. characters, all remaining cased characters have lower case.");
  5483. static PyObject*
  5484. unicode_title(PyUnicodeObject *self)
  5485. {
  5486. return fixup(self, fixtitle);
  5487. }
  5488. PyDoc_STRVAR(capitalize__doc__,
  5489. "S.capitalize() -> unicode\n\
  5490. \n\
  5491. Return a capitalized version of S, i.e. make the first character\n\
  5492. have upper case.");
  5493. static PyObject*
  5494. unicode_capitalize(PyUnicodeObject *self)
  5495. {
  5496. return fixup(self, fixcapitalize);
  5497. }
  5498. #if 0
  5499. PyDoc_STRVAR(capwords__doc__,
  5500. "S.capwords() -> unicode\n\
  5501. \n\
  5502. Apply .capitalize() to all words in S and return the result with\n\
  5503. normalized whitespace (all whitespace strings are replaced by ' ').");
  5504. static PyObject*
  5505. unicode_capwords(PyUnicodeObject *self)
  5506. {
  5507. PyObject *list;
  5508. PyObject *item;
  5509. Py_ssize_t i;
  5510. /* Split into words */
  5511. list = split(self, NULL, -1);
  5512. if (!list)
  5513. return NULL;
  5514. /* Capitalize each word */
  5515. for (i = 0; i < PyList_GET_SIZE(list); i++) {
  5516. item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
  5517. fixcapitalize);
  5518. if (item == NULL)
  5519. goto onError;
  5520. Py_DECREF(PyList_GET_ITEM(list, i));
  5521. PyList_SET_ITEM(list, i, item);
  5522. }
  5523. /* Join the words to form a new string */
  5524. item = PyUnicode_Join(NULL, list);
  5525. onError:
  5526. Py_DECREF(list);
  5527. return (PyObject *)item;
  5528. }
  5529. #endif
  5530. /* Argument converter. Coerces to a single unicode character */
  5531. static int
  5532. convert_uc(PyObject *obj, void *addr)
  5533. {
  5534. Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
  5535. PyObject *uniobj;
  5536. Py_UNICODE *unistr;
  5537. uniobj = PyUnicode_FromObject(obj);
  5538. if (uniobj == NULL) {
  5539. PyErr_SetString(PyExc_TypeError,
  5540. "The fill character cannot be converted to Unicode");
  5541. return 0;
  5542. }
  5543. if (PyUnicode_GET_SIZE(uniobj) != 1) {
  5544. PyErr_SetString(PyExc_TypeError,
  5545. "The fill character must be exactly one character long");
  5546. Py_DECREF(uniobj);
  5547. return 0;
  5548. }
  5549. unistr = PyUnicode_AS_UNICODE(uniobj);
  5550. *fillcharloc = unistr[0];
  5551. Py_DECREF(uniobj);
  5552. return 1;
  5553. }
  5554. PyDoc_STRVAR(center__doc__,
  5555. "S.center(width[, fillchar]) -> unicode\n\
  5556. \n\
  5557. Return S centered in a Unicode string of length width. Padding is\n\
  5558. done using the specified fill character (default is a space)");
  5559. static PyObject *
  5560. unicode_center(PyUnicodeObject *self, PyObject *args)
  5561. {
  5562. Py_ssize_t marg, left;
  5563. Py_ssize_t width;
  5564. Py_UNICODE fillchar = ' ';
  5565. if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
  5566. return NULL;
  5567. if (self->length >= width && PyUnicode_CheckExact(self)) {
  5568. Py_INCREF(self);
  5569. return (PyObject*) self;
  5570. }
  5571. marg = width - self->length;
  5572. left = marg / 2 + (marg & width & 1);
  5573. return (PyObject*) pad(self, left, marg - left, fillchar);
  5574. }
  5575. #if 0
  5576. /* This code should go into some future Unicode collation support
  5577. module. The basic comparison should compare ordinals on a naive
  5578. basis (this is what Java does and thus JPython too). */
  5579. /* speedy UTF-16 code point order comparison */
  5580. /* gleaned from: */
  5581. /* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
  5582. static short utf16Fixup[32] =
  5583. {
  5584. 0, 0, 0, 0, 0, 0, 0, 0,
  5585. 0, 0, 0, 0, 0, 0, 0, 0,
  5586. 0, 0, 0, 0, 0, 0, 0, 0,
  5587. 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
  5588. };
  5589. static int
  5590. unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
  5591. {
  5592. Py_ssize_t len1, len2;
  5593. Py_UNICODE *s1 = str1->str;
  5594. Py_UNICODE *s2 = str2->str;
  5595. len1 = str1->length;
  5596. len2 = str2->length;
  5597. while (len1 > 0 && len2 > 0) {
  5598. Py_UNICODE c1, c2;
  5599. c1 = *s1++;
  5600. c2 = *s2++;
  5601. if (c1 > (1<<11) * 26)
  5602. c1 += utf16Fixup[c1>>11];
  5603. if (c2 > (1<<11) * 26)
  5604. c2 += utf16Fixup[c2>>11];
  5605. /* now c1 and c2 are in UTF-32-compatible order */
  5606. if (c1 != c2)
  5607. return (c1 < c2) ? -1 : 1;
  5608. len1--; len2--;
  5609. }
  5610. return (len1 < len2) ? -1 : (len1 != len2);
  5611. }
  5612. #else
  5613. static int
  5614. unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
  5615. {
  5616. register Py_ssize_t len1, len2;
  5617. Py_UNICODE *s1 = str1->str;
  5618. Py_UNICODE *s2 = str2->str;
  5619. len1 = str1->length;
  5620. len2 = str2->length;
  5621. while (len1 > 0 && len2 > 0) {
  5622. Py_UNICODE c1, c2;
  5623. c1 = *s1++;
  5624. c2 = *s2++;
  5625. if (c1 != c2)
  5626. return (c1 < c2) ? -1 : 1;
  5627. len1--; len2--;
  5628. }
  5629. return (len1 < len2) ? -1 : (len1 != len2);
  5630. }
  5631. #endif
  5632. int PyUnicode_Compare(PyObject *left,
  5633. PyObject *right)
  5634. {
  5635. PyUnicodeObject *u = NULL, *v = NULL;
  5636. int result;
  5637. /* Coerce the two arguments */
  5638. u = (PyUnicodeObject *)PyUnicode_FromObject(left);
  5639. if (u == NULL)
  5640. goto onError;
  5641. v = (PyUnicodeObject *)PyUnicode_FromObject(right);
  5642. if (v == NULL)
  5643. goto onError;
  5644. /* Shortcut for empty or interned objects */
  5645. if (v == u) {
  5646. Py_DECREF(u);
  5647. Py_DECREF(v);
  5648. return 0;
  5649. }
  5650. result = unicode_compare(u, v);
  5651. Py_DECREF(u);
  5652. Py_DECREF(v);
  5653. return result;
  5654. onError:
  5655. Py_XDECREF(u);
  5656. Py_XDECREF(v);
  5657. return -1;
  5658. }
  5659. PyObject *PyUnicode_RichCompare(PyObject *left,
  5660. PyObject *right,
  5661. int op)
  5662. {
  5663. int result;
  5664. result = PyUnicode_Compare(left, right);
  5665. if (result == -1 && PyErr_Occurred())
  5666. goto onError;
  5667. /* Convert the return value to a Boolean */
  5668. switch (op) {
  5669. case Py_EQ:
  5670. result = (result == 0);
  5671. break;
  5672. case Py_NE:
  5673. result = (result != 0);
  5674. break;
  5675. case Py_LE:
  5676. result = (result <= 0);
  5677. break;
  5678. case Py_GE:
  5679. result = (result >= 0);
  5680. break;
  5681. case Py_LT:
  5682. result = (result == -1);
  5683. break;
  5684. case Py_GT:
  5685. result = (result == 1);
  5686. break;
  5687. }
  5688. return PyBool_FromLong(result);
  5689. onError:
  5690. /* Standard case
  5691. Type errors mean that PyUnicode_FromObject() could not convert
  5692. one of the arguments (usually the right hand side) to Unicode,
  5693. ie. we can't handle the comparison request. However, it is
  5694. possible that the other object knows a comparison method, which
  5695. is why we return Py_NotImplemented to give the other object a
  5696. chance.
  5697. */
  5698. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  5699. PyErr_Clear();
  5700. Py_INCREF(Py_NotImplemented);
  5701. return Py_NotImplemented;
  5702. }
  5703. if (op != Py_EQ && op != Py_NE)
  5704. return NULL;
  5705. /* Equality comparison.
  5706. This is a special case: we silence any PyExc_UnicodeDecodeError
  5707. and instead turn it into a PyErr_UnicodeWarning.
  5708. */
  5709. if (!PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))
  5710. return NULL;
  5711. PyErr_Clear();
  5712. if (PyErr_Warn(PyExc_UnicodeWarning,
  5713. (op == Py_EQ) ?
  5714. "Unicode equal comparison "
  5715. "failed to convert both arguments to Unicode - "
  5716. "interpreting them as being unequal" :
  5717. "Unicode unequal comparison "
  5718. "failed to convert both arguments to Unicode - "
  5719. "interpreting them as being unequal"
  5720. ) < 0)
  5721. return NULL;
  5722. result = (op == Py_NE);
  5723. return PyBool_FromLong(result);
  5724. }
  5725. int PyUnicode_Contains(PyObject *container,
  5726. PyObject *element)
  5727. {
  5728. PyObject *str, *sub;
  5729. int result;
  5730. /* Coerce the two arguments */
  5731. sub = PyUnicode_FromObject(element);
  5732. if (!sub) {
  5733. PyErr_SetString(PyExc_TypeError,
  5734. "'in <string>' requires string as left operand");
  5735. return -1;
  5736. }
  5737. str = PyUnicode_FromObject(container);
  5738. if (!str) {
  5739. Py_DECREF(sub);
  5740. return -1;
  5741. }
  5742. result = stringlib_contains_obj(str, sub);
  5743. Py_DECREF(str);
  5744. Py_DECREF(sub);
  5745. return result;
  5746. }
  5747. /* Concat to string or Unicode object giving a new Unicode object. */
  5748. PyObject *PyUnicode_Concat(PyObject *left,
  5749. PyObject *right)
  5750. {
  5751. PyUnicodeObject *u = NULL, *v = NULL, *w;
  5752. /* Coerce the two arguments */
  5753. u = (PyUnicodeObject *)PyUnicode_FromObject(left);
  5754. if (u == NULL)
  5755. goto onError;
  5756. v = (PyUnicodeObject *)PyUnicode_FromObject(right);
  5757. if (v == NULL)
  5758. goto onError;
  5759. /* Shortcuts */
  5760. if (v == unicode_empty) {
  5761. Py_DECREF(v);
  5762. return (PyObject *)u;
  5763. }
  5764. if (u == unicode_empty) {
  5765. Py_DECREF(u);
  5766. return (PyObject *)v;
  5767. }
  5768. /* Concat the two Unicode strings */
  5769. w = _PyUnicode_New(u->length + v->length);
  5770. if (w == NULL)
  5771. goto onError;
  5772. Py_UNICODE_COPY(w->str, u->str, u->length);
  5773. Py_UNICODE_COPY(w->str + u->length, v->str, v->length);
  5774. Py_DECREF(u);
  5775. Py_DECREF(v);
  5776. return (PyObject *)w;
  5777. onError:
  5778. Py_XDECREF(u);
  5779. Py_XDECREF(v);
  5780. return NULL;
  5781. }
  5782. PyDoc_STRVAR(count__doc__,
  5783. "S.count(sub[, start[, end]]) -> int\n\
  5784. \n\
  5785. Return the number of non-overlapping occurrences of substring sub in\n\
  5786. Unicode string S[start:end]. Optional arguments start and end are\n\
  5787. interpreted as in slice notation.");
  5788. static PyObject *
  5789. unicode_count(PyUnicodeObject *self, PyObject *args)
  5790. {
  5791. PyUnicodeObject *substring;
  5792. Py_ssize_t start = 0;
  5793. Py_ssize_t end = PY_SSIZE_T_MAX;
  5794. PyObject *result;
  5795. if (!PyArg_ParseTuple(args, "O|O&O&:count", &substring,
  5796. _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
  5797. return NULL;
  5798. substring = (PyUnicodeObject *)PyUnicode_FromObject(
  5799. (PyObject *)substring);
  5800. if (substring == NULL)
  5801. return NULL;
  5802. FIX_START_END(self);
  5803. result = PyInt_FromSsize_t(
  5804. stringlib_count(self->str + start, end - start,
  5805. substring->str, substring->length)
  5806. );
  5807. Py_DECREF(substring);
  5808. return result;
  5809. }
  5810. PyDoc_STRVAR(encode__doc__,
  5811. "S.encode([encoding[,errors]]) -> string or unicode\n\
  5812. \n\
  5813. Encodes S using the codec registered for encoding. encoding defaults\n\
  5814. to the default encoding. errors may be given to set a different error\n\
  5815. handling scheme. Default is 'strict' meaning that encoding errors raise\n\
  5816. a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
  5817. 'xmlcharrefreplace' as well as any other name registered with\n\
  5818. codecs.register_error that can handle UnicodeEncodeErrors.");
  5819. static PyObject *
  5820. unicode_encode(PyUnicodeObject *self, PyObject *pyencoding, PyObject *pyerrors)
  5821. {
  5822. char *encoding = NULL;
  5823. char *errors = NULL;
  5824. PyObject *v;
  5825. if (pyencoding != NULL) {
  5826. if (!(PyString_Check(pyencoding) || PyUnicode_Check(pyencoding))) {
  5827. PyErr_Format(PyExc_TypeError,
  5828. "encode() argument 1 must be string, not %.200s",
  5829. Py_TYPE(pyencoding)->tp_name);
  5830. return NULL;
  5831. }
  5832. if (PyUnicode_Check(pyencoding)) {
  5833. pyencoding = _PyUnicode_AsDefaultEncodedString(pyencoding, NULL);
  5834. }
  5835. encoding = PyString_AS_STRING(pyencoding);
  5836. }
  5837. if (pyerrors != NULL) {
  5838. if (!(PyString_Check(pyerrors) || PyUnicode_Check(pyerrors))) {
  5839. PyErr_Format(PyExc_TypeError,
  5840. "encode() argument 2 must be string, not %.200s",
  5841. Py_TYPE(pyerrors)->tp_name);
  5842. return NULL;
  5843. }
  5844. if (PyUnicode_Check(pyerrors)) {
  5845. pyerrors = _PyUnicode_AsDefaultEncodedString(pyerrors, NULL);
  5846. }
  5847. errors = PyString_AS_STRING(pyerrors);
  5848. }
  5849. v = PyUnicode_AsEncodedObject((PyObject *)self, encoding, errors);
  5850. if (v == NULL)
  5851. goto onError;
  5852. if (!PyString_Check(v) && !PyUnicode_Check(v)) {
  5853. PyErr_Format(PyExc_TypeError,
  5854. "encoder did not return a string/unicode object "
  5855. "(type=%.400s)",
  5856. Py_TYPE(v)->tp_name);
  5857. Py_DECREF(v);
  5858. return NULL;
  5859. }
  5860. return v;
  5861. onError:
  5862. return NULL;
  5863. }
  5864. PyDoc_STRVAR(decode__doc__,
  5865. "S.decode([encoding[,errors]]) -> string or unicode\n\
  5866. \n\
  5867. Decodes S using the codec registered for encoding. encoding defaults\n\
  5868. to the default encoding. errors may be given to set a different error\n\
  5869. handling scheme. Default is 'strict' meaning that encoding errors raise\n\
  5870. a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
  5871. as well as any other name registerd with codecs.register_error that is\n\
  5872. able to handle UnicodeDecodeErrors.");
  5873. static PyObject *
  5874. unicode_decode(PyUnicodeObject *self, PyObject *args)
  5875. {
  5876. char *encoding = NULL;
  5877. char *errors = NULL;
  5878. PyObject *v;
  5879. if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
  5880. return NULL;
  5881. v = PyUnicode_AsDecodedObject((PyObject *)self, encoding, errors);
  5882. if (v == NULL)
  5883. goto onError;
  5884. if (!PyString_Check(v) && !PyUnicode_Check(v)) {
  5885. PyErr_Format(PyExc_TypeError,
  5886. "decoder did not return a string/unicode object "
  5887. "(type=%.400s)",
  5888. Py_TYPE(v)->tp_name);
  5889. Py_DECREF(v);
  5890. return NULL;
  5891. }
  5892. return v;
  5893. onError:
  5894. return NULL;
  5895. }
  5896. PyDoc_STRVAR(expandtabs__doc__,
  5897. "S.expandtabs([tabsize]) -> unicode\n\
  5898. \n\
  5899. Return a copy of S where all tab characters are expanded using spaces.\n\
  5900. If tabsize is not given, a tab size of 8 characters is assumed.");
  5901. static PyObject*
  5902. unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
  5903. {
  5904. Py_UNICODE *e;
  5905. Py_UNICODE *p;
  5906. Py_UNICODE *q;
  5907. Py_UNICODE *qe;
  5908. Py_ssize_t i, j, incr;
  5909. PyUnicodeObject *u;
  5910. int tabsize = 8;
  5911. if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
  5912. return NULL;
  5913. /* First pass: determine size of output string */
  5914. i = 0; /* chars up to and including most recent \n or \r */
  5915. j = 0; /* chars since most recent \n or \r (use in tab calculations) */
  5916. e = self->str + self->length; /* end of input */
  5917. for (p = self->str; p < e; p++)
  5918. if (*p == '\t') {
  5919. if (tabsize > 0) {
  5920. incr = tabsize - (j % tabsize); /* cannot overflow */
  5921. if (j > PY_SSIZE_T_MAX - incr)
  5922. goto overflow1;
  5923. j += incr;
  5924. }
  5925. }
  5926. else {
  5927. if (j > PY_SSIZE_T_MAX - 1)
  5928. goto overflow1;
  5929. j++;
  5930. if (*p == '\n' || *p == '\r') {
  5931. if (i > PY_SSIZE_T_MAX - j)
  5932. goto overflow1;
  5933. i += j;
  5934. j = 0;
  5935. }
  5936. }
  5937. if (i > PY_SSIZE_T_MAX - j)
  5938. goto overflow1;
  5939. /* Second pass: create output string and fill it */
  5940. u = _PyUnicode_New(i + j);
  5941. if (!u)
  5942. return NULL;
  5943. j = 0; /* same as in first pass */
  5944. q = u->str; /* next output char */
  5945. qe = u->str + u->length; /* end of output */
  5946. for (p = self->str; p < e; p++)
  5947. if (*p == '\t') {
  5948. if (tabsize > 0) {
  5949. i = tabsize - (j % tabsize);
  5950. j += i;
  5951. while (i--) {
  5952. if (q >= qe)
  5953. goto overflow2;
  5954. *q++ = ' ';
  5955. }
  5956. }
  5957. }
  5958. else {
  5959. if (q >= qe)
  5960. goto overflow2;
  5961. *q++ = *p;
  5962. j++;
  5963. if (*p == '\n' || *p == '\r')
  5964. j = 0;
  5965. }
  5966. return (PyObject*) u;
  5967. overflow2:
  5968. Py_DECREF(u);
  5969. overflow1:
  5970. PyErr_SetString(PyExc_OverflowError, "new string is too long");
  5971. return NULL;
  5972. }
  5973. PyDoc_STRVAR(find__doc__,
  5974. "S.find(sub [,start [,end]]) -> int\n\
  5975. \n\
  5976. Return the lowest index in S where substring sub is found,\n\
  5977. such that sub is contained within s[start:end]. Optional\n\
  5978. arguments start and end are interpreted as in slice notation.\n\
  5979. \n\
  5980. Return -1 on failure.");
  5981. static PyObject *
  5982. unicode_find(PyUnicodeObject *self, PyObject *args)
  5983. {
  5984. PyObject *substring;
  5985. Py_ssize_t start;
  5986. Py_ssize_t end;
  5987. Py_ssize_t result;
  5988. if (!_ParseTupleFinds(args, &substring, &start, &end))
  5989. return NULL;
  5990. result = stringlib_find_slice(
  5991. PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
  5992. PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
  5993. start, end
  5994. );
  5995. Py_DECREF(substring);
  5996. return PyInt_FromSsize_t(result);
  5997. }
  5998. static PyObject *
  5999. unicode_getitem(PyUnicodeObject *self, Py_ssize_t index)
  6000. {
  6001. if (index < 0 || index >= self->length) {
  6002. PyErr_SetString(PyExc_IndexError, "string index out of range");
  6003. return NULL;
  6004. }
  6005. return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1);
  6006. }
  6007. static long
  6008. unicode_hash(PyUnicodeObject *self)
  6009. {
  6010. /* Since Unicode objects compare equal to their ASCII string
  6011. counterparts, they should use the individual character values
  6012. as basis for their hash value. This is needed to assure that
  6013. strings and Unicode objects behave in the same way as
  6014. dictionary keys. */
  6015. register Py_ssize_t len;
  6016. register Py_UNICODE *p;
  6017. register long x;
  6018. if (self->hash != -1)
  6019. return self->hash;
  6020. len = PyUnicode_GET_SIZE(self);
  6021. p = PyUnicode_AS_UNICODE(self);
  6022. x = *p << 7;
  6023. while (--len >= 0)
  6024. x = (1000003*x) ^ *p++;
  6025. x ^= PyUnicode_GET_SIZE(self);
  6026. if (x == -1)
  6027. x = -2;
  6028. self->hash = x;
  6029. return x;
  6030. }
  6031. PyDoc_STRVAR(index__doc__,
  6032. "S.index(sub [,start [,end]]) -> int\n\
  6033. \n\
  6034. Like S.find() but raise ValueError when the substring is not found.");
  6035. static PyObject *
  6036. unicode_index(PyUnicodeObject *self, PyObject *args)
  6037. {
  6038. Py_ssize_t result;
  6039. PyObject *substring;
  6040. Py_ssize_t start;
  6041. Py_ssize_t end;
  6042. if (!_ParseTupleFinds(args, &substring, &start, &end))
  6043. return NULL;
  6044. result = stringlib_find_slice(
  6045. PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
  6046. PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
  6047. start, end
  6048. );
  6049. Py_DECREF(substring);
  6050. if (result < 0) {
  6051. PyErr_SetString(PyExc_ValueError, "substring not found");
  6052. return NULL;
  6053. }
  6054. return PyInt_FromSsize_t(result);
  6055. }
  6056. PyDoc_STRVAR(islower__doc__,
  6057. "S.islower() -> bool\n\
  6058. \n\
  6059. Return True if all cased characters in S are lowercase and there is\n\
  6060. at least one cased character in S, False otherwise.");
  6061. static PyObject*
  6062. unicode_islower(PyUnicodeObject *self)
  6063. {
  6064. register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
  6065. register const Py_UNICODE *e;
  6066. int cased;
  6067. /* Shortcut for single character strings */
  6068. if (PyUnicode_GET_SIZE(self) == 1)
  6069. return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
  6070. /* Special case for empty strings */
  6071. if (PyUnicode_GET_SIZE(self) == 0)
  6072. return PyBool_FromLong(0);
  6073. e = p + PyUnicode_GET_SIZE(self);
  6074. cased = 0;
  6075. for (; p < e; p++) {
  6076. register const Py_UNICODE ch = *p;
  6077. if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
  6078. return PyBool_FromLong(0);
  6079. else if (!cased && Py_UNICODE_ISLOWER(ch))
  6080. cased = 1;
  6081. }
  6082. return PyBool_FromLong(cased);
  6083. }
  6084. PyDoc_STRVAR(isupper__doc__,
  6085. "S.isupper() -> bool\n\
  6086. \n\
  6087. Return True if all cased characters in S are uppercase and there is\n\
  6088. at least one cased character in S, False otherwise.");
  6089. static PyObject*
  6090. unicode_isupper(PyUnicodeObject *self)
  6091. {
  6092. register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
  6093. register const Py_UNICODE *e;
  6094. int cased;
  6095. /* Shortcut for single character strings */
  6096. if (PyUnicode_GET_SIZE(self) == 1)
  6097. return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
  6098. /* Special case for empty strings */
  6099. if (PyUnicode_GET_SIZE(self) == 0)
  6100. return PyBool_FromLong(0);
  6101. e = p + PyUnicode_GET_SIZE(self);
  6102. cased = 0;
  6103. for (; p < e; p++) {
  6104. register const Py_UNICODE ch = *p;
  6105. if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
  6106. return PyBool_FromLong(0);
  6107. else if (!cased && Py_UNICODE_ISUPPER(ch))
  6108. cased = 1;
  6109. }
  6110. return PyBool_FromLong(cased);
  6111. }
  6112. PyDoc_STRVAR(istitle__doc__,
  6113. "S.istitle() -> bool\n\
  6114. \n\
  6115. Return True if S is a titlecased string and there is at least one\n\
  6116. character in S, i.e. upper- and titlecase characters may only\n\
  6117. follow uncased characters and lowercase characters only cased ones.\n\
  6118. Return False otherwise.");
  6119. static PyObject*
  6120. unicode_istitle(PyUnicodeObject *self)
  6121. {
  6122. register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
  6123. register const Py_UNICODE *e;
  6124. int cased, previous_is_cased;
  6125. /* Shortcut for single character strings */
  6126. if (PyUnicode_GET_SIZE(self) == 1)
  6127. return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
  6128. (Py_UNICODE_ISUPPER(*p) != 0));
  6129. /* Special case for empty strings */
  6130. if (PyUnicode_GET_SIZE(self) == 0)
  6131. return PyBool_FromLong(0);
  6132. e = p + PyUnicode_GET_SIZE(self);
  6133. cased = 0;
  6134. previous_is_cased = 0;
  6135. for (; p < e; p++) {
  6136. register const Py_UNICODE ch = *p;
  6137. if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
  6138. if (previous_is_cased)
  6139. return PyBool_FromLong(0);
  6140. previous_is_cased = 1;
  6141. cased = 1;
  6142. }
  6143. else if (Py_UNICODE_ISLOWER(ch)) {
  6144. if (!previous_is_cased)
  6145. return PyBool_FromLong(0);
  6146. previous_is_cased = 1;
  6147. cased = 1;
  6148. }
  6149. else
  6150. previous_is_cased = 0;
  6151. }
  6152. return PyBool_FromLong(cased);
  6153. }
  6154. PyDoc_STRVAR(isspace__doc__,
  6155. "S.isspace() -> bool\n\
  6156. \n\
  6157. Return True if all characters in S are whitespace\n\
  6158. and there is at least one character in S, False otherwise.");
  6159. static PyObject*
  6160. unicode_isspace(PyUnicodeObject *self)
  6161. {
  6162. register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
  6163. register const Py_UNICODE *e;
  6164. /* Shortcut for single character strings */
  6165. if (PyUnicode_GET_SIZE(self) == 1 &&
  6166. Py_UNICODE_ISSPACE(*p))
  6167. return PyBool_FromLong(1);
  6168. /* Special case for empty strings */
  6169. if (PyUnicode_GET_SIZE(self) == 0)
  6170. return PyBool_FromLong(0);
  6171. e = p + PyUnicode_GET_SIZE(self);
  6172. for (; p < e; p++) {
  6173. if (!Py_UNICODE_ISSPACE(*p))
  6174. return PyBool_FromLong(0);
  6175. }
  6176. return PyBool_FromLong(1);
  6177. }
  6178. PyDoc_STRVAR(isalpha__doc__,
  6179. "S.isalpha() -> bool\n\
  6180. \n\
  6181. Return True if all characters in S are alphabetic\n\
  6182. and there is at least one character in S, False otherwise.");
  6183. static PyObject*
  6184. unicode_isalpha(PyUnicodeObject *self)
  6185. {
  6186. register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
  6187. register const Py_UNICODE *e;
  6188. /* Shortcut for single character strings */
  6189. if (PyUnicode_GET_SIZE(self) == 1 &&
  6190. Py_UNICODE_ISALPHA(*p))
  6191. return PyBool_FromLong(1);
  6192. /* Special case for empty strings */
  6193. if (PyUnicode_GET_SIZE(self) == 0)
  6194. return PyBool_FromLong(0);
  6195. e = p + PyUnicode_GET_SIZE(self);
  6196. for (; p < e; p++) {
  6197. if (!Py_UNICODE_ISALPHA(*p))
  6198. return PyBool_FromLong(0);
  6199. }
  6200. return PyBool_FromLong(1);
  6201. }
  6202. PyDoc_STRVAR(isalnum__doc__,
  6203. "S.isalnum() -> bool\n\
  6204. \n\
  6205. Return True if all characters in S are alphanumeric\n\
  6206. and there is at least one character in S, False otherwise.");
  6207. static PyObject*
  6208. unicode_isalnum(PyUnicodeObject *self)
  6209. {
  6210. register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
  6211. register const Py_UNICODE *e;
  6212. /* Shortcut for single character strings */
  6213. if (PyUnicode_GET_SIZE(self) == 1 &&
  6214. Py_UNICODE_ISALNUM(*p))
  6215. return PyBool_FromLong(1);
  6216. /* Special case for empty strings */
  6217. if (PyUnicode_GET_SIZE(self) == 0)
  6218. return PyBool_FromLong(0);
  6219. e = p + PyUnicode_GET_SIZE(self);
  6220. for (; p < e; p++) {
  6221. if (!Py_UNICODE_ISALNUM(*p))
  6222. return PyBool_FromLong(0);
  6223. }
  6224. return PyBool_FromLong(1);
  6225. }
  6226. PyDoc_STRVAR(isdecimal__doc__,
  6227. "S.isdecimal() -> bool\n\
  6228. \n\
  6229. Return True if there are only decimal characters in S,\n\
  6230. False otherwise.");
  6231. static PyObject*
  6232. unicode_isdecimal(PyUnicodeObject *self)
  6233. {
  6234. register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
  6235. register const Py_UNICODE *e;
  6236. /* Shortcut for single character strings */
  6237. if (PyUnicode_GET_SIZE(self) == 1 &&
  6238. Py_UNICODE_ISDECIMAL(*p))
  6239. return PyBool_FromLong(1);
  6240. /* Special case for empty strings */
  6241. if (PyUnicode_GET_SIZE(self) == 0)
  6242. return PyBool_FromLong(0);
  6243. e = p + PyUnicode_GET_SIZE(self);
  6244. for (; p < e; p++) {
  6245. if (!Py_UNICODE_ISDECIMAL(*p))
  6246. return PyBool_FromLong(0);
  6247. }
  6248. return PyBool_FromLong(1);
  6249. }
  6250. PyDoc_STRVAR(isdigit__doc__,
  6251. "S.isdigit() -> bool\n\
  6252. \n\
  6253. Return True if all characters in S are digits\n\
  6254. and there is at least one character in S, False otherwise.");
  6255. static PyObject*
  6256. unicode_isdigit(PyUnicodeObject *self)
  6257. {
  6258. register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
  6259. register const Py_UNICODE *e;
  6260. /* Shortcut for single character strings */
  6261. if (PyUnicode_GET_SIZE(self) == 1 &&
  6262. Py_UNICODE_ISDIGIT(*p))
  6263. return PyBool_FromLong(1);
  6264. /* Special case for empty strings */
  6265. if (PyUnicode_GET_SIZE(self) == 0)
  6266. return PyBool_FromLong(0);
  6267. e = p + PyUnicode_GET_SIZE(self);
  6268. for (; p < e; p++) {
  6269. if (!Py_UNICODE_ISDIGIT(*p))
  6270. return PyBool_FromLong(0);
  6271. }
  6272. return PyBool_FromLong(1);
  6273. }
  6274. PyDoc_STRVAR(isnumeric__doc__,
  6275. "S.isnumeric() -> bool\n\
  6276. \n\
  6277. Return True if there are only numeric characters in S,\n\
  6278. False otherwise.");
  6279. static PyObject*
  6280. unicode_isnumeric(PyUnicodeObject *self)
  6281. {
  6282. register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
  6283. register const Py_UNICODE *e;
  6284. /* Shortcut for single character strings */
  6285. if (PyUnicode_GET_SIZE(self) == 1 &&
  6286. Py_UNICODE_ISNUMERIC(*p))
  6287. return PyBool_FromLong(1);
  6288. /* Special case for empty strings */
  6289. if (PyUnicode_GET_SIZE(self) == 0)
  6290. return PyBool_FromLong(0);
  6291. e = p + PyUnicode_GET_SIZE(self);
  6292. for (; p < e; p++) {
  6293. if (!Py_UNICODE_ISNUMERIC(*p))
  6294. return PyBool_FromLong(0);
  6295. }
  6296. return PyBool_FromLong(1);
  6297. }
  6298. PyDoc_STRVAR(join__doc__,
  6299. "S.join(sequence) -> unicode\n\
  6300. \n\
  6301. Return a string which is the concatenation of the strings in the\n\
  6302. sequence. The separator between elements is S.");
  6303. static PyObject*
  6304. unicode_join(PyObject *self, PyObject *data)
  6305. {
  6306. return PyUnicode_Join(self, data);
  6307. }
  6308. static Py_ssize_t
  6309. unicode_length(PyUnicodeObject *self)
  6310. {
  6311. return self->length;
  6312. }
  6313. PyDoc_STRVAR(ljust__doc__,
  6314. "S.ljust(width[, fillchar]) -> int\n\
  6315. \n\
  6316. Return S left-justified in a Unicode string of length width. Padding is\n\
  6317. done using the specified fill character (default is a space).");
  6318. static PyObject *
  6319. unicode_ljust(PyUnicodeObject *self, PyObject *args)
  6320. {
  6321. Py_ssize_t width;
  6322. Py_UNICODE fillchar = ' ';
  6323. if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
  6324. return NULL;
  6325. if (self->length >= width && PyUnicode_CheckExact(self)) {
  6326. Py_INCREF(self);
  6327. return (PyObject*) self;
  6328. }
  6329. return (PyObject*) pad(self, 0, width - self->length, fillchar);
  6330. }
  6331. PyDoc_STRVAR(lower__doc__,
  6332. "S.lower() -> unicode\n\
  6333. \n\
  6334. Return a copy of the string S converted to lowercase.");
  6335. static PyObject*
  6336. unicode_lower(PyUnicodeObject *self)
  6337. {
  6338. return fixup(self, fixlower);
  6339. }
  6340. #define LEFTSTRIP 0
  6341. #define RIGHTSTRIP 1
  6342. #define BOTHSTRIP 2
  6343. /* Arrays indexed by above */
  6344. static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
  6345. #define STRIPNAME(i) (stripformat[i]+3)
  6346. /* externally visible for str.strip(unicode) */
  6347. PyObject *
  6348. _PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
  6349. {
  6350. Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
  6351. Py_ssize_t len = PyUnicode_GET_SIZE(self);
  6352. Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
  6353. Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj);
  6354. Py_ssize_t i, j;
  6355. BLOOM_MASK sepmask = make_bloom_mask(sep, seplen);
  6356. i = 0;
  6357. if (striptype != RIGHTSTRIP) {
  6358. while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) {
  6359. i++;
  6360. }
  6361. }
  6362. j = len;
  6363. if (striptype != LEFTSTRIP) {
  6364. do {
  6365. j--;
  6366. } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen));
  6367. j++;
  6368. }
  6369. if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
  6370. Py_INCREF(self);
  6371. return (PyObject*)self;
  6372. }
  6373. else
  6374. return PyUnicode_FromUnicode(s+i, j-i);
  6375. }
  6376. static PyObject *
  6377. do_strip(PyUnicodeObject *self, int striptype)
  6378. {
  6379. Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
  6380. Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j;
  6381. i = 0;
  6382. if (striptype != RIGHTSTRIP) {
  6383. while (i < len && Py_UNICODE_ISSPACE(s[i])) {
  6384. i++;
  6385. }
  6386. }
  6387. j = len;
  6388. if (striptype != LEFTSTRIP) {
  6389. do {
  6390. j--;
  6391. } while (j >= i && Py_UNICODE_ISSPACE(s[j]));
  6392. j++;
  6393. }
  6394. if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
  6395. Py_INCREF(self);
  6396. return (PyObject*)self;
  6397. }
  6398. else
  6399. return PyUnicode_FromUnicode(s+i, j-i);
  6400. }
  6401. static PyObject *
  6402. do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
  6403. {
  6404. PyObject *sep = NULL;
  6405. if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
  6406. return NULL;
  6407. if (sep != NULL && sep != Py_None) {
  6408. if (PyUnicode_Check(sep))
  6409. return _PyUnicode_XStrip(self, striptype, sep);
  6410. else if (PyString_Check(sep)) {
  6411. PyObject *res;
  6412. sep = PyUnicode_FromObject(sep);
  6413. if (sep==NULL)
  6414. return NULL;
  6415. res = _PyUnicode_XStrip(self, striptype, sep);
  6416. Py_DECREF(sep);
  6417. return res;
  6418. }
  6419. else {
  6420. PyErr_Format(PyExc_TypeError,
  6421. "%s arg must be None, unicode or str",
  6422. STRIPNAME(striptype));
  6423. return NULL;
  6424. }
  6425. }
  6426. return do_strip(self, striptype);
  6427. }
  6428. PyDoc_STRVAR(strip__doc__,
  6429. "S.strip([chars]) -> unicode\n\
  6430. \n\
  6431. Return a copy of the string S with leading and trailing\n\
  6432. whitespace removed.\n\
  6433. If chars is given and not None, remove characters in chars instead.\n\
  6434. If chars is a str, it will be converted to unicode before stripping");
  6435. static PyObject *
  6436. unicode_strip(PyUnicodeObject *self, PyObject *args)
  6437. {
  6438. if (PyTuple_GET_SIZE(args) == 0)
  6439. return do_strip(self, BOTHSTRIP); /* Common case */
  6440. else
  6441. return do_argstrip(self, BOTHSTRIP, args);
  6442. }
  6443. PyDoc_STRVAR(lstrip__doc__,
  6444. "S.lstrip([chars]) -> unicode\n\
  6445. \n\
  6446. Return a copy of the string S with leading whitespace removed.\n\
  6447. If chars is given and not None, remove characters in chars instead.\n\
  6448. If chars is a str, it will be converted to unicode before stripping");
  6449. static PyObject *
  6450. unicode_lstrip(PyUnicodeObject *self, PyObject *args)
  6451. {
  6452. if (PyTuple_GET_SIZE(args) == 0)
  6453. return do_strip(self, LEFTSTRIP); /* Common case */
  6454. else
  6455. return do_argstrip(self, LEFTSTRIP, args);
  6456. }
  6457. PyDoc_STRVAR(rstrip__doc__,
  6458. "S.rstrip([chars]) -> unicode\n\
  6459. \n\
  6460. Return a copy of the string S with trailing whitespace removed.\n\
  6461. If chars is given and not None, remove characters in chars instead.\n\
  6462. If chars is a str, it will be converted to unicode before stripping");
  6463. static PyObject *
  6464. unicode_rstrip(PyUnicodeObject *self, PyObject *args)
  6465. {
  6466. if (PyTuple_GET_SIZE(args) == 0)
  6467. return do_strip(self, RIGHTSTRIP); /* Common case */
  6468. else
  6469. return do_argstrip(self, RIGHTSTRIP, args);
  6470. }
  6471. static PyObject*
  6472. unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
  6473. {
  6474. PyUnicodeObject *u;
  6475. Py_UNICODE *p;
  6476. Py_ssize_t nchars;
  6477. size_t nbytes;
  6478. if (len < 0)
  6479. len = 0;
  6480. if (len == 1 && PyUnicode_CheckExact(str)) {
  6481. /* no repeat, return original string */
  6482. Py_INCREF(str);
  6483. return (PyObject*) str;
  6484. }
  6485. /* ensure # of chars needed doesn't overflow int and # of bytes
  6486. * needed doesn't overflow size_t
  6487. */
  6488. nchars = len * str->length;
  6489. if (len && nchars / len != str->length) {
  6490. PyErr_SetString(PyExc_OverflowError,
  6491. "repeated string is too long");
  6492. return NULL;
  6493. }
  6494. nbytes = (nchars + 1) * sizeof(Py_UNICODE);
  6495. if (nbytes / sizeof(Py_UNICODE) != (size_t)(nchars + 1)) {
  6496. PyErr_SetString(PyExc_OverflowError,
  6497. "repeated string is too long");
  6498. return NULL;
  6499. }
  6500. u = _PyUnicode_New(nchars);
  6501. if (!u)
  6502. return NULL;
  6503. p = u->str;
  6504. if (str->length == 1 && len > 0) {
  6505. Py_UNICODE_FILL(p, str->str[0], len);
  6506. } else {
  6507. Py_ssize_t done = 0; /* number of characters copied this far */
  6508. if (done < nchars) {
  6509. Py_UNICODE_COPY(p, str->str, str->length);
  6510. done = str->length;
  6511. }
  6512. while (done < nchars) {
  6513. Py_ssize_t n = (done <= nchars-done) ? done : nchars-done;
  6514. Py_UNICODE_COPY(p+done, p, n);
  6515. done += n;
  6516. }
  6517. }
  6518. return (PyObject*) u;
  6519. }
  6520. PyObject *PyUnicode_Replace(PyObject *obj,
  6521. PyObject *subobj,
  6522. PyObject *replobj,
  6523. Py_ssize_t maxcount)
  6524. {
  6525. PyObject *self;
  6526. PyObject *str1;
  6527. PyObject *str2;
  6528. PyObject *result;
  6529. self = PyUnicode_FromObject(obj);
  6530. if (self == NULL)
  6531. return NULL;
  6532. str1 = PyUnicode_FromObject(subobj);
  6533. if (str1 == NULL) {
  6534. Py_DECREF(self);
  6535. return NULL;
  6536. }
  6537. str2 = PyUnicode_FromObject(replobj);
  6538. if (str2 == NULL) {
  6539. Py_DECREF(self);
  6540. Py_DECREF(str1);
  6541. return NULL;
  6542. }
  6543. result = replace((PyUnicodeObject *)self,
  6544. (PyUnicodeObject *)str1,
  6545. (PyUnicodeObject *)str2,
  6546. maxcount);
  6547. Py_DECREF(self);
  6548. Py_DECREF(str1);
  6549. Py_DECREF(str2);
  6550. return result;
  6551. }
  6552. PyDoc_STRVAR(replace__doc__,
  6553. "S.replace (old, new[, count]) -> unicode\n\
  6554. \n\
  6555. Return a copy of S with all occurrences of substring\n\
  6556. old replaced by new. If the optional argument count is\n\
  6557. given, only the first count occurrences are replaced.");
  6558. static PyObject*
  6559. unicode_replace(PyUnicodeObject *self, PyObject *old, PyObject *new,
  6560. PyObject *count)
  6561. {
  6562. PyUnicodeObject *str1;
  6563. PyUnicodeObject *str2;
  6564. Py_ssize_t maxcount = -1;
  6565. PyObject *result;
  6566. str1 = (PyUnicodeObject *)PyUnicode_FromObject(old);
  6567. if (str1 == NULL)
  6568. return NULL;
  6569. str2 = (PyUnicodeObject *)PyUnicode_FromObject(new);
  6570. if (str2 == NULL) {
  6571. Py_DECREF(str1);
  6572. return NULL;
  6573. }
  6574. if (count != NULL) {
  6575. maxcount = PyInt_AsSsize_t(count);
  6576. if (maxcount == -1 && PyErr_Occurred()) {
  6577. Py_DECREF(str1);
  6578. Py_DECREF(str2);
  6579. PyErr_Format(PyExc_TypeError, "an integer is required");
  6580. return NULL;
  6581. }
  6582. }
  6583. result = replace(self, str1, str2, maxcount);
  6584. Py_DECREF(str1);
  6585. Py_DECREF(str2);
  6586. return result;
  6587. }
  6588. static
  6589. PyObject *unicode_repr(PyObject *unicode)
  6590. {
  6591. return unicodeescape_string(PyUnicode_AS_UNICODE(unicode),
  6592. PyUnicode_GET_SIZE(unicode),
  6593. 1);
  6594. }
  6595. PyDoc_STRVAR(rfind__doc__,
  6596. "S.rfind(sub [,start [,end]]) -> int\n\
  6597. \n\
  6598. Return the highest index in S where substring sub is found,\n\
  6599. such that sub is contained within s[start:end]. Optional\n\
  6600. arguments start and end are interpreted as in slice notation.\n\
  6601. \n\
  6602. Return -1 on failure.");
  6603. static PyObject *
  6604. unicode_rfind(PyUnicodeObject *self, PyObject *args)
  6605. {
  6606. PyObject *substring;
  6607. Py_ssize_t start;
  6608. Py_ssize_t end;
  6609. Py_ssize_t result;
  6610. if (!_ParseTupleFinds(args, &substring, &start, &end))
  6611. return NULL;
  6612. result = stringlib_rfind_slice(
  6613. PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
  6614. PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
  6615. start, end
  6616. );
  6617. Py_DECREF(substring);
  6618. return PyInt_FromSsize_t(result);
  6619. }
  6620. PyDoc_STRVAR(rindex__doc__,
  6621. "S.rindex(sub [,start [,end]]) -> int\n\
  6622. \n\
  6623. Like S.rfind() but raise ValueError when the substring is not found.");
  6624. static PyObject *
  6625. unicode_rindex(PyUnicodeObject *self, PyObject *args)
  6626. {
  6627. PyObject *substring;
  6628. Py_ssize_t start;
  6629. Py_ssize_t end;
  6630. Py_ssize_t result;
  6631. if (!_ParseTupleFinds(args, &substring, &start, &end))
  6632. return NULL;
  6633. result = stringlib_rfind_slice(
  6634. PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
  6635. PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
  6636. start, end
  6637. );
  6638. Py_DECREF(substring);
  6639. if (result < 0) {
  6640. PyErr_SetString(PyExc_ValueError, "substring not found");
  6641. return NULL;
  6642. }
  6643. return PyInt_FromSsize_t(result);
  6644. }
  6645. PyDoc_STRVAR(rjust__doc__,
  6646. "S.rjust(width[, fillchar]) -> unicode\n\
  6647. \n\
  6648. Return S right-justified in a Unicode string of length width. Padding is\n\
  6649. done using the specified fill character (default is a space).");
  6650. static PyObject *
  6651. unicode_rjust(PyUnicodeObject *self, PyObject *args)
  6652. {
  6653. Py_ssize_t width;
  6654. Py_UNICODE fillchar = ' ';
  6655. if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
  6656. return NULL;
  6657. if (self->length >= width && PyUnicode_CheckExact(self)) {
  6658. Py_INCREF(self);
  6659. return (PyObject*) self;
  6660. }
  6661. return (PyObject*) pad(self, width - self->length, 0, fillchar);
  6662. }
  6663. static PyObject*
  6664. unicode_slice(PyUnicodeObject *self, Py_ssize_t start, Py_ssize_t end)
  6665. {
  6666. /* standard clamping */
  6667. if (start < 0)
  6668. start = 0;
  6669. if (end < 0)
  6670. end = 0;
  6671. if (end > self->length)
  6672. end = self->length;
  6673. if (start == 0 && end == self->length && PyUnicode_CheckExact(self)) {
  6674. /* full slice, return original string */
  6675. Py_INCREF(self);
  6676. return (PyObject*) self;
  6677. }
  6678. if (start > end)
  6679. start = end;
  6680. /* copy slice */
  6681. return (PyObject*) PyUnicode_FromUnicode(self->str + start,
  6682. end - start);
  6683. }
  6684. PyObject *PyUnicode_Split(PyObject *s,
  6685. PyObject *sep,
  6686. Py_ssize_t maxsplit)
  6687. {
  6688. PyObject *result;
  6689. s = PyUnicode_FromObject(s);
  6690. if (s == NULL)
  6691. return NULL;
  6692. if (sep != NULL) {
  6693. sep = PyUnicode_FromObject(sep);
  6694. if (sep == NULL) {
  6695. Py_DECREF(s);
  6696. return NULL;
  6697. }
  6698. }
  6699. result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
  6700. Py_DECREF(s);
  6701. Py_XDECREF(sep);
  6702. return result;
  6703. }
  6704. PyDoc_STRVAR(split__doc__,
  6705. "S.split([sep [,maxsplit]]) -> list of strings\n\
  6706. \n\
  6707. Return a list of the words in S, using sep as the\n\
  6708. delimiter string. If maxsplit is given, at most maxsplit\n\
  6709. splits are done. If sep is not specified or is None, any\n\
  6710. whitespace string is a separator and empty strings are\n\
  6711. removed from the result.");
  6712. static PyObject*
  6713. unicode_split(PyUnicodeObject *self, PyObject *args)
  6714. {
  6715. PyObject *substring = Py_None;
  6716. Py_ssize_t maxcount = -1;
  6717. if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
  6718. return NULL;
  6719. if (substring == Py_None)
  6720. return split(self, NULL, maxcount);
  6721. else if (PyUnicode_Check(substring))
  6722. return split(self, (PyUnicodeObject *)substring, maxcount);
  6723. else
  6724. return PyUnicode_Split((PyObject *)self, substring, maxcount);
  6725. }
  6726. PyObject *
  6727. PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
  6728. {
  6729. PyObject* str_obj;
  6730. PyObject* sep_obj;
  6731. PyObject* out;
  6732. str_obj = PyUnicode_FromObject(str_in);
  6733. if (!str_obj)
  6734. return NULL;
  6735. sep_obj = PyUnicode_FromObject(sep_in);
  6736. if (!sep_obj) {
  6737. Py_DECREF(str_obj);
  6738. return NULL;
  6739. }
  6740. out = stringlib_partition(
  6741. str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
  6742. sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
  6743. );
  6744. Py_DECREF(sep_obj);
  6745. Py_DECREF(str_obj);
  6746. return out;
  6747. }
  6748. PyObject *
  6749. PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
  6750. {
  6751. PyObject* str_obj;
  6752. PyObject* sep_obj;
  6753. PyObject* out;
  6754. str_obj = PyUnicode_FromObject(str_in);
  6755. if (!str_obj)
  6756. return NULL;
  6757. sep_obj = PyUnicode_FromObject(sep_in);
  6758. if (!sep_obj) {
  6759. Py_DECREF(str_obj);
  6760. return NULL;
  6761. }
  6762. out = stringlib_rpartition(
  6763. str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
  6764. sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
  6765. );
  6766. Py_DECREF(sep_obj);
  6767. Py_DECREF(str_obj);
  6768. return out;
  6769. }
  6770. PyDoc_STRVAR(partition__doc__,
  6771. "S.partition(sep) -> (head, sep, tail)\n\
  6772. \n\
  6773. Search for the separator sep in S, and return the part before it,\n\
  6774. the separator itself, and the part after it. If the separator is not\n\
  6775. found, return S and two empty strings.");
  6776. static PyObject*
  6777. unicode_partition(PyUnicodeObject *self, PyObject *separator)
  6778. {
  6779. return PyUnicode_Partition((PyObject *)self, separator);
  6780. }
  6781. PyDoc_STRVAR(rpartition__doc__,
  6782. "S.rpartition(sep) -> (tail, sep, head)\n\
  6783. \n\
  6784. Search for the separator sep in S, starting at the end of S, and return\n\
  6785. the part before it, the separator itself, and the part after it. If the\n\
  6786. separator is not found, return two empty strings and S.");
  6787. static PyObject*
  6788. unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
  6789. {
  6790. return PyUnicode_RPartition((PyObject *)self, separator);
  6791. }
  6792. PyObject *PyUnicode_RSplit(PyObject *s,
  6793. PyObject *sep,
  6794. Py_ssize_t maxsplit)
  6795. {
  6796. PyObject *result;
  6797. s = PyUnicode_FromObject(s);
  6798. if (s == NULL)
  6799. return NULL;
  6800. if (sep != NULL) {
  6801. sep = PyUnicode_FromObject(sep);
  6802. if (sep == NULL) {
  6803. Py_DECREF(s);
  6804. return NULL;
  6805. }
  6806. }
  6807. result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
  6808. Py_DECREF(s);
  6809. Py_XDECREF(sep);
  6810. return result;
  6811. }
  6812. PyDoc_STRVAR(rsplit__doc__,
  6813. "S.rsplit([sep [,maxsplit]]) -> list of strings\n\
  6814. \n\
  6815. Return a list of the words in S, using sep as the\n\
  6816. delimiter string, starting at the end of the string and\n\
  6817. working to the front. If maxsplit is given, at most maxsplit\n\
  6818. splits are done. If sep is not specified, any whitespace string\n\
  6819. is a separator.");
  6820. static PyObject*
  6821. unicode_rsplit(PyUnicodeObject *self, PyObject *args)
  6822. {
  6823. PyObject *substring = Py_None;
  6824. Py_ssize_t maxcount = -1;
  6825. if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
  6826. return NULL;
  6827. if (substring == Py_None)
  6828. return rsplit(self, NULL, maxcount);
  6829. else if (PyUnicode_Check(substring))
  6830. return rsplit(self, (PyUnicodeObject *)substring, maxcount);
  6831. else
  6832. return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
  6833. }
  6834. PyDoc_STRVAR(splitlines__doc__,
  6835. "S.splitlines([keepends]) -> list of strings\n\
  6836. \n\
  6837. Return a list of the lines in S, breaking at line boundaries.\n\
  6838. Line breaks are not included in the resulting list unless keepends\n\
  6839. is given and true.");
  6840. static PyObject*
  6841. unicode_splitlines(PyUnicodeObject *self, PyObject *args)
  6842. {
  6843. int keepends = 0;
  6844. if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
  6845. return NULL;
  6846. return PyUnicode_Splitlines((PyObject *)self, keepends);
  6847. }
  6848. static
  6849. PyObject *unicode_str(PyUnicodeObject *self)
  6850. {
  6851. return PyUnicode_AsEncodedString((PyObject *)self, NULL, NULL);
  6852. }
  6853. PyDoc_STRVAR(swapcase__doc__,
  6854. "S.swapcase() -> unicode\n\
  6855. \n\
  6856. Return a copy of S with uppercase characters converted to lowercase\n\
  6857. and vice versa.");
  6858. static PyObject*
  6859. unicode_swapcase(PyUnicodeObject *self)
  6860. {
  6861. return fixup(self, fixswapcase);
  6862. }
  6863. PyDoc_STRVAR(translate__doc__,
  6864. "S.translate(table) -> unicode\n\
  6865. \n\
  6866. Return a copy of the string S, where all characters have been mapped\n\
  6867. through the given translation table, which must be a mapping of\n\
  6868. Unicode ordinals to Unicode ordinals, Unicode strings or None.\n\
  6869. Unmapped characters are left untouched. Characters mapped to None\n\
  6870. are deleted.");
  6871. static PyObject*
  6872. unicode_translate(PyUnicodeObject *self, PyObject *table)
  6873. {
  6874. return PyUnicode_TranslateCharmap(self->str,
  6875. self->length,
  6876. table,
  6877. "ignore");
  6878. }
  6879. PyDoc_STRVAR(upper__doc__,
  6880. "S.upper() -> unicode\n\
  6881. \n\
  6882. Return a copy of S converted to uppercase.");
  6883. static PyObject*
  6884. unicode_upper(PyUnicodeObject *self)
  6885. {
  6886. return fixup(self, fixupper);
  6887. }
  6888. PyDoc_STRVAR(zfill__doc__,
  6889. "S.zfill(width) -> unicode\n\
  6890. \n\
  6891. Pad a numeric string S with zeros on the left, to fill a field\n\
  6892. of the specified width. The string S is never truncated.");
  6893. static PyObject *
  6894. unicode_zfill(PyUnicodeObject *self, PyObject *args)
  6895. {
  6896. Py_ssize_t fill;
  6897. PyUnicodeObject *u;
  6898. Py_ssize_t width;
  6899. if (!PyArg_ParseTuple(args, "n:zfill", &width))
  6900. return NULL;
  6901. if (self->length >= width) {
  6902. if (PyUnicode_CheckExact(self)) {
  6903. Py_INCREF(self);
  6904. return (PyObject*) self;
  6905. }
  6906. else
  6907. return PyUnicode_FromUnicode(
  6908. PyUnicode_AS_UNICODE(self),
  6909. PyUnicode_GET_SIZE(self)
  6910. );
  6911. }
  6912. fill = width - self->length;
  6913. u = pad(self, fill, 0, '0');
  6914. if (u == NULL)
  6915. return NULL;
  6916. if (u->str[fill] == '+' || u->str[fill] == '-') {
  6917. /* move sign to beginning of string */
  6918. u->str[0] = u->str[fill];
  6919. u->str[fill] = '0';
  6920. }
  6921. return (PyObject*) u;
  6922. }
  6923. #if 0
  6924. static PyObject*
  6925. free_listsize(PyUnicodeObject *self)
  6926. {
  6927. return PyInt_FromLong(numfree);
  6928. }
  6929. #endif
  6930. PyDoc_STRVAR(startswith__doc__,
  6931. "S.startswith(prefix[, start[, end]]) -> bool\n\
  6932. \n\
  6933. Return True if S starts with the specified prefix, False otherwise.\n\
  6934. With optional start, test S beginning at that position.\n\
  6935. With optional end, stop comparing S at that position.\n\
  6936. prefix can also be a tuple of strings to try.");
  6937. static PyObject *
  6938. unicode_startswith(PyUnicodeObject *self,
  6939. PyObject *args)
  6940. {
  6941. PyObject *subobj;
  6942. PyUnicodeObject *substring;
  6943. Py_ssize_t start = 0;
  6944. Py_ssize_t end = PY_SSIZE_T_MAX;
  6945. int result;
  6946. if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
  6947. _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
  6948. return NULL;
  6949. if (PyTuple_Check(subobj)) {
  6950. Py_ssize_t i;
  6951. for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
  6952. substring = (PyUnicodeObject *)PyUnicode_FromObject(
  6953. PyTuple_GET_ITEM(subobj, i));
  6954. if (substring == NULL)
  6955. return NULL;
  6956. result = tailmatch(self, substring, start, end, -1);
  6957. Py_DECREF(substring);
  6958. if (result) {
  6959. Py_RETURN_TRUE;
  6960. }
  6961. }
  6962. /* nothing matched */
  6963. Py_RETURN_FALSE;
  6964. }
  6965. substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
  6966. if (substring == NULL)
  6967. return NULL;
  6968. result = tailmatch(self, substring, start, end, -1);
  6969. Py_DECREF(substring);
  6970. return PyBool_FromLong(result);
  6971. }
  6972. PyDoc_STRVAR(endswith__doc__,
  6973. "S.endswith(suffix[, start[, end]]) -> bool\n\
  6974. \n\
  6975. Return True if S ends with the specified suffix, False otherwise.\n\
  6976. With optional start, test S beginning at that position.\n\
  6977. With optional end, stop comparing S at that position.\n\
  6978. suffix can also be a tuple of strings to try.");
  6979. static PyObject *
  6980. unicode_endswith(PyUnicodeObject *self,
  6981. PyObject *args)
  6982. {
  6983. PyObject *subobj;
  6984. PyUnicodeObject *substring;
  6985. Py_ssize_t start = 0;
  6986. Py_ssize_t end = PY_SSIZE_T_MAX;
  6987. int result;
  6988. if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
  6989. _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
  6990. return NULL;
  6991. if (PyTuple_Check(subobj)) {
  6992. Py_ssize_t i;
  6993. for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
  6994. substring = (PyUnicodeObject *)PyUnicode_FromObject(
  6995. PyTuple_GET_ITEM(subobj, i));
  6996. if (substring == NULL)
  6997. return NULL;
  6998. result = tailmatch(self, substring, start, end, +1);
  6999. Py_DECREF(substring);
  7000. if (result) {
  7001. Py_RETURN_TRUE;
  7002. }
  7003. }
  7004. Py_RETURN_FALSE;
  7005. }
  7006. substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
  7007. if (substring == NULL)
  7008. return NULL;
  7009. result = tailmatch(self, substring, start, end, +1);
  7010. Py_DECREF(substring);
  7011. return PyBool_FromLong(result);
  7012. }
  7013. /* Implements do_string_format, which is unicode because of stringlib */
  7014. #include "stringlib/string_format.h"
  7015. PyDoc_STRVAR(format__doc__,
  7016. "S.format(*args, **kwargs) -> unicode\n\
  7017. \n\
  7018. ");
  7019. static PyObject *
  7020. unicode__format__(PyObject *self, PyObject *args)
  7021. {
  7022. PyObject *format_spec;
  7023. PyObject *result = NULL;
  7024. PyObject *tmp = NULL;
  7025. /* If 2.x, convert format_spec to the same type as value */
  7026. /* This is to allow things like u''.format('') */
  7027. if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
  7028. goto done;
  7029. if (!(PyBytes_Check(format_spec) || PyUnicode_Check(format_spec))) {
  7030. PyErr_Format(PyExc_TypeError, "__format__ arg must be str "
  7031. "or unicode, not %s", Py_TYPE(format_spec)->tp_name);
  7032. goto done;
  7033. }
  7034. tmp = PyObject_Unicode(format_spec);
  7035. if (tmp == NULL)
  7036. goto done;
  7037. format_spec = tmp;
  7038. result = _PyUnicode_FormatAdvanced(self,
  7039. PyUnicode_AS_UNICODE(format_spec),
  7040. PyUnicode_GET_SIZE(format_spec));
  7041. done:
  7042. Py_XDECREF(tmp);
  7043. return result;
  7044. }
  7045. PyDoc_STRVAR(p_format__doc__,
  7046. "S.__format__(format_spec) -> unicode\n\
  7047. \n\
  7048. ");
  7049. static PyObject *
  7050. unicode__sizeof__(PyUnicodeObject *v)
  7051. {
  7052. return PyInt_FromSsize_t(sizeof(PyUnicodeObject) +
  7053. sizeof(Py_UNICODE) * (v->length + 1));
  7054. }
  7055. PyDoc_STRVAR(sizeof__doc__,
  7056. "S.__sizeof__() -> size of S in memory, in bytes\n\
  7057. \n\
  7058. ");
  7059. static PyObject *
  7060. unicode_getnewargs(PyUnicodeObject *v)
  7061. {
  7062. return Py_BuildValue("(u#)", v->str, v->length);
  7063. }
  7064. static PyMethodDef unicode_methods[] = {
  7065. /* Order is according to common usage: often used methods should
  7066. appear first, since lookup is done sequentially. */
  7067. {"encode", (PyCFunction) unicode_encode, METH_ARG_RANGE, encode__doc__,
  7068. /*min_arity=*/0, /*max_arity=*/2},
  7069. {"replace", (PyCFunction) unicode_replace, METH_ARG_RANGE, replace__doc__,
  7070. /*min_arity=*/2, /*max_arity=*/3},
  7071. {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
  7072. {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
  7073. {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
  7074. {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
  7075. {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
  7076. {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
  7077. {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
  7078. {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
  7079. {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
  7080. {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
  7081. {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
  7082. {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
  7083. {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
  7084. {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
  7085. {"decode", (PyCFunction) unicode_decode, METH_VARARGS, decode__doc__},
  7086. /* {"maketrans", (PyCFunction) unicode_maketrans, METH_VARARGS, maketrans__doc__}, */
  7087. {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
  7088. {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
  7089. {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
  7090. {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
  7091. {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
  7092. {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS, splitlines__doc__},
  7093. {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
  7094. {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
  7095. {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
  7096. {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
  7097. {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
  7098. {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
  7099. {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
  7100. {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
  7101. {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
  7102. {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
  7103. {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
  7104. {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
  7105. {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
  7106. {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
  7107. {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
  7108. {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
  7109. {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
  7110. {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
  7111. {"_formatter_field_name_split", (PyCFunction) formatter_field_name_split, METH_NOARGS},
  7112. {"_formatter_parser", (PyCFunction) formatter_parser, METH_NOARGS},
  7113. {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
  7114. #if 0
  7115. {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
  7116. #endif
  7117. #if 0
  7118. /* This one is just used for debugging the implementation. */
  7119. {"freelistsize", (PyCFunction) free_listsize, METH_NOARGS},
  7120. #endif
  7121. {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
  7122. {NULL, NULL}
  7123. };
  7124. static PyObject *
  7125. unicode_mod(PyObject *v, PyObject *w)
  7126. {
  7127. if (!PyUnicode_Check(v)) {
  7128. Py_INCREF(Py_NotImplemented);
  7129. return Py_NotImplemented;
  7130. }
  7131. return PyUnicode_Format(v, w);
  7132. }
  7133. static PyNumberMethods unicode_as_number = {
  7134. 0, /*nb_add*/
  7135. 0, /*nb_subtract*/
  7136. 0, /*nb_multiply*/
  7137. 0, /*nb_divide*/
  7138. unicode_mod, /*nb_remainder*/
  7139. };
  7140. static PySequenceMethods unicode_as_sequence = {
  7141. (lenfunc) unicode_length, /* sq_length */
  7142. PyUnicode_Concat, /* sq_concat */
  7143. (ssizeargfunc) unicode_repeat, /* sq_repeat */
  7144. (ssizeargfunc) unicode_getitem, /* sq_item */
  7145. (ssizessizeargfunc) unicode_slice, /* sq_slice */
  7146. 0, /* sq_ass_item */
  7147. 0, /* sq_ass_slice */
  7148. PyUnicode_Contains, /* sq_contains */
  7149. };
  7150. static PyObject*
  7151. unicode_subscript(PyUnicodeObject* self, PyObject* item)
  7152. {
  7153. if (PyIndex_Check(item)) {
  7154. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  7155. if (i == -1 && PyErr_Occurred())
  7156. return NULL;
  7157. if (i < 0)
  7158. i += PyUnicode_GET_SIZE(self);
  7159. return unicode_getitem(self, i);
  7160. } else if (PySlice_Check(item)) {
  7161. Py_ssize_t start, stop, step, slicelength, cur, i;
  7162. Py_UNICODE* source_buf;
  7163. Py_UNICODE* result_buf;
  7164. PyObject* result;
  7165. if (PySlice_GetIndicesEx((PySliceObject*)item, PyUnicode_GET_SIZE(self),
  7166. &start, &stop, &step, &slicelength) < 0) {
  7167. return NULL;
  7168. }
  7169. if (slicelength <= 0) {
  7170. return PyUnicode_FromUnicode(NULL, 0);
  7171. } else if (start == 0 && step == 1 && slicelength == self->length &&
  7172. PyUnicode_CheckExact(self)) {
  7173. Py_INCREF(self);
  7174. return (PyObject *)self;
  7175. } else if (step == 1) {
  7176. return PyUnicode_FromUnicode(self->str + start, slicelength);
  7177. } else {
  7178. source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
  7179. result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
  7180. sizeof(Py_UNICODE));
  7181. if (result_buf == NULL)
  7182. return PyErr_NoMemory();
  7183. for (cur = start, i = 0; i < slicelength; cur += step, i++) {
  7184. result_buf[i] = source_buf[cur];
  7185. }
  7186. result = PyUnicode_FromUnicode(result_buf, slicelength);
  7187. PyObject_FREE(result_buf);
  7188. return result;
  7189. }
  7190. } else {
  7191. PyErr_SetString(PyExc_TypeError, "string indices must be integers");
  7192. return NULL;
  7193. }
  7194. }
  7195. static PyMappingMethods unicode_as_mapping = {
  7196. (lenfunc)unicode_length, /* mp_length */
  7197. (binaryfunc)unicode_subscript, /* mp_subscript */
  7198. (objobjargproc)0, /* mp_ass_subscript */
  7199. };
  7200. static Py_ssize_t
  7201. unicode_buffer_getreadbuf(PyUnicodeObject *self,
  7202. Py_ssize_t index,
  7203. const void **ptr)
  7204. {
  7205. if (index != 0) {
  7206. PyErr_SetString(PyExc_SystemError,
  7207. "accessing non-existent unicode segment");
  7208. return -1;
  7209. }
  7210. *ptr = (void *) self->str;
  7211. return PyUnicode_GET_DATA_SIZE(self);
  7212. }
  7213. static Py_ssize_t
  7214. unicode_buffer_getwritebuf(PyUnicodeObject *self, Py_ssize_t index,
  7215. const void **ptr)
  7216. {
  7217. PyErr_SetString(PyExc_TypeError,
  7218. "cannot use unicode as modifiable buffer");
  7219. return -1;
  7220. }
  7221. static int
  7222. unicode_buffer_getsegcount(PyUnicodeObject *self,
  7223. Py_ssize_t *lenp)
  7224. {
  7225. if (lenp)
  7226. *lenp = PyUnicode_GET_DATA_SIZE(self);
  7227. return 1;
  7228. }
  7229. static Py_ssize_t
  7230. unicode_buffer_getcharbuf(PyUnicodeObject *self,
  7231. Py_ssize_t index,
  7232. const void **ptr)
  7233. {
  7234. PyObject *str;
  7235. if (index != 0) {
  7236. PyErr_SetString(PyExc_SystemError,
  7237. "accessing non-existent unicode segment");
  7238. return -1;
  7239. }
  7240. str = _PyUnicode_AsDefaultEncodedString((PyObject *)self, NULL);
  7241. if (str == NULL)
  7242. return -1;
  7243. *ptr = (void *) PyString_AS_STRING(str);
  7244. return PyString_GET_SIZE(str);
  7245. }
  7246. /* Helpers for PyUnicode_Format() */
  7247. static PyObject *
  7248. getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
  7249. {
  7250. Py_ssize_t argidx = *p_argidx;
  7251. if (argidx < arglen) {
  7252. (*p_argidx)++;
  7253. if (arglen < 0)
  7254. return args;
  7255. else
  7256. return PyTuple_GetItem(args, argidx);
  7257. }
  7258. PyErr_SetString(PyExc_TypeError,
  7259. "not enough arguments for format string");
  7260. return NULL;
  7261. }
  7262. #define F_LJUST (1<<0)
  7263. #define F_SIGN (1<<1)
  7264. #define F_BLANK (1<<2)
  7265. #define F_ALT (1<<3)
  7266. #define F_ZERO (1<<4)
  7267. static Py_ssize_t
  7268. strtounicode(Py_UNICODE *buffer, const char *charbuffer)
  7269. {
  7270. register Py_ssize_t i;
  7271. Py_ssize_t len = strlen(charbuffer);
  7272. for (i = len - 1; i >= 0; i--)
  7273. buffer[i] = (Py_UNICODE) charbuffer[i];
  7274. return len;
  7275. }
  7276. static int
  7277. doubletounicode(Py_UNICODE *buffer, size_t len, const char *format, double x)
  7278. {
  7279. Py_ssize_t result;
  7280. PyOS_ascii_formatd((char *)buffer, len, format, x);
  7281. result = strtounicode(buffer, (char *)buffer);
  7282. return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
  7283. }
  7284. static int
  7285. longtounicode(Py_UNICODE *buffer, size_t len, const char *format, long x)
  7286. {
  7287. Py_ssize_t result;
  7288. PyOS_snprintf((char *)buffer, len, format, x);
  7289. result = strtounicode(buffer, (char *)buffer);
  7290. return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
  7291. }
  7292. /* XXX To save some code duplication, formatfloat/long/int could have been
  7293. shared with stringobject.c, converting from 8-bit to Unicode after the
  7294. formatting is done. */
  7295. static int
  7296. formatfloat(Py_UNICODE *buf,
  7297. size_t buflen,
  7298. int flags,
  7299. int prec,
  7300. int type,
  7301. PyObject *v)
  7302. {
  7303. /* fmt = '%#.' + `prec` + `type`
  7304. worst case length = 3 + 10 (len of INT_MAX) + 1 = 14 (use 20)*/
  7305. char fmt[20];
  7306. double x;
  7307. x = PyFloat_AsDouble(v);
  7308. if (x == -1.0 && PyErr_Occurred())
  7309. return -1;
  7310. if (prec < 0)
  7311. prec = 6;
  7312. #if SIZEOF_INT > 4
  7313. /* make sure that the decimal representation of precision really does
  7314. need at most 10 digits: platforms with sizeof(int) == 8 exist! */
  7315. if (prec > 0x7fffffff) {
  7316. PyErr_SetString(PyExc_OverflowError,
  7317. "outrageously large precision "
  7318. "for formatted float");
  7319. return -1;
  7320. }
  7321. #endif
  7322. if (type == 'f' && fabs(x) >= 1e50)
  7323. type = 'g';
  7324. /* Worst case length calc to ensure no buffer overrun:
  7325. 'g' formats:
  7326. fmt = %#.<prec>g
  7327. buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
  7328. for any double rep.)
  7329. len = 1 + prec + 1 + 2 + 5 = 9 + prec
  7330. 'f' formats:
  7331. buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50)
  7332. len = 1 + 50 + 1 + prec = 52 + prec
  7333. If prec=0 the effective precision is 1 (the leading digit is
  7334. always given), therefore increase the length by one.
  7335. */
  7336. if (((type == 'g' || type == 'G') &&
  7337. buflen <= (size_t)10 + (size_t)prec) ||
  7338. (type == 'f' && buflen <= (size_t)53 + (size_t)prec)) {
  7339. PyErr_SetString(PyExc_OverflowError,
  7340. "formatted float is too long (precision too large?)");
  7341. return -1;
  7342. }
  7343. PyOS_snprintf(fmt, sizeof(fmt), "%%%s.%d%c",
  7344. (flags&F_ALT) ? "#" : "",
  7345. prec, type);
  7346. return doubletounicode(buf, buflen, fmt, x);
  7347. }
  7348. static PyObject*
  7349. formatlong(PyObject *val, int flags, int prec, int type)
  7350. {
  7351. char *buf;
  7352. int i, len;
  7353. PyObject *str; /* temporary string object. */
  7354. PyUnicodeObject *result;
  7355. str = _PyString_FormatLong(val, flags, prec, type, &buf, &len);
  7356. if (!str)
  7357. return NULL;
  7358. result = _PyUnicode_New(len);
  7359. if (!result) {
  7360. Py_DECREF(str);
  7361. return NULL;
  7362. }
  7363. for (i = 0; i < len; i++)
  7364. result->str[i] = buf[i];
  7365. result->str[len] = 0;
  7366. Py_DECREF(str);
  7367. return (PyObject*)result;
  7368. }
  7369. static int
  7370. formatint(Py_UNICODE *buf,
  7371. size_t buflen,
  7372. int flags,
  7373. int prec,
  7374. int type,
  7375. PyObject *v)
  7376. {
  7377. /* fmt = '%#.' + `prec` + 'l' + `type`
  7378. * worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine)
  7379. * + 1 + 1
  7380. * = 24
  7381. */
  7382. char fmt[64]; /* plenty big enough! */
  7383. char *sign;
  7384. long x;
  7385. x = PyInt_AsLong(v);
  7386. if (x == -1 && PyErr_Occurred())
  7387. return -1;
  7388. if (x < 0 && type == 'u') {
  7389. type = 'd';
  7390. }
  7391. if (x < 0 && (type == 'x' || type == 'X' || type == 'o'))
  7392. sign = "-";
  7393. else
  7394. sign = "";
  7395. if (prec < 0)
  7396. prec = 1;
  7397. /* buf = '+'/'-'/'' + '0'/'0x'/'' + '[0-9]'*max(prec, len(x in octal))
  7398. * worst case buf = '-0x' + [0-9]*prec, where prec >= 11
  7399. */
  7400. if (buflen <= 14 || buflen <= (size_t)3 + (size_t)prec) {
  7401. PyErr_SetString(PyExc_OverflowError,
  7402. "formatted integer is too long (precision too large?)");
  7403. return -1;
  7404. }
  7405. if ((flags & F_ALT) &&
  7406. (type == 'x' || type == 'X')) {
  7407. /* When converting under %#x or %#X, there are a number
  7408. * of issues that cause pain:
  7409. * - when 0 is being converted, the C standard leaves off
  7410. * the '0x' or '0X', which is inconsistent with other
  7411. * %#x/%#X conversions and inconsistent with Python's
  7412. * hex() function
  7413. * - there are platforms that violate the standard and
  7414. * convert 0 with the '0x' or '0X'
  7415. * (Metrowerks, Compaq Tru64)
  7416. * - there are platforms that give '0x' when converting
  7417. * under %#X, but convert 0 in accordance with the
  7418. * standard (OS/2 EMX)
  7419. *
  7420. * We can achieve the desired consistency by inserting our
  7421. * own '0x' or '0X' prefix, and substituting %x/%X in place
  7422. * of %#x/%#X.
  7423. *
  7424. * Note that this is the same approach as used in
  7425. * formatint() in stringobject.c
  7426. */
  7427. PyOS_snprintf(fmt, sizeof(fmt), "%s0%c%%.%dl%c",
  7428. sign, type, prec, type);
  7429. }
  7430. else {
  7431. PyOS_snprintf(fmt, sizeof(fmt), "%s%%%s.%dl%c",
  7432. sign, (flags&F_ALT) ? "#" : "",
  7433. prec, type);
  7434. }
  7435. if (sign[0])
  7436. return longtounicode(buf, buflen, fmt, -x);
  7437. else
  7438. return longtounicode(buf, buflen, fmt, x);
  7439. }
  7440. static int
  7441. formatchar(Py_UNICODE *buf,
  7442. size_t buflen,
  7443. PyObject *v)
  7444. {
  7445. /* presume that the buffer is at least 2 characters long */
  7446. if (PyUnicode_Check(v)) {
  7447. if (PyUnicode_GET_SIZE(v) != 1)
  7448. goto onError;
  7449. buf[0] = PyUnicode_AS_UNICODE(v)[0];
  7450. }
  7451. else if (PyString_Check(v)) {
  7452. if (PyString_GET_SIZE(v) != 1)
  7453. goto onError;
  7454. buf[0] = (Py_UNICODE)PyString_AS_STRING(v)[0];
  7455. }
  7456. else {
  7457. /* Integer input truncated to a character */
  7458. long x;
  7459. x = PyInt_AsLong(v);
  7460. if (x == -1 && PyErr_Occurred())
  7461. goto onError;
  7462. #ifdef Py_UNICODE_WIDE
  7463. if (x < 0 || x > 0x10ffff) {
  7464. PyErr_SetString(PyExc_OverflowError,
  7465. "%c arg not in range(0x110000) "
  7466. "(wide Python build)");
  7467. return -1;
  7468. }
  7469. #else
  7470. if (x < 0 || x > 0xffff) {
  7471. PyErr_SetString(PyExc_OverflowError,
  7472. "%c arg not in range(0x10000) "
  7473. "(narrow Python build)");
  7474. return -1;
  7475. }
  7476. #endif
  7477. buf[0] = (Py_UNICODE) x;
  7478. }
  7479. buf[1] = '\0';
  7480. return 1;
  7481. onError:
  7482. PyErr_SetString(PyExc_TypeError,
  7483. "%c requires int or char");
  7484. return -1;
  7485. }
  7486. /* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
  7487. FORMATBUFLEN is the length of the buffer in which the floats, ints, &
  7488. chars are formatted. XXX This is a magic number. Each formatting
  7489. routine does bounds checking to ensure no overflow, but a better
  7490. solution may be to malloc a buffer of appropriate size for each
  7491. format. For now, the current solution is sufficient.
  7492. */
  7493. #define FORMATBUFLEN (size_t)120
  7494. PyObject *PyUnicode_Format(PyObject *format,
  7495. PyObject *args)
  7496. {
  7497. Py_UNICODE *fmt, *res;
  7498. Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx;
  7499. int args_owned = 0;
  7500. PyUnicodeObject *result = NULL;
  7501. PyObject *dict = NULL;
  7502. PyObject *uformat;
  7503. if (format == NULL || args == NULL) {
  7504. PyErr_BadInternalCall();
  7505. return NULL;
  7506. }
  7507. uformat = PyUnicode_FromObject(format);
  7508. if (uformat == NULL)
  7509. return NULL;
  7510. fmt = PyUnicode_AS_UNICODE(uformat);
  7511. fmtcnt = PyUnicode_GET_SIZE(uformat);
  7512. reslen = rescnt = fmtcnt + 100;
  7513. result = _PyUnicode_New(reslen);
  7514. if (result == NULL)
  7515. goto onError;
  7516. res = PyUnicode_AS_UNICODE(result);
  7517. if (PyTuple_Check(args)) {
  7518. arglen = PyTuple_Size(args);
  7519. argidx = 0;
  7520. }
  7521. else {
  7522. arglen = -1;
  7523. argidx = -2;
  7524. }
  7525. if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
  7526. !PyObject_TypeCheck(args, &PyBaseString_Type))
  7527. dict = args;
  7528. while (--fmtcnt >= 0) {
  7529. if (*fmt != '%') {
  7530. if (--rescnt < 0) {
  7531. rescnt = fmtcnt + 100;
  7532. reslen += rescnt;
  7533. if (_PyUnicode_Resize(&result, reslen) < 0)
  7534. goto onError;
  7535. res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
  7536. --rescnt;
  7537. }
  7538. *res++ = *fmt++;
  7539. }
  7540. else {
  7541. /* Got a format specifier */
  7542. int flags = 0;
  7543. Py_ssize_t width = -1;
  7544. int prec = -1;
  7545. Py_UNICODE c = '\0';
  7546. Py_UNICODE fill;
  7547. int isnumok;
  7548. PyObject *v = NULL;
  7549. PyObject *temp = NULL;
  7550. Py_UNICODE *pbuf;
  7551. Py_UNICODE sign;
  7552. Py_ssize_t len;
  7553. Py_UNICODE formatbuf[FORMATBUFLEN]; /* For format{float,int,char}() */
  7554. fmt++;
  7555. if (*fmt == '(') {
  7556. Py_UNICODE *keystart;
  7557. Py_ssize_t keylen;
  7558. PyObject *key;
  7559. int pcount = 1;
  7560. if (dict == NULL) {
  7561. PyErr_SetString(PyExc_TypeError,
  7562. "format requires a mapping");
  7563. goto onError;
  7564. }
  7565. ++fmt;
  7566. --fmtcnt;
  7567. keystart = fmt;
  7568. /* Skip over balanced parentheses */
  7569. while (pcount > 0 && --fmtcnt >= 0) {
  7570. if (*fmt == ')')
  7571. --pcount;
  7572. else if (*fmt == '(')
  7573. ++pcount;
  7574. fmt++;
  7575. }
  7576. keylen = fmt - keystart - 1;
  7577. if (fmtcnt < 0 || pcount > 0) {
  7578. PyErr_SetString(PyExc_ValueError,
  7579. "incomplete format key");
  7580. goto onError;
  7581. }
  7582. #if 0
  7583. /* keys are converted to strings using UTF-8 and
  7584. then looked up since Python uses strings to hold
  7585. variables names etc. in its namespaces and we
  7586. wouldn't want to break common idioms. */
  7587. key = PyUnicode_EncodeUTF8(keystart,
  7588. keylen,
  7589. NULL);
  7590. #else
  7591. key = PyUnicode_FromUnicode(keystart, keylen);
  7592. #endif
  7593. if (key == NULL)
  7594. goto onError;
  7595. if (args_owned) {
  7596. Py_DECREF(args);
  7597. args_owned = 0;
  7598. }
  7599. args = PyObject_GetItem(dict, key);
  7600. Py_DECREF(key);
  7601. if (args == NULL) {
  7602. goto onError;
  7603. }
  7604. args_owned = 1;
  7605. arglen = -1;
  7606. argidx = -2;
  7607. }
  7608. while (--fmtcnt >= 0) {
  7609. switch (c = *fmt++) {
  7610. case '-': flags |= F_LJUST; continue;
  7611. case '+': flags |= F_SIGN; continue;
  7612. case ' ': flags |= F_BLANK; continue;
  7613. case '#': flags |= F_ALT; continue;
  7614. case '0': flags |= F_ZERO; continue;
  7615. }
  7616. break;
  7617. }
  7618. if (c == '*') {
  7619. v = getnextarg(args, arglen, &argidx);
  7620. if (v == NULL)
  7621. goto onError;
  7622. if (!PyInt_Check(v)) {
  7623. PyErr_SetString(PyExc_TypeError,
  7624. "* wants int");
  7625. goto onError;
  7626. }
  7627. width = PyInt_AsLong(v);
  7628. if (width < 0) {
  7629. flags |= F_LJUST;
  7630. width = -width;
  7631. }
  7632. if (--fmtcnt >= 0)
  7633. c = *fmt++;
  7634. }
  7635. else if (c >= '0' && c <= '9') {
  7636. width = c - '0';
  7637. while (--fmtcnt >= 0) {
  7638. c = *fmt++;
  7639. if (c < '0' || c > '9')
  7640. break;
  7641. if ((width*10) / 10 != width) {
  7642. PyErr_SetString(PyExc_ValueError,
  7643. "width too big");
  7644. goto onError;
  7645. }
  7646. width = width*10 + (c - '0');
  7647. }
  7648. }
  7649. if (c == '.') {
  7650. prec = 0;
  7651. if (--fmtcnt >= 0)
  7652. c = *fmt++;
  7653. if (c == '*') {
  7654. v = getnextarg(args, arglen, &argidx);
  7655. if (v == NULL)
  7656. goto onError;
  7657. if (!PyInt_Check(v)) {
  7658. PyErr_SetString(PyExc_TypeError,
  7659. "* wants int");
  7660. goto onError;
  7661. }
  7662. prec = PyInt_AsLong(v);
  7663. if (prec < 0)
  7664. prec = 0;
  7665. if (--fmtcnt >= 0)
  7666. c = *fmt++;
  7667. }
  7668. else if (c >= '0' && c <= '9') {
  7669. prec = c - '0';
  7670. while (--fmtcnt >= 0) {
  7671. c = Py_CHARMASK(*fmt++);
  7672. if (c < '0' || c > '9')
  7673. break;
  7674. if ((prec*10) / 10 != prec) {
  7675. PyErr_SetString(PyExc_ValueError,
  7676. "prec too big");
  7677. goto onError;
  7678. }
  7679. prec = prec*10 + (c - '0');
  7680. }
  7681. }
  7682. } /* prec */
  7683. if (fmtcnt >= 0) {
  7684. if (c == 'h' || c == 'l' || c == 'L') {
  7685. if (--fmtcnt >= 0)
  7686. c = *fmt++;
  7687. }
  7688. }
  7689. if (fmtcnt < 0) {
  7690. PyErr_SetString(PyExc_ValueError,
  7691. "incomplete format");
  7692. goto onError;
  7693. }
  7694. if (c != '%') {
  7695. v = getnextarg(args, arglen, &argidx);
  7696. if (v == NULL)
  7697. goto onError;
  7698. }
  7699. sign = 0;
  7700. fill = ' ';
  7701. switch (c) {
  7702. case '%':
  7703. pbuf = formatbuf;
  7704. /* presume that buffer length is at least 1 */
  7705. pbuf[0] = '%';
  7706. len = 1;
  7707. break;
  7708. case 's':
  7709. case 'r':
  7710. if (PyUnicode_Check(v) && c == 's') {
  7711. temp = v;
  7712. Py_INCREF(temp);
  7713. }
  7714. else {
  7715. PyObject *unicode;
  7716. if (c == 's')
  7717. temp = PyObject_Unicode(v);
  7718. else
  7719. temp = PyObject_Repr(v);
  7720. if (temp == NULL)
  7721. goto onError;
  7722. if (PyUnicode_Check(temp))
  7723. /* nothing to do */;
  7724. else if (PyString_Check(temp)) {
  7725. /* convert to string to Unicode */
  7726. unicode = PyUnicode_Decode(PyString_AS_STRING(temp),
  7727. PyString_GET_SIZE(temp),
  7728. NULL,
  7729. "strict");
  7730. Py_DECREF(temp);
  7731. temp = unicode;
  7732. if (temp == NULL)
  7733. goto onError;
  7734. }
  7735. else {
  7736. Py_DECREF(temp);
  7737. PyErr_SetString(PyExc_TypeError,
  7738. "%s argument has non-string str()");
  7739. goto onError;
  7740. }
  7741. }
  7742. pbuf = PyUnicode_AS_UNICODE(temp);
  7743. len = PyUnicode_GET_SIZE(temp);
  7744. if (prec >= 0 && len > prec)
  7745. len = prec;
  7746. break;
  7747. case 'i':
  7748. case 'd':
  7749. case 'u':
  7750. case 'o':
  7751. case 'x':
  7752. case 'X':
  7753. if (c == 'i')
  7754. c = 'd';
  7755. isnumok = 0;
  7756. if (PyNumber_Check(v)) {
  7757. PyObject *iobj=NULL;
  7758. if (PyInt_Check(v) || (PyLong_Check(v))) {
  7759. iobj = v;
  7760. Py_INCREF(iobj);
  7761. }
  7762. else {
  7763. iobj = PyNumber_Int(v);
  7764. if (iobj==NULL) iobj = PyNumber_Long(v);
  7765. }
  7766. if (iobj!=NULL) {
  7767. if (PyInt_Check(iobj)) {
  7768. isnumok = 1;
  7769. pbuf = formatbuf;
  7770. len = formatint(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE),
  7771. flags, prec, c, iobj);
  7772. Py_DECREF(iobj);
  7773. if (len < 0)
  7774. goto onError;
  7775. sign = 1;
  7776. }
  7777. else if (PyLong_Check(iobj)) {
  7778. isnumok = 1;
  7779. temp = formatlong(iobj, flags, prec, c);
  7780. Py_DECREF(iobj);
  7781. if (!temp)
  7782. goto onError;
  7783. pbuf = PyUnicode_AS_UNICODE(temp);
  7784. len = PyUnicode_GET_SIZE(temp);
  7785. sign = 1;
  7786. }
  7787. else {
  7788. Py_DECREF(iobj);
  7789. }
  7790. }
  7791. }
  7792. if (!isnumok) {
  7793. PyErr_Format(PyExc_TypeError,
  7794. "%%%c format: a number is required, "
  7795. "not %.200s", (char)c, Py_TYPE(v)->tp_name);
  7796. goto onError;
  7797. }
  7798. if (flags & F_ZERO)
  7799. fill = '0';
  7800. break;
  7801. case 'e':
  7802. case 'E':
  7803. case 'f':
  7804. case 'F':
  7805. case 'g':
  7806. case 'G':
  7807. if (c == 'F')
  7808. c = 'f';
  7809. pbuf = formatbuf;
  7810. len = formatfloat(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE),
  7811. flags, prec, c, v);
  7812. if (len < 0)
  7813. goto onError;
  7814. sign = 1;
  7815. if (flags & F_ZERO)
  7816. fill = '0';
  7817. break;
  7818. case 'c':
  7819. pbuf = formatbuf;
  7820. len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
  7821. if (len < 0)
  7822. goto onError;
  7823. break;
  7824. default:
  7825. PyErr_Format(PyExc_ValueError,
  7826. "unsupported format character '%c' (0x%x) "
  7827. "at index %zd",
  7828. (31<=c && c<=126) ? (char)c : '?',
  7829. (int)c,
  7830. (Py_ssize_t)(fmt - 1 -
  7831. PyUnicode_AS_UNICODE(uformat)));
  7832. goto onError;
  7833. }
  7834. if (sign) {
  7835. if (*pbuf == '-' || *pbuf == '+') {
  7836. sign = *pbuf++;
  7837. len--;
  7838. }
  7839. else if (flags & F_SIGN)
  7840. sign = '+';
  7841. else if (flags & F_BLANK)
  7842. sign = ' ';
  7843. else
  7844. sign = 0;
  7845. }
  7846. if (width < len)
  7847. width = len;
  7848. if (rescnt - (sign != 0) < width) {
  7849. reslen -= rescnt;
  7850. rescnt = width + fmtcnt + 100;
  7851. reslen += rescnt;
  7852. if (reslen < 0) {
  7853. Py_XDECREF(temp);
  7854. PyErr_NoMemory();
  7855. goto onError;
  7856. }
  7857. if (_PyUnicode_Resize(&result, reslen) < 0) {
  7858. Py_XDECREF(temp);
  7859. goto onError;
  7860. }
  7861. res = PyUnicode_AS_UNICODE(result)
  7862. + reslen - rescnt;
  7863. }
  7864. if (sign) {
  7865. if (fill != ' ')
  7866. *res++ = sign;
  7867. rescnt--;
  7868. if (width > len)
  7869. width--;
  7870. }
  7871. if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
  7872. assert(pbuf[0] == '0');
  7873. assert(pbuf[1] == c);
  7874. if (fill != ' ') {
  7875. *res++ = *pbuf++;
  7876. *res++ = *pbuf++;
  7877. }
  7878. rescnt -= 2;
  7879. width -= 2;
  7880. if (width < 0)
  7881. width = 0;
  7882. len -= 2;
  7883. }
  7884. if (width > len && !(flags & F_LJUST)) {
  7885. do {
  7886. --rescnt;
  7887. *res++ = fill;
  7888. } while (--width > len);
  7889. }
  7890. if (fill == ' ') {
  7891. if (sign)
  7892. *res++ = sign;
  7893. if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
  7894. assert(pbuf[0] == '0');
  7895. assert(pbuf[1] == c);
  7896. *res++ = *pbuf++;
  7897. *res++ = *pbuf++;
  7898. }
  7899. }
  7900. Py_UNICODE_COPY(res, pbuf, len);
  7901. res += len;
  7902. rescnt -= len;
  7903. while (--width >= len) {
  7904. --rescnt;
  7905. *res++ = ' ';
  7906. }
  7907. if (dict && (argidx < arglen) && c != '%') {
  7908. PyErr_SetString(PyExc_TypeError,
  7909. "not all arguments converted during string formatting");
  7910. Py_XDECREF(temp);
  7911. goto onError;
  7912. }
  7913. Py_XDECREF(temp);
  7914. } /* '%' */
  7915. } /* until end */
  7916. if (argidx < arglen && !dict) {
  7917. PyErr_SetString(PyExc_TypeError,
  7918. "not all arguments converted during string formatting");
  7919. goto onError;
  7920. }
  7921. if (_PyUnicode_Resize(&result, reslen - rescnt) < 0)
  7922. goto onError;
  7923. if (args_owned) {
  7924. Py_DECREF(args);
  7925. }
  7926. Py_DECREF(uformat);
  7927. return (PyObject *)result;
  7928. onError:
  7929. Py_XDECREF(result);
  7930. Py_DECREF(uformat);
  7931. if (args_owned) {
  7932. Py_DECREF(args);
  7933. }
  7934. return NULL;
  7935. }
  7936. static PyBufferProcs unicode_as_buffer = {
  7937. (readbufferproc) unicode_buffer_getreadbuf,
  7938. (writebufferproc) unicode_buffer_getwritebuf,
  7939. (segcountproc) unicode_buffer_getsegcount,
  7940. (charbufferproc) unicode_buffer_getcharbuf,
  7941. };
  7942. static PyObject *
  7943. unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
  7944. static PyObject *
  7945. unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  7946. {
  7947. PyObject *x = NULL;
  7948. static char *kwlist[] = {"string", "encoding", "errors", 0};
  7949. char *encoding = NULL;
  7950. char *errors = NULL;
  7951. if (type != &PyUnicode_Type)
  7952. return unicode_subtype_new(type, args, kwds);
  7953. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:unicode",
  7954. kwlist, &x, &encoding, &errors))
  7955. return NULL;
  7956. if (x == NULL)
  7957. return (PyObject *)_PyUnicode_New(0);
  7958. if (encoding == NULL && errors == NULL)
  7959. return PyObject_Unicode(x);
  7960. else
  7961. return PyUnicode_FromEncodedObject(x, encoding, errors);
  7962. }
  7963. static PyObject *
  7964. unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  7965. {
  7966. PyUnicodeObject *tmp, *pnew;
  7967. Py_ssize_t n;
  7968. assert(PyType_IsSubtype(type, &PyUnicode_Type));
  7969. tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
  7970. if (tmp == NULL)
  7971. return NULL;
  7972. assert(PyUnicode_Check(tmp));
  7973. pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
  7974. if (pnew == NULL) {
  7975. Py_DECREF(tmp);
  7976. return NULL;
  7977. }
  7978. pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
  7979. if (pnew->str == NULL) {
  7980. _Py_ForgetReference((PyObject *)pnew);
  7981. PyObject_Del(pnew);
  7982. Py_DECREF(tmp);
  7983. return PyErr_NoMemory();
  7984. }
  7985. Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
  7986. pnew->length = n;
  7987. pnew->hash = tmp->hash;
  7988. Py_DECREF(tmp);
  7989. return (PyObject *)pnew;
  7990. }
  7991. PyDoc_STRVAR(unicode_doc,
  7992. "unicode(string [, encoding[, errors]]) -> object\n\
  7993. \n\
  7994. Create a new Unicode object from the given encoded string.\n\
  7995. encoding defaults to the current default string encoding.\n\
  7996. errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
  7997. PyTypeObject PyUnicode_Type = {
  7998. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  7999. "unicode", /* tp_name */
  8000. sizeof(PyUnicodeObject), /* tp_size */
  8001. 0, /* tp_itemsize */
  8002. /* Slots */
  8003. (destructor)unicode_dealloc, /* tp_dealloc */
  8004. 0, /* tp_print */
  8005. 0, /* tp_getattr */
  8006. 0, /* tp_setattr */
  8007. 0, /* tp_compare */
  8008. unicode_repr, /* tp_repr */
  8009. &unicode_as_number, /* tp_as_number */
  8010. &unicode_as_sequence, /* tp_as_sequence */
  8011. &unicode_as_mapping, /* tp_as_mapping */
  8012. (hashfunc) unicode_hash, /* tp_hash*/
  8013. 0, /* tp_call*/
  8014. (reprfunc) unicode_str, /* tp_str */
  8015. PyObject_GenericGetAttr, /* tp_getattro */
  8016. 0, /* tp_setattro */
  8017. &unicode_as_buffer, /* tp_as_buffer */
  8018. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
  8019. Py_TPFLAGS_BASETYPE | Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
  8020. unicode_doc, /* tp_doc */
  8021. 0, /* tp_traverse */
  8022. 0, /* tp_clear */
  8023. PyUnicode_RichCompare, /* tp_richcompare */
  8024. 0, /* tp_weaklistoffset */
  8025. 0, /* tp_iter */
  8026. 0, /* tp_iternext */
  8027. unicode_methods, /* tp_methods */
  8028. 0, /* tp_members */
  8029. 0, /* tp_getset */
  8030. &PyBaseString_Type, /* tp_base */
  8031. 0, /* tp_dict */
  8032. 0, /* tp_descr_get */
  8033. 0, /* tp_descr_set */
  8034. 0, /* tp_dictoffset */
  8035. 0, /* tp_init */
  8036. 0, /* tp_alloc */
  8037. unicode_new, /* tp_new */
  8038. PyObject_Del, /* tp_free */
  8039. };
  8040. /* Initialize the Unicode implementation */
  8041. void _PyUnicode_Init(void)
  8042. {
  8043. int i;
  8044. /* XXX - move this array to unicodectype.c ? */
  8045. Py_UNICODE linebreak[] = {
  8046. 0x000A, /* LINE FEED */
  8047. 0x000D, /* CARRIAGE RETURN */
  8048. 0x001C, /* FILE SEPARATOR */
  8049. 0x001D, /* GROUP SEPARATOR */
  8050. 0x001E, /* RECORD SEPARATOR */
  8051. 0x0085, /* NEXT LINE */
  8052. 0x2028, /* LINE SEPARATOR */
  8053. 0x2029, /* PARAGRAPH SEPARATOR */
  8054. };
  8055. /* Init the implementation */
  8056. free_list = NULL;
  8057. numfree = 0;
  8058. unicode_empty = _PyUnicode_New(0);
  8059. if (!unicode_empty)
  8060. return;
  8061. strcpy(unicode_default_encoding, "ascii");
  8062. for (i = 0; i < 256; i++)
  8063. unicode_latin1[i] = NULL;
  8064. if (PyType_Ready(&PyUnicode_Type) < 0)
  8065. Py_FatalError("Can't initialize 'unicode'");
  8066. /* initialize the linebreak bloom filter */
  8067. bloom_linebreak = make_bloom_mask(
  8068. linebreak, sizeof(linebreak) / sizeof(linebreak[0])
  8069. );
  8070. PyType_Ready(&EncodingMapType);
  8071. }
  8072. /* Finalize the Unicode implementation */
  8073. int
  8074. PyUnicode_ClearFreeList(void)
  8075. {
  8076. int freelist_size = numfree;
  8077. PyUnicodeObject *u;
  8078. for (u = free_list; u != NULL;) {
  8079. PyUnicodeObject *v = u;
  8080. u = *(PyUnicodeObject **)u;
  8081. if (v->str)
  8082. PyObject_DEL(v->str);
  8083. Py_XDECREF(v->defenc);
  8084. PyObject_Del(v);
  8085. numfree--;
  8086. }
  8087. free_list = NULL;
  8088. assert(numfree == 0);
  8089. return freelist_size;
  8090. }
  8091. void
  8092. _PyUnicode_Fini(void)
  8093. {
  8094. int i;
  8095. Py_XDECREF(unicode_empty);
  8096. unicode_empty = NULL;
  8097. for (i = 0; i < 256; i++) {
  8098. if (unicode_latin1[i]) {
  8099. Py_DECREF(unicode_latin1[i]);
  8100. unicode_latin1[i] = NULL;
  8101. }
  8102. }
  8103. (void)PyUnicode_ClearFreeList();
  8104. }
  8105. #ifdef __cplusplus
  8106. }
  8107. #endif
  8108. /*
  8109. Local variables:
  8110. c-basic-offset: 4
  8111. indent-tabs-mode: nil
  8112. End:
  8113. */