Debian Codegraph @

cpython27/Objects/unicodeobject.c

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