PageRenderTime 49ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 1ms

/python/src/Objects/unicodeobject.c

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