blob: 72326530c7b8a8f7e84339627a11cbc1850e1425 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Fred Drake785d14f2000-05-09 19:54:43 +00004modified by Marc-Andre Lemburg <mal@lemburg.com> according to the
Guido van Rossumd57fd912000-03-10 22:53:23 +00005Unicode Integration Proposal (see file Misc/unicode.txt).
6
Thomas Wouters477c8d52006-05-27 19:21:47 +00007Major speed upgrades to the method implementations at the Reykjavik
8NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
9
Guido van Rossum16b1ad92000-08-03 16:24:25 +000010Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000011
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000012--------------------------------------------------------------------
13The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000014
Benjamin Peterson29060642009-01-31 22:14:21 +000015 Copyright (c) 1999 by Secret Labs AB
16 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000017
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000018By obtaining, using, and/or copying this software and/or its
19associated documentation, you agree that you have read, understood,
20and will comply with the following terms and conditions:
21
22Permission to use, copy, modify, and distribute this software and its
23associated documentation for any purpose and without fee is hereby
24granted, provided that the above copyright notice appears in all
25copies, and that both that copyright notice and this permission notice
26appear in supporting documentation, and that the name of Secret Labs
27AB or the author not be used in advertising or publicity pertaining to
28distribution of the software without specific, written prior
29permission.
30
31SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
32THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
33FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
34ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
35WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
36ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
37OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38--------------------------------------------------------------------
39
40*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000041
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000042#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000043#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000044#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Guido van Rossumd57fd912000-03-10 22:53:23 +000050/* Limit for the Unicode object free list */
51
Christian Heimes2202f872008-02-06 14:31:34 +000052#define PyUnicode_MAXFREELIST 1024
Guido van Rossumd57fd912000-03-10 22:53:23 +000053
54/* Limit for the Unicode object free list stay alive optimization.
55
56 The implementation will keep allocated Unicode memory intact for
57 all objects on the free list having a size less than this
Tim Petersced69f82003-09-16 20:30:58 +000058 limit. This reduces malloc() overhead for small Unicode objects.
Guido van Rossumd57fd912000-03-10 22:53:23 +000059
Christian Heimes2202f872008-02-06 14:31:34 +000060 At worst this will result in PyUnicode_MAXFREELIST *
Guido van Rossumfd4b9572000-04-10 13:51:10 +000061 (sizeof(PyUnicodeObject) + KEEPALIVE_SIZE_LIMIT +
Guido van Rossumd57fd912000-03-10 22:53:23 +000062 malloc()-overhead) bytes of unused garbage.
63
64 Setting the limit to 0 effectively turns the feature off.
65
Guido van Rossumfd4b9572000-04-10 13:51:10 +000066 Note: This is an experimental feature ! If you get core dumps when
67 using Unicode objects, turn this feature off.
Guido van Rossumd57fd912000-03-10 22:53:23 +000068
69*/
70
Guido van Rossumfd4b9572000-04-10 13:51:10 +000071#define KEEPALIVE_SIZE_LIMIT 9
Guido van Rossumd57fd912000-03-10 22:53:23 +000072
73/* Endianness switches; defaults to little endian */
74
75#ifdef WORDS_BIGENDIAN
76# define BYTEORDER_IS_BIG_ENDIAN
77#else
78# define BYTEORDER_IS_LITTLE_ENDIAN
79#endif
80
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000081/* --- Globals ------------------------------------------------------------
82
83 The globals are initialized by the _PyUnicode_Init() API and should
84 not be used before calling that API.
85
86*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000087
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000088
89#ifdef __cplusplus
90extern "C" {
91#endif
92
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020093#define _PyUnicode_WSTR(op) (((PyASCIIObject*)(op))->wstr)
94#define _PyUnicode_WSTR_LENGTH(op) (((PyCompactUnicodeObject*)(op))->wstr_length)
95#define _PyUnicode_LENGTH(op) (((PyASCIIObject *)(op))->length)
96#define _PyUnicode_STATE(op) (((PyASCIIObject *)(op))->state)
97#define _PyUnicode_HASH(op) (((PyASCIIObject *)(op))->hash)
98#define _PyUnicode_KIND(op) \
99 (assert(PyUnicode_Check(op)), \
100 ((PyASCIIObject *)(op))->state.kind)
101#define _PyUnicode_GET_LENGTH(op) \
102 (assert(PyUnicode_Check(op)), \
103 ((PyASCIIObject *)(op))->length)
104
105
Walter Dörwald16807132007-05-25 13:52:07 +0000106/* This dictionary holds all interned unicode strings. Note that references
107 to strings in this dictionary are *not* counted in the string's ob_refcnt.
108 When the interned string reaches a refcnt of 0 the string deallocation
109 function will delete the reference from this dictionary.
110
111 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000112 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000113*/
114static PyObject *interned;
115
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000116/* The empty Unicode object is shared to improve performance. */
117static PyUnicodeObject *unicode_empty;
118
119/* Single character Unicode strings in the Latin-1 range are being
120 shared as well. */
121static PyUnicodeObject *unicode_latin1[256];
122
Christian Heimes190d79e2008-01-30 11:58:22 +0000123/* Fast detection of the most frequent whitespace characters */
124const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000125 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000126/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000127/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000128/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000129/* case 0x000C: * FORM FEED */
130/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000131 0, 1, 1, 1, 1, 1, 0, 0,
132 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000133/* case 0x001C: * FILE SEPARATOR */
134/* case 0x001D: * GROUP SEPARATOR */
135/* case 0x001E: * RECORD SEPARATOR */
136/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000137 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000138/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000139 1, 0, 0, 0, 0, 0, 0, 0,
140 0, 0, 0, 0, 0, 0, 0, 0,
141 0, 0, 0, 0, 0, 0, 0, 0,
142 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000143
Benjamin Peterson14339b62009-01-31 16:36:08 +0000144 0, 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 0, 0, 0, 0, 0, 0, 0, 0,
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
Christian Heimes190d79e2008-01-30 11:58:22 +0000152};
153
Alexander Belopolsky40018472011-02-26 01:02:56 +0000154static PyObject *
155unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000156 PyObject **errorHandler,const char *encoding, const char *reason,
157 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
158 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
159
Alexander Belopolsky40018472011-02-26 01:02:56 +0000160static void
161raise_encode_exception(PyObject **exceptionObject,
162 const char *encoding,
163 const Py_UNICODE *unicode, Py_ssize_t size,
164 Py_ssize_t startpos, Py_ssize_t endpos,
165 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000166
Christian Heimes190d79e2008-01-30 11:58:22 +0000167/* Same for linebreaks */
168static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000169 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000170/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000171/* 0x000B, * LINE TABULATION */
172/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000173/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000174 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000175 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000176/* 0x001C, * FILE SEPARATOR */
177/* 0x001D, * GROUP SEPARATOR */
178/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000179 0, 0, 0, 0, 1, 1, 1, 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,
Christian Heimes190d79e2008-01-30 11:58:22 +0000184
Benjamin Peterson14339b62009-01-31 16:36:08 +0000185 0, 0, 0, 0, 0, 0, 0, 0,
186 0, 0, 0, 0, 0, 0, 0, 0,
187 0, 0, 0, 0, 0, 0, 0, 0,
188 0, 0, 0, 0, 0, 0, 0, 0,
189 0, 0, 0, 0, 0, 0, 0, 0,
190 0, 0, 0, 0, 0, 0, 0, 0,
191 0, 0, 0, 0, 0, 0, 0, 0,
192 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000193};
194
195
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000196Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000197PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000198{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000199#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000200 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000201#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000202 /* This is actually an illegal character, so it should
203 not be passed to unichr. */
204 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000205#endif
206}
207
Thomas Wouters477c8d52006-05-27 19:21:47 +0000208/* --- Bloom Filters ----------------------------------------------------- */
209
210/* stuff to implement simple "bloom filters" for Unicode characters.
211 to keep things simple, we use a single bitmask, using the least 5
212 bits from each unicode characters as the bit index. */
213
214/* the linebreak mask is set up by Unicode_Init below */
215
Antoine Pitrouf068f942010-01-13 14:19:12 +0000216#if LONG_BIT >= 128
217#define BLOOM_WIDTH 128
218#elif LONG_BIT >= 64
219#define BLOOM_WIDTH 64
220#elif LONG_BIT >= 32
221#define BLOOM_WIDTH 32
222#else
223#error "LONG_BIT is smaller than 32"
224#endif
225
Thomas Wouters477c8d52006-05-27 19:21:47 +0000226#define BLOOM_MASK unsigned long
227
228static BLOOM_MASK bloom_linebreak;
229
Antoine Pitrouf068f942010-01-13 14:19:12 +0000230#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
231#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000232
Benjamin Peterson29060642009-01-31 22:14:21 +0000233#define BLOOM_LINEBREAK(ch) \
234 ((ch) < 128U ? ascii_linebreak[(ch)] : \
235 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000236
Alexander Belopolsky40018472011-02-26 01:02:56 +0000237Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200238make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000239{
240 /* calculate simple bloom-style bitmask for a given unicode string */
241
Antoine Pitrouf068f942010-01-13 14:19:12 +0000242 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000243 Py_ssize_t i;
244
245 mask = 0;
246 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200247 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000248
249 return mask;
250}
251
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200252#define BLOOM_MEMBER(mask, chr, str) \
253 (BLOOM(mask, chr) \
254 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000255
Guido van Rossumd57fd912000-03-10 22:53:23 +0000256/* --- Unicode Object ----------------------------------------------------- */
257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200258static PyObject *
259substring(PyUnicodeObject *self, Py_ssize_t start, Py_ssize_t len);
260
261static PyObject *
262fixup(PyUnicodeObject *self, Py_UCS4 (*fixfct)(PyUnicodeObject *s));
263
264Py_LOCAL_INLINE(char *) findchar(void *s, int kind,
265 Py_ssize_t size, Py_UCS4 ch,
266 int direction)
267{
268 /* like wcschr, but doesn't stop at NULL characters */
269 Py_ssize_t i;
270 if (direction == 1) {
271 for(i = 0; i < size; i++)
272 if (PyUnicode_READ(kind, s, i) == ch)
273 return (char*)s + PyUnicode_KIND_SIZE(kind, i);
274 }
275 else {
276 for(i = size-1; i >= 0; i--)
277 if (PyUnicode_READ(kind, s, i) == ch)
278 return (char*)s + PyUnicode_KIND_SIZE(kind, i);
279 }
280 return NULL;
281}
282
Alexander Belopolsky40018472011-02-26 01:02:56 +0000283static int
284unicode_resize(register PyUnicodeObject *unicode,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200285 Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000286{
287 void *oldstr;
Tim Petersced69f82003-09-16 20:30:58 +0000288
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200289 /* Resizing is only supported for old unicode objects. */
290 assert(!PyUnicode_IS_COMPACT(unicode));
291 assert(_PyUnicode_WSTR(unicode) != NULL);
292
293 /* ... and only if they have not been readied yet, because
294 callees usually rely on the wstr representation when resizing. */
295 assert(unicode->data.any == NULL);
296
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000297 /* Shortcut if there's nothing much to do. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200298 if (_PyUnicode_WSTR_LENGTH(unicode) == length)
Benjamin Peterson29060642009-01-31 22:14:21 +0000299 goto reset;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000300
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000301 /* Resizing shared object (unicode_empty or single character
302 objects) in-place is not allowed. Use PyUnicode_Resize()
303 instead ! */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000304
Benjamin Peterson14339b62009-01-31 16:36:08 +0000305 if (unicode == unicode_empty ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200306 (_PyUnicode_WSTR_LENGTH(unicode) == 1 &&
307 _PyUnicode_WSTR(unicode)[0] < 256U &&
308 unicode_latin1[_PyUnicode_WSTR(unicode)[0]] == unicode)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +0000309 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson142957c2008-07-04 19:55:29 +0000310 "can't resize shared str objects");
Guido van Rossumd57fd912000-03-10 22:53:23 +0000311 return -1;
312 }
313
Thomas Wouters477c8d52006-05-27 19:21:47 +0000314 /* We allocate one more byte to make sure the string is Ux0000 terminated.
315 The overallocation is also used by fastsearch, which assumes that it's
316 safe to look at str[length] (without making any assumptions about what
317 it contains). */
318
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200319 oldstr = _PyUnicode_WSTR(unicode);
320 _PyUnicode_WSTR(unicode) = PyObject_REALLOC(_PyUnicode_WSTR(unicode),
321 sizeof(Py_UNICODE) * (length + 1));
322 if (!_PyUnicode_WSTR(unicode)) {
323 _PyUnicode_WSTR(unicode) = (Py_UNICODE *)oldstr;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000324 PyErr_NoMemory();
325 return -1;
326 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200327 _PyUnicode_WSTR(unicode)[length] = 0;
328 _PyUnicode_WSTR_LENGTH(unicode) = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000329
Benjamin Peterson29060642009-01-31 22:14:21 +0000330 reset:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200331 if (unicode->data.any != NULL) {
332 PyObject_FREE(unicode->data.any);
333 if (unicode->_base.utf8 && unicode->_base.utf8 != unicode->data.any) {
334 PyObject_FREE(unicode->_base.utf8);
335 }
336 unicode->_base.utf8 = NULL;
337 unicode->_base.utf8_length = 0;
338 unicode->data.any = NULL;
339 _PyUnicode_LENGTH(unicode) = 0;
340 _PyUnicode_STATE(unicode).interned = _PyUnicode_STATE(unicode).interned;
341 _PyUnicode_STATE(unicode).kind = PyUnicode_WCHAR_KIND;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000342 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200343 _PyUnicode_HASH(unicode) = -1;
Tim Petersced69f82003-09-16 20:30:58 +0000344
Guido van Rossumd57fd912000-03-10 22:53:23 +0000345 return 0;
346}
347
348/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000349 Ux0000 terminated; some code (e.g. new_identifier)
350 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000351
352 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000353 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000354
355*/
356
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200357#ifdef Py_DEBUG
358int unicode_old_new_calls = 0;
359#endif
360
Alexander Belopolsky40018472011-02-26 01:02:56 +0000361static PyUnicodeObject *
362_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000363{
364 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200365 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000366
Thomas Wouters477c8d52006-05-27 19:21:47 +0000367 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000368 if (length == 0 && unicode_empty != NULL) {
369 Py_INCREF(unicode_empty);
370 return unicode_empty;
371 }
372
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000373 /* Ensure we won't overflow the size. */
374 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
375 return (PyUnicodeObject *)PyErr_NoMemory();
376 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200377 if (length < 0) {
378 PyErr_SetString(PyExc_SystemError,
379 "Negative size passed to _PyUnicode_New");
380 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000381 }
382
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200383#ifdef Py_DEBUG
384 ++unicode_old_new_calls;
385#endif
386
387 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
388 if (unicode == NULL)
389 return NULL;
390 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
391 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
392 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000393 PyErr_NoMemory();
394 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000395 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200396
Jeremy Hyltond8082792003-09-16 19:41:39 +0000397 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000398 * the caller fails before initializing str -- unicode_resize()
399 * reads str[0], and the Keep-Alive optimization can keep memory
400 * allocated for str alive across a call to unicode_dealloc(unicode).
401 * We don't want unicode_resize to read uninitialized memory in
402 * that case.
403 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200404 _PyUnicode_WSTR(unicode)[0] = 0;
405 _PyUnicode_WSTR(unicode)[length] = 0;
406 _PyUnicode_WSTR_LENGTH(unicode) = length;
407 _PyUnicode_HASH(unicode) = -1;
408 _PyUnicode_STATE(unicode).interned = 0;
409 _PyUnicode_STATE(unicode).kind = 0;
410 _PyUnicode_STATE(unicode).compact = 0;
411 _PyUnicode_STATE(unicode).ready = 0;
412 _PyUnicode_STATE(unicode).ascii = 0;
413 unicode->data.any = NULL;
414 _PyUnicode_LENGTH(unicode) = 0;
415 unicode->_base.utf8 = NULL;
416 unicode->_base.utf8_length = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000417 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000418
Benjamin Peterson29060642009-01-31 22:14:21 +0000419 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000420 /* XXX UNREF/NEWREF interface should be more symmetrical */
421 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000422 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000423 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000424 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000425}
426
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200427#ifdef Py_DEBUG
428int unicode_new_new_calls = 0;
429
430/* Functions wrapping macros for use in debugger */
431char *_PyUnicode_utf8(void *unicode){
432 return _PyUnicode_UTF8(unicode);
433}
434
435void *_PyUnicode_compact_data(void *unicode) {
436 return _PyUnicode_COMPACT_DATA(unicode);
437}
438void *_PyUnicode_data(void *unicode){
439 printf("obj %p\n", unicode);
440 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
441 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
442 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
443 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
444 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
445 return PyUnicode_DATA(unicode);
446}
447#endif
448
449PyObject *
450PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
451{
452 PyObject *obj;
453 PyCompactUnicodeObject *unicode;
454 void *data;
455 int kind_state;
456 int is_sharing = 0, is_ascii = 0;
457 Py_ssize_t char_size;
458 Py_ssize_t struct_size;
459
460 /* Optimization for empty strings */
461 if (size == 0 && unicode_empty != NULL) {
462 Py_INCREF(unicode_empty);
463 return (PyObject *)unicode_empty;
464 }
465
466#ifdef Py_DEBUG
467 ++unicode_new_new_calls;
468#endif
469
470 struct_size = sizeof(PyCompactUnicodeObject);
471 if (maxchar < 128) {
472 kind_state = PyUnicode_1BYTE_KIND;
473 char_size = 1;
474 is_ascii = 1;
475 struct_size = sizeof(PyASCIIObject);
476 }
477 else if (maxchar < 256) {
478 kind_state = PyUnicode_1BYTE_KIND;
479 char_size = 1;
480 }
481 else if (maxchar < 65536) {
482 kind_state = PyUnicode_2BYTE_KIND;
483 char_size = 2;
484 if (sizeof(wchar_t) == 2)
485 is_sharing = 1;
486 }
487 else {
488 kind_state = PyUnicode_4BYTE_KIND;
489 char_size = 4;
490 if (sizeof(wchar_t) == 4)
491 is_sharing = 1;
492 }
493
494 /* Ensure we won't overflow the size. */
495 if (size < 0) {
496 PyErr_SetString(PyExc_SystemError,
497 "Negative size passed to PyUnicode_New");
498 return NULL;
499 }
500 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
501 return PyErr_NoMemory();
502
503 /* Duplicated allocation code from _PyObject_New() instead of a call to
504 * PyObject_New() so we are able to allocate space for the object and
505 * it's data buffer.
506 */
507 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
508 if (obj == NULL)
509 return PyErr_NoMemory();
510 obj = PyObject_INIT(obj, &PyUnicode_Type);
511 if (obj == NULL)
512 return NULL;
513
514 unicode = (PyCompactUnicodeObject *)obj;
515 if (is_ascii)
516 data = ((PyASCIIObject*)obj) + 1;
517 else
518 data = unicode + 1;
519 _PyUnicode_LENGTH(unicode) = size;
520 _PyUnicode_HASH(unicode) = -1;
521 _PyUnicode_STATE(unicode).interned = 0;
522 _PyUnicode_STATE(unicode).kind = kind_state;
523 _PyUnicode_STATE(unicode).compact = 1;
524 _PyUnicode_STATE(unicode).ready = 1;
525 _PyUnicode_STATE(unicode).ascii = is_ascii;
526 if (is_ascii) {
527 ((char*)data)[size] = 0;
528 _PyUnicode_WSTR(unicode) = NULL;
529 }
530 else if (kind_state == PyUnicode_1BYTE_KIND) {
531 ((char*)data)[size] = 0;
532 _PyUnicode_WSTR(unicode) = NULL;
533 _PyUnicode_WSTR_LENGTH(unicode) = 0;
534 unicode->utf8_length = 0;
535 unicode->utf8 = NULL;
536 }
537 else {
538 unicode->utf8 = NULL;
539 if (kind_state == PyUnicode_2BYTE_KIND)
540 ((Py_UCS2*)data)[size] = 0;
541 else /* kind_state == PyUnicode_4BYTE_KIND */
542 ((Py_UCS4*)data)[size] = 0;
543 if (is_sharing) {
544 _PyUnicode_WSTR_LENGTH(unicode) = size;
545 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
546 }
547 else {
548 _PyUnicode_WSTR_LENGTH(unicode) = 0;
549 _PyUnicode_WSTR(unicode) = NULL;
550 }
551 }
552 return obj;
553}
554
555#if SIZEOF_WCHAR_T == 2
556/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
557 will decode surrogate pairs, the other conversions are implemented as macros
558 for efficency.
559
560 This function assumes that unicode can hold one more code point than wstr
561 characters for a terminating null character. */
562static int
563unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
564 PyUnicodeObject *unicode)
565{
566 const wchar_t *iter;
567 Py_UCS4 *ucs4_out;
568
569 assert(unicode && PyUnicode_Check(unicode));
570 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
571 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
572
573 for (iter = begin; iter < end; ) {
574 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
575 _PyUnicode_GET_LENGTH(unicode)));
576 if (*iter >= 0xD800 && *iter <= 0xDBFF
577 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
578 {
579 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
580 iter += 2;
581 }
582 else {
583 *ucs4_out++ = *iter;
584 iter++;
585 }
586 }
587 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
588 _PyUnicode_GET_LENGTH(unicode)));
589
590 return 0;
591}
592#endif
593
594int
595PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
596 PyObject *from, Py_ssize_t from_start,
597 Py_ssize_t how_many)
598{
599 int from_kind;
600 int to_kind;
601
602 assert(PyUnicode_Check(from));
603 assert(PyUnicode_Check(to));
604
605 if (PyUnicode_READY(from))
606 return -1;
607 if (PyUnicode_READY(to))
608 return -1;
609
610 from_kind = PyUnicode_KIND(from);
611 to_kind = PyUnicode_KIND(to);
612
613 if (from_kind == to_kind) {
614 const Py_ssize_t char_size = PyUnicode_CHARACTER_SIZE(to);
615 Py_MEMCPY(PyUnicode_1BYTE_DATA(to) + (to_start * char_size),
616 PyUnicode_1BYTE_DATA(from) + (from_start * char_size),
617 how_many * char_size);
618 return 0;
619 }
620
621 switch (from_kind) {
622 case PyUnicode_1BYTE_KIND:
623 switch (to_kind) {
624 case PyUnicode_2BYTE_KIND:
625 PyUnicode_CONVERT_BYTES(
626 unsigned char, Py_UCS2,
627 PyUnicode_1BYTE_DATA(from) + from_start,
628 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
629 PyUnicode_2BYTE_DATA(to) + to_start
630 );
631 break;
632 case PyUnicode_4BYTE_KIND:
633 PyUnicode_CONVERT_BYTES(
634 unsigned char, Py_UCS4,
635 PyUnicode_1BYTE_DATA(from) + from_start,
636 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
637 PyUnicode_4BYTE_DATA(to) + to_start
638 );
639 break;
640 default:
641 goto invalid_state;
642 }
643 break;
644 case PyUnicode_2BYTE_KIND:
645 switch (to_kind) {
646 case PyUnicode_1BYTE_KIND:
647 PyUnicode_CONVERT_BYTES(
648 Py_UCS2, unsigned char,
649 PyUnicode_2BYTE_DATA(from) + from_start,
650 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
651 PyUnicode_1BYTE_DATA(to) + to_start
652 );
653 break;
654 case PyUnicode_4BYTE_KIND:
655 PyUnicode_CONVERT_BYTES(
656 Py_UCS2, Py_UCS4,
657 PyUnicode_2BYTE_DATA(from) + from_start,
658 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
659 PyUnicode_4BYTE_DATA(to) + to_start
660 );
661 break;
662 default:
663 goto invalid_state;
664 }
665 break;
666 case PyUnicode_4BYTE_KIND:
667 switch (to_kind) {
668 case PyUnicode_1BYTE_KIND:
669 PyUnicode_CONVERT_BYTES(
670 Py_UCS4, unsigned char,
671 PyUnicode_4BYTE_DATA(from) + from_start,
672 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
673 PyUnicode_1BYTE_DATA(to) + to_start
674 );
675 break;
676 case PyUnicode_2BYTE_KIND:
677 PyUnicode_CONVERT_BYTES(
678 Py_UCS4, Py_UCS2,
679 PyUnicode_4BYTE_DATA(from) + from_start,
680 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
681 PyUnicode_2BYTE_DATA(to) + to_start
682 );
683 break;
684 default:
685 goto invalid_state;
686 }
687 break;
688 default:
689 goto invalid_state;
690 }
691 return 0;
692
693invalid_state:
694 PyErr_Format(PyExc_ValueError,
695 "Impossible kind state (from=%i, to=%i) "
696 "in PyUnicode_CopyCharacters",
697 from_kind, to_kind);
698 return -1;
699}
700
701int
702_PyUnicode_FindMaxCharAndNumSurrogatePairs(const wchar_t *begin,
703 const wchar_t *end,
704 Py_UCS4 *maxchar,
705 Py_ssize_t *num_surrogates)
706{
707 const wchar_t *iter;
708
709 if (num_surrogates == NULL || maxchar == NULL) {
710 PyErr_SetString(PyExc_SystemError,
711 "unexpected NULL arguments to "
712 "PyUnicode_FindMaxCharAndNumSurrogatePairs");
713 return -1;
714 }
715
716 *num_surrogates = 0;
717 *maxchar = 0;
718
719 for (iter = begin; iter < end; ) {
720 if (*iter > *maxchar)
721 *maxchar = *iter;
722#if SIZEOF_WCHAR_T == 2
723 if (*iter >= 0xD800 && *iter <= 0xDBFF
724 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
725 {
726 Py_UCS4 surrogate_val;
727 surrogate_val = (((iter[0] & 0x3FF)<<10)
728 | (iter[1] & 0x3FF)) + 0x10000;
729 ++(*num_surrogates);
730 if (surrogate_val > *maxchar)
731 *maxchar = surrogate_val;
732 iter += 2;
733 }
734 else
735 iter++;
736#else
737 iter++;
738#endif
739 }
740 return 0;
741}
742
743#ifdef Py_DEBUG
744int unicode_ready_calls = 0;
745#endif
746
747int
748_PyUnicode_Ready(PyUnicodeObject *unicode)
749{
750 wchar_t *end;
751 Py_UCS4 maxchar = 0;
752 Py_ssize_t num_surrogates;
753#if SIZEOF_WCHAR_T == 2
754 Py_ssize_t length_wo_surrogates;
755#endif
756
757 assert(PyUnicode_Check(unicode));
758
759 if (unicode->data.any != NULL) {
760 assert(PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND);
761 return 0;
762 }
763
764 /* _PyUnicode_Ready() is only intented for old-style API usage where
765 * strings were created using _PyObject_New() and where no canonical
766 * representation (the str field) has been set yet aka strings
767 * which are not yet ready.
768 */
769 assert(_PyUnicode_WSTR(unicode) != NULL);
770 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
771 assert(!PyUnicode_IS_COMPACT(unicode));
772 assert(!PyUnicode_IS_READY(unicode));
773 /* Actually, it should neither be interned nor be anything else: */
774 assert(_PyUnicode_STATE(unicode).interned == 0);
775 assert(unicode->_base.utf8 == NULL);
776
777#ifdef Py_DEBUG
778 ++unicode_ready_calls;
779#endif
780
781 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
782 if (_PyUnicode_FindMaxCharAndNumSurrogatePairs(_PyUnicode_WSTR(unicode), end,
783 &maxchar,
784 &num_surrogates) == -1) {
785 assert(0 && "PyUnicode_FindMaxCharAndNumSurrogatePairs failed");
786 return -1;
787 }
788
789 if (maxchar < 256) {
790 unicode->data.any = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
791 if (!unicode->data.any) {
792 PyErr_NoMemory();
793 return -1;
794 }
795 PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
796 _PyUnicode_WSTR(unicode), end,
797 PyUnicode_1BYTE_DATA(unicode));
798 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
799 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
800 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
801 if (maxchar < 128) {
802 unicode->_base.utf8 = unicode->data.any;
803 unicode->_base.utf8_length = _PyUnicode_WSTR_LENGTH(unicode);
804 }
805 else {
806 unicode->_base.utf8 = NULL;
807 unicode->_base.utf8_length = 0;
808 }
809 PyObject_FREE(_PyUnicode_WSTR(unicode));
810 _PyUnicode_WSTR(unicode) = NULL;
811 _PyUnicode_WSTR_LENGTH(unicode) = 0;
812 }
813 /* In this case we might have to convert down from 4-byte native
814 wchar_t to 2-byte unicode. */
815 else if (maxchar < 65536) {
816 assert(num_surrogates == 0 &&
817 "FindMaxCharAndNumSurrogatePairs() messed up");
818
819 if (sizeof(wchar_t) == 2) {
820 /* We can share representations and are done. */
821 unicode->data.any = _PyUnicode_WSTR(unicode);
822 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
823 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
824 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
825 unicode->_base.utf8 = NULL;
826 unicode->_base.utf8_length = 0;
827 }
828 else {
829 assert(sizeof(wchar_t) == 4);
830
831 unicode->data.any = PyObject_MALLOC(
832 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
833 if (!unicode->data.any) {
834 PyErr_NoMemory();
835 return -1;
836 }
837 PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
838 _PyUnicode_WSTR(unicode), end,
839 PyUnicode_2BYTE_DATA(unicode));
840 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
841 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
842 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
843 unicode->_base.utf8 = NULL;
844 unicode->_base.utf8_length = 0;
845 PyObject_FREE(_PyUnicode_WSTR(unicode));
846 _PyUnicode_WSTR(unicode) = NULL;
847 _PyUnicode_WSTR_LENGTH(unicode) = 0;
848 }
849 }
850 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
851 else {
852#if SIZEOF_WCHAR_T == 2
853 /* in case the native representation is 2-bytes, we need to allocate a
854 new normalized 4-byte version. */
855 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
856 unicode->data.any = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
857 if (!unicode->data.any) {
858 PyErr_NoMemory();
859 return -1;
860 }
861 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
862 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
863 unicode->_base.utf8 = NULL;
864 unicode->_base.utf8_length = 0;
865 if (unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end,
866 unicode) < 0) {
867 assert(0 && "ConvertWideCharToUCS4 failed");
868 return -1;
869 }
870 PyObject_FREE(_PyUnicode_WSTR(unicode));
871 _PyUnicode_WSTR(unicode) = NULL;
872 _PyUnicode_WSTR_LENGTH(unicode) = 0;
873#else
874 assert(num_surrogates == 0);
875
876 unicode->data.any = _PyUnicode_WSTR(unicode);
877 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
878 unicode->_base.utf8 = NULL;
879 unicode->_base.utf8_length = 0;
880 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
881#endif
882 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
883 }
884 _PyUnicode_STATE(unicode).ready = 1;
885 return 0;
886}
887
Alexander Belopolsky40018472011-02-26 01:02:56 +0000888static void
889unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000890{
Walter Dörwald16807132007-05-25 13:52:07 +0000891 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000892 case SSTATE_NOT_INTERNED:
893 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000894
Benjamin Peterson29060642009-01-31 22:14:21 +0000895 case SSTATE_INTERNED_MORTAL:
896 /* revive dead object temporarily for DelItem */
897 Py_REFCNT(unicode) = 3;
898 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
899 Py_FatalError(
900 "deletion of interned string failed");
901 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000902
Benjamin Peterson29060642009-01-31 22:14:21 +0000903 case SSTATE_INTERNED_IMMORTAL:
904 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +0000905
Benjamin Peterson29060642009-01-31 22:14:21 +0000906 default:
907 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +0000908 }
909
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200910 if (_PyUnicode_WSTR(unicode) &&
911 (!PyUnicode_IS_READY(unicode) ||
912 _PyUnicode_WSTR(unicode) != PyUnicode_DATA(unicode)))
913 PyObject_DEL(_PyUnicode_WSTR(unicode));
914 if (_PyUnicode_UTF8(unicode) && _PyUnicode_UTF8(unicode) != PyUnicode_DATA(unicode))
915 PyObject_DEL(unicode->_base.utf8);
916
917 if (PyUnicode_IS_COMPACT(unicode)) {
918 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000919 }
920 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200921 if (unicode->data.any)
922 PyObject_DEL(unicode->data.any);
Benjamin Peterson29060642009-01-31 22:14:21 +0000923 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000924 }
925}
926
Alexander Belopolsky40018472011-02-26 01:02:56 +0000927static int
928_PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000929{
930 register PyUnicodeObject *v;
931
932 /* Argument checks */
933 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000934 PyErr_BadInternalCall();
935 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000936 }
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000937 v = *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200938 if (v == NULL || !PyUnicode_Check(v) || Py_REFCNT(v) != 1 || length < 0 ||
939 PyUnicode_IS_COMPACT(v) || _PyUnicode_WSTR(v) == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000940 PyErr_BadInternalCall();
941 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000942 }
943
944 /* Resizing unicode_empty and single character objects is not
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200945 possible since these are being shared.
946 The same goes for new-representation unicode objects or objects which
947 have already been readied.
948 For these, we simply return a fresh copy with the same Unicode content.
949 */
950 if ((_PyUnicode_WSTR_LENGTH(v) != length &&
951 (v == unicode_empty || _PyUnicode_WSTR_LENGTH(v) == 1)) ||
952 PyUnicode_IS_COMPACT(v) || v->data.any) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000953 PyUnicodeObject *w = _PyUnicode_New(length);
954 if (w == NULL)
955 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200956 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(v),
957 length < _PyUnicode_WSTR_LENGTH(v) ? length : _PyUnicode_WSTR_LENGTH(v));
Benjamin Peterson29060642009-01-31 22:14:21 +0000958 Py_DECREF(*unicode);
959 *unicode = w;
960 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000961 }
962
963 /* Note that we don't have to modify *unicode for unshared Unicode
964 objects, since we can modify them in-place. */
965 return unicode_resize(v, length);
966}
967
Alexander Belopolsky40018472011-02-26 01:02:56 +0000968int
969PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000970{
971 return _PyUnicode_Resize((PyUnicodeObject **)unicode, length);
972}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000973
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200974static PyObject*
975get_latin1_char(unsigned char ch)
976{
977 PyUnicodeObject *unicode = unicode_latin1[ch];
978 if (!unicode) {
979 unicode = (PyUnicodeObject *)PyUnicode_New(1, ch);
980 if (!unicode)
981 return NULL;
982 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
983 unicode_latin1[ch] = unicode;
984 }
985 Py_INCREF(unicode);
986 return (PyObject *)unicode;
987}
988
Alexander Belopolsky40018472011-02-26 01:02:56 +0000989PyObject *
990PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000991{
992 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200993 Py_UCS4 maxchar = 0;
994 Py_ssize_t num_surrogates;
995
996 if (u == NULL)
997 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000998
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000999 /* If the Unicode data is known at construction time, we can apply
1000 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001001
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001002 /* Optimization for empty strings */
1003 if (size == 0 && unicode_empty != NULL) {
1004 Py_INCREF(unicode_empty);
1005 return (PyObject *)unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001006 }
Tim Petersced69f82003-09-16 20:30:58 +00001007
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001008 /* Single character Unicode objects in the Latin-1 range are
1009 shared when using this constructor */
1010 if (size == 1 && *u < 256)
1011 return get_latin1_char((unsigned char)*u);
1012
1013 /* If not empty and not single character, copy the Unicode data
1014 into the new object */
1015 if (_PyUnicode_FindMaxCharAndNumSurrogatePairs(u, u + size, &maxchar,
1016 &num_surrogates) == -1)
1017 return NULL;
1018
1019 unicode = (PyUnicodeObject *) PyUnicode_New(size - num_surrogates,
1020 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001021 if (!unicode)
1022 return NULL;
1023
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001024 switch (PyUnicode_KIND(unicode)) {
1025 case PyUnicode_1BYTE_KIND:
1026 PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
1027 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1028 break;
1029 case PyUnicode_2BYTE_KIND:
1030#if Py_UNICODE_SIZE == 2
1031 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1032#else
1033 PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
1034 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1035#endif
1036 break;
1037 case PyUnicode_4BYTE_KIND:
1038#if SIZEOF_WCHAR_T == 2
1039 /* This is the only case which has to process surrogates, thus
1040 a simple copy loop is not enough and we need a function. */
1041 if (unicode_convert_wchar_to_ucs4(u, u + size, unicode) < 0) {
1042 Py_DECREF(unicode);
1043 return NULL;
1044 }
1045#else
1046 assert(num_surrogates == 0);
1047 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1048#endif
1049 break;
1050 default:
1051 assert(0 && "Impossible state");
1052 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001053
1054 return (PyObject *)unicode;
1055}
1056
Alexander Belopolsky40018472011-02-26 01:02:56 +00001057PyObject *
1058PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001059{
1060 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +00001061
Benjamin Peterson14339b62009-01-31 16:36:08 +00001062 if (size < 0) {
1063 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001064 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001065 return NULL;
1066 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001067
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001068 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001069 some optimizations which share commonly used objects.
1070 Also, this means the input must be UTF-8, so fall back to the
1071 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001072 if (u != NULL) {
1073
Benjamin Peterson29060642009-01-31 22:14:21 +00001074 /* Optimization for empty strings */
1075 if (size == 0 && unicode_empty != NULL) {
1076 Py_INCREF(unicode_empty);
1077 return (PyObject *)unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001078 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001079
1080 /* Single characters are shared when using this constructor.
1081 Restrict to ASCII, since the input must be UTF-8. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001082 if (size == 1 && Py_CHARMASK(*u) < 128)
1083 return get_latin1_char(Py_CHARMASK(*u));
Martin v. Löwis9c121062007-08-05 20:26:11 +00001084
1085 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001086 }
1087
Walter Dörwald55507312007-05-18 13:12:10 +00001088 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001089 if (!unicode)
1090 return NULL;
1091
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001092 return (PyObject *)unicode;
1093}
1094
Alexander Belopolsky40018472011-02-26 01:02:56 +00001095PyObject *
1096PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001097{
1098 size_t size = strlen(u);
1099 if (size > PY_SSIZE_T_MAX) {
1100 PyErr_SetString(PyExc_OverflowError, "input too long");
1101 return NULL;
1102 }
1103
1104 return PyUnicode_FromStringAndSize(u, size);
1105}
1106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001107PyObject*
1108PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001109{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001110 PyObject *res;
1111 unsigned char max = 127;
1112 Py_ssize_t i;
1113 for (i = 0; i < size; i++) {
1114 if (u[i] & 0x80) {
1115 max = 255;
1116 break;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001117 }
1118 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001119 res = PyUnicode_New(size, max);
1120 if (!res)
1121 return NULL;
1122 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
1123 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001124}
1125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001126PyObject*
1127PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
1128{
1129 PyObject *res;
1130 Py_UCS2 max = 0;
1131 Py_ssize_t i;
1132 for (i = 0; i < size; i++)
1133 if (u[i] > max)
1134 max = u[i];
1135 res = PyUnicode_New(size, max);
1136 if (!res)
1137 return NULL;
1138 if (max >= 256)
1139 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
1140 else
1141 for (i = 0; i < size; i++)
1142 PyUnicode_1BYTE_DATA(res)[i] = (Py_UCS1)u[i];
1143 return res;
1144}
1145
1146PyObject*
1147PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
1148{
1149 PyObject *res;
1150 Py_UCS4 max = 0;
1151 Py_ssize_t i;
1152 for (i = 0; i < size; i++)
1153 if (u[i] > max)
1154 max = u[i];
1155 res = PyUnicode_New(size, max);
1156 if (!res)
1157 return NULL;
1158 if (max >= 0x10000)
1159 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
1160 else {
1161 int kind = PyUnicode_KIND(res);
1162 void *data = PyUnicode_DATA(res);
1163 for (i = 0; i < size; i++)
1164 PyUnicode_WRITE(kind, data, i, u[i]);
1165 }
1166 return res;
1167}
1168
1169PyObject*
1170PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1171{
1172 switch(kind) {
1173 case PyUnicode_1BYTE_KIND:
1174 return PyUnicode_FromUCS1(buffer, size);
1175 case PyUnicode_2BYTE_KIND:
1176 return PyUnicode_FromUCS2(buffer, size);
1177 case PyUnicode_4BYTE_KIND:
1178 return PyUnicode_FromUCS4(buffer, size);
1179 }
1180 assert(0);
1181 return NULL;
1182}
1183
1184
1185/* Widen Unicode objects to larger buffers.
1186 Return NULL if the string is too wide already. */
1187
1188void*
1189_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1190{
1191 Py_ssize_t i;
1192 Py_ssize_t len = PyUnicode_GET_LENGTH(s);
1193 void *d = PyUnicode_DATA(s);
1194 unsigned int skind = PyUnicode_KIND(s);
1195 if (PyUnicode_KIND(s) >= kind) {
1196 PyErr_SetString(PyExc_RuntimeError, "invalid widening attempt");
1197 return NULL;
1198 }
1199 switch(kind) {
1200 case PyUnicode_2BYTE_KIND: {
1201 Py_UCS2 *result = PyMem_Malloc(PyUnicode_GET_LENGTH(s) * sizeof(Py_UCS2));
1202 if (!result) {
1203 PyErr_NoMemory();
1204 return 0;
1205 }
1206 for (i = 0; i < len; i++)
1207 result[i] = ((Py_UCS1*)d)[i];
1208 return result;
1209 }
1210 case PyUnicode_4BYTE_KIND: {
1211 Py_UCS4 *result = PyMem_Malloc(PyUnicode_GET_LENGTH(s) * sizeof(Py_UCS4));
1212 if (!result) {
1213 PyErr_NoMemory();
1214 return 0;
1215 }
1216 for (i = 0; i < len; i++)
1217 result[i] = PyUnicode_READ(skind, d, i);
1218 return result;
1219 }
1220 }
1221 Py_FatalError("invalid kind");
1222 return NULL;
1223}
1224
1225static Py_UCS4*
1226as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1227 int copy_null)
1228{
1229 int kind;
1230 void *data;
1231 Py_ssize_t len, targetlen;
1232 if (PyUnicode_READY(string) == -1)
1233 return NULL;
1234 kind = PyUnicode_KIND(string);
1235 data = PyUnicode_DATA(string);
1236 len = PyUnicode_GET_LENGTH(string);
1237 targetlen = len;
1238 if (copy_null)
1239 targetlen++;
1240 if (!target) {
1241 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1242 PyErr_NoMemory();
1243 return NULL;
1244 }
1245 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1246 if (!target) {
1247 PyErr_NoMemory();
1248 return NULL;
1249 }
1250 }
1251 else {
1252 if (targetsize < targetlen) {
1253 PyErr_Format(PyExc_SystemError,
1254 "string is longer than the buffer");
1255 if (copy_null && 0 < targetsize)
1256 target[0] = 0;
1257 return NULL;
1258 }
1259 }
1260 if (kind != PyUnicode_4BYTE_KIND) {
1261 Py_ssize_t i;
1262 for (i = 0; i < len; i++)
1263 target[i] = PyUnicode_READ(kind, data, i);
1264 }
1265 else
1266 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
1267 if (copy_null)
1268 target[len] = 0;
1269 return target;
1270}
1271
1272Py_UCS4*
1273PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1274 int copy_null)
1275{
1276 if (target == NULL || targetsize < 1) {
1277 PyErr_BadInternalCall();
1278 return NULL;
1279 }
1280 return as_ucs4(string, target, targetsize, copy_null);
1281}
1282
1283Py_UCS4*
1284PyUnicode_AsUCS4Copy(PyObject *string)
1285{
1286 return as_ucs4(string, NULL, 0, 1);
1287}
1288
1289#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00001290
Alexander Belopolsky40018472011-02-26 01:02:56 +00001291PyObject *
1292PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001293{
Guido van Rossumd57fd912000-03-10 22:53:23 +00001294 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00001295 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001296 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00001297 PyErr_BadInternalCall();
1298 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001299 }
1300
Martin v. Löwis790465f2008-04-05 20:41:37 +00001301 if (size == -1) {
1302 size = wcslen(w);
1303 }
1304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001305 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001306}
1307
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001308#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00001309
Walter Dörwald346737f2007-05-31 10:44:43 +00001310static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001311makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
1312 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00001313{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001314 *fmt++ = '%';
1315 if (width) {
1316 if (zeropad)
1317 *fmt++ = '0';
1318 fmt += sprintf(fmt, "%d", width);
1319 }
1320 if (precision)
1321 fmt += sprintf(fmt, ".%d", precision);
1322 if (longflag)
1323 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001324 else if (longlongflag) {
1325 /* longlongflag should only ever be nonzero on machines with
1326 HAVE_LONG_LONG defined */
1327#ifdef HAVE_LONG_LONG
1328 char *f = PY_FORMAT_LONG_LONG;
1329 while (*f)
1330 *fmt++ = *f++;
1331#else
1332 /* we shouldn't ever get here */
1333 assert(0);
1334 *fmt++ = 'l';
1335#endif
1336 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001337 else if (size_tflag) {
1338 char *f = PY_FORMAT_SIZE_T;
1339 while (*f)
1340 *fmt++ = *f++;
1341 }
1342 *fmt++ = c;
1343 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00001344}
1345
Victor Stinner96865452011-03-01 23:44:09 +00001346/* helper for PyUnicode_FromFormatV() */
1347
1348static const char*
1349parse_format_flags(const char *f,
1350 int *p_width, int *p_precision,
1351 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
1352{
1353 int width, precision, longflag, longlongflag, size_tflag;
1354
1355 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
1356 f++;
1357 width = 0;
1358 while (Py_ISDIGIT((unsigned)*f))
1359 width = (width*10) + *f++ - '0';
1360 precision = 0;
1361 if (*f == '.') {
1362 f++;
1363 while (Py_ISDIGIT((unsigned)*f))
1364 precision = (precision*10) + *f++ - '0';
1365 if (*f == '%') {
1366 /* "%.3%s" => f points to "3" */
1367 f--;
1368 }
1369 }
1370 if (*f == '\0') {
1371 /* bogus format "%.1" => go backward, f points to "1" */
1372 f--;
1373 }
1374 if (p_width != NULL)
1375 *p_width = width;
1376 if (p_precision != NULL)
1377 *p_precision = precision;
1378
1379 /* Handle %ld, %lu, %lld and %llu. */
1380 longflag = 0;
1381 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00001382 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00001383
1384 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00001385 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00001386 longflag = 1;
1387 ++f;
1388 }
1389#ifdef HAVE_LONG_LONG
1390 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00001391 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00001392 longlongflag = 1;
1393 f += 2;
1394 }
1395#endif
1396 }
1397 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00001398 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00001399 size_tflag = 1;
1400 ++f;
1401 }
1402 if (p_longflag != NULL)
1403 *p_longflag = longflag;
1404 if (p_longlongflag != NULL)
1405 *p_longlongflag = longlongflag;
1406 if (p_size_tflag != NULL)
1407 *p_size_tflag = size_tflag;
1408 return f;
1409}
1410
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001411/* maximum number of characters required for output of %ld. 21 characters
1412 allows for 64-bit integers (in decimal) and an optional sign. */
1413#define MAX_LONG_CHARS 21
1414/* maximum number of characters required for output of %lld.
1415 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
1416 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
1417#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
1418
Walter Dörwaldd2034312007-05-18 16:29:38 +00001419PyObject *
1420PyUnicode_FromFormatV(const char *format, va_list vargs)
1421{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001422 va_list count;
1423 Py_ssize_t callcount = 0;
1424 PyObject **callresults = NULL;
1425 PyObject **callresult = NULL;
1426 Py_ssize_t n = 0;
1427 int width = 0;
1428 int precision = 0;
1429 int zeropad;
1430 const char* f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001431 PyUnicodeObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001432 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001433 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001434 Py_UCS4 maxchar = 127; /* result is ASCII by default */
1435 Py_UCS4 argmaxchar;
1436 Py_ssize_t numbersize = 0;
1437 char *numberresults = NULL;
1438 char *numberresult = NULL;
1439 Py_ssize_t i;
1440 int kind;
1441 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001442
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001443 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001444 /* step 1: count the number of %S/%R/%A/%s format specifications
1445 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
1446 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001447 * result in an array)
1448 * also esimate a upper bound for all the number formats in the string,
1449 * numbers will be formated in step 3 and be keept in a '\0'-separated
1450 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00001451 for (f = format; *f; f++) {
1452 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00001453 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001454 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
1455 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
1456 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
1457 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001459 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001460#ifdef HAVE_LONG_LONG
1461 if (longlongflag) {
1462 if (width < MAX_LONG_LONG_CHARS)
1463 width = MAX_LONG_LONG_CHARS;
1464 }
1465 else
1466#endif
1467 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
1468 including sign. Decimal takes the most space. This
1469 isn't enough for octal. If a width is specified we
1470 need more (which we allocate later). */
1471 if (width < MAX_LONG_CHARS)
1472 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001473
1474 /* account for the size + '\0' to separate numbers
1475 inside of the numberresults buffer */
1476 numbersize += (width + 1);
1477 }
1478 }
1479 else if ((unsigned char)*f > 127) {
1480 PyErr_Format(PyExc_ValueError,
1481 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
1482 "string, got a non-ASCII byte: 0x%02x",
1483 (unsigned char)*f);
1484 return NULL;
1485 }
1486 }
1487 /* step 2: allocate memory for the results of
1488 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
1489 if (callcount) {
1490 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
1491 if (!callresults) {
1492 PyErr_NoMemory();
1493 return NULL;
1494 }
1495 callresult = callresults;
1496 }
1497 /* step 2.5: allocate memory for the results of formating numbers */
1498 if (numbersize) {
1499 numberresults = PyObject_Malloc(numbersize);
1500 if (!numberresults) {
1501 PyErr_NoMemory();
1502 goto fail;
1503 }
1504 numberresult = numberresults;
1505 }
1506
1507 /* step 3: format numbers and figure out how large a buffer we need */
1508 for (f = format; *f; f++) {
1509 if (*f == '%') {
1510 const char* p;
1511 int longflag;
1512 int longlongflag;
1513 int size_tflag;
1514 int numprinted;
1515
1516 p = f;
1517 zeropad = (f[1] == '0');
1518 f = parse_format_flags(f, &width, &precision,
1519 &longflag, &longlongflag, &size_tflag);
1520 switch (*f) {
1521 case 'c':
1522 {
1523 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001524 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001525 n++;
1526 break;
1527 }
1528 case '%':
1529 n++;
1530 break;
1531 case 'i':
1532 case 'd':
1533 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1534 width, precision, *f);
1535 if (longflag)
1536 numprinted = sprintf(numberresult, fmt,
1537 va_arg(count, long));
1538#ifdef HAVE_LONG_LONG
1539 else if (longlongflag)
1540 numprinted = sprintf(numberresult, fmt,
1541 va_arg(count, PY_LONG_LONG));
1542#endif
1543 else if (size_tflag)
1544 numprinted = sprintf(numberresult, fmt,
1545 va_arg(count, Py_ssize_t));
1546 else
1547 numprinted = sprintf(numberresult, fmt,
1548 va_arg(count, int));
1549 n += numprinted;
1550 /* advance by +1 to skip over the '\0' */
1551 numberresult += (numprinted + 1);
1552 assert(*(numberresult - 1) == '\0');
1553 assert(*(numberresult - 2) != '\0');
1554 assert(numprinted >= 0);
1555 assert(numberresult <= numberresults + numbersize);
1556 break;
1557 case 'u':
1558 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1559 width, precision, 'u');
1560 if (longflag)
1561 numprinted = sprintf(numberresult, fmt,
1562 va_arg(count, unsigned long));
1563#ifdef HAVE_LONG_LONG
1564 else if (longlongflag)
1565 numprinted = sprintf(numberresult, fmt,
1566 va_arg(count, unsigned PY_LONG_LONG));
1567#endif
1568 else if (size_tflag)
1569 numprinted = sprintf(numberresult, fmt,
1570 va_arg(count, size_t));
1571 else
1572 numprinted = sprintf(numberresult, fmt,
1573 va_arg(count, unsigned int));
1574 n += numprinted;
1575 numberresult += (numprinted + 1);
1576 assert(*(numberresult - 1) == '\0');
1577 assert(*(numberresult - 2) != '\0');
1578 assert(numprinted >= 0);
1579 assert(numberresult <= numberresults + numbersize);
1580 break;
1581 case 'x':
1582 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
1583 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
1584 n += numprinted;
1585 numberresult += (numprinted + 1);
1586 assert(*(numberresult - 1) == '\0');
1587 assert(*(numberresult - 2) != '\0');
1588 assert(numprinted >= 0);
1589 assert(numberresult <= numberresults + numbersize);
1590 break;
1591 case 'p':
1592 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
1593 /* %p is ill-defined: ensure leading 0x. */
1594 if (numberresult[1] == 'X')
1595 numberresult[1] = 'x';
1596 else if (numberresult[1] != 'x') {
1597 memmove(numberresult + 2, numberresult,
1598 strlen(numberresult) + 1);
1599 numberresult[0] = '0';
1600 numberresult[1] = 'x';
1601 numprinted += 2;
1602 }
1603 n += numprinted;
1604 numberresult += (numprinted + 1);
1605 assert(*(numberresult - 1) == '\0');
1606 assert(*(numberresult - 2) != '\0');
1607 assert(numprinted >= 0);
1608 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001609 break;
1610 case 's':
1611 {
1612 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00001613 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001614 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
1615 if (!str)
1616 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617 /* since PyUnicode_DecodeUTF8 returns already flexible
1618 unicode objects, there is no need to call ready on them */
1619 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001620 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001621 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001622 /* Remember the str and switch to the next slot */
1623 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001624 break;
1625 }
1626 case 'U':
1627 {
1628 PyObject *obj = va_arg(count, PyObject *);
1629 assert(obj && PyUnicode_Check(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001630 if (PyUnicode_READY(obj) == -1)
1631 goto fail;
1632 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001633 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001634 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001635 break;
1636 }
1637 case 'V':
1638 {
1639 PyObject *obj = va_arg(count, PyObject *);
1640 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00001641 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001642 assert(obj || str);
1643 assert(!obj || PyUnicode_Check(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00001644 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001645 if (PyUnicode_READY(obj) == -1)
1646 goto fail;
1647 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001648 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00001650 *callresult++ = NULL;
1651 }
1652 else {
1653 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
1654 if (!str_obj)
1655 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001656 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001657 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001658 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00001659 *callresult++ = str_obj;
1660 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001661 break;
1662 }
1663 case 'S':
1664 {
1665 PyObject *obj = va_arg(count, PyObject *);
1666 PyObject *str;
1667 assert(obj);
1668 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00001670 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001671 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001672 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001673 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001674 /* Remember the str and switch to the next slot */
1675 *callresult++ = str;
1676 break;
1677 }
1678 case 'R':
1679 {
1680 PyObject *obj = va_arg(count, PyObject *);
1681 PyObject *repr;
1682 assert(obj);
1683 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001684 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00001685 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001686 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001687 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001688 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001689 /* Remember the repr and switch to the next slot */
1690 *callresult++ = repr;
1691 break;
1692 }
1693 case 'A':
1694 {
1695 PyObject *obj = va_arg(count, PyObject *);
1696 PyObject *ascii;
1697 assert(obj);
1698 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001699 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00001700 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001701 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001702 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001703 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001704 /* Remember the repr and switch to the next slot */
1705 *callresult++ = ascii;
1706 break;
1707 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001708 default:
1709 /* if we stumble upon an unknown
1710 formatting code, copy the rest of
1711 the format string to the output
1712 string. (we cannot just skip the
1713 code, since there's no way to know
1714 what's in the argument list) */
1715 n += strlen(p);
1716 goto expand;
1717 }
1718 } else
1719 n++;
1720 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001721 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001722 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001723 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00001724 we don't have to resize the string.
1725 There can be no errors beyond this point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001726 string = (PyUnicodeObject *)PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001727 if (!string)
1728 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001729 kind = PyUnicode_KIND(string);
1730 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001731 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001732 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001734 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00001735 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00001736 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00001737
1738 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001739 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
1740 /* checking for == because the last argument could be a empty
1741 string, which causes i to point to end, the assert at the end of
1742 the loop */
1743 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00001744
Benjamin Peterson14339b62009-01-31 16:36:08 +00001745 switch (*f) {
1746 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00001747 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001748 const int ordinal = va_arg(vargs, int);
1749 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001750 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00001751 }
Victor Stinner6d970f42011-03-02 00:04:25 +00001752 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00001753 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00001754 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00001755 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001756 case 'p':
1757 /* unused, since we already have the result */
1758 if (*f == 'p')
1759 (void) va_arg(vargs, void *);
1760 else
1761 (void) va_arg(vargs, int);
1762 /* extract the result from numberresults and append. */
1763 for (; *numberresult; ++i, ++numberresult)
1764 PyUnicode_WRITE(kind, data, i, *numberresult);
1765 /* skip over the separating '\0' */
1766 assert(*numberresult == '\0');
1767 numberresult++;
1768 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001769 break;
1770 case 's':
1771 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001772 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001773 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001774 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001775 size = PyUnicode_GET_LENGTH(*callresult);
1776 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
1777 PyUnicode_CopyCharacters((PyObject*)string, i,
1778 *callresult, 0,
1779 size);
1780 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001781 /* We're done with the unicode()/repr() => forget it */
1782 Py_DECREF(*callresult);
1783 /* switch to next unicode()/repr() result */
1784 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001785 break;
1786 }
1787 case 'U':
1788 {
1789 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001790 Py_ssize_t size;
1791 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
1792 size = PyUnicode_GET_LENGTH(obj);
1793 PyUnicode_CopyCharacters((PyObject*)string, i,
1794 obj, 0,
1795 size);
1796 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001797 break;
1798 }
1799 case 'V':
1800 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001801 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001802 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00001803 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001804 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805 size = PyUnicode_GET_LENGTH(obj);
1806 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
1807 PyUnicode_CopyCharacters((PyObject*)string, i,
1808 obj, 0,
1809 size);
1810 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001811 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001812 size = PyUnicode_GET_LENGTH(*callresult);
1813 assert(PyUnicode_KIND(*callresult) <=
1814 PyUnicode_KIND(string));
1815 PyUnicode_CopyCharacters((PyObject*)string, i,
1816 *callresult,
1817 0, size);
1818 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00001819 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001820 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00001821 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001822 break;
1823 }
1824 case 'S':
1825 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00001826 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00001827 {
Benjamin Peterson14339b62009-01-31 16:36:08 +00001828 /* unused, since we already have the result */
1829 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001830 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
1831 PyUnicode_CopyCharacters((PyObject*)string, i,
1832 *callresult, 0,
1833 PyUnicode_GET_LENGTH(*callresult));
1834 i += PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001835 /* We're done with the unicode()/repr() => forget it */
1836 Py_DECREF(*callresult);
1837 /* switch to next unicode()/repr() result */
1838 ++callresult;
1839 break;
1840 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001841 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001842 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001843 break;
1844 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001845 for (; *p; ++p, ++i)
1846 PyUnicode_WRITE(kind, data, i, *p);
1847 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00001848 goto end;
1849 }
Victor Stinner1205f272010-09-11 00:54:47 +00001850 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001851 else {
1852 assert(i < PyUnicode_GET_LENGTH(string));
1853 PyUnicode_WRITE(kind, data, i++, *f);
1854 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001855 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001856 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00001857
Benjamin Peterson29060642009-01-31 22:14:21 +00001858 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001859 if (callresults)
1860 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001861 if (numberresults)
1862 PyObject_Free(numberresults);
1863 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00001864 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001865 if (callresults) {
1866 PyObject **callresult2 = callresults;
1867 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00001868 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001869 ++callresult2;
1870 }
1871 PyObject_Free(callresults);
1872 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001873 if (numberresults)
1874 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001875 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001876}
1877
Walter Dörwaldd2034312007-05-18 16:29:38 +00001878PyObject *
1879PyUnicode_FromFormat(const char *format, ...)
1880{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001881 PyObject* ret;
1882 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001883
1884#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00001885 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001886#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001887 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001888#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001889 ret = PyUnicode_FromFormatV(format, vargs);
1890 va_end(vargs);
1891 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001892}
1893
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001894#ifdef HAVE_WCHAR_H
1895
Victor Stinner5593d8a2010-10-02 11:11:27 +00001896/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
1897 convert a Unicode object to a wide character string.
1898
Victor Stinnerd88d9832011-09-06 02:00:05 +02001899 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00001900 character) required to convert the unicode object. Ignore size argument.
1901
Victor Stinnerd88d9832011-09-06 02:00:05 +02001902 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00001903 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02001904 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00001905static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00001906unicode_aswidechar(PyUnicodeObject *unicode,
1907 wchar_t *w,
1908 Py_ssize_t size)
1909{
Victor Stinner5593d8a2010-10-02 11:11:27 +00001910 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001911 const wchar_t *wstr;
1912
1913 wstr = PyUnicode_AsUnicodeAndSize((PyObject *)unicode, &res);
1914 if (wstr == NULL)
1915 return -1;
1916
Victor Stinner5593d8a2010-10-02 11:11:27 +00001917 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00001918 if (size > res)
1919 size = res + 1;
1920 else
1921 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001922 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00001923 return res;
1924 }
1925 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001926 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00001927}
1928
1929Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001930PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00001931 wchar_t *w,
1932 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001933{
1934 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001935 PyErr_BadInternalCall();
1936 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001937 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001938 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001939}
1940
Victor Stinner137c34c2010-09-29 10:25:54 +00001941wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001942PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00001943 Py_ssize_t *size)
1944{
1945 wchar_t* buffer;
1946 Py_ssize_t buflen;
1947
1948 if (unicode == NULL) {
1949 PyErr_BadInternalCall();
1950 return NULL;
1951 }
1952
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001953 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954 if (buflen == -1)
1955 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00001956 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00001957 PyErr_NoMemory();
1958 return NULL;
1959 }
1960
Victor Stinner137c34c2010-09-29 10:25:54 +00001961 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
1962 if (buffer == NULL) {
1963 PyErr_NoMemory();
1964 return NULL;
1965 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00001966 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001967 if (buflen == -1)
1968 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00001969 if (size != NULL)
1970 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00001971 return buffer;
1972}
1973
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001975
Alexander Belopolsky40018472011-02-26 01:02:56 +00001976PyObject *
1977PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001978{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001979 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001980 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001981 PyErr_SetString(PyExc_ValueError,
1982 "chr() arg not in range(0x110000)");
1983 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001984 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001985
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001986 if (ordinal < 256)
1987 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001988
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001989 v = PyUnicode_New(1, ordinal);
1990 if (v == NULL)
1991 return NULL;
1992 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
1993 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001994}
1995
Alexander Belopolsky40018472011-02-26 01:02:56 +00001996PyObject *
1997PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001998{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001999 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002000 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002001 if (PyUnicode_CheckExact(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002002 Py_INCREF(obj);
2003 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002004 }
2005 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002006 /* For a Unicode subtype that's not a Unicode object,
2007 return a true Unicode object with the same data. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002008 if (PyUnicode_READY(obj) == -1)
2009 return NULL;
2010 return substring((PyUnicodeObject *)obj, 0, PyUnicode_GET_LENGTH(obj));
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002011 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002012 PyErr_Format(PyExc_TypeError,
2013 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002014 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002015 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002016}
2017
Alexander Belopolsky40018472011-02-26 01:02:56 +00002018PyObject *
2019PyUnicode_FromEncodedObject(register PyObject *obj,
2020 const char *encoding,
2021 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002022{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002023 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002024 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002025
Guido van Rossumd57fd912000-03-10 22:53:23 +00002026 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002027 PyErr_BadInternalCall();
2028 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002029 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002030
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002031 /* Decoding bytes objects is the most common case and should be fast */
2032 if (PyBytes_Check(obj)) {
2033 if (PyBytes_GET_SIZE(obj) == 0) {
2034 Py_INCREF(unicode_empty);
2035 v = (PyObject *) unicode_empty;
2036 }
2037 else {
2038 v = PyUnicode_Decode(
2039 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2040 encoding, errors);
2041 }
2042 return v;
2043 }
2044
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002045 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002046 PyErr_SetString(PyExc_TypeError,
2047 "decoding str is not supported");
2048 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002049 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002050
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002051 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2052 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2053 PyErr_Format(PyExc_TypeError,
2054 "coercing to str: need bytes, bytearray "
2055 "or buffer-like object, %.80s found",
2056 Py_TYPE(obj)->tp_name);
2057 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002058 }
Tim Petersced69f82003-09-16 20:30:58 +00002059
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002060 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002061 Py_INCREF(unicode_empty);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002062 v = (PyObject *) unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002063 }
Tim Petersced69f82003-09-16 20:30:58 +00002064 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002065 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002066
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002067 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002068 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002069}
2070
Victor Stinner600d3be2010-06-10 12:00:55 +00002071/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002072 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2073 1 on success. */
2074static int
2075normalize_encoding(const char *encoding,
2076 char *lower,
2077 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002078{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002079 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002080 char *l;
2081 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002082
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002083 e = encoding;
2084 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002085 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002086 while (*e) {
2087 if (l == l_end)
2088 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002089 if (Py_ISUPPER(*e)) {
2090 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002091 }
2092 else if (*e == '_') {
2093 *l++ = '-';
2094 e++;
2095 }
2096 else {
2097 *l++ = *e++;
2098 }
2099 }
2100 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002101 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002102}
2103
Alexander Belopolsky40018472011-02-26 01:02:56 +00002104PyObject *
2105PyUnicode_Decode(const char *s,
2106 Py_ssize_t size,
2107 const char *encoding,
2108 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002109{
2110 PyObject *buffer = NULL, *unicode;
2111 Py_buffer info;
2112 char lower[11]; /* Enough for any encoding shortcut */
2113
2114 if (encoding == NULL)
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002115 return PyUnicode_DecodeUTF8(s, size, errors);
Fred Drakee4315f52000-05-09 19:53:39 +00002116
2117 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002118 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002119 if ((strcmp(lower, "utf-8") == 0) ||
2120 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002121 return PyUnicode_DecodeUTF8(s, size, errors);
2122 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002123 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002124 (strcmp(lower, "iso-8859-1") == 0))
2125 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002126#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002127 else if (strcmp(lower, "mbcs") == 0)
2128 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002129#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002130 else if (strcmp(lower, "ascii") == 0)
2131 return PyUnicode_DecodeASCII(s, size, errors);
2132 else if (strcmp(lower, "utf-16") == 0)
2133 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2134 else if (strcmp(lower, "utf-32") == 0)
2135 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2136 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002137
2138 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002139 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002140 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002141 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002142 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002143 if (buffer == NULL)
2144 goto onError;
2145 unicode = PyCodec_Decode(buffer, encoding, errors);
2146 if (unicode == NULL)
2147 goto onError;
2148 if (!PyUnicode_Check(unicode)) {
2149 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002150 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002151 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002152 Py_DECREF(unicode);
2153 goto onError;
2154 }
2155 Py_DECREF(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002156 if (PyUnicode_READY(unicode)) {
2157 Py_DECREF(unicode);
2158 return NULL;
2159 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002160 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002161
Benjamin Peterson29060642009-01-31 22:14:21 +00002162 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002163 Py_XDECREF(buffer);
2164 return NULL;
2165}
2166
Alexander Belopolsky40018472011-02-26 01:02:56 +00002167PyObject *
2168PyUnicode_AsDecodedObject(PyObject *unicode,
2169 const char *encoding,
2170 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002171{
2172 PyObject *v;
2173
2174 if (!PyUnicode_Check(unicode)) {
2175 PyErr_BadArgument();
2176 goto onError;
2177 }
2178
2179 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002180 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002181
2182 /* Decode via the codec registry */
2183 v = PyCodec_Decode(unicode, encoding, errors);
2184 if (v == NULL)
2185 goto onError;
2186 return v;
2187
Benjamin Peterson29060642009-01-31 22:14:21 +00002188 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002189 return NULL;
2190}
2191
Alexander Belopolsky40018472011-02-26 01:02:56 +00002192PyObject *
2193PyUnicode_AsDecodedUnicode(PyObject *unicode,
2194 const char *encoding,
2195 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002196{
2197 PyObject *v;
2198
2199 if (!PyUnicode_Check(unicode)) {
2200 PyErr_BadArgument();
2201 goto onError;
2202 }
2203
2204 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002205 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002206
2207 /* Decode via the codec registry */
2208 v = PyCodec_Decode(unicode, encoding, errors);
2209 if (v == NULL)
2210 goto onError;
2211 if (!PyUnicode_Check(v)) {
2212 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002213 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002214 Py_TYPE(v)->tp_name);
2215 Py_DECREF(v);
2216 goto onError;
2217 }
2218 return v;
2219
Benjamin Peterson29060642009-01-31 22:14:21 +00002220 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002221 return NULL;
2222}
2223
Alexander Belopolsky40018472011-02-26 01:02:56 +00002224PyObject *
2225PyUnicode_Encode(const Py_UNICODE *s,
2226 Py_ssize_t size,
2227 const char *encoding,
2228 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002229{
2230 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002231
Guido van Rossumd57fd912000-03-10 22:53:23 +00002232 unicode = PyUnicode_FromUnicode(s, size);
2233 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002234 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002235 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2236 Py_DECREF(unicode);
2237 return v;
2238}
2239
Alexander Belopolsky40018472011-02-26 01:02:56 +00002240PyObject *
2241PyUnicode_AsEncodedObject(PyObject *unicode,
2242 const char *encoding,
2243 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002244{
2245 PyObject *v;
2246
2247 if (!PyUnicode_Check(unicode)) {
2248 PyErr_BadArgument();
2249 goto onError;
2250 }
2251
2252 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002253 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002254
2255 /* Encode via the codec registry */
2256 v = PyCodec_Encode(unicode, encoding, errors);
2257 if (v == NULL)
2258 goto onError;
2259 return v;
2260
Benjamin Peterson29060642009-01-31 22:14:21 +00002261 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002262 return NULL;
2263}
2264
Victor Stinnerad158722010-10-27 00:25:46 +00002265PyObject *
2266PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00002267{
Victor Stinner99b95382011-07-04 14:23:54 +02002268#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002269 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2270 PyUnicode_GET_SIZE(unicode),
2271 NULL);
2272#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002273 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00002274#else
Victor Stinner793b5312011-04-27 00:24:21 +02002275 PyInterpreterState *interp = PyThreadState_GET()->interp;
2276 /* Bootstrap check: if the filesystem codec is implemented in Python, we
2277 cannot use it to encode and decode filenames before it is loaded. Load
2278 the Python codec requires to encode at least its own filename. Use the C
2279 version of the locale codec until the codec registry is initialized and
2280 the Python codec is loaded.
2281
2282 Py_FileSystemDefaultEncoding is shared between all interpreters, we
2283 cannot only rely on it: check also interp->fscodec_initialized for
2284 subinterpreters. */
2285 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00002286 return PyUnicode_AsEncodedString(unicode,
2287 Py_FileSystemDefaultEncoding,
2288 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00002289 }
2290 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002291 /* locale encoding with surrogateescape */
2292 wchar_t *wchar;
2293 char *bytes;
2294 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00002295 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002296
2297 wchar = PyUnicode_AsWideCharString(unicode, NULL);
2298 if (wchar == NULL)
2299 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00002300 bytes = _Py_wchar2char(wchar, &error_pos);
2301 if (bytes == NULL) {
2302 if (error_pos != (size_t)-1) {
2303 char *errmsg = strerror(errno);
2304 PyObject *exc = NULL;
2305 if (errmsg == NULL)
2306 errmsg = "Py_wchar2char() failed";
2307 raise_encode_exception(&exc,
2308 "filesystemencoding",
2309 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
2310 error_pos, error_pos+1,
2311 errmsg);
2312 Py_XDECREF(exc);
2313 }
2314 else
2315 PyErr_NoMemory();
2316 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002317 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00002318 }
2319 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002320
2321 bytes_obj = PyBytes_FromString(bytes);
2322 PyMem_Free(bytes);
2323 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00002324 }
Victor Stinnerad158722010-10-27 00:25:46 +00002325#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00002326}
2327
Alexander Belopolsky40018472011-02-26 01:02:56 +00002328PyObject *
2329PyUnicode_AsEncodedString(PyObject *unicode,
2330 const char *encoding,
2331 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002332{
2333 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00002334 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00002335
Guido van Rossumd57fd912000-03-10 22:53:23 +00002336 if (!PyUnicode_Check(unicode)) {
2337 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002338 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002339 }
Fred Drakee4315f52000-05-09 19:53:39 +00002340
Victor Stinner2f283c22011-03-02 01:21:46 +00002341 if (encoding == NULL) {
2342 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002343 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00002344 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002345 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner2f283c22011-03-02 01:21:46 +00002346 }
Fred Drakee4315f52000-05-09 19:53:39 +00002347
2348 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002349 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002350 if ((strcmp(lower, "utf-8") == 0) ||
2351 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00002352 {
Victor Stinner2f283c22011-03-02 01:21:46 +00002353 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002354 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00002355 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002356 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00002357 }
Victor Stinner37296e82010-06-10 13:36:23 +00002358 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002359 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002360 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002361 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002362#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002363 else if (strcmp(lower, "mbcs") == 0)
2364 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2365 PyUnicode_GET_SIZE(unicode),
2366 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002367#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002368 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002369 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00002370 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002371
2372 /* Encode via the codec registry */
2373 v = PyCodec_Encode(unicode, encoding, errors);
2374 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002375 return NULL;
2376
2377 /* The normal path */
2378 if (PyBytes_Check(v))
2379 return v;
2380
2381 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002382 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002383 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002384 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002385
2386 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
2387 "encoder %s returned bytearray instead of bytes",
2388 encoding);
2389 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002390 Py_DECREF(v);
2391 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002392 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002393
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002394 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
2395 Py_DECREF(v);
2396 return b;
2397 }
2398
2399 PyErr_Format(PyExc_TypeError,
2400 "encoder did not return a bytes object (type=%.400s)",
2401 Py_TYPE(v)->tp_name);
2402 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002403 return NULL;
2404}
2405
Alexander Belopolsky40018472011-02-26 01:02:56 +00002406PyObject *
2407PyUnicode_AsEncodedUnicode(PyObject *unicode,
2408 const char *encoding,
2409 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002410{
2411 PyObject *v;
2412
2413 if (!PyUnicode_Check(unicode)) {
2414 PyErr_BadArgument();
2415 goto onError;
2416 }
2417
2418 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002419 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002420
2421 /* Encode via the codec registry */
2422 v = PyCodec_Encode(unicode, encoding, errors);
2423 if (v == NULL)
2424 goto onError;
2425 if (!PyUnicode_Check(v)) {
2426 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002427 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002428 Py_TYPE(v)->tp_name);
2429 Py_DECREF(v);
2430 goto onError;
2431 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002432 return v;
Tim Petersced69f82003-09-16 20:30:58 +00002433
Benjamin Peterson29060642009-01-31 22:14:21 +00002434 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002435 return NULL;
2436}
2437
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002438PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00002439PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002440 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00002441 return PyUnicode_DecodeFSDefaultAndSize(s, size);
2442}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002443
Christian Heimes5894ba72007-11-04 11:43:14 +00002444PyObject*
2445PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
2446{
Victor Stinner99b95382011-07-04 14:23:54 +02002447#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002448 return PyUnicode_DecodeMBCS(s, size, NULL);
2449#elif defined(__APPLE__)
2450 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
2451#else
Victor Stinner793b5312011-04-27 00:24:21 +02002452 PyInterpreterState *interp = PyThreadState_GET()->interp;
2453 /* Bootstrap check: if the filesystem codec is implemented in Python, we
2454 cannot use it to encode and decode filenames before it is loaded. Load
2455 the Python codec requires to encode at least its own filename. Use the C
2456 version of the locale codec until the codec registry is initialized and
2457 the Python codec is loaded.
2458
2459 Py_FileSystemDefaultEncoding is shared between all interpreters, we
2460 cannot only rely on it: check also interp->fscodec_initialized for
2461 subinterpreters. */
2462 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002463 return PyUnicode_Decode(s, size,
2464 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00002465 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002466 }
2467 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002468 /* locale encoding with surrogateescape */
2469 wchar_t *wchar;
2470 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00002471 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002472
2473 if (s[size] != '\0' || size != strlen(s)) {
2474 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
2475 return NULL;
2476 }
2477
Victor Stinner168e1172010-10-16 23:16:16 +00002478 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002479 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00002480 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002481
Victor Stinner168e1172010-10-16 23:16:16 +00002482 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002483 PyMem_Free(wchar);
2484 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002485 }
Victor Stinnerad158722010-10-27 00:25:46 +00002486#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002487}
2488
Martin v. Löwis011e8422009-05-05 04:43:17 +00002489
2490int
2491PyUnicode_FSConverter(PyObject* arg, void* addr)
2492{
2493 PyObject *output = NULL;
2494 Py_ssize_t size;
2495 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00002496 if (arg == NULL) {
2497 Py_DECREF(*(PyObject**)addr);
2498 return 1;
2499 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00002500 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00002501 output = arg;
2502 Py_INCREF(output);
2503 }
2504 else {
2505 arg = PyUnicode_FromObject(arg);
2506 if (!arg)
2507 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002508 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00002509 Py_DECREF(arg);
2510 if (!output)
2511 return 0;
2512 if (!PyBytes_Check(output)) {
2513 Py_DECREF(output);
2514 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
2515 return 0;
2516 }
2517 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00002518 size = PyBytes_GET_SIZE(output);
2519 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00002520 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05002521 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00002522 Py_DECREF(output);
2523 return 0;
2524 }
2525 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00002526 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00002527}
2528
2529
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002530int
2531PyUnicode_FSDecoder(PyObject* arg, void* addr)
2532{
2533 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002534 if (arg == NULL) {
2535 Py_DECREF(*(PyObject**)addr);
2536 return 1;
2537 }
2538 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002539 if (PyUnicode_READY(arg))
2540 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002541 output = arg;
2542 Py_INCREF(output);
2543 }
2544 else {
2545 arg = PyBytes_FromObject(arg);
2546 if (!arg)
2547 return 0;
2548 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
2549 PyBytes_GET_SIZE(arg));
2550 Py_DECREF(arg);
2551 if (!output)
2552 return 0;
2553 if (!PyUnicode_Check(output)) {
2554 Py_DECREF(output);
2555 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
2556 return 0;
2557 }
2558 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002559 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
2560 PyUnicode_GET_LENGTH(output), 0, 1)) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002561 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
2562 Py_DECREF(output);
2563 return 0;
2564 }
2565 *(PyObject**)addr = output;
2566 return Py_CLEANUP_SUPPORTED;
2567}
2568
2569
Martin v. Löwis5b222132007-06-10 09:51:05 +00002570char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002571PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002572{
Christian Heimesf3863112007-11-22 07:46:41 +00002573 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002574 PyUnicodeObject *u = (PyUnicodeObject *)unicode;
2575
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00002576 if (!PyUnicode_Check(unicode)) {
2577 PyErr_BadArgument();
2578 return NULL;
2579 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002580 if (PyUnicode_READY(u) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002581 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002582
2583 if (_PyUnicode_UTF8(unicode) == NULL) {
2584 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
2585 if (bytes == NULL)
2586 return NULL;
2587 u->_base.utf8 = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
2588 if (u->_base.utf8 == NULL) {
2589 Py_DECREF(bytes);
2590 return NULL;
2591 }
2592 u->_base.utf8_length = PyBytes_GET_SIZE(bytes);
2593 Py_MEMCPY(u->_base.utf8, PyBytes_AS_STRING(bytes), u->_base.utf8_length + 1);
2594 Py_DECREF(bytes);
2595 }
2596
2597 if (psize)
2598 *psize = _PyUnicode_UTF8_LENGTH(unicode);
2599 return _PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00002600}
2601
2602char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002603PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00002604{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002605 return PyUnicode_AsUTF8AndSize(unicode, NULL);
2606}
2607
2608#ifdef Py_DEBUG
2609int unicode_as_unicode_calls = 0;
2610#endif
2611
2612
2613Py_UNICODE *
2614PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
2615{
2616 PyUnicodeObject *u;
2617 const unsigned char *one_byte;
2618#if SIZEOF_WCHAR_T == 4
2619 const Py_UCS2 *two_bytes;
2620#else
2621 const Py_UCS4 *four_bytes;
2622 const Py_UCS4 *ucs4_end;
2623 Py_ssize_t num_surrogates;
2624#endif
2625 wchar_t *w;
2626 wchar_t *wchar_end;
2627
2628 if (!PyUnicode_Check(unicode)) {
2629 PyErr_BadArgument();
2630 return NULL;
2631 }
2632 u = (PyUnicodeObject*)unicode;
2633 if (_PyUnicode_WSTR(u) == NULL) {
2634 /* Non-ASCII compact unicode object */
2635 assert(_PyUnicode_KIND(u) != 0);
2636 assert(PyUnicode_IS_READY(u));
2637
2638#ifdef Py_DEBUG
2639 ++unicode_as_unicode_calls;
2640#endif
2641
2642 if (PyUnicode_KIND(u) == PyUnicode_4BYTE_KIND) {
2643#if SIZEOF_WCHAR_T == 2
2644 four_bytes = PyUnicode_4BYTE_DATA(u);
2645 ucs4_end = four_bytes + _PyUnicode_LENGTH(u);
2646 num_surrogates = 0;
2647
2648 for (; four_bytes < ucs4_end; ++four_bytes) {
2649 if (*four_bytes > 0xFFFF)
2650 ++num_surrogates;
2651 }
2652
2653 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(
2654 sizeof(wchar_t) * (_PyUnicode_LENGTH(u) + 1 + num_surrogates));
2655 if (!_PyUnicode_WSTR(u)) {
2656 PyErr_NoMemory();
2657 return NULL;
2658 }
2659 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u) + num_surrogates;
2660
2661 w = _PyUnicode_WSTR(u);
2662 wchar_end = w + _PyUnicode_WSTR_LENGTH(u);
2663 four_bytes = PyUnicode_4BYTE_DATA(u);
2664 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
2665 if (*four_bytes > 0xFFFF) {
2666 /* encode surrogate pair in this case */
2667 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
2668 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
2669 }
2670 else
2671 *w = *four_bytes;
2672
2673 if (w > wchar_end) {
2674 assert(0 && "Miscalculated string end");
2675 }
2676 }
2677 *w = 0;
2678#else
2679 /* sizeof(wchar_t) == 4 */
2680 Py_FatalError("Impossible unicode object state, wstr and str "
2681 "should share memory already.");
2682 return NULL;
2683#endif
2684 }
2685 else {
2686 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
2687 (_PyUnicode_LENGTH(u) + 1));
2688 if (!_PyUnicode_WSTR(u)) {
2689 PyErr_NoMemory();
2690 return NULL;
2691 }
2692 if (!PyUnicode_IS_COMPACT_ASCII(u))
2693 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u);
2694 w = _PyUnicode_WSTR(u);
2695 wchar_end = w + _PyUnicode_LENGTH(u);
2696
2697 if (PyUnicode_KIND(u) == PyUnicode_1BYTE_KIND) {
2698 one_byte = PyUnicode_1BYTE_DATA(u);
2699 for (; w < wchar_end; ++one_byte, ++w)
2700 *w = *one_byte;
2701 /* null-terminate the wstr */
2702 *w = 0;
2703 }
2704 else if (PyUnicode_KIND(u) == PyUnicode_2BYTE_KIND) {
2705#if SIZEOF_WCHAR_T == 4
2706 two_bytes = PyUnicode_2BYTE_DATA(u);
2707 for (; w < wchar_end; ++two_bytes, ++w)
2708 *w = *two_bytes;
2709 /* null-terminate the wstr */
2710 *w = 0;
2711#else
2712 /* sizeof(wchar_t) == 2 */
2713 PyObject_FREE(_PyUnicode_WSTR(u));
2714 _PyUnicode_WSTR(u) = NULL;
2715 Py_FatalError("Impossible unicode object state, wstr "
2716 "and str should share memory already.");
2717 return NULL;
2718#endif
2719 }
2720 else {
2721 assert(0 && "This should never happen.");
2722 }
2723 }
2724 }
2725 if (size != NULL)
2726 *size = PyUnicode_WSTR_LENGTH(u);
2727 return _PyUnicode_WSTR(u);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002728}
2729
Alexander Belopolsky40018472011-02-26 01:02:56 +00002730Py_UNICODE *
2731PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002732{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002733 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002734}
2735
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002736
Alexander Belopolsky40018472011-02-26 01:02:56 +00002737Py_ssize_t
2738PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002739{
2740 if (!PyUnicode_Check(unicode)) {
2741 PyErr_BadArgument();
2742 goto onError;
2743 }
2744 return PyUnicode_GET_SIZE(unicode);
2745
Benjamin Peterson29060642009-01-31 22:14:21 +00002746 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002747 return -1;
2748}
2749
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002750Py_ssize_t
2751PyUnicode_GetLength(PyObject *unicode)
2752{
2753 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) != -1) {
2754 PyErr_BadArgument();
2755 return -1;
2756 }
2757
2758 return PyUnicode_GET_LENGTH(unicode);
2759}
2760
2761Py_UCS4
2762PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
2763{
2764 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) != -1) {
2765 return PyErr_BadArgument();
2766 return (Py_UCS4)-1;
2767 }
2768 return PyUnicode_READ_CHAR(unicode, index);
2769}
2770
2771int
2772PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
2773{
2774 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
2775 return PyErr_BadArgument();
2776 return -1;
2777 }
2778
2779 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
2780 index, ch);
2781 return 0;
2782}
2783
Alexander Belopolsky40018472011-02-26 01:02:56 +00002784const char *
2785PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00002786{
Victor Stinner42cb4622010-09-01 19:39:01 +00002787 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00002788}
2789
Victor Stinner554f3f02010-06-16 23:33:54 +00002790/* create or adjust a UnicodeDecodeError */
2791static void
2792make_decode_exception(PyObject **exceptionObject,
2793 const char *encoding,
2794 const char *input, Py_ssize_t length,
2795 Py_ssize_t startpos, Py_ssize_t endpos,
2796 const char *reason)
2797{
2798 if (*exceptionObject == NULL) {
2799 *exceptionObject = PyUnicodeDecodeError_Create(
2800 encoding, input, length, startpos, endpos, reason);
2801 }
2802 else {
2803 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
2804 goto onError;
2805 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
2806 goto onError;
2807 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
2808 goto onError;
2809 }
2810 return;
2811
2812onError:
2813 Py_DECREF(*exceptionObject);
2814 *exceptionObject = NULL;
2815}
2816
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002817/* error handling callback helper:
2818 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00002819 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002820 and adjust various state variables.
2821 return 0 on success, -1 on error
2822*/
2823
Alexander Belopolsky40018472011-02-26 01:02:56 +00002824static int
2825unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
2826 const char *encoding, const char *reason,
2827 const char **input, const char **inend, Py_ssize_t *startinpos,
2828 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
2829 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002830{
Benjamin Peterson142957c2008-07-04 19:55:29 +00002831 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002832
2833 PyObject *restuple = NULL;
2834 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002835 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002836 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002837 Py_ssize_t requiredsize;
2838 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002839 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002840 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002841 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002842 int res = -1;
2843
2844 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002845 *errorHandler = PyCodec_LookupError(errors);
2846 if (*errorHandler == NULL)
2847 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002848 }
2849
Victor Stinner554f3f02010-06-16 23:33:54 +00002850 make_decode_exception(exceptionObject,
2851 encoding,
2852 *input, *inend - *input,
2853 *startinpos, *endinpos,
2854 reason);
2855 if (*exceptionObject == NULL)
2856 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002857
2858 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
2859 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002860 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002861 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00002862 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00002863 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002864 }
2865 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00002866 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002867
2868 /* Copy back the bytes variables, which might have been modified by the
2869 callback */
2870 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
2871 if (!inputobj)
2872 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00002873 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002874 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00002875 }
Christian Heimes72b710a2008-05-26 13:28:38 +00002876 *input = PyBytes_AS_STRING(inputobj);
2877 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002878 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00002879 /* we can DECREF safely, as the exception has another reference,
2880 so the object won't go away. */
2881 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002882
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002883 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002884 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002885 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002886 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
2887 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002888 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002889
2890 /* need more space? (at least enough for what we
2891 have+the replacement+the rest of the string (starting
2892 at the new input position), so we won't have to check space
2893 when there are no errors in the rest of the string) */
2894 repptr = PyUnicode_AS_UNICODE(repunicode);
2895 repsize = PyUnicode_GET_SIZE(repunicode);
2896 requiredsize = *outpos + repsize + insize-newpos;
2897 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002898 if (requiredsize<2*outsize)
2899 requiredsize = 2*outsize;
2900 if (_PyUnicode_Resize(output, requiredsize) < 0)
2901 goto onError;
2902 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002903 }
2904 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002905 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002906 Py_UNICODE_COPY(*outptr, repptr, repsize);
2907 *outptr += repsize;
2908 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002909
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002910 /* we made it! */
2911 res = 0;
2912
Benjamin Peterson29060642009-01-31 22:14:21 +00002913 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002914 Py_XDECREF(restuple);
2915 return res;
2916}
2917
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002918/* --- UTF-7 Codec -------------------------------------------------------- */
2919
Antoine Pitrou244651a2009-05-04 18:56:13 +00002920/* See RFC2152 for details. We encode conservatively and decode liberally. */
2921
2922/* Three simple macros defining base-64. */
2923
2924/* Is c a base-64 character? */
2925
2926#define IS_BASE64(c) \
2927 (((c) >= 'A' && (c) <= 'Z') || \
2928 ((c) >= 'a' && (c) <= 'z') || \
2929 ((c) >= '0' && (c) <= '9') || \
2930 (c) == '+' || (c) == '/')
2931
2932/* given that c is a base-64 character, what is its base-64 value? */
2933
2934#define FROM_BASE64(c) \
2935 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
2936 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
2937 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
2938 (c) == '+' ? 62 : 63)
2939
2940/* What is the base-64 character of the bottom 6 bits of n? */
2941
2942#define TO_BASE64(n) \
2943 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
2944
2945/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
2946 * decoded as itself. We are permissive on decoding; the only ASCII
2947 * byte not decoding to itself is the + which begins a base64
2948 * string. */
2949
2950#define DECODE_DIRECT(c) \
2951 ((c) <= 127 && (c) != '+')
2952
2953/* The UTF-7 encoder treats ASCII characters differently according to
2954 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
2955 * the above). See RFC2152. This array identifies these different
2956 * sets:
2957 * 0 : "Set D"
2958 * alphanumeric and '(),-./:?
2959 * 1 : "Set O"
2960 * !"#$%&*;<=>@[]^_`{|}
2961 * 2 : "whitespace"
2962 * ht nl cr sp
2963 * 3 : special (must be base64 encoded)
2964 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
2965 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002966
Tim Petersced69f82003-09-16 20:30:58 +00002967static
Antoine Pitrou244651a2009-05-04 18:56:13 +00002968char utf7_category[128] = {
2969/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
2970 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
2971/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
2972 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2973/* sp ! " # $ % & ' ( ) * + , - . / */
2974 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
2975/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
2976 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
2977/* @ A B C D E F G H I J K L M N O */
2978 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2979/* P Q R S T U V W X Y Z [ \ ] ^ _ */
2980 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
2981/* ` a b c d e f g h i j k l m n o */
2982 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2983/* p q r s t u v w x y z { | } ~ del */
2984 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002985};
2986
Antoine Pitrou244651a2009-05-04 18:56:13 +00002987/* ENCODE_DIRECT: this character should be encoded as itself. The
2988 * answer depends on whether we are encoding set O as itself, and also
2989 * on whether we are encoding whitespace as itself. RFC2152 makes it
2990 * clear that the answers to these questions vary between
2991 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00002992
Antoine Pitrou244651a2009-05-04 18:56:13 +00002993#define ENCODE_DIRECT(c, directO, directWS) \
2994 ((c) < 128 && (c) > 0 && \
2995 ((utf7_category[(c)] == 0) || \
2996 (directWS && (utf7_category[(c)] == 2)) || \
2997 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002998
Alexander Belopolsky40018472011-02-26 01:02:56 +00002999PyObject *
3000PyUnicode_DecodeUTF7(const char *s,
3001 Py_ssize_t size,
3002 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003003{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003004 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3005}
3006
Antoine Pitrou244651a2009-05-04 18:56:13 +00003007/* The decoder. The only state we preserve is our read position,
3008 * i.e. how many characters we have consumed. So if we end in the
3009 * middle of a shift sequence we have to back off the read position
3010 * and the output to the beginning of the sequence, otherwise we lose
3011 * all the shift state (seen bits, number of bits seen, high
3012 * surrogate). */
3013
Alexander Belopolsky40018472011-02-26 01:02:56 +00003014PyObject *
3015PyUnicode_DecodeUTF7Stateful(const char *s,
3016 Py_ssize_t size,
3017 const char *errors,
3018 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003019{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003020 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003021 Py_ssize_t startinpos;
3022 Py_ssize_t endinpos;
3023 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003024 const char *e;
3025 PyUnicodeObject *unicode;
3026 Py_UNICODE *p;
3027 const char *errmsg = "";
3028 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003029 Py_UNICODE *shiftOutStart;
3030 unsigned int base64bits = 0;
3031 unsigned long base64buffer = 0;
3032 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003033 PyObject *errorHandler = NULL;
3034 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003035
3036 unicode = _PyUnicode_New(size);
3037 if (!unicode)
3038 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003039 if (size == 0) {
3040 if (consumed)
3041 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003042 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003043 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003044
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003045 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003046 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003047 e = s + size;
3048
3049 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003050 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003051 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003052 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003053
Antoine Pitrou244651a2009-05-04 18:56:13 +00003054 if (inShift) { /* in a base-64 section */
3055 if (IS_BASE64(ch)) { /* consume a base-64 character */
3056 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3057 base64bits += 6;
3058 s++;
3059 if (base64bits >= 16) {
3060 /* we have enough bits for a UTF-16 value */
3061 Py_UNICODE outCh = (Py_UNICODE)
3062 (base64buffer >> (base64bits-16));
3063 base64bits -= 16;
3064 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3065 if (surrogate) {
3066 /* expecting a second surrogate */
3067 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3068#ifdef Py_UNICODE_WIDE
3069 *p++ = (((surrogate & 0x3FF)<<10)
3070 | (outCh & 0x3FF)) + 0x10000;
3071#else
3072 *p++ = surrogate;
3073 *p++ = outCh;
3074#endif
3075 surrogate = 0;
3076 }
3077 else {
3078 surrogate = 0;
3079 errmsg = "second surrogate missing";
3080 goto utf7Error;
3081 }
3082 }
3083 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3084 /* first surrogate */
3085 surrogate = outCh;
3086 }
3087 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3088 errmsg = "unexpected second surrogate";
3089 goto utf7Error;
3090 }
3091 else {
3092 *p++ = outCh;
3093 }
3094 }
3095 }
3096 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003097 inShift = 0;
3098 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003099 if (surrogate) {
3100 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003101 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003102 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003103 if (base64bits > 0) { /* left-over bits */
3104 if (base64bits >= 6) {
3105 /* We've seen at least one base-64 character */
3106 errmsg = "partial character in shift sequence";
3107 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003108 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003109 else {
3110 /* Some bits remain; they should be zero */
3111 if (base64buffer != 0) {
3112 errmsg = "non-zero padding bits in shift sequence";
3113 goto utf7Error;
3114 }
3115 }
3116 }
3117 if (ch != '-') {
3118 /* '-' is absorbed; other terminating
3119 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003120 *p++ = ch;
3121 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003122 }
3123 }
3124 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003125 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003126 s++; /* consume '+' */
3127 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003128 s++;
3129 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003130 }
3131 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003132 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003133 shiftOutStart = p;
3134 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003135 }
3136 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003137 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003138 *p++ = ch;
3139 s++;
3140 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003141 else {
3142 startinpos = s-starts;
3143 s++;
3144 errmsg = "unexpected special character";
3145 goto utf7Error;
3146 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003147 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003148utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003149 outpos = p-PyUnicode_AS_UNICODE(unicode);
3150 endinpos = s-starts;
3151 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003152 errors, &errorHandler,
3153 "utf7", errmsg,
3154 &starts, &e, &startinpos, &endinpos, &exc, &s,
3155 &unicode, &outpos, &p))
3156 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003157 }
3158
Antoine Pitrou244651a2009-05-04 18:56:13 +00003159 /* end of string */
3160
3161 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3162 /* if we're in an inconsistent state, that's an error */
3163 if (surrogate ||
3164 (base64bits >= 6) ||
3165 (base64bits > 0 && base64buffer != 0)) {
3166 outpos = p-PyUnicode_AS_UNICODE(unicode);
3167 endinpos = size;
3168 if (unicode_decode_call_errorhandler(
3169 errors, &errorHandler,
3170 "utf7", "unterminated shift sequence",
3171 &starts, &e, &startinpos, &endinpos, &exc, &s,
3172 &unicode, &outpos, &p))
3173 goto onError;
3174 if (s < e)
3175 goto restart;
3176 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003177 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003178
3179 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003180 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003181 if (inShift) {
3182 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003183 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003184 }
3185 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003186 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003187 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003188 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003189
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00003190 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003191 goto onError;
3192
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003193 Py_XDECREF(errorHandler);
3194 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003195 if (PyUnicode_READY(unicode) == -1) {
3196 Py_DECREF(unicode);
3197 return NULL;
3198 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003199 return (PyObject *)unicode;
3200
Benjamin Peterson29060642009-01-31 22:14:21 +00003201 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003202 Py_XDECREF(errorHandler);
3203 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003204 Py_DECREF(unicode);
3205 return NULL;
3206}
3207
3208
Alexander Belopolsky40018472011-02-26 01:02:56 +00003209PyObject *
3210PyUnicode_EncodeUTF7(const Py_UNICODE *s,
3211 Py_ssize_t size,
3212 int base64SetO,
3213 int base64WhiteSpace,
3214 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003215{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003216 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003217 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003218 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003219 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003220 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003221 unsigned int base64bits = 0;
3222 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003223 char * out;
3224 char * start;
3225
3226 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003227 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003228
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003229 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003230 return PyErr_NoMemory();
3231
Antoine Pitrou244651a2009-05-04 18:56:13 +00003232 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003233 if (v == NULL)
3234 return NULL;
3235
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003236 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003237 for (;i < size; ++i) {
3238 Py_UNICODE ch = s[i];
3239
Antoine Pitrou244651a2009-05-04 18:56:13 +00003240 if (inShift) {
3241 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3242 /* shifting out */
3243 if (base64bits) { /* output remaining bits */
3244 *out++ = TO_BASE64(base64buffer << (6-base64bits));
3245 base64buffer = 0;
3246 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003247 }
3248 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003249 /* Characters not in the BASE64 set implicitly unshift the sequence
3250 so no '-' is required, except if the character is itself a '-' */
3251 if (IS_BASE64(ch) || ch == '-') {
3252 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003253 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003254 *out++ = (char) ch;
3255 }
3256 else {
3257 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00003258 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003259 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003260 else { /* not in a shift sequence */
3261 if (ch == '+') {
3262 *out++ = '+';
3263 *out++ = '-';
3264 }
3265 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3266 *out++ = (char) ch;
3267 }
3268 else {
3269 *out++ = '+';
3270 inShift = 1;
3271 goto encode_char;
3272 }
3273 }
3274 continue;
3275encode_char:
3276#ifdef Py_UNICODE_WIDE
3277 if (ch >= 0x10000) {
3278 /* code first surrogate */
3279 base64bits += 16;
3280 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
3281 while (base64bits >= 6) {
3282 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3283 base64bits -= 6;
3284 }
3285 /* prepare second surrogate */
3286 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
3287 }
3288#endif
3289 base64bits += 16;
3290 base64buffer = (base64buffer << 16) | ch;
3291 while (base64bits >= 6) {
3292 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3293 base64bits -= 6;
3294 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00003295 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003296 if (base64bits)
3297 *out++= TO_BASE64(base64buffer << (6-base64bits) );
3298 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003299 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003300 if (_PyBytes_Resize(&v, out - start) < 0)
3301 return NULL;
3302 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003303}
3304
Antoine Pitrou244651a2009-05-04 18:56:13 +00003305#undef IS_BASE64
3306#undef FROM_BASE64
3307#undef TO_BASE64
3308#undef DECODE_DIRECT
3309#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003310
Guido van Rossumd57fd912000-03-10 22:53:23 +00003311/* --- UTF-8 Codec -------------------------------------------------------- */
3312
Tim Petersced69f82003-09-16 20:30:58 +00003313static
Guido van Rossumd57fd912000-03-10 22:53:23 +00003314char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00003315 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
3316 illegal prefix. See RFC 3629 for details */
3317 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
3318 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003319 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00003320 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3321 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3322 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3323 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00003324 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
3325 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80-8F */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003326 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3327 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00003328 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
3329 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
3330 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
3331 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
3332 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0-F4 + F5-FF */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003333};
3334
Alexander Belopolsky40018472011-02-26 01:02:56 +00003335PyObject *
3336PyUnicode_DecodeUTF8(const char *s,
3337 Py_ssize_t size,
3338 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003339{
Walter Dörwald69652032004-09-07 20:24:22 +00003340 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3341}
3342
Antoine Pitrouab868312009-01-10 15:40:25 +00003343/* Mask to check or force alignment of a pointer to C 'long' boundaries */
3344#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
3345
3346/* Mask to quickly check whether a C 'long' contains a
3347 non-ASCII, UTF8-encoded char. */
3348#if (SIZEOF_LONG == 8)
3349# define ASCII_CHAR_MASK 0x8080808080808080L
3350#elif (SIZEOF_LONG == 4)
3351# define ASCII_CHAR_MASK 0x80808080L
3352#else
3353# error C 'long' size should be either 4 or 8!
3354#endif
3355
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003356/* Scans a UTF-8 string and returns the maximum character to be expected,
3357 the size of the decoded unicode string and if any major errors were
3358 encountered.
3359
3360 This function does check basic UTF-8 sanity, it does however NOT CHECK
3361 if the string contains surrogates, and if all continuation bytes are
3362 within the correct ranges, these checks are performed in
3363 PyUnicode_DecodeUTF8Stateful.
3364
3365 If it sets has_errors to 1, it means the value of unicode_size and max_char
3366 will be bogus and you should not rely on useful information in them.
3367 */
3368static Py_UCS4
3369utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
3370 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
3371 int *has_errors)
3372{
3373 Py_ssize_t n;
3374 Py_ssize_t char_count = 0;
3375 Py_UCS4 max_char = 127, new_max;
3376 Py_UCS4 upper_bound;
3377 const unsigned char *p = (const unsigned char *)s;
3378 const unsigned char *end = p + string_size;
3379 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
3380 int err = 0;
3381
3382 for (; p < end && !err; ++p, ++char_count) {
3383 /* Only check value if it's not a ASCII char... */
3384 if (*p < 0x80) {
3385 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
3386 an explanation. */
3387 if (!((size_t) p & LONG_PTR_MASK)) {
3388 /* Help register allocation */
3389 register const unsigned char *_p = p;
3390 while (_p < aligned_end) {
3391 unsigned long value = *(unsigned long *) _p;
3392 if (value & ASCII_CHAR_MASK)
3393 break;
3394 _p += SIZEOF_LONG;
3395 char_count += SIZEOF_LONG;
3396 }
3397 p = _p;
3398 if (p == end)
3399 break;
3400 }
3401 }
3402 if (*p >= 0x80) {
3403 n = utf8_code_length[*p];
3404 new_max = max_char;
3405 switch (n) {
3406 /* invalid start byte */
3407 case 0:
3408 err = 1;
3409 break;
3410 case 2:
3411 /* Code points between 0x00FF and 0x07FF inclusive.
3412 Approximate the upper bound of the code point,
3413 if this flips over 255 we can be sure it will be more
3414 than 255 and the string will need 2 bytes per code coint,
3415 if it stays under or equal to 255, we can be sure 1 byte
3416 is enough.
3417 ((*p & 0b00011111) << 6) | 0b00111111 */
3418 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
3419 if (max_char < upper_bound)
3420 new_max = upper_bound;
3421 /* Ensure we track at least that we left ASCII space. */
3422 if (new_max < 128)
3423 new_max = 128;
3424 break;
3425 case 3:
3426 /* Between 0x0FFF and 0xFFFF inclusive, so values are
3427 always > 255 and <= 65535 and will always need 2 bytes. */
3428 if (max_char < 65535)
3429 new_max = 65535;
3430 break;
3431 case 4:
3432 /* Code point will be above 0xFFFF for sure in this case. */
3433 new_max = 65537;
3434 break;
3435 /* Internal error, this should be caught by the first if */
3436 case 1:
3437 default:
3438 assert(0 && "Impossible case in utf8_max_char_and_size");
3439 err = 1;
3440 }
3441 /* Instead of number of overall bytes for this code point,
3442 n containts the number of following bytes: */
3443 --n;
3444 /* Check if the follow up chars are all valid continuation bytes */
3445 if (n >= 1) {
3446 const unsigned char *cont;
3447 if ((p + n) >= end) {
3448 if (consumed == 0)
3449 /* incomplete data, non-incremental decoding */
3450 err = 1;
3451 break;
3452 }
3453 for (cont = p + 1; cont < (p + n); ++cont) {
3454 if ((*cont & 0xc0) != 0x80) {
3455 err = 1;
3456 break;
3457 }
3458 }
3459 p += n;
3460 }
3461 else
3462 err = 1;
3463 max_char = new_max;
3464 }
3465 }
3466
3467 if (unicode_size)
3468 *unicode_size = char_count;
3469 if (has_errors)
3470 *has_errors = err;
3471 return max_char;
3472}
3473
3474/* Similar to PyUnicode_WRITE but can also write into wstr field
3475 of the legacy unicode representation */
3476#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
3477 do { \
3478 const int k_ = (kind); \
3479 if (k_ == PyUnicode_WCHAR_KIND) \
3480 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
3481 else if (k_ == PyUnicode_1BYTE_KIND) \
3482 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
3483 else if (k_ == PyUnicode_2BYTE_KIND) \
3484 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
3485 else \
3486 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
3487 } while (0)
3488
Alexander Belopolsky40018472011-02-26 01:02:56 +00003489PyObject *
3490PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003491 Py_ssize_t size,
3492 const char *errors,
3493 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00003494{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003495 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003496 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00003497 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003498 Py_ssize_t startinpos;
3499 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00003500 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003501 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003502 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003503 PyObject *errorHandler = NULL;
3504 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003505 Py_UCS4 maxchar = 0;
3506 Py_ssize_t unicode_size;
3507 Py_ssize_t i;
3508 int kind;
3509 void *data;
3510 int has_errors;
3511 Py_UNICODE *error_outptr;
3512#if SIZEOF_WCHAR_T == 2
3513 Py_ssize_t wchar_offset = 0;
3514#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00003515
Walter Dörwald69652032004-09-07 20:24:22 +00003516 if (size == 0) {
3517 if (consumed)
3518 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003519 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00003520 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003521 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
3522 consumed, &has_errors);
3523 if (has_errors) {
3524 unicode = _PyUnicode_New(size);
3525 if (!unicode)
3526 return NULL;
3527 kind = PyUnicode_WCHAR_KIND;
3528 data = PyUnicode_AS_UNICODE(unicode);
3529 assert(data != NULL);
3530 }
3531 else {
3532 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
3533 if (!unicode)
3534 return NULL;
3535 /* When the string is ASCII only, just use memcpy and return.
3536 unicode_size may be != size if there is an incomplete UTF-8
3537 sequence at the end of the ASCII block. */
3538 if (maxchar < 128 && size == unicode_size) {
3539 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
3540 return (PyObject *)unicode;
3541 }
3542 kind = PyUnicode_KIND(unicode);
3543 data = PyUnicode_DATA(unicode);
3544 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003545 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003546 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003547 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00003548 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003549
3550 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00003551 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003552
3553 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00003554 /* Fast path for runs of ASCII characters. Given that common UTF-8
3555 input will consist of an overwhelming majority of ASCII
3556 characters, we try to optimize for this case by checking
3557 as many characters as a C 'long' can contain.
3558 First, check if we can do an aligned read, as most CPUs have
3559 a penalty for unaligned reads.
3560 */
3561 if (!((size_t) s & LONG_PTR_MASK)) {
3562 /* Help register allocation */
3563 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003564 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00003565 while (_s < aligned_end) {
3566 /* Read a whole long at a time (either 4 or 8 bytes),
3567 and do a fast unrolled copy if it only contains ASCII
3568 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003569 unsigned long value = *(unsigned long *) _s;
3570 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00003571 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003572 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
3573 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
3574 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
3575 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00003576#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003577 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
3578 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
3579 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
3580 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00003581#endif
3582 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003583 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00003584 }
3585 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003586 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00003587 if (s == e)
3588 break;
3589 ch = (unsigned char)*s;
3590 }
3591 }
3592
3593 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003594 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003595 s++;
3596 continue;
3597 }
3598
3599 n = utf8_code_length[ch];
3600
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003601 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003602 if (consumed)
3603 break;
3604 else {
3605 errmsg = "unexpected end of data";
3606 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00003607 endinpos = startinpos+1;
3608 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
3609 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00003610 goto utf8Error;
3611 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00003612 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003613
3614 switch (n) {
3615
3616 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00003617 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00003618 startinpos = s-starts;
3619 endinpos = startinpos+1;
3620 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003621
3622 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003623 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00003624 startinpos = s-starts;
3625 endinpos = startinpos+1;
3626 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003627
3628 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003629 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00003630 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00003631 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00003632 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00003633 goto utf8Error;
3634 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003635 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00003636 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003637 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003638 break;
3639
3640 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00003641 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
3642 will result in surrogates in range d800-dfff. Surrogates are
3643 not valid UTF-8 so they are rejected.
3644 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
3645 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00003646 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00003647 (s[2] & 0xc0) != 0x80 ||
3648 ((unsigned char)s[0] == 0xE0 &&
3649 (unsigned char)s[1] < 0xA0) ||
3650 ((unsigned char)s[0] == 0xED &&
3651 (unsigned char)s[1] > 0x9F)) {
3652 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00003653 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00003654 endinpos = startinpos + 1;
3655
3656 /* if s[1] first two bits are 1 and 0, then the invalid
3657 continuation byte is s[2], so increment endinpos by 1,
3658 if not, s[1] is invalid and endinpos doesn't need to
3659 be incremented. */
3660 if ((s[1] & 0xC0) == 0x80)
3661 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00003662 goto utf8Error;
3663 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003664 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00003665 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003666 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00003667 break;
3668
3669 case 4:
3670 if ((s[1] & 0xc0) != 0x80 ||
3671 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00003672 (s[3] & 0xc0) != 0x80 ||
3673 ((unsigned char)s[0] == 0xF0 &&
3674 (unsigned char)s[1] < 0x90) ||
3675 ((unsigned char)s[0] == 0xF4 &&
3676 (unsigned char)s[1] > 0x8F)) {
3677 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00003678 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00003679 endinpos = startinpos + 1;
3680 if ((s[1] & 0xC0) == 0x80) {
3681 endinpos++;
3682 if ((s[2] & 0xC0) == 0x80)
3683 endinpos++;
3684 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003685 goto utf8Error;
3686 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00003687 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00003688 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
3689 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
3690
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003691 /* If the string is flexible or we have native UCS-4, write
3692 directly.. */
3693 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
3694 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00003695
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003696 else {
3697 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00003698
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003699 /* translate from 10000..10FFFF to 0..FFFF */
3700 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00003701
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003702 /* high surrogate = top 10 bits added to D800 */
3703 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
3704 (Py_UNICODE)(0xD800 + (ch >> 10)));
3705
3706 /* low surrogate = bottom 10 bits added to DC00 */
3707 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
3708 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
3709 }
3710#if SIZEOF_WCHAR_T == 2
3711 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003712#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00003713 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003714 }
3715 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00003716 continue;
Tim Petersced69f82003-09-16 20:30:58 +00003717
Benjamin Peterson29060642009-01-31 22:14:21 +00003718 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003719 /* If this is not yet a resizable string, make it one.. */
3720 if (kind != PyUnicode_WCHAR_KIND) {
3721 const Py_UNICODE *u;
3722 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
3723 if (!new_unicode)
3724 goto onError;
3725 u = PyUnicode_AsUnicode((PyObject *)unicode);
3726 if (!u)
3727 goto onError;
3728#if SIZEOF_WCHAR_T == 2
3729 i += wchar_offset;
3730#endif
3731 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
3732 Py_DECREF(unicode);
3733 unicode = new_unicode;
3734 kind = 0;
3735 data = PyUnicode_AS_UNICODE(new_unicode);
3736 assert(data != NULL);
3737 }
3738 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00003739 if (unicode_decode_call_errorhandler(
3740 errors, &errorHandler,
3741 "utf8", errmsg,
3742 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003743 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00003744 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003745 /* Update data because unicode_decode_call_errorhandler might have
3746 re-created or resized the unicode object. */
3747 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00003748 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003749 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003750 /* Ensure the unicode_size calculation above was correct: */
3751 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
3752
Walter Dörwald69652032004-09-07 20:24:22 +00003753 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003754 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003755
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003756 /* Adjust length and ready string when it contained errors and
3757 is of the old resizable kind. */
3758 if (kind == PyUnicode_WCHAR_KIND) {
3759 if (_PyUnicode_Resize(&unicode, i) < 0 ||
3760 PyUnicode_READY(unicode) == -1)
3761 goto onError;
3762 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003763
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003764 Py_XDECREF(errorHandler);
3765 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003766 if (PyUnicode_READY(unicode) == -1) {
3767 Py_DECREF(unicode);
3768 return NULL;
3769 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003770 return (PyObject *)unicode;
3771
Benjamin Peterson29060642009-01-31 22:14:21 +00003772 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003773 Py_XDECREF(errorHandler);
3774 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003775 Py_DECREF(unicode);
3776 return NULL;
3777}
3778
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003779#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00003780
Victor Stinnerf933e1a2010-10-20 22:58:25 +00003781#ifdef __APPLE__
3782
3783/* Simplified UTF-8 decoder using surrogateescape error handler,
3784 used to decode the command line arguments on Mac OS X. */
3785
3786wchar_t*
3787_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
3788{
3789 int n;
3790 const char *e;
3791 wchar_t *unicode, *p;
3792
3793 /* Note: size will always be longer than the resulting Unicode
3794 character count */
3795 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
3796 PyErr_NoMemory();
3797 return NULL;
3798 }
3799 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
3800 if (!unicode)
3801 return NULL;
3802
3803 /* Unpack UTF-8 encoded data */
3804 p = unicode;
3805 e = s + size;
3806 while (s < e) {
3807 Py_UCS4 ch = (unsigned char)*s;
3808
3809 if (ch < 0x80) {
3810 *p++ = (wchar_t)ch;
3811 s++;
3812 continue;
3813 }
3814
3815 n = utf8_code_length[ch];
3816 if (s + n > e) {
3817 goto surrogateescape;
3818 }
3819
3820 switch (n) {
3821 case 0:
3822 case 1:
3823 goto surrogateescape;
3824
3825 case 2:
3826 if ((s[1] & 0xc0) != 0x80)
3827 goto surrogateescape;
3828 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
3829 assert ((ch > 0x007F) && (ch <= 0x07FF));
3830 *p++ = (wchar_t)ch;
3831 break;
3832
3833 case 3:
3834 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
3835 will result in surrogates in range d800-dfff. Surrogates are
3836 not valid UTF-8 so they are rejected.
3837 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
3838 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
3839 if ((s[1] & 0xc0) != 0x80 ||
3840 (s[2] & 0xc0) != 0x80 ||
3841 ((unsigned char)s[0] == 0xE0 &&
3842 (unsigned char)s[1] < 0xA0) ||
3843 ((unsigned char)s[0] == 0xED &&
3844 (unsigned char)s[1] > 0x9F)) {
3845
3846 goto surrogateescape;
3847 }
3848 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
3849 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003850 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00003851 break;
3852
3853 case 4:
3854 if ((s[1] & 0xc0) != 0x80 ||
3855 (s[2] & 0xc0) != 0x80 ||
3856 (s[3] & 0xc0) != 0x80 ||
3857 ((unsigned char)s[0] == 0xF0 &&
3858 (unsigned char)s[1] < 0x90) ||
3859 ((unsigned char)s[0] == 0xF4 &&
3860 (unsigned char)s[1] > 0x8F)) {
3861 goto surrogateescape;
3862 }
3863 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
3864 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
3865 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
3866
3867#if SIZEOF_WCHAR_T == 4
3868 *p++ = (wchar_t)ch;
3869#else
3870 /* compute and append the two surrogates: */
3871
3872 /* translate from 10000..10FFFF to 0..FFFF */
3873 ch -= 0x10000;
3874
3875 /* high surrogate = top 10 bits added to D800 */
3876 *p++ = (wchar_t)(0xD800 + (ch >> 10));
3877
3878 /* low surrogate = bottom 10 bits added to DC00 */
3879 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
3880#endif
3881 break;
3882 }
3883 s += n;
3884 continue;
3885
3886 surrogateescape:
3887 *p++ = 0xDC00 + ch;
3888 s++;
3889 }
3890 *p = L'\0';
3891 return unicode;
3892}
3893
3894#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00003895
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003896/* Primary internal function which creates utf8 encoded bytes objects.
3897
3898 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00003899 and allocate exactly as much space needed at the end. Else allocate the
3900 maximum possible needed (4 result bytes per Unicode character), and return
3901 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00003902*/
Tim Peters7e3d9612002-04-21 03:26:37 +00003903PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003904_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003905{
Tim Peters602f7402002-04-27 18:03:26 +00003906#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00003907
Guido van Rossum98297ee2007-11-06 21:34:58 +00003908 Py_ssize_t i; /* index into s of next input byte */
3909 PyObject *result; /* result string object */
3910 char *p; /* next free byte in output buffer */
3911 Py_ssize_t nallocated; /* number of result bytes allocated */
3912 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00003913 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00003914 PyObject *errorHandler = NULL;
3915 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003916 int kind;
3917 void *data;
3918 Py_ssize_t size;
3919 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
3920#if SIZEOF_WCHAR_T == 2
3921 Py_ssize_t wchar_offset = 0;
3922#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00003923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003924 if (!PyUnicode_Check(unicode)) {
3925 PyErr_BadArgument();
3926 return NULL;
3927 }
3928
3929 if (PyUnicode_READY(unicode) == -1)
3930 return NULL;
3931
3932 if (_PyUnicode_UTF8(unicode))
3933 return PyBytes_FromStringAndSize(_PyUnicode_UTF8(unicode),
3934 _PyUnicode_UTF8_LENGTH(unicode));
3935
3936 kind = PyUnicode_KIND(unicode);
3937 data = PyUnicode_DATA(unicode);
3938 size = PyUnicode_GET_LENGTH(unicode);
3939
Tim Peters602f7402002-04-27 18:03:26 +00003940 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003941
Tim Peters602f7402002-04-27 18:03:26 +00003942 if (size <= MAX_SHORT_UNICHARS) {
3943 /* Write into the stack buffer; nallocated can't overflow.
3944 * At the end, we'll allocate exactly as much heap space as it
3945 * turns out we need.
3946 */
3947 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003948 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00003949 p = stackbuf;
3950 }
3951 else {
3952 /* Overallocate on the heap, and give the excess back at the end. */
3953 nallocated = size * 4;
3954 if (nallocated / 4 != size) /* overflow! */
3955 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00003956 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003957 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00003958 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00003959 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00003960 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00003961
Tim Peters602f7402002-04-27 18:03:26 +00003962 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003963 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00003964
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00003965 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00003966 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003967 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00003968
Guido van Rossumd57fd912000-03-10 22:53:23 +00003969 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00003970 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00003971 *p++ = (char)(0xc0 | (ch >> 6));
3972 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00003973 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003974 Py_ssize_t newpos;
3975 PyObject *rep;
3976 Py_ssize_t repsize, k, startpos;
3977 startpos = i-1;
3978#if SIZEOF_WCHAR_T == 2
3979 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00003980#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003981 rep = unicode_encode_call_errorhandler(
3982 errors, &errorHandler, "utf-8", "surrogates not allowed",
3983 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
3984 &exc, startpos, startpos+1, &newpos);
3985 if (!rep)
3986 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00003987
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003988 if (PyBytes_Check(rep))
3989 repsize = PyBytes_GET_SIZE(rep);
3990 else
3991 repsize = PyUnicode_GET_SIZE(rep);
3992
3993 if (repsize > 4) {
3994 Py_ssize_t offset;
3995
3996 if (result == NULL)
3997 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00003998 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003999 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004001 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4002 /* integer overflow */
4003 PyErr_NoMemory();
4004 goto error;
4005 }
4006 nallocated += repsize - 4;
4007 if (result != NULL) {
4008 if (_PyBytes_Resize(&result, nallocated) < 0)
4009 goto error;
4010 } else {
4011 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004012 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004013 goto error;
4014 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4015 }
4016 p = PyBytes_AS_STRING(result) + offset;
4017 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004018
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004019 if (PyBytes_Check(rep)) {
4020 char *prep = PyBytes_AS_STRING(rep);
4021 for(k = repsize; k > 0; k--)
4022 *p++ = *prep++;
4023 } else /* rep is unicode */ {
4024 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4025 Py_UNICODE c;
4026
4027 for(k=0; k<repsize; k++) {
4028 c = prep[k];
4029 if (0x80 <= c) {
4030 raise_encode_exception(&exc, "utf-8",
4031 PyUnicode_AS_UNICODE(unicode),
4032 size, i-1, i,
4033 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004034 goto error;
4035 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004036 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004037 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004038 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004039 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004040 } else if (ch < 0x10000) {
4041 *p++ = (char)(0xe0 | (ch >> 12));
4042 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4043 *p++ = (char)(0x80 | (ch & 0x3f));
4044 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004045 /* Encode UCS4 Unicode ordinals */
4046 *p++ = (char)(0xf0 | (ch >> 18));
4047 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4048 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4049 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004050#if SIZEOF_WCHAR_T == 2
4051 wchar_offset++;
4052#endif
Tim Peters602f7402002-04-27 18:03:26 +00004053 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004054 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004055
Guido van Rossum98297ee2007-11-06 21:34:58 +00004056 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004057 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004058 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004059 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004060 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004061 }
4062 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004063 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004064 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004065 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004066 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004067 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004068
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004069 Py_XDECREF(errorHandler);
4070 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004071 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004072 error:
4073 Py_XDECREF(errorHandler);
4074 Py_XDECREF(exc);
4075 Py_XDECREF(result);
4076 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004077
Tim Peters602f7402002-04-27 18:03:26 +00004078#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004079}
4080
Alexander Belopolsky40018472011-02-26 01:02:56 +00004081PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004082PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4083 Py_ssize_t size,
4084 const char *errors)
4085{
4086 PyObject *v, *unicode;
4087
4088 unicode = PyUnicode_FromUnicode(s, size);
4089 if (unicode == NULL)
4090 return NULL;
4091 v = _PyUnicode_AsUTF8String(unicode, errors);
4092 Py_DECREF(unicode);
4093 return v;
4094}
4095
4096PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004097PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004098{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004099 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004100}
4101
Walter Dörwald41980ca2007-08-16 21:55:45 +00004102/* --- UTF-32 Codec ------------------------------------------------------- */
4103
4104PyObject *
4105PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004106 Py_ssize_t size,
4107 const char *errors,
4108 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004109{
4110 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4111}
4112
4113PyObject *
4114PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004115 Py_ssize_t size,
4116 const char *errors,
4117 int *byteorder,
4118 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004119{
4120 const char *starts = s;
4121 Py_ssize_t startinpos;
4122 Py_ssize_t endinpos;
4123 Py_ssize_t outpos;
4124 PyUnicodeObject *unicode;
4125 Py_UNICODE *p;
4126#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004127 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004128 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004129#else
4130 const int pairs = 0;
4131#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004132 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004133 int bo = 0; /* assume native ordering by default */
4134 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004135 /* Offsets from q for retrieving bytes in the right order. */
4136#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4137 int iorder[] = {0, 1, 2, 3};
4138#else
4139 int iorder[] = {3, 2, 1, 0};
4140#endif
4141 PyObject *errorHandler = NULL;
4142 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004143
Walter Dörwald41980ca2007-08-16 21:55:45 +00004144 q = (unsigned char *)s;
4145 e = q + size;
4146
4147 if (byteorder)
4148 bo = *byteorder;
4149
4150 /* Check for BOM marks (U+FEFF) in the input and adjust current
4151 byte order setting accordingly. In native mode, the leading BOM
4152 mark is skipped, in all other modes, it is copied to the output
4153 stream as-is (giving a ZWNBSP character). */
4154 if (bo == 0) {
4155 if (size >= 4) {
4156 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004157 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004158#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004159 if (bom == 0x0000FEFF) {
4160 q += 4;
4161 bo = -1;
4162 }
4163 else if (bom == 0xFFFE0000) {
4164 q += 4;
4165 bo = 1;
4166 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004167#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004168 if (bom == 0x0000FEFF) {
4169 q += 4;
4170 bo = 1;
4171 }
4172 else if (bom == 0xFFFE0000) {
4173 q += 4;
4174 bo = -1;
4175 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004176#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004177 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004178 }
4179
4180 if (bo == -1) {
4181 /* force LE */
4182 iorder[0] = 0;
4183 iorder[1] = 1;
4184 iorder[2] = 2;
4185 iorder[3] = 3;
4186 }
4187 else if (bo == 1) {
4188 /* force BE */
4189 iorder[0] = 3;
4190 iorder[1] = 2;
4191 iorder[2] = 1;
4192 iorder[3] = 0;
4193 }
4194
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004195 /* On narrow builds we split characters outside the BMP into two
4196 codepoints => count how much extra space we need. */
4197#ifndef Py_UNICODE_WIDE
4198 for (qq = q; qq < e; qq += 4)
4199 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4200 pairs++;
4201#endif
4202
4203 /* This might be one to much, because of a BOM */
4204 unicode = _PyUnicode_New((size+3)/4+pairs);
4205 if (!unicode)
4206 return NULL;
4207 if (size == 0)
4208 return (PyObject *)unicode;
4209
4210 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004211 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004212
Walter Dörwald41980ca2007-08-16 21:55:45 +00004213 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004214 Py_UCS4 ch;
4215 /* remaining bytes at the end? (size should be divisible by 4) */
4216 if (e-q<4) {
4217 if (consumed)
4218 break;
4219 errmsg = "truncated data";
4220 startinpos = ((const char *)q)-starts;
4221 endinpos = ((const char *)e)-starts;
4222 goto utf32Error;
4223 /* The remaining input chars are ignored if the callback
4224 chooses to skip the input */
4225 }
4226 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4227 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004228
Benjamin Peterson29060642009-01-31 22:14:21 +00004229 if (ch >= 0x110000)
4230 {
4231 errmsg = "codepoint not in range(0x110000)";
4232 startinpos = ((const char *)q)-starts;
4233 endinpos = startinpos+4;
4234 goto utf32Error;
4235 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004236#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004237 if (ch >= 0x10000)
4238 {
4239 *p++ = 0xD800 | ((ch-0x10000) >> 10);
4240 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
4241 }
4242 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00004243#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004244 *p++ = ch;
4245 q += 4;
4246 continue;
4247 utf32Error:
4248 outpos = p-PyUnicode_AS_UNICODE(unicode);
4249 if (unicode_decode_call_errorhandler(
4250 errors, &errorHandler,
4251 "utf32", errmsg,
4252 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
4253 &unicode, &outpos, &p))
4254 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004255 }
4256
4257 if (byteorder)
4258 *byteorder = bo;
4259
4260 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004261 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004262
4263 /* Adjust length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004264 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004265 goto onError;
4266
4267 Py_XDECREF(errorHandler);
4268 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004269 if (PyUnicode_READY(unicode) == -1) {
4270 Py_DECREF(unicode);
4271 return NULL;
4272 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004273 return (PyObject *)unicode;
4274
Benjamin Peterson29060642009-01-31 22:14:21 +00004275 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00004276 Py_DECREF(unicode);
4277 Py_XDECREF(errorHandler);
4278 Py_XDECREF(exc);
4279 return NULL;
4280}
4281
4282PyObject *
4283PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004284 Py_ssize_t size,
4285 const char *errors,
4286 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004287{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004288 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004289 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004290 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004291#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004292 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004293#else
4294 const int pairs = 0;
4295#endif
4296 /* Offsets from p for storing byte pairs in the right order. */
4297#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4298 int iorder[] = {0, 1, 2, 3};
4299#else
4300 int iorder[] = {3, 2, 1, 0};
4301#endif
4302
Benjamin Peterson29060642009-01-31 22:14:21 +00004303#define STORECHAR(CH) \
4304 do { \
4305 p[iorder[3]] = ((CH) >> 24) & 0xff; \
4306 p[iorder[2]] = ((CH) >> 16) & 0xff; \
4307 p[iorder[1]] = ((CH) >> 8) & 0xff; \
4308 p[iorder[0]] = (CH) & 0xff; \
4309 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00004310 } while(0)
4311
4312 /* In narrow builds we can output surrogate pairs as one codepoint,
4313 so we need less space. */
4314#ifndef Py_UNICODE_WIDE
4315 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00004316 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
4317 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
4318 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004319#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004320 nsize = (size - pairs + (byteorder == 0));
4321 bytesize = nsize * 4;
4322 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004323 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004324 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004325 if (v == NULL)
4326 return NULL;
4327
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004328 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004329 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004330 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004331 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004332 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004333
4334 if (byteorder == -1) {
4335 /* force LE */
4336 iorder[0] = 0;
4337 iorder[1] = 1;
4338 iorder[2] = 2;
4339 iorder[3] = 3;
4340 }
4341 else if (byteorder == 1) {
4342 /* force BE */
4343 iorder[0] = 3;
4344 iorder[1] = 2;
4345 iorder[2] = 1;
4346 iorder[3] = 0;
4347 }
4348
4349 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004350 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004351#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004352 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
4353 Py_UCS4 ch2 = *s;
4354 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
4355 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
4356 s++;
4357 size--;
4358 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004359 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004360#endif
4361 STORECHAR(ch);
4362 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004363
4364 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004365 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004366#undef STORECHAR
4367}
4368
Alexander Belopolsky40018472011-02-26 01:02:56 +00004369PyObject *
4370PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004371{
4372 if (!PyUnicode_Check(unicode)) {
4373 PyErr_BadArgument();
4374 return NULL;
4375 }
4376 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004377 PyUnicode_GET_SIZE(unicode),
4378 NULL,
4379 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004380}
4381
Guido van Rossumd57fd912000-03-10 22:53:23 +00004382/* --- UTF-16 Codec ------------------------------------------------------- */
4383
Tim Peters772747b2001-08-09 22:21:55 +00004384PyObject *
4385PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004386 Py_ssize_t size,
4387 const char *errors,
4388 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004389{
Walter Dörwald69652032004-09-07 20:24:22 +00004390 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
4391}
4392
Antoine Pitrouab868312009-01-10 15:40:25 +00004393/* Two masks for fast checking of whether a C 'long' may contain
4394 UTF16-encoded surrogate characters. This is an efficient heuristic,
4395 assuming that non-surrogate characters with a code point >= 0x8000 are
4396 rare in most input.
4397 FAST_CHAR_MASK is used when the input is in native byte ordering,
4398 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00004399*/
Antoine Pitrouab868312009-01-10 15:40:25 +00004400#if (SIZEOF_LONG == 8)
4401# define FAST_CHAR_MASK 0x8000800080008000L
4402# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
4403#elif (SIZEOF_LONG == 4)
4404# define FAST_CHAR_MASK 0x80008000L
4405# define SWAPPED_FAST_CHAR_MASK 0x00800080L
4406#else
4407# error C 'long' size should be either 4 or 8!
4408#endif
4409
Walter Dörwald69652032004-09-07 20:24:22 +00004410PyObject *
4411PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004412 Py_ssize_t size,
4413 const char *errors,
4414 int *byteorder,
4415 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004416{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004417 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004418 Py_ssize_t startinpos;
4419 Py_ssize_t endinpos;
4420 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004421 PyUnicodeObject *unicode;
4422 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00004423 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00004424 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00004425 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004426 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00004427 /* Offsets from q for retrieving byte pairs in the right order. */
4428#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4429 int ihi = 1, ilo = 0;
4430#else
4431 int ihi = 0, ilo = 1;
4432#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004433 PyObject *errorHandler = NULL;
4434 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004435
4436 /* Note: size will always be longer than the resulting Unicode
4437 character count */
4438 unicode = _PyUnicode_New(size);
4439 if (!unicode)
4440 return NULL;
4441 if (size == 0)
4442 return (PyObject *)unicode;
4443
4444 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004445 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00004446 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00004447 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004448
4449 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00004450 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004451
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004452 /* Check for BOM marks (U+FEFF) in the input and adjust current
4453 byte order setting accordingly. In native mode, the leading BOM
4454 mark is skipped, in all other modes, it is copied to the output
4455 stream as-is (giving a ZWNBSP character). */
4456 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00004457 if (size >= 2) {
4458 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004459#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004460 if (bom == 0xFEFF) {
4461 q += 2;
4462 bo = -1;
4463 }
4464 else if (bom == 0xFFFE) {
4465 q += 2;
4466 bo = 1;
4467 }
Tim Petersced69f82003-09-16 20:30:58 +00004468#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004469 if (bom == 0xFEFF) {
4470 q += 2;
4471 bo = 1;
4472 }
4473 else if (bom == 0xFFFE) {
4474 q += 2;
4475 bo = -1;
4476 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004477#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004478 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004479 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004480
Tim Peters772747b2001-08-09 22:21:55 +00004481 if (bo == -1) {
4482 /* force LE */
4483 ihi = 1;
4484 ilo = 0;
4485 }
4486 else if (bo == 1) {
4487 /* force BE */
4488 ihi = 0;
4489 ilo = 1;
4490 }
Antoine Pitrouab868312009-01-10 15:40:25 +00004491#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4492 native_ordering = ilo < ihi;
4493#else
4494 native_ordering = ilo > ihi;
4495#endif
Tim Peters772747b2001-08-09 22:21:55 +00004496
Antoine Pitrouab868312009-01-10 15:40:25 +00004497 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00004498 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004499 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00004500 /* First check for possible aligned read of a C 'long'. Unaligned
4501 reads are more expensive, better to defer to another iteration. */
4502 if (!((size_t) q & LONG_PTR_MASK)) {
4503 /* Fast path for runs of non-surrogate chars. */
4504 register const unsigned char *_q = q;
4505 Py_UNICODE *_p = p;
4506 if (native_ordering) {
4507 /* Native ordering is simple: as long as the input cannot
4508 possibly contain a surrogate char, do an unrolled copy
4509 of several 16-bit code points to the target object.
4510 The non-surrogate check is done on several input bytes
4511 at a time (as many as a C 'long' can contain). */
4512 while (_q < aligned_end) {
4513 unsigned long data = * (unsigned long *) _q;
4514 if (data & FAST_CHAR_MASK)
4515 break;
4516 _p[0] = ((unsigned short *) _q)[0];
4517 _p[1] = ((unsigned short *) _q)[1];
4518#if (SIZEOF_LONG == 8)
4519 _p[2] = ((unsigned short *) _q)[2];
4520 _p[3] = ((unsigned short *) _q)[3];
4521#endif
4522 _q += SIZEOF_LONG;
4523 _p += SIZEOF_LONG / 2;
4524 }
4525 }
4526 else {
4527 /* Byteswapped ordering is similar, but we must decompose
4528 the copy bytewise, and take care of zero'ing out the
4529 upper bytes if the target object is in 32-bit units
4530 (that is, in UCS-4 builds). */
4531 while (_q < aligned_end) {
4532 unsigned long data = * (unsigned long *) _q;
4533 if (data & SWAPPED_FAST_CHAR_MASK)
4534 break;
4535 /* Zero upper bytes in UCS-4 builds */
4536#if (Py_UNICODE_SIZE > 2)
4537 _p[0] = 0;
4538 _p[1] = 0;
4539#if (SIZEOF_LONG == 8)
4540 _p[2] = 0;
4541 _p[3] = 0;
4542#endif
4543#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00004544 /* Issue #4916; UCS-4 builds on big endian machines must
4545 fill the two last bytes of each 4-byte unit. */
4546#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
4547# define OFF 2
4548#else
4549# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00004550#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00004551 ((unsigned char *) _p)[OFF + 1] = _q[0];
4552 ((unsigned char *) _p)[OFF + 0] = _q[1];
4553 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
4554 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
4555#if (SIZEOF_LONG == 8)
4556 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
4557 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
4558 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
4559 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
4560#endif
4561#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00004562 _q += SIZEOF_LONG;
4563 _p += SIZEOF_LONG / 2;
4564 }
4565 }
4566 p = _p;
4567 q = _q;
4568 if (q >= e)
4569 break;
4570 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004571 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004572
Benjamin Peterson14339b62009-01-31 16:36:08 +00004573 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00004574
4575 if (ch < 0xD800 || ch > 0xDFFF) {
4576 *p++ = ch;
4577 continue;
4578 }
4579
4580 /* UTF-16 code pair: */
4581 if (q > e) {
4582 errmsg = "unexpected end of data";
4583 startinpos = (((const char *)q) - 2) - starts;
4584 endinpos = ((const char *)e) + 1 - starts;
4585 goto utf16Error;
4586 }
4587 if (0xD800 <= ch && ch <= 0xDBFF) {
4588 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
4589 q += 2;
4590 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00004591#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004592 *p++ = ch;
4593 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004594#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004595 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004596#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004597 continue;
4598 }
4599 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004600 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00004601 startinpos = (((const char *)q)-4)-starts;
4602 endinpos = startinpos+2;
4603 goto utf16Error;
4604 }
4605
Benjamin Peterson14339b62009-01-31 16:36:08 +00004606 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004607 errmsg = "illegal encoding";
4608 startinpos = (((const char *)q)-2)-starts;
4609 endinpos = startinpos+2;
4610 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004611
Benjamin Peterson29060642009-01-31 22:14:21 +00004612 utf16Error:
4613 outpos = p - PyUnicode_AS_UNICODE(unicode);
4614 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00004615 errors,
4616 &errorHandler,
4617 "utf16", errmsg,
4618 &starts,
4619 (const char **)&e,
4620 &startinpos,
4621 &endinpos,
4622 &exc,
4623 (const char **)&q,
4624 &unicode,
4625 &outpos,
4626 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00004627 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004628 }
Antoine Pitrouab868312009-01-10 15:40:25 +00004629 /* remaining byte at the end? (size should be even) */
4630 if (e == q) {
4631 if (!consumed) {
4632 errmsg = "truncated data";
4633 startinpos = ((const char *)q) - starts;
4634 endinpos = ((const char *)e) + 1 - starts;
4635 outpos = p - PyUnicode_AS_UNICODE(unicode);
4636 if (unicode_decode_call_errorhandler(
4637 errors,
4638 &errorHandler,
4639 "utf16", errmsg,
4640 &starts,
4641 (const char **)&e,
4642 &startinpos,
4643 &endinpos,
4644 &exc,
4645 (const char **)&q,
4646 &unicode,
4647 &outpos,
4648 &p))
4649 goto onError;
4650 /* The remaining input chars are ignored if the callback
4651 chooses to skip the input */
4652 }
4653 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004654
4655 if (byteorder)
4656 *byteorder = bo;
4657
Walter Dörwald69652032004-09-07 20:24:22 +00004658 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004659 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00004660
Guido van Rossumd57fd912000-03-10 22:53:23 +00004661 /* Adjust length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004662 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004663 goto onError;
4664
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004665 Py_XDECREF(errorHandler);
4666 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004667 if (PyUnicode_READY(unicode) == -1) {
4668 Py_DECREF(unicode);
4669 return NULL;
4670 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004671 return (PyObject *)unicode;
4672
Benjamin Peterson29060642009-01-31 22:14:21 +00004673 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004674 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004675 Py_XDECREF(errorHandler);
4676 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004677 return NULL;
4678}
4679
Antoine Pitrouab868312009-01-10 15:40:25 +00004680#undef FAST_CHAR_MASK
4681#undef SWAPPED_FAST_CHAR_MASK
4682
Tim Peters772747b2001-08-09 22:21:55 +00004683PyObject *
4684PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004685 Py_ssize_t size,
4686 const char *errors,
4687 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004688{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004689 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00004690 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004691 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004692#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004693 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004694#else
4695 const int pairs = 0;
4696#endif
Tim Peters772747b2001-08-09 22:21:55 +00004697 /* Offsets from p for storing byte pairs in the right order. */
4698#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4699 int ihi = 1, ilo = 0;
4700#else
4701 int ihi = 0, ilo = 1;
4702#endif
4703
Benjamin Peterson29060642009-01-31 22:14:21 +00004704#define STORECHAR(CH) \
4705 do { \
4706 p[ihi] = ((CH) >> 8) & 0xff; \
4707 p[ilo] = (CH) & 0xff; \
4708 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00004709 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004710
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004711#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004712 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00004713 if (s[i] >= 0x10000)
4714 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004715#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004716 /* 2 * (size + pairs + (byteorder == 0)) */
4717 if (size > PY_SSIZE_T_MAX ||
4718 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00004719 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004720 nsize = size + pairs + (byteorder == 0);
4721 bytesize = nsize * 2;
4722 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004723 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004724 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004725 if (v == NULL)
4726 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004727
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004728 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004729 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004730 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00004731 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004732 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00004733
4734 if (byteorder == -1) {
4735 /* force LE */
4736 ihi = 1;
4737 ilo = 0;
4738 }
4739 else if (byteorder == 1) {
4740 /* force BE */
4741 ihi = 0;
4742 ilo = 1;
4743 }
4744
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004745 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004746 Py_UNICODE ch = *s++;
4747 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004748#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004749 if (ch >= 0x10000) {
4750 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
4751 ch = 0xD800 | ((ch-0x10000) >> 10);
4752 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004753#endif
Tim Peters772747b2001-08-09 22:21:55 +00004754 STORECHAR(ch);
4755 if (ch2)
4756 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004757 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004758
4759 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004760 return v;
Tim Peters772747b2001-08-09 22:21:55 +00004761#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00004762}
4763
Alexander Belopolsky40018472011-02-26 01:02:56 +00004764PyObject *
4765PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004766{
4767 if (!PyUnicode_Check(unicode)) {
4768 PyErr_BadArgument();
4769 return NULL;
4770 }
4771 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004772 PyUnicode_GET_SIZE(unicode),
4773 NULL,
4774 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004775}
4776
4777/* --- Unicode Escape Codec ----------------------------------------------- */
4778
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004779/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
4780 if all the escapes in the string make it still a valid ASCII string.
4781 Returns -1 if any escapes were found which cause the string to
4782 pop out of ASCII range. Otherwise returns the length of the
4783 required buffer to hold the string.
4784 */
4785Py_ssize_t
4786length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
4787{
4788 const unsigned char *p = (const unsigned char *)s;
4789 const unsigned char *end = p + size;
4790 Py_ssize_t length = 0;
4791
4792 if (size < 0)
4793 return -1;
4794
4795 for (; p < end; ++p) {
4796 if (*p > 127) {
4797 /* Non-ASCII */
4798 return -1;
4799 }
4800 else if (*p != '\\') {
4801 /* Normal character */
4802 ++length;
4803 }
4804 else {
4805 /* Backslash-escape, check next char */
4806 ++p;
4807 /* Escape sequence reaches till end of string or
4808 non-ASCII follow-up. */
4809 if (p >= end || *p > 127)
4810 return -1;
4811 switch (*p) {
4812 case '\n':
4813 /* backslash + \n result in zero characters */
4814 break;
4815 case '\\': case '\'': case '\"':
4816 case 'b': case 'f': case 't':
4817 case 'n': case 'r': case 'v': case 'a':
4818 ++length;
4819 break;
4820 case '0': case '1': case '2': case '3':
4821 case '4': case '5': case '6': case '7':
4822 case 'x': case 'u': case 'U': case 'N':
4823 /* these do not guarantee ASCII characters */
4824 return -1;
4825 default:
4826 /* count the backslash + the other character */
4827 length += 2;
4828 }
4829 }
4830 }
4831 return length;
4832}
4833
4834/* Similar to PyUnicode_WRITE but either write into wstr field
4835 or treat string as ASCII. */
4836#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
4837 do { \
4838 if ((kind) != PyUnicode_WCHAR_KIND) \
4839 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
4840 else \
4841 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
4842 } while (0)
4843
4844#define WRITE_WSTR(buf, index, value) \
4845 assert(kind == PyUnicode_WCHAR_KIND), \
4846 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
4847
4848
Fredrik Lundh06d12682001-01-24 07:59:11 +00004849static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00004850
Alexander Belopolsky40018472011-02-26 01:02:56 +00004851PyObject *
4852PyUnicode_DecodeUnicodeEscape(const char *s,
4853 Py_ssize_t size,
4854 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004855{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004856 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004857 Py_ssize_t startinpos;
4858 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004859 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004860 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004861 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004862 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00004863 char* message;
4864 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004865 PyObject *errorHandler = NULL;
4866 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004867 Py_ssize_t ascii_length;
4868 Py_ssize_t i;
4869 int kind;
4870 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00004871
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004872 ascii_length = length_of_escaped_ascii_string(s, size);
4873
4874 /* After length_of_escaped_ascii_string() there are two alternatives,
4875 either the string is pure ASCII with named escapes like \n, etc.
4876 and we determined it's exact size (common case)
4877 or it contains \x, \u, ... escape sequences. then we create a
4878 legacy wchar string and resize it at the end of this function. */
4879 if (ascii_length >= 0) {
4880 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
4881 if (!v)
4882 goto onError;
4883 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
4884 kind = PyUnicode_1BYTE_KIND;
4885 data = PyUnicode_DATA(v);
4886 }
4887 else {
4888 /* Escaped strings will always be longer than the resulting
4889 Unicode string, so we start with size here and then reduce the
4890 length after conversion to the true value.
4891 (but if the error callback returns a long replacement string
4892 we'll have to allocate more space) */
4893 v = _PyUnicode_New(size);
4894 if (!v)
4895 goto onError;
4896 kind = PyUnicode_WCHAR_KIND;
4897 data = PyUnicode_AS_UNICODE(v);
4898 }
4899
Guido van Rossumd57fd912000-03-10 22:53:23 +00004900 if (size == 0)
4901 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004902 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004903 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00004904
Guido van Rossumd57fd912000-03-10 22:53:23 +00004905 while (s < end) {
4906 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00004907 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004908 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004909
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004910 if (kind == PyUnicode_WCHAR_KIND) {
4911 assert(i < _PyUnicode_WSTR_LENGTH(v));
4912 }
4913 else {
4914 /* The only case in which i == ascii_length is a backslash
4915 followed by a newline. */
4916 assert(i <= ascii_length);
4917 }
4918
Guido van Rossumd57fd912000-03-10 22:53:23 +00004919 /* Non-escape characters are interpreted as Unicode ordinals */
4920 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004921 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004922 continue;
4923 }
4924
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004925 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004926 /* \ - Escapes */
4927 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004928 c = *s++;
4929 if (s > end)
4930 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004931
4932 if (kind == PyUnicode_WCHAR_KIND) {
4933 assert(i < _PyUnicode_WSTR_LENGTH(v));
4934 }
4935 else {
4936 /* The only case in which i == ascii_length is a backslash
4937 followed by a newline. */
4938 assert(i < ascii_length || (i == ascii_length && c == '\n'));
4939 }
4940
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004941 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004942
Benjamin Peterson29060642009-01-31 22:14:21 +00004943 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004944 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004945 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
4946 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
4947 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
4948 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
4949 /* FF */
4950 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
4951 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
4952 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
4953 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
4954 /* VT */
4955 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
4956 /* BEL, not classic C */
4957 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004958
Benjamin Peterson29060642009-01-31 22:14:21 +00004959 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004960 case '0': case '1': case '2': case '3':
4961 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00004962 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004963 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00004964 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004965 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00004966 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00004967 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004968 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004969 break;
4970
Benjamin Peterson29060642009-01-31 22:14:21 +00004971 /* hex escapes */
4972 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004973 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00004974 digits = 2;
4975 message = "truncated \\xXX escape";
4976 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004977
Benjamin Peterson29060642009-01-31 22:14:21 +00004978 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004979 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00004980 digits = 4;
4981 message = "truncated \\uXXXX escape";
4982 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004983
Benjamin Peterson29060642009-01-31 22:14:21 +00004984 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00004985 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00004986 digits = 8;
4987 message = "truncated \\UXXXXXXXX escape";
4988 hexescape:
4989 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004990 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004991 if (s+digits>end) {
4992 endinpos = size;
4993 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004994 errors, &errorHandler,
4995 "unicodeescape", "end of string in escape sequence",
4996 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004997 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004998 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004999 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005000 goto nextByte;
5001 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005002 for (j = 0; j < digits; ++j) {
5003 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005004 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005005 endinpos = (s+j+1)-starts;
5006 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005007 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005008 errors, &errorHandler,
5009 "unicodeescape", message,
5010 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005011 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005012 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005013 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005014 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005015 }
5016 chr = (chr<<4) & ~0xF;
5017 if (c >= '0' && c <= '9')
5018 chr += c - '0';
5019 else if (c >= 'a' && c <= 'f')
5020 chr += 10 + c - 'a';
5021 else
5022 chr += 10 + c - 'A';
5023 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005024 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005025 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005026 /* _decoding_error will have already written into the
5027 target buffer. */
5028 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005029 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005030 /* when we get here, chr is a 32-bit unicode character */
5031 if (chr <= 0xffff)
5032 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005033 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005034 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005035 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005036 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005037#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005038 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005039#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005040 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005041 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5042 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005043#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005044 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005045 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005046 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005047 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005048 errors, &errorHandler,
5049 "unicodeescape", "illegal Unicode character",
5050 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005051 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005052 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005053 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005054 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005055 break;
5056
Benjamin Peterson29060642009-01-31 22:14:21 +00005057 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005058 case 'N':
5059 message = "malformed \\N character escape";
5060 if (ucnhash_CAPI == NULL) {
5061 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005062 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5063 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005064 if (ucnhash_CAPI == NULL)
5065 goto ucnhashError;
5066 }
5067 if (*s == '{') {
5068 const char *start = s+1;
5069 /* look for the closing brace */
5070 while (*s != '}' && s < end)
5071 s++;
5072 if (s > start && s < end && *s == '}') {
5073 /* found a name. look it up in the unicode database */
5074 message = "unknown Unicode character name";
5075 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005076 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
5077 &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005078 goto store;
5079 }
5080 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005081 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005082 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005083 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005084 errors, &errorHandler,
5085 "unicodeescape", message,
5086 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005087 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005088 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005089 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005090 break;
5091
5092 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005093 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005094 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005095 message = "\\ at end of string";
5096 s--;
5097 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005098 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005099 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005100 errors, &errorHandler,
5101 "unicodeescape", message,
5102 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005103 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005104 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005105 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005106 }
5107 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005108 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5109 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005110 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005111 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005112 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005113 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005114 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005115 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005116 /* Ensure the length prediction worked in case of ASCII strings */
5117 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5118
5119 if (kind == PyUnicode_WCHAR_KIND && (_PyUnicode_Resize(&v, i) < 0 ||
5120 PyUnicode_READY(v) == -1))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005121 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005122 Py_XDECREF(errorHandler);
5123 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005124 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005125
Benjamin Peterson29060642009-01-31 22:14:21 +00005126 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005127 PyErr_SetString(
5128 PyExc_UnicodeError,
5129 "\\N escapes not supported (can't load unicodedata module)"
5130 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005131 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005132 Py_XDECREF(errorHandler);
5133 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005134 return NULL;
5135
Benjamin Peterson29060642009-01-31 22:14:21 +00005136 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005137 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005138 Py_XDECREF(errorHandler);
5139 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005140 return NULL;
5141}
5142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005143#undef WRITE_ASCII_OR_WSTR
5144#undef WRITE_WSTR
5145
Guido van Rossumd57fd912000-03-10 22:53:23 +00005146/* Return a Unicode-Escape string version of the Unicode object.
5147
5148 If quotes is true, the string is enclosed in u"" or u'' quotes as
5149 appropriate.
5150
5151*/
5152
Walter Dörwald79e913e2007-05-12 11:08:06 +00005153static const char *hexdigits = "0123456789abcdef";
5154
Alexander Belopolsky40018472011-02-26 01:02:56 +00005155PyObject *
5156PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5157 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005158{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005159 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005160 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005161
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005162#ifdef Py_UNICODE_WIDE
5163 const Py_ssize_t expandsize = 10;
5164#else
5165 const Py_ssize_t expandsize = 6;
5166#endif
5167
Thomas Wouters89f507f2006-12-13 04:49:30 +00005168 /* XXX(nnorwitz): rather than over-allocating, it would be
5169 better to choose a different scheme. Perhaps scan the
5170 first N-chars of the string and allocate based on that size.
5171 */
5172 /* Initial allocation is based on the longest-possible unichr
5173 escape.
5174
5175 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5176 unichr, so in this case it's the longest unichr escape. In
5177 narrow (UTF-16) builds this is five chars per source unichr
5178 since there are two unichrs in the surrogate pair, so in narrow
5179 (UTF-16) builds it's not the longest unichr escape.
5180
5181 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5182 so in the narrow (UTF-16) build case it's the longest unichr
5183 escape.
5184 */
5185
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005186 if (size == 0)
5187 return PyBytes_FromStringAndSize(NULL, 0);
5188
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005189 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005190 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005191
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005192 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005193 2
5194 + expandsize*size
5195 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005196 if (repr == NULL)
5197 return NULL;
5198
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005199 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005200
Guido van Rossumd57fd912000-03-10 22:53:23 +00005201 while (size-- > 0) {
5202 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005203
Walter Dörwald79e913e2007-05-12 11:08:06 +00005204 /* Escape backslashes */
5205 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005206 *p++ = '\\';
5207 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005208 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005209 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005210
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005211#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005212 /* Map 21-bit characters to '\U00xxxxxx' */
5213 else if (ch >= 0x10000) {
5214 *p++ = '\\';
5215 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005216 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
5217 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
5218 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
5219 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
5220 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
5221 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
5222 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
5223 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005224 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005225 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005226#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005227 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5228 else if (ch >= 0xD800 && ch < 0xDC00) {
5229 Py_UNICODE ch2;
5230 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00005231
Benjamin Peterson29060642009-01-31 22:14:21 +00005232 ch2 = *s++;
5233 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005234 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005235 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5236 *p++ = '\\';
5237 *p++ = 'U';
5238 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
5239 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
5240 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
5241 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
5242 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
5243 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
5244 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
5245 *p++ = hexdigits[ucs & 0x0000000F];
5246 continue;
5247 }
5248 /* Fall through: isolated surrogates are copied as-is */
5249 s--;
5250 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005251 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005252#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005253
Guido van Rossumd57fd912000-03-10 22:53:23 +00005254 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005255 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005256 *p++ = '\\';
5257 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005258 *p++ = hexdigits[(ch >> 12) & 0x000F];
5259 *p++ = hexdigits[(ch >> 8) & 0x000F];
5260 *p++ = hexdigits[(ch >> 4) & 0x000F];
5261 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005262 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005263
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005264 /* Map special whitespace to '\t', \n', '\r' */
5265 else if (ch == '\t') {
5266 *p++ = '\\';
5267 *p++ = 't';
5268 }
5269 else if (ch == '\n') {
5270 *p++ = '\\';
5271 *p++ = 'n';
5272 }
5273 else if (ch == '\r') {
5274 *p++ = '\\';
5275 *p++ = 'r';
5276 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005277
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005278 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005279 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005280 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005281 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005282 *p++ = hexdigits[(ch >> 4) & 0x000F];
5283 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005284 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005285
Guido van Rossumd57fd912000-03-10 22:53:23 +00005286 /* Copy everything else as-is */
5287 else
5288 *p++ = (char) ch;
5289 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005290
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005291 assert(p - PyBytes_AS_STRING(repr) > 0);
5292 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5293 return NULL;
5294 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005295}
5296
Alexander Belopolsky40018472011-02-26 01:02:56 +00005297PyObject *
5298PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005299{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005300 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005301 if (!PyUnicode_Check(unicode)) {
5302 PyErr_BadArgument();
5303 return NULL;
5304 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00005305 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
5306 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005307 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005308}
5309
5310/* --- Raw Unicode Escape Codec ------------------------------------------- */
5311
Alexander Belopolsky40018472011-02-26 01:02:56 +00005312PyObject *
5313PyUnicode_DecodeRawUnicodeEscape(const char *s,
5314 Py_ssize_t size,
5315 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005316{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005317 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005318 Py_ssize_t startinpos;
5319 Py_ssize_t endinpos;
5320 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005321 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005322 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005323 const char *end;
5324 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005325 PyObject *errorHandler = NULL;
5326 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005327
Guido van Rossumd57fd912000-03-10 22:53:23 +00005328 /* Escaped strings will always be longer than the resulting
5329 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005330 length after conversion to the true value. (But decoding error
5331 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005332 v = _PyUnicode_New(size);
5333 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005334 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005335 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005336 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005337 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005338 end = s + size;
5339 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005340 unsigned char c;
5341 Py_UCS4 x;
5342 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005343 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005344
Benjamin Peterson29060642009-01-31 22:14:21 +00005345 /* Non-escape characters are interpreted as Unicode ordinals */
5346 if (*s != '\\') {
5347 *p++ = (unsigned char)*s++;
5348 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005349 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005350 startinpos = s-starts;
5351
5352 /* \u-escapes are only interpreted iff the number of leading
5353 backslashes if odd */
5354 bs = s;
5355 for (;s < end;) {
5356 if (*s != '\\')
5357 break;
5358 *p++ = (unsigned char)*s++;
5359 }
5360 if (((s - bs) & 1) == 0 ||
5361 s >= end ||
5362 (*s != 'u' && *s != 'U')) {
5363 continue;
5364 }
5365 p--;
5366 count = *s=='u' ? 4 : 8;
5367 s++;
5368
5369 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
5370 outpos = p-PyUnicode_AS_UNICODE(v);
5371 for (x = 0, i = 0; i < count; ++i, ++s) {
5372 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005373 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005374 endinpos = s-starts;
5375 if (unicode_decode_call_errorhandler(
5376 errors, &errorHandler,
5377 "rawunicodeescape", "truncated \\uXXXX",
5378 &starts, &end, &startinpos, &endinpos, &exc, &s,
5379 &v, &outpos, &p))
5380 goto onError;
5381 goto nextByte;
5382 }
5383 x = (x<<4) & ~0xF;
5384 if (c >= '0' && c <= '9')
5385 x += c - '0';
5386 else if (c >= 'a' && c <= 'f')
5387 x += 10 + c - 'a';
5388 else
5389 x += 10 + c - 'A';
5390 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00005391 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00005392 /* UCS-2 character */
5393 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005394 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005395 /* UCS-4 character. Either store directly, or as
5396 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00005397#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005398 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005399#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005400 x -= 0x10000L;
5401 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
5402 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00005403#endif
5404 } else {
5405 endinpos = s-starts;
5406 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005407 if (unicode_decode_call_errorhandler(
5408 errors, &errorHandler,
5409 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005410 &starts, &end, &startinpos, &endinpos, &exc, &s,
5411 &v, &outpos, &p))
5412 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005413 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005414 nextByte:
5415 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005416 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005417 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005418 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005419 Py_XDECREF(errorHandler);
5420 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005421 if (PyUnicode_READY(v) == -1) {
5422 Py_DECREF(v);
5423 return NULL;
5424 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005425 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00005426
Benjamin Peterson29060642009-01-31 22:14:21 +00005427 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005429 Py_XDECREF(errorHandler);
5430 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005431 return NULL;
5432}
5433
Alexander Belopolsky40018472011-02-26 01:02:56 +00005434PyObject *
5435PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
5436 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005438 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005439 char *p;
5440 char *q;
5441
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005442#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005443 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005444#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005445 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005446#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00005447
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005448 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005449 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00005450
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005451 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005452 if (repr == NULL)
5453 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005454 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005455 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005456
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005457 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005458 while (size-- > 0) {
5459 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005460#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005461 /* Map 32-bit characters to '\Uxxxxxxxx' */
5462 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005463 *p++ = '\\';
5464 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00005465 *p++ = hexdigits[(ch >> 28) & 0xf];
5466 *p++ = hexdigits[(ch >> 24) & 0xf];
5467 *p++ = hexdigits[(ch >> 20) & 0xf];
5468 *p++ = hexdigits[(ch >> 16) & 0xf];
5469 *p++ = hexdigits[(ch >> 12) & 0xf];
5470 *p++ = hexdigits[(ch >> 8) & 0xf];
5471 *p++ = hexdigits[(ch >> 4) & 0xf];
5472 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00005473 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005474 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00005475#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005476 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5477 if (ch >= 0xD800 && ch < 0xDC00) {
5478 Py_UNICODE ch2;
5479 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005480
Benjamin Peterson29060642009-01-31 22:14:21 +00005481 ch2 = *s++;
5482 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005483 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005484 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5485 *p++ = '\\';
5486 *p++ = 'U';
5487 *p++ = hexdigits[(ucs >> 28) & 0xf];
5488 *p++ = hexdigits[(ucs >> 24) & 0xf];
5489 *p++ = hexdigits[(ucs >> 20) & 0xf];
5490 *p++ = hexdigits[(ucs >> 16) & 0xf];
5491 *p++ = hexdigits[(ucs >> 12) & 0xf];
5492 *p++ = hexdigits[(ucs >> 8) & 0xf];
5493 *p++ = hexdigits[(ucs >> 4) & 0xf];
5494 *p++ = hexdigits[ucs & 0xf];
5495 continue;
5496 }
5497 /* Fall through: isolated surrogates are copied as-is */
5498 s--;
5499 size++;
5500 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005501#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005502 /* Map 16-bit characters to '\uxxxx' */
5503 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005504 *p++ = '\\';
5505 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00005506 *p++ = hexdigits[(ch >> 12) & 0xf];
5507 *p++ = hexdigits[(ch >> 8) & 0xf];
5508 *p++ = hexdigits[(ch >> 4) & 0xf];
5509 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005510 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005511 /* Copy everything else as-is */
5512 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00005513 *p++ = (char) ch;
5514 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005515 size = p - q;
5516
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005517 assert(size > 0);
5518 if (_PyBytes_Resize(&repr, size) < 0)
5519 return NULL;
5520 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005521}
5522
Alexander Belopolsky40018472011-02-26 01:02:56 +00005523PyObject *
5524PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005525{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005526 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005527 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00005528 PyErr_BadArgument();
5529 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005530 }
Walter Dörwald711005d2007-05-12 12:03:26 +00005531 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
5532 PyUnicode_GET_SIZE(unicode));
5533
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005534 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005535}
5536
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005537/* --- Unicode Internal Codec ------------------------------------------- */
5538
Alexander Belopolsky40018472011-02-26 01:02:56 +00005539PyObject *
5540_PyUnicode_DecodeUnicodeInternal(const char *s,
5541 Py_ssize_t size,
5542 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005543{
5544 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005545 Py_ssize_t startinpos;
5546 Py_ssize_t endinpos;
5547 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005548 PyUnicodeObject *v;
5549 Py_UNICODE *p;
5550 const char *end;
5551 const char *reason;
5552 PyObject *errorHandler = NULL;
5553 PyObject *exc = NULL;
5554
Neal Norwitzd43069c2006-01-08 01:12:10 +00005555#ifdef Py_UNICODE_WIDE
5556 Py_UNICODE unimax = PyUnicode_GetMax();
5557#endif
5558
Thomas Wouters89f507f2006-12-13 04:49:30 +00005559 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005560 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
5561 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005562 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005563 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
5564 as string was created with the old API. */
5565 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005566 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005567 p = PyUnicode_AS_UNICODE(v);
5568 end = s + size;
5569
5570 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00005571 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005572 /* We have to sanity check the raw data, otherwise doom looms for
5573 some malformed UCS-4 data. */
5574 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00005575#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005576 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00005577#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005578 end-s < Py_UNICODE_SIZE
5579 )
Benjamin Peterson29060642009-01-31 22:14:21 +00005580 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005581 startinpos = s - starts;
5582 if (end-s < Py_UNICODE_SIZE) {
5583 endinpos = end-starts;
5584 reason = "truncated input";
5585 }
5586 else {
5587 endinpos = s - starts + Py_UNICODE_SIZE;
5588 reason = "illegal code point (> 0x10FFFF)";
5589 }
5590 outpos = p - PyUnicode_AS_UNICODE(v);
5591 if (unicode_decode_call_errorhandler(
5592 errors, &errorHandler,
5593 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00005594 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00005595 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005596 goto onError;
5597 }
5598 }
5599 else {
5600 p++;
5601 s += Py_UNICODE_SIZE;
5602 }
5603 }
5604
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005605 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005606 goto onError;
5607 Py_XDECREF(errorHandler);
5608 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005609 if (PyUnicode_READY(v) == -1) {
5610 Py_DECREF(v);
5611 return NULL;
5612 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005613 return (PyObject *)v;
5614
Benjamin Peterson29060642009-01-31 22:14:21 +00005615 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005616 Py_XDECREF(v);
5617 Py_XDECREF(errorHandler);
5618 Py_XDECREF(exc);
5619 return NULL;
5620}
5621
Guido van Rossumd57fd912000-03-10 22:53:23 +00005622/* --- Latin-1 Codec ------------------------------------------------------ */
5623
Alexander Belopolsky40018472011-02-26 01:02:56 +00005624PyObject *
5625PyUnicode_DecodeLatin1(const char *s,
5626 Py_ssize_t size,
5627 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005628{
Guido van Rossumd57fd912000-03-10 22:53:23 +00005629 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005630 return PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005631}
5632
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005633/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00005634static void
5635make_encode_exception(PyObject **exceptionObject,
5636 const char *encoding,
5637 const Py_UNICODE *unicode, Py_ssize_t size,
5638 Py_ssize_t startpos, Py_ssize_t endpos,
5639 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005640{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005641 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005642 *exceptionObject = PyUnicodeEncodeError_Create(
5643 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005644 }
5645 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005646 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
5647 goto onError;
5648 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
5649 goto onError;
5650 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
5651 goto onError;
5652 return;
5653 onError:
5654 Py_DECREF(*exceptionObject);
5655 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005656 }
5657}
5658
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005659/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00005660static void
5661raise_encode_exception(PyObject **exceptionObject,
5662 const char *encoding,
5663 const Py_UNICODE *unicode, Py_ssize_t size,
5664 Py_ssize_t startpos, Py_ssize_t endpos,
5665 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005666{
5667 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005668 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005669 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005670 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005671}
5672
5673/* error handling callback helper:
5674 build arguments, call the callback and check the arguments,
5675 put the result into newpos and return the replacement string, which
5676 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00005677static PyObject *
5678unicode_encode_call_errorhandler(const char *errors,
5679 PyObject **errorHandler,
5680 const char *encoding, const char *reason,
5681 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
5682 Py_ssize_t startpos, Py_ssize_t endpos,
5683 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005684{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005685 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005686
5687 PyObject *restuple;
5688 PyObject *resunicode;
5689
5690 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005691 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005692 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005693 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005694 }
5695
5696 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005697 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005698 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005699 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005700
5701 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00005702 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005703 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005704 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005705 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005706 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00005707 Py_DECREF(restuple);
5708 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005709 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005710 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00005711 &resunicode, newpos)) {
5712 Py_DECREF(restuple);
5713 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005714 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005715 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
5716 PyErr_SetString(PyExc_TypeError, &argparse[3]);
5717 Py_DECREF(restuple);
5718 return NULL;
5719 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005720 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005721 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005722 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005723 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
5724 Py_DECREF(restuple);
5725 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005726 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005727 Py_INCREF(resunicode);
5728 Py_DECREF(restuple);
5729 return resunicode;
5730}
5731
Alexander Belopolsky40018472011-02-26 01:02:56 +00005732static PyObject *
5733unicode_encode_ucs1(const Py_UNICODE *p,
5734 Py_ssize_t size,
5735 const char *errors,
5736 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005737{
5738 /* output object */
5739 PyObject *res;
5740 /* pointers to the beginning and end+1 of input */
5741 const Py_UNICODE *startp = p;
5742 const Py_UNICODE *endp = p + size;
5743 /* pointer to the beginning of the unencodable characters */
5744 /* const Py_UNICODE *badp = NULL; */
5745 /* pointer into the output */
5746 char *str;
5747 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005748 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005749 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
5750 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005751 PyObject *errorHandler = NULL;
5752 PyObject *exc = NULL;
5753 /* the following variable is used for caching string comparisons
5754 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
5755 int known_errorHandler = -1;
5756
5757 /* allocate enough for a simple encoding without
5758 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00005759 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00005760 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005761 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005762 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005763 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005764 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005765 ressize = size;
5766
5767 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005768 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005769
Benjamin Peterson29060642009-01-31 22:14:21 +00005770 /* can we encode this? */
5771 if (c<limit) {
5772 /* no overflow check, because we know that the space is enough */
5773 *str++ = (char)c;
5774 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005775 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005776 else {
5777 Py_ssize_t unicodepos = p-startp;
5778 Py_ssize_t requiredsize;
5779 PyObject *repunicode;
5780 Py_ssize_t repsize;
5781 Py_ssize_t newpos;
5782 Py_ssize_t respos;
5783 Py_UNICODE *uni2;
5784 /* startpos for collecting unencodable chars */
5785 const Py_UNICODE *collstart = p;
5786 const Py_UNICODE *collend = p;
5787 /* find all unecodable characters */
5788 while ((collend < endp) && ((*collend)>=limit))
5789 ++collend;
5790 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
5791 if (known_errorHandler==-1) {
5792 if ((errors==NULL) || (!strcmp(errors, "strict")))
5793 known_errorHandler = 1;
5794 else if (!strcmp(errors, "replace"))
5795 known_errorHandler = 2;
5796 else if (!strcmp(errors, "ignore"))
5797 known_errorHandler = 3;
5798 else if (!strcmp(errors, "xmlcharrefreplace"))
5799 known_errorHandler = 4;
5800 else
5801 known_errorHandler = 0;
5802 }
5803 switch (known_errorHandler) {
5804 case 1: /* strict */
5805 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
5806 goto onError;
5807 case 2: /* replace */
5808 while (collstart++<collend)
5809 *str++ = '?'; /* fall through */
5810 case 3: /* ignore */
5811 p = collend;
5812 break;
5813 case 4: /* xmlcharrefreplace */
5814 respos = str - PyBytes_AS_STRING(res);
5815 /* determine replacement size (temporarily (mis)uses p) */
5816 for (p = collstart, repsize = 0; p < collend; ++p) {
5817 if (*p<10)
5818 repsize += 2+1+1;
5819 else if (*p<100)
5820 repsize += 2+2+1;
5821 else if (*p<1000)
5822 repsize += 2+3+1;
5823 else if (*p<10000)
5824 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00005825#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005826 else
5827 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00005828#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005829 else if (*p<100000)
5830 repsize += 2+5+1;
5831 else if (*p<1000000)
5832 repsize += 2+6+1;
5833 else
5834 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005835#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005836 }
5837 requiredsize = respos+repsize+(endp-collend);
5838 if (requiredsize > ressize) {
5839 if (requiredsize<2*ressize)
5840 requiredsize = 2*ressize;
5841 if (_PyBytes_Resize(&res, requiredsize))
5842 goto onError;
5843 str = PyBytes_AS_STRING(res) + respos;
5844 ressize = requiredsize;
5845 }
5846 /* generate replacement (temporarily (mis)uses p) */
5847 for (p = collstart; p < collend; ++p) {
5848 str += sprintf(str, "&#%d;", (int)*p);
5849 }
5850 p = collend;
5851 break;
5852 default:
5853 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
5854 encoding, reason, startp, size, &exc,
5855 collstart-startp, collend-startp, &newpos);
5856 if (repunicode == NULL)
5857 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005858 if (PyBytes_Check(repunicode)) {
5859 /* Directly copy bytes result to output. */
5860 repsize = PyBytes_Size(repunicode);
5861 if (repsize > 1) {
5862 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00005863 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005864 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
5865 Py_DECREF(repunicode);
5866 goto onError;
5867 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00005868 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005869 ressize += repsize-1;
5870 }
5871 memcpy(str, PyBytes_AsString(repunicode), repsize);
5872 str += repsize;
5873 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005874 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005875 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005876 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005877 /* need more space? (at least enough for what we
5878 have+the replacement+the rest of the string, so
5879 we won't have to check space for encodable characters) */
5880 respos = str - PyBytes_AS_STRING(res);
5881 repsize = PyUnicode_GET_SIZE(repunicode);
5882 requiredsize = respos+repsize+(endp-collend);
5883 if (requiredsize > ressize) {
5884 if (requiredsize<2*ressize)
5885 requiredsize = 2*ressize;
5886 if (_PyBytes_Resize(&res, requiredsize)) {
5887 Py_DECREF(repunicode);
5888 goto onError;
5889 }
5890 str = PyBytes_AS_STRING(res) + respos;
5891 ressize = requiredsize;
5892 }
5893 /* check if there is anything unencodable in the replacement
5894 and copy it to the output */
5895 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
5896 c = *uni2;
5897 if (c >= limit) {
5898 raise_encode_exception(&exc, encoding, startp, size,
5899 unicodepos, unicodepos+1, reason);
5900 Py_DECREF(repunicode);
5901 goto onError;
5902 }
5903 *str = (char)c;
5904 }
5905 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005906 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005907 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005908 }
5909 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005910 /* Resize if we allocated to much */
5911 size = str - PyBytes_AS_STRING(res);
5912 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00005913 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005914 if (_PyBytes_Resize(&res, size) < 0)
5915 goto onError;
5916 }
5917
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005918 Py_XDECREF(errorHandler);
5919 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005920 return res;
5921
5922 onError:
5923 Py_XDECREF(res);
5924 Py_XDECREF(errorHandler);
5925 Py_XDECREF(exc);
5926 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005927}
5928
Alexander Belopolsky40018472011-02-26 01:02:56 +00005929PyObject *
5930PyUnicode_EncodeLatin1(const Py_UNICODE *p,
5931 Py_ssize_t size,
5932 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005934 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935}
5936
Alexander Belopolsky40018472011-02-26 01:02:56 +00005937PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005938_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005939{
5940 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005941 PyErr_BadArgument();
5942 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005943 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005944 if (PyUnicode_READY(unicode) == -1)
5945 return NULL;
5946 /* Fast path: if it is a one-byte string, construct
5947 bytes object directly. */
5948 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
5949 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
5950 PyUnicode_GET_LENGTH(unicode));
5951 /* Non-Latin-1 characters present. Defer to above function to
5952 raise the exception. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005953 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005954 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005955 errors);
5956}
5957
5958PyObject*
5959PyUnicode_AsLatin1String(PyObject *unicode)
5960{
5961 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962}
5963
5964/* --- 7-bit ASCII Codec -------------------------------------------------- */
5965
Alexander Belopolsky40018472011-02-26 01:02:56 +00005966PyObject *
5967PyUnicode_DecodeASCII(const char *s,
5968 Py_ssize_t size,
5969 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005971 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005972 PyUnicodeObject *v;
5973 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005974 Py_ssize_t startinpos;
5975 Py_ssize_t endinpos;
5976 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005977 const char *e;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005978 unsigned char* d;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005979 PyObject *errorHandler = NULL;
5980 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005981 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00005982
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005984 if (size == 1 && *(unsigned char*)s < 128)
5985 return PyUnicode_FromOrdinal(*(unsigned char*)s);
5986
5987 /* Fast path. Assume the input actually *is* ASCII, and allocate
5988 a single-block Unicode object with that assumption. If there is
5989 an error, drop the object and start over. */
5990 v = (PyUnicodeObject*)PyUnicode_New(size, 127);
5991 if (v == NULL)
5992 goto onError;
5993 d = PyUnicode_1BYTE_DATA(v);
5994 for (i = 0; i < size; i++) {
5995 unsigned char ch = ((unsigned char*)s)[i];
5996 if (ch < 128)
5997 d[i] = ch;
5998 else
5999 break;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006000 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006001 if (i == size)
6002 return (PyObject*)v;
6003 Py_DECREF(v); /* start over */
Tim Petersced69f82003-09-16 20:30:58 +00006004
Guido van Rossumd57fd912000-03-10 22:53:23 +00006005 v = _PyUnicode_New(size);
6006 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006007 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006009 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006010 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006011 e = s + size;
6012 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006013 register unsigned char c = (unsigned char)*s;
6014 if (c < 128) {
6015 *p++ = c;
6016 ++s;
6017 }
6018 else {
6019 startinpos = s-starts;
6020 endinpos = startinpos + 1;
6021 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
6022 if (unicode_decode_call_errorhandler(
6023 errors, &errorHandler,
6024 "ascii", "ordinal not in range(128)",
6025 &starts, &e, &startinpos, &endinpos, &exc, &s,
6026 &v, &outpos, &p))
6027 goto onError;
6028 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006029 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00006030 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00006031 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
6032 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006033 Py_XDECREF(errorHandler);
6034 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006035 if (PyUnicode_READY(v) == -1) {
6036 Py_DECREF(v);
6037 return NULL;
6038 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006040
Benjamin Peterson29060642009-01-31 22:14:21 +00006041 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006042 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006043 Py_XDECREF(errorHandler);
6044 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006045 return NULL;
6046}
6047
Alexander Belopolsky40018472011-02-26 01:02:56 +00006048PyObject *
6049PyUnicode_EncodeASCII(const Py_UNICODE *p,
6050 Py_ssize_t size,
6051 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006052{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006053 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006054}
6055
Alexander Belopolsky40018472011-02-26 01:02:56 +00006056PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006057_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006058{
6059 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006060 PyErr_BadArgument();
6061 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006062 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006063 if (PyUnicode_READY(unicode) == -1)
6064 return NULL;
6065 /* Fast path: if it is an ASCII-only string, construct bytes object
6066 directly. Else defer to above function to raise the exception. */
6067 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6068 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6069 PyUnicode_GET_LENGTH(unicode));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006070 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006071 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006072 errors);
6073}
6074
6075PyObject *
6076PyUnicode_AsASCIIString(PyObject *unicode)
6077{
6078 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079}
6080
Victor Stinner99b95382011-07-04 14:23:54 +02006081#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006082
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006083/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006084
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006085#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006086#define NEED_RETRY
6087#endif
6088
6089/* XXX This code is limited to "true" double-byte encodings, as
6090 a) it assumes an incomplete character consists of a single byte, and
6091 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00006092 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006093
Alexander Belopolsky40018472011-02-26 01:02:56 +00006094static int
6095is_dbcs_lead_byte(const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006096{
6097 const char *curr = s + offset;
6098
6099 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006100 const char *prev = CharPrev(s, curr);
6101 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006102 }
6103 return 0;
6104}
6105
6106/*
6107 * Decode MBCS string into unicode object. If 'final' is set, converts
6108 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
6109 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006110static int
6111decode_mbcs(PyUnicodeObject **v,
6112 const char *s, /* MBCS string */
6113 int size, /* sizeof MBCS string */
6114 int final,
6115 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006116{
6117 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00006118 Py_ssize_t n;
6119 DWORD usize;
6120 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006121
6122 assert(size >= 0);
6123
Victor Stinner554f3f02010-06-16 23:33:54 +00006124 /* check and handle 'errors' arg */
6125 if (errors==NULL || strcmp(errors, "strict")==0)
6126 flags = MB_ERR_INVALID_CHARS;
6127 else if (strcmp(errors, "ignore")==0)
6128 flags = 0;
6129 else {
6130 PyErr_Format(PyExc_ValueError,
6131 "mbcs encoding does not support errors='%s'",
6132 errors);
6133 return -1;
6134 }
6135
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006136 /* Skip trailing lead-byte unless 'final' is set */
6137 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006138 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006139
6140 /* First get the size of the result */
6141 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006142 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
6143 if (usize==0)
6144 goto mbcs_decode_error;
6145 } else
6146 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006147
6148 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006149 /* Create unicode object */
6150 *v = _PyUnicode_New(usize);
6151 if (*v == NULL)
6152 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006153 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006154 }
6155 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006156 /* Extend unicode object */
6157 n = PyUnicode_GET_SIZE(*v);
6158 if (_PyUnicode_Resize(v, n + usize) < 0)
6159 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006160 }
6161
6162 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00006163 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006164 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006165 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
6166 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00006167 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006168 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006169 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00006170
6171mbcs_decode_error:
6172 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
6173 we raise a UnicodeDecodeError - else it is a 'generic'
6174 windows error
6175 */
6176 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
6177 /* Ideally, we should get reason from FormatMessage - this
6178 is the Windows 2000 English version of the message
6179 */
6180 PyObject *exc = NULL;
6181 const char *reason = "No mapping for the Unicode character exists "
6182 "in the target multi-byte code page.";
6183 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
6184 if (exc != NULL) {
6185 PyCodec_StrictErrors(exc);
6186 Py_DECREF(exc);
6187 }
6188 } else {
6189 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6190 }
6191 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006192}
6193
Alexander Belopolsky40018472011-02-26 01:02:56 +00006194PyObject *
6195PyUnicode_DecodeMBCSStateful(const char *s,
6196 Py_ssize_t size,
6197 const char *errors,
6198 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006199{
6200 PyUnicodeObject *v = NULL;
6201 int done;
6202
6203 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006204 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006205
6206#ifdef NEED_RETRY
6207 retry:
6208 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006209 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006210 else
6211#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006212 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006213
6214 if (done < 0) {
6215 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006216 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006217 }
6218
6219 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006220 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006221
6222#ifdef NEED_RETRY
6223 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006224 s += done;
6225 size -= done;
6226 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006227 }
6228#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006229 if (PyUnicode_READY(v) == -1) {
6230 Py_DECREF(v);
6231 return NULL;
6232 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006233 return (PyObject *)v;
6234}
6235
Alexander Belopolsky40018472011-02-26 01:02:56 +00006236PyObject *
6237PyUnicode_DecodeMBCS(const char *s,
6238 Py_ssize_t size,
6239 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006240{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006241 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6242}
6243
6244/*
6245 * Convert unicode into string object (MBCS).
6246 * Returns 0 if succeed, -1 otherwise.
6247 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006248static int
6249encode_mbcs(PyObject **repr,
6250 const Py_UNICODE *p, /* unicode */
6251 int size, /* size of unicode */
6252 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006253{
Victor Stinner554f3f02010-06-16 23:33:54 +00006254 BOOL usedDefaultChar = FALSE;
6255 BOOL *pusedDefaultChar;
6256 int mbcssize;
6257 Py_ssize_t n;
6258 PyObject *exc = NULL;
6259 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006260
6261 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006262
Victor Stinner554f3f02010-06-16 23:33:54 +00006263 /* check and handle 'errors' arg */
6264 if (errors==NULL || strcmp(errors, "strict")==0) {
6265 flags = WC_NO_BEST_FIT_CHARS;
6266 pusedDefaultChar = &usedDefaultChar;
6267 } else if (strcmp(errors, "replace")==0) {
6268 flags = 0;
6269 pusedDefaultChar = NULL;
6270 } else {
6271 PyErr_Format(PyExc_ValueError,
6272 "mbcs encoding does not support errors='%s'",
6273 errors);
6274 return -1;
6275 }
6276
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006277 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006278 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006279 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
6280 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00006281 if (mbcssize == 0) {
6282 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6283 return -1;
6284 }
Victor Stinner554f3f02010-06-16 23:33:54 +00006285 /* If we used a default char, then we failed! */
6286 if (pusedDefaultChar && *pusedDefaultChar)
6287 goto mbcs_encode_error;
6288 } else {
6289 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006290 }
6291
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006292 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006293 /* Create string object */
6294 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
6295 if (*repr == NULL)
6296 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006297 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006298 }
6299 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006300 /* Extend string object */
6301 n = PyBytes_Size(*repr);
6302 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
6303 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006304 }
6305
6306 /* Do the conversion */
6307 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006308 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006309 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
6310 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006311 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6312 return -1;
6313 }
Victor Stinner554f3f02010-06-16 23:33:54 +00006314 if (pusedDefaultChar && *pusedDefaultChar)
6315 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006316 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006317 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00006318
6319mbcs_encode_error:
6320 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
6321 Py_XDECREF(exc);
6322 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006323}
6324
Alexander Belopolsky40018472011-02-26 01:02:56 +00006325PyObject *
6326PyUnicode_EncodeMBCS(const Py_UNICODE *p,
6327 Py_ssize_t size,
6328 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006329{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006330 PyObject *repr = NULL;
6331 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00006332
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006333#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00006334 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006335 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006336 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006337 else
6338#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006339 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006340
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006341 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006342 Py_XDECREF(repr);
6343 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006344 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006345
6346#ifdef NEED_RETRY
6347 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006348 p += INT_MAX;
6349 size -= INT_MAX;
6350 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006351 }
6352#endif
6353
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006354 return repr;
6355}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006356
Alexander Belopolsky40018472011-02-26 01:02:56 +00006357PyObject *
6358PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00006359{
6360 if (!PyUnicode_Check(unicode)) {
6361 PyErr_BadArgument();
6362 return NULL;
6363 }
6364 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006365 PyUnicode_GET_SIZE(unicode),
6366 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00006367}
6368
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006369#undef NEED_RETRY
6370
Victor Stinner99b95382011-07-04 14:23:54 +02006371#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006372
Guido van Rossumd57fd912000-03-10 22:53:23 +00006373/* --- Character Mapping Codec -------------------------------------------- */
6374
Alexander Belopolsky40018472011-02-26 01:02:56 +00006375PyObject *
6376PyUnicode_DecodeCharmap(const char *s,
6377 Py_ssize_t size,
6378 PyObject *mapping,
6379 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006380{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006381 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006382 Py_ssize_t startinpos;
6383 Py_ssize_t endinpos;
6384 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006385 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006386 PyUnicodeObject *v;
6387 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006388 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006389 PyObject *errorHandler = NULL;
6390 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006391 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006392 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006393
Guido van Rossumd57fd912000-03-10 22:53:23 +00006394 /* Default to Latin-1 */
6395 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006396 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006397
6398 v = _PyUnicode_New(size);
6399 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006400 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006401 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006402 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006403 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006404 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006405 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006406 mapstring = PyUnicode_AS_UNICODE(mapping);
6407 maplen = PyUnicode_GET_SIZE(mapping);
6408 while (s < e) {
6409 unsigned char ch = *s;
6410 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006411
Benjamin Peterson29060642009-01-31 22:14:21 +00006412 if (ch < maplen)
6413 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006414
Benjamin Peterson29060642009-01-31 22:14:21 +00006415 if (x == 0xfffe) {
6416 /* undefined mapping */
6417 outpos = p-PyUnicode_AS_UNICODE(v);
6418 startinpos = s-starts;
6419 endinpos = startinpos+1;
6420 if (unicode_decode_call_errorhandler(
6421 errors, &errorHandler,
6422 "charmap", "character maps to <undefined>",
6423 &starts, &e, &startinpos, &endinpos, &exc, &s,
6424 &v, &outpos, &p)) {
6425 goto onError;
6426 }
6427 continue;
6428 }
6429 *p++ = x;
6430 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006431 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006432 }
6433 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006434 while (s < e) {
6435 unsigned char ch = *s;
6436 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006437
Benjamin Peterson29060642009-01-31 22:14:21 +00006438 /* Get mapping (char ordinal -> integer, Unicode char or None) */
6439 w = PyLong_FromLong((long)ch);
6440 if (w == NULL)
6441 goto onError;
6442 x = PyObject_GetItem(mapping, w);
6443 Py_DECREF(w);
6444 if (x == NULL) {
6445 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
6446 /* No mapping found means: mapping is undefined. */
6447 PyErr_Clear();
6448 x = Py_None;
6449 Py_INCREF(x);
6450 } else
6451 goto onError;
6452 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006453
Benjamin Peterson29060642009-01-31 22:14:21 +00006454 /* Apply mapping */
6455 if (PyLong_Check(x)) {
6456 long value = PyLong_AS_LONG(x);
6457 if (value < 0 || value > 65535) {
6458 PyErr_SetString(PyExc_TypeError,
6459 "character mapping must be in range(65536)");
6460 Py_DECREF(x);
6461 goto onError;
6462 }
6463 *p++ = (Py_UNICODE)value;
6464 }
6465 else if (x == Py_None) {
6466 /* undefined mapping */
6467 outpos = p-PyUnicode_AS_UNICODE(v);
6468 startinpos = s-starts;
6469 endinpos = startinpos+1;
6470 if (unicode_decode_call_errorhandler(
6471 errors, &errorHandler,
6472 "charmap", "character maps to <undefined>",
6473 &starts, &e, &startinpos, &endinpos, &exc, &s,
6474 &v, &outpos, &p)) {
6475 Py_DECREF(x);
6476 goto onError;
6477 }
6478 Py_DECREF(x);
6479 continue;
6480 }
6481 else if (PyUnicode_Check(x)) {
6482 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006483
Benjamin Peterson29060642009-01-31 22:14:21 +00006484 if (targetsize == 1)
6485 /* 1-1 mapping */
6486 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006487
Benjamin Peterson29060642009-01-31 22:14:21 +00006488 else if (targetsize > 1) {
6489 /* 1-n mapping */
6490 if (targetsize > extrachars) {
6491 /* resize first */
6492 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
6493 Py_ssize_t needed = (targetsize - extrachars) + \
6494 (targetsize << 2);
6495 extrachars += needed;
6496 /* XXX overflow detection missing */
6497 if (_PyUnicode_Resize(&v,
6498 PyUnicode_GET_SIZE(v) + needed) < 0) {
6499 Py_DECREF(x);
6500 goto onError;
6501 }
6502 p = PyUnicode_AS_UNICODE(v) + oldpos;
6503 }
6504 Py_UNICODE_COPY(p,
6505 PyUnicode_AS_UNICODE(x),
6506 targetsize);
6507 p += targetsize;
6508 extrachars -= targetsize;
6509 }
6510 /* 1-0 mapping: skip the character */
6511 }
6512 else {
6513 /* wrong return value */
6514 PyErr_SetString(PyExc_TypeError,
6515 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006516 Py_DECREF(x);
6517 goto onError;
6518 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006519 Py_DECREF(x);
6520 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006521 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006522 }
6523 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00006524 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
6525 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006526 Py_XDECREF(errorHandler);
6527 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006528 if (PyUnicode_READY(v) == -1) {
6529 Py_DECREF(v);
6530 return NULL;
6531 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006532 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006533
Benjamin Peterson29060642009-01-31 22:14:21 +00006534 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006535 Py_XDECREF(errorHandler);
6536 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006537 Py_XDECREF(v);
6538 return NULL;
6539}
6540
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006541/* Charmap encoding: the lookup table */
6542
Alexander Belopolsky40018472011-02-26 01:02:56 +00006543struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00006544 PyObject_HEAD
6545 unsigned char level1[32];
6546 int count2, count3;
6547 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006548};
6549
6550static PyObject*
6551encoding_map_size(PyObject *obj, PyObject* args)
6552{
6553 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006554 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00006555 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006556}
6557
6558static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006559 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00006560 PyDoc_STR("Return the size (in bytes) of this object") },
6561 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006562};
6563
6564static void
6565encoding_map_dealloc(PyObject* o)
6566{
Benjamin Peterson14339b62009-01-31 16:36:08 +00006567 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006568}
6569
6570static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006571 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006572 "EncodingMap", /*tp_name*/
6573 sizeof(struct encoding_map), /*tp_basicsize*/
6574 0, /*tp_itemsize*/
6575 /* methods */
6576 encoding_map_dealloc, /*tp_dealloc*/
6577 0, /*tp_print*/
6578 0, /*tp_getattr*/
6579 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00006580 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00006581 0, /*tp_repr*/
6582 0, /*tp_as_number*/
6583 0, /*tp_as_sequence*/
6584 0, /*tp_as_mapping*/
6585 0, /*tp_hash*/
6586 0, /*tp_call*/
6587 0, /*tp_str*/
6588 0, /*tp_getattro*/
6589 0, /*tp_setattro*/
6590 0, /*tp_as_buffer*/
6591 Py_TPFLAGS_DEFAULT, /*tp_flags*/
6592 0, /*tp_doc*/
6593 0, /*tp_traverse*/
6594 0, /*tp_clear*/
6595 0, /*tp_richcompare*/
6596 0, /*tp_weaklistoffset*/
6597 0, /*tp_iter*/
6598 0, /*tp_iternext*/
6599 encoding_map_methods, /*tp_methods*/
6600 0, /*tp_members*/
6601 0, /*tp_getset*/
6602 0, /*tp_base*/
6603 0, /*tp_dict*/
6604 0, /*tp_descr_get*/
6605 0, /*tp_descr_set*/
6606 0, /*tp_dictoffset*/
6607 0, /*tp_init*/
6608 0, /*tp_alloc*/
6609 0, /*tp_new*/
6610 0, /*tp_free*/
6611 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006612};
6613
6614PyObject*
6615PyUnicode_BuildEncodingMap(PyObject* string)
6616{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006617 PyObject *result;
6618 struct encoding_map *mresult;
6619 int i;
6620 int need_dict = 0;
6621 unsigned char level1[32];
6622 unsigned char level2[512];
6623 unsigned char *mlevel1, *mlevel2, *mlevel3;
6624 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006625 int kind;
6626 void *data;
6627 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006629 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006630 PyErr_BadArgument();
6631 return NULL;
6632 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006633 kind = PyUnicode_KIND(string);
6634 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006635 memset(level1, 0xFF, sizeof level1);
6636 memset(level2, 0xFF, sizeof level2);
6637
6638 /* If there isn't a one-to-one mapping of NULL to \0,
6639 or if there are non-BMP characters, we need to use
6640 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006641 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006642 need_dict = 1;
6643 for (i = 1; i < 256; i++) {
6644 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006645 ch = PyUnicode_READ(kind, data, i);
6646 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006647 need_dict = 1;
6648 break;
6649 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006650 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006651 /* unmapped character */
6652 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006653 l1 = ch >> 11;
6654 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006655 if (level1[l1] == 0xFF)
6656 level1[l1] = count2++;
6657 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00006658 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006659 }
6660
6661 if (count2 >= 0xFF || count3 >= 0xFF)
6662 need_dict = 1;
6663
6664 if (need_dict) {
6665 PyObject *result = PyDict_New();
6666 PyObject *key, *value;
6667 if (!result)
6668 return NULL;
6669 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006670 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00006671 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006672 if (!key || !value)
6673 goto failed1;
6674 if (PyDict_SetItem(result, key, value) == -1)
6675 goto failed1;
6676 Py_DECREF(key);
6677 Py_DECREF(value);
6678 }
6679 return result;
6680 failed1:
6681 Py_XDECREF(key);
6682 Py_XDECREF(value);
6683 Py_DECREF(result);
6684 return NULL;
6685 }
6686
6687 /* Create a three-level trie */
6688 result = PyObject_MALLOC(sizeof(struct encoding_map) +
6689 16*count2 + 128*count3 - 1);
6690 if (!result)
6691 return PyErr_NoMemory();
6692 PyObject_Init(result, &EncodingMapType);
6693 mresult = (struct encoding_map*)result;
6694 mresult->count2 = count2;
6695 mresult->count3 = count3;
6696 mlevel1 = mresult->level1;
6697 mlevel2 = mresult->level23;
6698 mlevel3 = mresult->level23 + 16*count2;
6699 memcpy(mlevel1, level1, 32);
6700 memset(mlevel2, 0xFF, 16*count2);
6701 memset(mlevel3, 0, 128*count3);
6702 count3 = 0;
6703 for (i = 1; i < 256; i++) {
6704 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006705 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006706 /* unmapped character */
6707 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006708 o1 = PyUnicode_READ(kind, data, i)>>11;
6709 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006710 i2 = 16*mlevel1[o1] + o2;
6711 if (mlevel2[i2] == 0xFF)
6712 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006713 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006714 i3 = 128*mlevel2[i2] + o3;
6715 mlevel3[i3] = i;
6716 }
6717 return result;
6718}
6719
6720static int
6721encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
6722{
6723 struct encoding_map *map = (struct encoding_map*)mapping;
6724 int l1 = c>>11;
6725 int l2 = (c>>7) & 0xF;
6726 int l3 = c & 0x7F;
6727 int i;
6728
6729#ifdef Py_UNICODE_WIDE
6730 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006732 }
6733#endif
6734 if (c == 0)
6735 return 0;
6736 /* level 1*/
6737 i = map->level1[l1];
6738 if (i == 0xFF) {
6739 return -1;
6740 }
6741 /* level 2*/
6742 i = map->level23[16*i+l2];
6743 if (i == 0xFF) {
6744 return -1;
6745 }
6746 /* level 3 */
6747 i = map->level23[16*map->count2 + 128*i + l3];
6748 if (i == 0) {
6749 return -1;
6750 }
6751 return i;
6752}
6753
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006754/* Lookup the character ch in the mapping. If the character
6755 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00006756 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006757static PyObject *
6758charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006759{
Christian Heimes217cfd12007-12-02 14:31:20 +00006760 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006761 PyObject *x;
6762
6763 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006764 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006765 x = PyObject_GetItem(mapping, w);
6766 Py_DECREF(w);
6767 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006768 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
6769 /* No mapping found means: mapping is undefined. */
6770 PyErr_Clear();
6771 x = Py_None;
6772 Py_INCREF(x);
6773 return x;
6774 } else
6775 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006776 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00006777 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00006778 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00006779 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006780 long value = PyLong_AS_LONG(x);
6781 if (value < 0 || value > 255) {
6782 PyErr_SetString(PyExc_TypeError,
6783 "character mapping must be in range(256)");
6784 Py_DECREF(x);
6785 return NULL;
6786 }
6787 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006788 }
Christian Heimes72b710a2008-05-26 13:28:38 +00006789 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00006790 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006791 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006792 /* wrong return value */
6793 PyErr_Format(PyExc_TypeError,
6794 "character mapping must return integer, bytes or None, not %.400s",
6795 x->ob_type->tp_name);
6796 Py_DECREF(x);
6797 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006798 }
6799}
6800
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006801static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00006802charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006803{
Benjamin Peterson14339b62009-01-31 16:36:08 +00006804 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
6805 /* exponentially overallocate to minimize reallocations */
6806 if (requiredsize < 2*outsize)
6807 requiredsize = 2*outsize;
6808 if (_PyBytes_Resize(outobj, requiredsize))
6809 return -1;
6810 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006811}
6812
Benjamin Peterson14339b62009-01-31 16:36:08 +00006813typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00006814 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00006815} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006816/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00006817 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006818 space is available. Return a new reference to the object that
6819 was put in the output buffer, or Py_None, if the mapping was undefined
6820 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00006821 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006822static charmapencode_result
6823charmapencode_output(Py_UNICODE c, PyObject *mapping,
6824 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006825{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006826 PyObject *rep;
6827 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00006828 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006829
Christian Heimes90aa7642007-12-19 02:45:37 +00006830 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006831 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00006832 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006833 if (res == -1)
6834 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00006835 if (outsize<requiredsize)
6836 if (charmapencode_resize(outobj, outpos, requiredsize))
6837 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00006838 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00006839 outstart[(*outpos)++] = (char)res;
6840 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006841 }
6842
6843 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006844 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006845 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006846 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006847 Py_DECREF(rep);
6848 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006849 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006850 if (PyLong_Check(rep)) {
6851 Py_ssize_t requiredsize = *outpos+1;
6852 if (outsize<requiredsize)
6853 if (charmapencode_resize(outobj, outpos, requiredsize)) {
6854 Py_DECREF(rep);
6855 return enc_EXCEPTION;
6856 }
Christian Heimes72b710a2008-05-26 13:28:38 +00006857 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00006858 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006859 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006860 else {
6861 const char *repchars = PyBytes_AS_STRING(rep);
6862 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
6863 Py_ssize_t requiredsize = *outpos+repsize;
6864 if (outsize<requiredsize)
6865 if (charmapencode_resize(outobj, outpos, requiredsize)) {
6866 Py_DECREF(rep);
6867 return enc_EXCEPTION;
6868 }
Christian Heimes72b710a2008-05-26 13:28:38 +00006869 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00006870 memcpy(outstart + *outpos, repchars, repsize);
6871 *outpos += repsize;
6872 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006873 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006874 Py_DECREF(rep);
6875 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006876}
6877
6878/* handle an error in PyUnicode_EncodeCharmap
6879 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006880static int
6881charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00006882 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006883 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00006884 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00006885 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006886{
6887 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006888 Py_ssize_t repsize;
6889 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006890 Py_UNICODE *uni2;
6891 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006892 Py_ssize_t collstartpos = *inpos;
6893 Py_ssize_t collendpos = *inpos+1;
6894 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006895 char *encoding = "charmap";
6896 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006897 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006898
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006899 /* find all unencodable characters */
6900 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006901 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00006902 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006903 int res = encoding_map_lookup(p[collendpos], mapping);
6904 if (res != -1)
6905 break;
6906 ++collendpos;
6907 continue;
6908 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006909
Benjamin Peterson29060642009-01-31 22:14:21 +00006910 rep = charmapencode_lookup(p[collendpos], mapping);
6911 if (rep==NULL)
6912 return -1;
6913 else if (rep!=Py_None) {
6914 Py_DECREF(rep);
6915 break;
6916 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006917 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00006918 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006919 }
6920 /* cache callback name lookup
6921 * (if not done yet, i.e. it's the first error) */
6922 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006923 if ((errors==NULL) || (!strcmp(errors, "strict")))
6924 *known_errorHandler = 1;
6925 else if (!strcmp(errors, "replace"))
6926 *known_errorHandler = 2;
6927 else if (!strcmp(errors, "ignore"))
6928 *known_errorHandler = 3;
6929 else if (!strcmp(errors, "xmlcharrefreplace"))
6930 *known_errorHandler = 4;
6931 else
6932 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006933 }
6934 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006935 case 1: /* strict */
6936 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
6937 return -1;
6938 case 2: /* replace */
6939 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006940 x = charmapencode_output('?', mapping, res, respos);
6941 if (x==enc_EXCEPTION) {
6942 return -1;
6943 }
6944 else if (x==enc_FAILED) {
6945 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
6946 return -1;
6947 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006948 }
6949 /* fall through */
6950 case 3: /* ignore */
6951 *inpos = collendpos;
6952 break;
6953 case 4: /* xmlcharrefreplace */
6954 /* generate replacement (temporarily (mis)uses p) */
6955 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006956 char buffer[2+29+1+1];
6957 char *cp;
6958 sprintf(buffer, "&#%d;", (int)p[collpos]);
6959 for (cp = buffer; *cp; ++cp) {
6960 x = charmapencode_output(*cp, mapping, res, respos);
6961 if (x==enc_EXCEPTION)
6962 return -1;
6963 else if (x==enc_FAILED) {
6964 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
6965 return -1;
6966 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006967 }
6968 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006969 *inpos = collendpos;
6970 break;
6971 default:
6972 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00006973 encoding, reason, p, size, exceptionObject,
6974 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006975 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006976 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006977 if (PyBytes_Check(repunicode)) {
6978 /* Directly copy bytes result to output. */
6979 Py_ssize_t outsize = PyBytes_Size(*res);
6980 Py_ssize_t requiredsize;
6981 repsize = PyBytes_Size(repunicode);
6982 requiredsize = *respos + repsize;
6983 if (requiredsize > outsize)
6984 /* Make room for all additional bytes. */
6985 if (charmapencode_resize(res, respos, requiredsize)) {
6986 Py_DECREF(repunicode);
6987 return -1;
6988 }
6989 memcpy(PyBytes_AsString(*res) + *respos,
6990 PyBytes_AsString(repunicode), repsize);
6991 *respos += repsize;
6992 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006993 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006994 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006995 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006996 /* generate replacement */
6997 repsize = PyUnicode_GET_SIZE(repunicode);
6998 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006999 x = charmapencode_output(*uni2, mapping, res, respos);
7000 if (x==enc_EXCEPTION) {
7001 return -1;
7002 }
7003 else if (x==enc_FAILED) {
7004 Py_DECREF(repunicode);
7005 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7006 return -1;
7007 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007008 }
7009 *inpos = newpos;
7010 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007011 }
7012 return 0;
7013}
7014
Alexander Belopolsky40018472011-02-26 01:02:56 +00007015PyObject *
7016PyUnicode_EncodeCharmap(const Py_UNICODE *p,
7017 Py_ssize_t size,
7018 PyObject *mapping,
7019 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007020{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007021 /* output object */
7022 PyObject *res = NULL;
7023 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007024 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007025 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007026 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007027 PyObject *errorHandler = NULL;
7028 PyObject *exc = NULL;
7029 /* the following variable is used for caching string comparisons
7030 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7031 * 3=ignore, 4=xmlcharrefreplace */
7032 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007033
7034 /* Default to Latin-1 */
7035 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007036 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007037
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007038 /* allocate enough for a simple encoding without
7039 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00007040 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007041 if (res == NULL)
7042 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00007043 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007044 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007045
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007046 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007047 /* try to encode it */
7048 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
7049 if (x==enc_EXCEPTION) /* error */
7050 goto onError;
7051 if (x==enc_FAILED) { /* unencodable character */
7052 if (charmap_encoding_error(p, size, &inpos, mapping,
7053 &exc,
7054 &known_errorHandler, &errorHandler, errors,
7055 &res, &respos)) {
7056 goto onError;
7057 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007058 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007059 else
7060 /* done with this character => adjust input position */
7061 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007062 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007063
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007064 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00007065 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007066 if (_PyBytes_Resize(&res, respos) < 0)
7067 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00007068
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007069 Py_XDECREF(exc);
7070 Py_XDECREF(errorHandler);
7071 return res;
7072
Benjamin Peterson29060642009-01-31 22:14:21 +00007073 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007074 Py_XDECREF(res);
7075 Py_XDECREF(exc);
7076 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007077 return NULL;
7078}
7079
Alexander Belopolsky40018472011-02-26 01:02:56 +00007080PyObject *
7081PyUnicode_AsCharmapString(PyObject *unicode,
7082 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007083{
7084 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007085 PyErr_BadArgument();
7086 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007087 }
7088 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007089 PyUnicode_GET_SIZE(unicode),
7090 mapping,
7091 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007092}
7093
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007094/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007095static void
7096make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007097 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007098 Py_ssize_t startpos, Py_ssize_t endpos,
7099 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007100{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007101 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007102 *exceptionObject = _PyUnicodeTranslateError_Create(
7103 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007104 }
7105 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007106 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
7107 goto onError;
7108 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
7109 goto onError;
7110 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
7111 goto onError;
7112 return;
7113 onError:
7114 Py_DECREF(*exceptionObject);
7115 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007116 }
7117}
7118
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007119/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007120static void
7121raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007122 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007123 Py_ssize_t startpos, Py_ssize_t endpos,
7124 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007125{
7126 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007127 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007128 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007129 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007130}
7131
7132/* error handling callback helper:
7133 build arguments, call the callback and check the arguments,
7134 put the result into newpos and return the replacement string, which
7135 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007136static PyObject *
7137unicode_translate_call_errorhandler(const char *errors,
7138 PyObject **errorHandler,
7139 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007140 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007141 Py_ssize_t startpos, Py_ssize_t endpos,
7142 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007143{
Benjamin Peterson142957c2008-07-04 19:55:29 +00007144 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007145
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007146 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007147 PyObject *restuple;
7148 PyObject *resunicode;
7149
7150 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007151 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007152 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007153 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007154 }
7155
7156 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007157 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007158 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007159 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007160
7161 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00007162 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007163 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007164 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007165 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00007166 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00007167 Py_DECREF(restuple);
7168 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007169 }
7170 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00007171 &resunicode, &i_newpos)) {
7172 Py_DECREF(restuple);
7173 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007174 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00007175 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007176 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007177 else
7178 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007179 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007180 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
7181 Py_DECREF(restuple);
7182 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00007183 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007184 Py_INCREF(resunicode);
7185 Py_DECREF(restuple);
7186 return resunicode;
7187}
7188
7189/* Lookup the character ch in the mapping and put the result in result,
7190 which must be decrefed by the caller.
7191 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007192static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007193charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007194{
Christian Heimes217cfd12007-12-02 14:31:20 +00007195 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007196 PyObject *x;
7197
7198 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007199 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007200 x = PyObject_GetItem(mapping, w);
7201 Py_DECREF(w);
7202 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007203 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7204 /* No mapping found means: use 1:1 mapping. */
7205 PyErr_Clear();
7206 *result = NULL;
7207 return 0;
7208 } else
7209 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007210 }
7211 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007212 *result = x;
7213 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007214 }
Christian Heimes217cfd12007-12-02 14:31:20 +00007215 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007216 long value = PyLong_AS_LONG(x);
7217 long max = PyUnicode_GetMax();
7218 if (value < 0 || value > max) {
7219 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00007220 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007221 Py_DECREF(x);
7222 return -1;
7223 }
7224 *result = x;
7225 return 0;
7226 }
7227 else if (PyUnicode_Check(x)) {
7228 *result = x;
7229 return 0;
7230 }
7231 else {
7232 /* wrong return value */
7233 PyErr_SetString(PyExc_TypeError,
7234 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007235 Py_DECREF(x);
7236 return -1;
7237 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007238}
7239/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00007240 if not reallocate and adjust various state variables.
7241 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007242static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007243charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00007244 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007245{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007246 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00007247 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007248 /* exponentially overallocate to minimize reallocations */
7249 if (requiredsize < 2 * oldsize)
7250 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007251 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
7252 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007253 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007254 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007255 }
7256 return 0;
7257}
7258/* lookup the character, put the result in the output string and adjust
7259 various state variables. Return a new reference to the object that
7260 was put in the output buffer in *result, or Py_None, if the mapping was
7261 undefined (in which case no character was written).
7262 The called must decref result.
7263 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007264static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007265charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
7266 PyObject *mapping, Py_UCS4 **output,
7267 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007268 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007269{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007270 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
7271 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00007272 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007273 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007274 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007275 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007276 }
7277 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007278 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00007279 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007280 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007281 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007282 }
7283 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007284 Py_ssize_t repsize;
7285 if (PyUnicode_READY(*res) == -1)
7286 return -1;
7287 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00007288 if (repsize==1) {
7289 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007290 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00007291 }
7292 else if (repsize!=0) {
7293 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007294 Py_ssize_t requiredsize = *opos +
7295 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00007296 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007297 Py_ssize_t i;
7298 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007299 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007300 for(i = 0; i < repsize; i++)
7301 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00007302 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007303 }
7304 else
Benjamin Peterson29060642009-01-31 22:14:21 +00007305 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007306 return 0;
7307}
7308
Alexander Belopolsky40018472011-02-26 01:02:56 +00007309PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007310_PyUnicode_TranslateCharmap(PyObject *input,
7311 PyObject *mapping,
7312 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007313{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007314 /* input object */
7315 char *idata;
7316 Py_ssize_t size, i;
7317 int kind;
7318 /* output buffer */
7319 Py_UCS4 *output = NULL;
7320 Py_ssize_t osize;
7321 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007322 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007323 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007324 char *reason = "character maps to <undefined>";
7325 PyObject *errorHandler = NULL;
7326 PyObject *exc = NULL;
7327 /* the following variable is used for caching string comparisons
7328 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7329 * 3=ignore, 4=xmlcharrefreplace */
7330 int known_errorHandler = -1;
7331
Guido van Rossumd57fd912000-03-10 22:53:23 +00007332 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007333 PyErr_BadArgument();
7334 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007335 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007337 if (PyUnicode_READY(input) == -1)
7338 return NULL;
7339 idata = (char*)PyUnicode_DATA(input);
7340 kind = PyUnicode_KIND(input);
7341 size = PyUnicode_GET_LENGTH(input);
7342 i = 0;
7343
7344 if (size == 0) {
7345 Py_INCREF(input);
7346 return input;
7347 }
7348
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007349 /* allocate enough for a simple 1:1 translation without
7350 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007351 osize = size;
7352 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
7353 opos = 0;
7354 if (output == NULL) {
7355 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00007356 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007357 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007358
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007359 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007360 /* try to encode it */
7361 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007362 if (charmaptranslate_output(input, i, mapping,
7363 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007364 Py_XDECREF(x);
7365 goto onError;
7366 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007367 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00007368 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007369 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00007370 else { /* untranslatable character */
7371 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
7372 Py_ssize_t repsize;
7373 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007374 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00007375 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007376 Py_ssize_t collstart = i;
7377 Py_ssize_t collend = i+1;
7378 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007379
Benjamin Peterson29060642009-01-31 22:14:21 +00007380 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007381 while (collend < size) {
7382 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007383 goto onError;
7384 Py_XDECREF(x);
7385 if (x!=Py_None)
7386 break;
7387 ++collend;
7388 }
7389 /* cache callback name lookup
7390 * (if not done yet, i.e. it's the first error) */
7391 if (known_errorHandler==-1) {
7392 if ((errors==NULL) || (!strcmp(errors, "strict")))
7393 known_errorHandler = 1;
7394 else if (!strcmp(errors, "replace"))
7395 known_errorHandler = 2;
7396 else if (!strcmp(errors, "ignore"))
7397 known_errorHandler = 3;
7398 else if (!strcmp(errors, "xmlcharrefreplace"))
7399 known_errorHandler = 4;
7400 else
7401 known_errorHandler = 0;
7402 }
7403 switch (known_errorHandler) {
7404 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007405 raise_translate_exception(&exc, input, collstart,
7406 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007407 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007408 case 2: /* replace */
7409 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007410 for (coll = collstart; coll<collend; coll++)
7411 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00007412 /* fall through */
7413 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007414 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00007415 break;
7416 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007417 /* generate replacement (temporarily (mis)uses i) */
7418 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007419 char buffer[2+29+1+1];
7420 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007421 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
7422 if (charmaptranslate_makespace(&output, &osize,
7423 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00007424 goto onError;
7425 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007426 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00007427 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007428 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00007429 break;
7430 default:
7431 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007432 reason, input, &exc,
7433 collstart, collend, &newpos);
7434 if (repunicode == NULL || PyUnicode_READY(repunicode) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007435 goto onError;
7436 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007437 repsize = PyUnicode_GET_LENGTH(repunicode);
7438 if (charmaptranslate_makespace(&output, &osize,
7439 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007440 Py_DECREF(repunicode);
7441 goto onError;
7442 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007443 for (uni2 = 0; repsize-->0; ++uni2)
7444 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
7445 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00007446 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007447 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007448 }
7449 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007450 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
7451 if (!res)
7452 goto onError;
7453 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007454 Py_XDECREF(exc);
7455 Py_XDECREF(errorHandler);
7456 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007457
Benjamin Peterson29060642009-01-31 22:14:21 +00007458 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007459 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007460 Py_XDECREF(exc);
7461 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007462 return NULL;
7463}
7464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007465/* Deprecated. Use PyUnicode_Translate instead. */
7466PyObject *
7467PyUnicode_TranslateCharmap(const Py_UNICODE *p,
7468 Py_ssize_t size,
7469 PyObject *mapping,
7470 const char *errors)
7471{
7472 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7473 if (!unicode)
7474 return NULL;
7475 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
7476}
7477
Alexander Belopolsky40018472011-02-26 01:02:56 +00007478PyObject *
7479PyUnicode_Translate(PyObject *str,
7480 PyObject *mapping,
7481 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007482{
7483 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00007484
Guido van Rossumd57fd912000-03-10 22:53:23 +00007485 str = PyUnicode_FromObject(str);
7486 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007487 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007488 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007489 Py_DECREF(str);
7490 return result;
Tim Petersced69f82003-09-16 20:30:58 +00007491
Benjamin Peterson29060642009-01-31 22:14:21 +00007492 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007493 Py_XDECREF(str);
7494 return NULL;
7495}
Tim Petersced69f82003-09-16 20:30:58 +00007496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007497static Py_UCS4
7498fix_decimal_and_space_to_ascii(PyUnicodeObject *self)
7499{
7500 /* No need to call PyUnicode_READY(self) because this function is only
7501 called as a callback from fixup() which does it already. */
7502 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
7503 const int kind = PyUnicode_KIND(self);
7504 void *data = PyUnicode_DATA(self);
7505 Py_UCS4 maxchar = 0, ch, fixed;
7506 Py_ssize_t i;
7507
7508 for (i = 0; i < len; ++i) {
7509 ch = PyUnicode_READ(kind, data, i);
7510 fixed = 0;
7511 if (ch > 127) {
7512 if (Py_UNICODE_ISSPACE(ch))
7513 fixed = ' ';
7514 else {
7515 const int decimal = Py_UNICODE_TODECIMAL(ch);
7516 if (decimal >= 0)
7517 fixed = '0' + decimal;
7518 }
7519 if (fixed != 0) {
7520 if (fixed > maxchar)
7521 maxchar = fixed;
7522 PyUnicode_WRITE(kind, data, i, fixed);
7523 }
7524 else if (ch > maxchar)
7525 maxchar = ch;
7526 }
7527 else if (ch > maxchar)
7528 maxchar = ch;
7529 }
7530
7531 return maxchar;
7532}
7533
7534PyObject *
7535_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
7536{
7537 if (!PyUnicode_Check(unicode)) {
7538 PyErr_BadInternalCall();
7539 return NULL;
7540 }
7541 if (PyUnicode_READY(unicode) == -1)
7542 return NULL;
7543 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
7544 /* If the string is already ASCII, just return the same string */
7545 Py_INCREF(unicode);
7546 return unicode;
7547 }
7548 return fixup((PyUnicodeObject *)unicode, fix_decimal_and_space_to_ascii);
7549}
7550
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00007551PyObject *
7552PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
7553 Py_ssize_t length)
7554{
7555 PyObject *result;
7556 Py_UNICODE *p; /* write pointer into result */
7557 Py_ssize_t i;
7558 /* Copy to a new string */
7559 result = (PyObject *)_PyUnicode_New(length);
7560 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
7561 if (result == NULL)
7562 return result;
7563 p = PyUnicode_AS_UNICODE(result);
7564 /* Iterate over code points */
7565 for (i = 0; i < length; i++) {
7566 Py_UNICODE ch =s[i];
7567 if (ch > 127) {
7568 int decimal = Py_UNICODE_TODECIMAL(ch);
7569 if (decimal >= 0)
7570 p[i] = '0' + decimal;
7571 }
7572 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007573 if (PyUnicode_READY((PyUnicodeObject*)result) == -1) {
7574 Py_DECREF(result);
7575 return NULL;
7576 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00007577 return result;
7578}
Guido van Rossum9e896b32000-04-05 20:11:21 +00007579/* --- Decimal Encoder ---------------------------------------------------- */
7580
Alexander Belopolsky40018472011-02-26 01:02:56 +00007581int
7582PyUnicode_EncodeDecimal(Py_UNICODE *s,
7583 Py_ssize_t length,
7584 char *output,
7585 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00007586{
7587 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007588 PyObject *errorHandler = NULL;
7589 PyObject *exc = NULL;
7590 const char *encoding = "decimal";
7591 const char *reason = "invalid decimal Unicode string";
7592 /* the following variable is used for caching string comparisons
7593 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
7594 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00007595
7596 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007597 PyErr_BadArgument();
7598 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00007599 }
7600
7601 p = s;
7602 end = s + length;
7603 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007604 register Py_UNICODE ch = *p;
7605 int decimal;
7606 PyObject *repunicode;
7607 Py_ssize_t repsize;
7608 Py_ssize_t newpos;
7609 Py_UNICODE *uni2;
7610 Py_UNICODE *collstart;
7611 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00007612
Benjamin Peterson29060642009-01-31 22:14:21 +00007613 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007614 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00007615 ++p;
7616 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007617 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007618 decimal = Py_UNICODE_TODECIMAL(ch);
7619 if (decimal >= 0) {
7620 *output++ = '0' + decimal;
7621 ++p;
7622 continue;
7623 }
7624 if (0 < ch && ch < 256) {
7625 *output++ = (char)ch;
7626 ++p;
7627 continue;
7628 }
7629 /* All other characters are considered unencodable */
7630 collstart = p;
7631 collend = p+1;
7632 while (collend < end) {
7633 if ((0 < *collend && *collend < 256) ||
7634 !Py_UNICODE_ISSPACE(*collend) ||
7635 Py_UNICODE_TODECIMAL(*collend))
7636 break;
7637 }
7638 /* cache callback name lookup
7639 * (if not done yet, i.e. it's the first error) */
7640 if (known_errorHandler==-1) {
7641 if ((errors==NULL) || (!strcmp(errors, "strict")))
7642 known_errorHandler = 1;
7643 else if (!strcmp(errors, "replace"))
7644 known_errorHandler = 2;
7645 else if (!strcmp(errors, "ignore"))
7646 known_errorHandler = 3;
7647 else if (!strcmp(errors, "xmlcharrefreplace"))
7648 known_errorHandler = 4;
7649 else
7650 known_errorHandler = 0;
7651 }
7652 switch (known_errorHandler) {
7653 case 1: /* strict */
7654 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
7655 goto onError;
7656 case 2: /* replace */
7657 for (p = collstart; p < collend; ++p)
7658 *output++ = '?';
7659 /* fall through */
7660 case 3: /* ignore */
7661 p = collend;
7662 break;
7663 case 4: /* xmlcharrefreplace */
7664 /* generate replacement (temporarily (mis)uses p) */
7665 for (p = collstart; p < collend; ++p)
7666 output += sprintf(output, "&#%d;", (int)*p);
7667 p = collend;
7668 break;
7669 default:
7670 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
7671 encoding, reason, s, length, &exc,
7672 collstart-s, collend-s, &newpos);
7673 if (repunicode == NULL)
7674 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007675 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00007676 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007677 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
7678 Py_DECREF(repunicode);
7679 goto onError;
7680 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007681 /* generate replacement */
7682 repsize = PyUnicode_GET_SIZE(repunicode);
7683 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
7684 Py_UNICODE ch = *uni2;
7685 if (Py_UNICODE_ISSPACE(ch))
7686 *output++ = ' ';
7687 else {
7688 decimal = Py_UNICODE_TODECIMAL(ch);
7689 if (decimal >= 0)
7690 *output++ = '0' + decimal;
7691 else if (0 < ch && ch < 256)
7692 *output++ = (char)ch;
7693 else {
7694 Py_DECREF(repunicode);
7695 raise_encode_exception(&exc, encoding,
7696 s, length, collstart-s, collend-s, reason);
7697 goto onError;
7698 }
7699 }
7700 }
7701 p = s + newpos;
7702 Py_DECREF(repunicode);
7703 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00007704 }
7705 /* 0-terminate the output string */
7706 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007707 Py_XDECREF(exc);
7708 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00007709 return 0;
7710
Benjamin Peterson29060642009-01-31 22:14:21 +00007711 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007712 Py_XDECREF(exc);
7713 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00007714 return -1;
7715}
7716
Guido van Rossumd57fd912000-03-10 22:53:23 +00007717/* --- Helpers ------------------------------------------------------------ */
7718
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007719#include "stringlib/ucs1lib.h"
7720#include "stringlib/fastsearch.h"
7721#include "stringlib/partition.h"
7722#include "stringlib/split.h"
7723#include "stringlib/count.h"
7724#include "stringlib/find.h"
7725#include "stringlib/localeutil.h"
7726#include "stringlib/undef.h"
7727
7728#include "stringlib/ucs2lib.h"
7729#include "stringlib/fastsearch.h"
7730#include "stringlib/partition.h"
7731#include "stringlib/split.h"
7732#include "stringlib/count.h"
7733#include "stringlib/find.h"
7734#include "stringlib/localeutil.h"
7735#include "stringlib/undef.h"
7736
7737#include "stringlib/ucs4lib.h"
7738#include "stringlib/fastsearch.h"
7739#include "stringlib/partition.h"
7740#include "stringlib/split.h"
7741#include "stringlib/count.h"
7742#include "stringlib/find.h"
7743#include "stringlib/localeutil.h"
7744#include "stringlib/undef.h"
7745
7746static Py_ssize_t
7747any_find_slice(Py_ssize_t Py_LOCAL_CALLBACK(ucs1)(const Py_UCS1*, Py_ssize_t,
7748 const Py_UCS1*, Py_ssize_t,
7749 Py_ssize_t, Py_ssize_t),
7750 Py_ssize_t Py_LOCAL_CALLBACK(ucs2)(const Py_UCS2*, Py_ssize_t,
7751 const Py_UCS2*, Py_ssize_t,
7752 Py_ssize_t, Py_ssize_t),
7753 Py_ssize_t Py_LOCAL_CALLBACK(ucs4)(const Py_UCS4*, Py_ssize_t,
7754 const Py_UCS4*, Py_ssize_t,
7755 Py_ssize_t, Py_ssize_t),
7756 PyObject* s1, PyObject* s2,
7757 Py_ssize_t start,
7758 Py_ssize_t end)
7759{
7760 int kind1, kind2, kind;
7761 void *buf1, *buf2;
7762 Py_ssize_t len1, len2, result;
7763
7764 kind1 = PyUnicode_KIND(s1);
7765 kind2 = PyUnicode_KIND(s2);
7766 kind = kind1 > kind2 ? kind1 : kind2;
7767 buf1 = PyUnicode_DATA(s1);
7768 buf2 = PyUnicode_DATA(s2);
7769 if (kind1 != kind)
7770 buf1 = _PyUnicode_AsKind(s1, kind);
7771 if (!buf1)
7772 return -2;
7773 if (kind2 != kind)
7774 buf2 = _PyUnicode_AsKind(s2, kind);
7775 if (!buf2) {
7776 if (kind1 != kind) PyMem_Free(buf1);
7777 return -2;
7778 }
7779 len1 = PyUnicode_GET_LENGTH(s1);
7780 len2 = PyUnicode_GET_LENGTH(s2);
7781
7782 switch(kind) {
7783 case PyUnicode_1BYTE_KIND:
7784 result = ucs1(buf1, len1, buf2, len2, start, end);
7785 break;
7786 case PyUnicode_2BYTE_KIND:
7787 result = ucs2(buf1, len1, buf2, len2, start, end);
7788 break;
7789 case PyUnicode_4BYTE_KIND:
7790 result = ucs4(buf1, len1, buf2, len2, start, end);
7791 break;
7792 default:
7793 assert(0); result = -2;
7794 }
7795
7796 if (kind1 != kind)
7797 PyMem_Free(buf1);
7798 if (kind2 != kind)
7799 PyMem_Free(buf2);
7800
7801 return result;
7802}
7803
7804Py_ssize_t
7805_PyUnicode_InsertThousandsGrouping(int kind, void *data,
7806 Py_ssize_t n_buffer,
7807 void *digits, Py_ssize_t n_digits,
7808 Py_ssize_t min_width,
7809 const char *grouping,
7810 const char *thousands_sep)
7811{
7812 switch(kind) {
7813 case PyUnicode_1BYTE_KIND:
7814 return _PyUnicode_ucs1_InsertThousandsGrouping(
7815 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
7816 min_width, grouping, thousands_sep);
7817 case PyUnicode_2BYTE_KIND:
7818 return _PyUnicode_ucs2_InsertThousandsGrouping(
7819 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
7820 min_width, grouping, thousands_sep);
7821 case PyUnicode_4BYTE_KIND:
7822 return _PyUnicode_ucs4_InsertThousandsGrouping(
7823 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
7824 min_width, grouping, thousands_sep);
7825 }
7826 assert(0);
7827 return -1;
7828}
7829
7830
Eric Smith8c663262007-08-25 02:26:07 +00007831#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00007832#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007833
Thomas Wouters477c8d52006-05-27 19:21:47 +00007834#include "stringlib/count.h"
7835#include "stringlib/find.h"
Eric Smith5807c412008-05-11 21:00:57 +00007836
Thomas Wouters477c8d52006-05-27 19:21:47 +00007837/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007838#define ADJUST_INDICES(start, end, len) \
7839 if (end > len) \
7840 end = len; \
7841 else if (end < 0) { \
7842 end += len; \
7843 if (end < 0) \
7844 end = 0; \
7845 } \
7846 if (start < 0) { \
7847 start += len; \
7848 if (start < 0) \
7849 start = 0; \
7850 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007851
Alexander Belopolsky40018472011-02-26 01:02:56 +00007852Py_ssize_t
7853PyUnicode_Count(PyObject *str,
7854 PyObject *substr,
7855 Py_ssize_t start,
7856 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007857{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007858 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007859 PyUnicodeObject* str_obj;
7860 PyUnicodeObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007861 int kind1, kind2, kind;
7862 void *buf1 = NULL, *buf2 = NULL;
7863 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00007864
Thomas Wouters477c8d52006-05-27 19:21:47 +00007865 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007866 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007867 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007868 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007869 if (!sub_obj || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007870 Py_DECREF(str_obj);
7871 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007872 }
Tim Petersced69f82003-09-16 20:30:58 +00007873
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007874 kind1 = PyUnicode_KIND(str_obj);
7875 kind2 = PyUnicode_KIND(sub_obj);
7876 kind = kind1 > kind2 ? kind1 : kind2;
7877 buf1 = PyUnicode_DATA(str_obj);
7878 if (kind1 != kind)
7879 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
7880 if (!buf1)
7881 goto onError;
7882 buf2 = PyUnicode_DATA(sub_obj);
7883 if (kind2 != kind)
7884 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
7885 if (!buf2)
7886 goto onError;
7887 len1 = PyUnicode_GET_LENGTH(str_obj);
7888 len2 = PyUnicode_GET_LENGTH(sub_obj);
7889
7890 ADJUST_INDICES(start, end, len1);
7891 switch(kind) {
7892 case PyUnicode_1BYTE_KIND:
7893 result = ucs1lib_count(
7894 ((Py_UCS1*)buf1) + start, end - start,
7895 buf2, len2, PY_SSIZE_T_MAX
7896 );
7897 break;
7898 case PyUnicode_2BYTE_KIND:
7899 result = ucs2lib_count(
7900 ((Py_UCS2*)buf1) + start, end - start,
7901 buf2, len2, PY_SSIZE_T_MAX
7902 );
7903 break;
7904 case PyUnicode_4BYTE_KIND:
7905 result = ucs4lib_count(
7906 ((Py_UCS4*)buf1) + start, end - start,
7907 buf2, len2, PY_SSIZE_T_MAX
7908 );
7909 break;
7910 default:
7911 assert(0); result = 0;
7912 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007913
7914 Py_DECREF(sub_obj);
7915 Py_DECREF(str_obj);
7916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007917 if (kind1 != kind)
7918 PyMem_Free(buf1);
7919 if (kind2 != kind)
7920 PyMem_Free(buf2);
7921
Guido van Rossumd57fd912000-03-10 22:53:23 +00007922 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007923 onError:
7924 Py_DECREF(sub_obj);
7925 Py_DECREF(str_obj);
7926 if (kind1 != kind && buf1)
7927 PyMem_Free(buf1);
7928 if (kind2 != kind && buf2)
7929 PyMem_Free(buf2);
7930 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007931}
7932
Alexander Belopolsky40018472011-02-26 01:02:56 +00007933Py_ssize_t
7934PyUnicode_Find(PyObject *str,
7935 PyObject *sub,
7936 Py_ssize_t start,
7937 Py_ssize_t end,
7938 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007939{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007940 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00007941
Guido van Rossumd57fd912000-03-10 22:53:23 +00007942 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007943 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007944 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007945 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007946 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007947 Py_DECREF(str);
7948 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007949 }
Tim Petersced69f82003-09-16 20:30:58 +00007950
Thomas Wouters477c8d52006-05-27 19:21:47 +00007951 if (direction > 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007952 result = any_find_slice(
7953 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
7954 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00007955 );
7956 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007957 result = any_find_slice(
7958 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
7959 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00007960 );
7961
Guido van Rossumd57fd912000-03-10 22:53:23 +00007962 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007963 Py_DECREF(sub);
7964
Guido van Rossumd57fd912000-03-10 22:53:23 +00007965 return result;
7966}
7967
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007968Py_ssize_t
7969PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
7970 Py_ssize_t start, Py_ssize_t end,
7971 int direction)
7972{
7973 char *result;
7974 int kind;
7975 if (PyUnicode_READY(str) == -1)
7976 return -2;
7977 if (end > PyUnicode_GET_LENGTH(str))
7978 end = PyUnicode_GET_LENGTH(str);
7979 kind = PyUnicode_KIND(str);
7980 result = findchar(PyUnicode_1BYTE_DATA(str)
7981 + PyUnicode_KIND_SIZE(kind, start),
7982 kind,
7983 end-start, ch, direction);
7984 if (!result)
7985 return -1;
7986 return (result-(char*)PyUnicode_DATA(str)) >> (kind-1);
7987}
7988
Alexander Belopolsky40018472011-02-26 01:02:56 +00007989static int
7990tailmatch(PyUnicodeObject *self,
7991 PyUnicodeObject *substring,
7992 Py_ssize_t start,
7993 Py_ssize_t end,
7994 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007995{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007996 int kind_self;
7997 int kind_sub;
7998 void *data_self;
7999 void *data_sub;
8000 Py_ssize_t offset;
8001 Py_ssize_t i;
8002 Py_ssize_t end_sub;
8003
8004 if (PyUnicode_READY(self) == -1 ||
8005 PyUnicode_READY(substring) == -1)
8006 return 0;
8007
8008 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008009 return 1;
8010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008011 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
8012 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008013 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00008014 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008016 kind_self = PyUnicode_KIND(self);
8017 data_self = PyUnicode_DATA(self);
8018 kind_sub = PyUnicode_KIND(substring);
8019 data_sub = PyUnicode_DATA(substring);
8020 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
8021
8022 if (direction > 0)
8023 offset = end;
8024 else
8025 offset = start;
8026
8027 if (PyUnicode_READ(kind_self, data_self, offset) ==
8028 PyUnicode_READ(kind_sub, data_sub, 0) &&
8029 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
8030 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
8031 /* If both are of the same kind, memcmp is sufficient */
8032 if (kind_self == kind_sub) {
8033 return ! memcmp((char *)data_self +
8034 (offset * PyUnicode_CHARACTER_SIZE(substring)),
8035 data_sub,
8036 PyUnicode_GET_LENGTH(substring) *
8037 PyUnicode_CHARACTER_SIZE(substring));
8038 }
8039 /* otherwise we have to compare each character by first accesing it */
8040 else {
8041 /* We do not need to compare 0 and len(substring)-1 because
8042 the if statement above ensured already that they are equal
8043 when we end up here. */
8044 // TODO: honor direction and do a forward or backwards search
8045 for (i = 1; i < end_sub; ++i) {
8046 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
8047 PyUnicode_READ(kind_sub, data_sub, i))
8048 return 0;
8049 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008050 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008051 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008052 }
8053
8054 return 0;
8055}
8056
Alexander Belopolsky40018472011-02-26 01:02:56 +00008057Py_ssize_t
8058PyUnicode_Tailmatch(PyObject *str,
8059 PyObject *substr,
8060 Py_ssize_t start,
8061 Py_ssize_t end,
8062 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008063{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008064 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008065
Guido van Rossumd57fd912000-03-10 22:53:23 +00008066 str = PyUnicode_FromObject(str);
8067 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008068 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008069 substr = PyUnicode_FromObject(substr);
8070 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 Py_DECREF(str);
8072 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008073 }
Tim Petersced69f82003-09-16 20:30:58 +00008074
Guido van Rossumd57fd912000-03-10 22:53:23 +00008075 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00008076 (PyUnicodeObject *)substr,
8077 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008078 Py_DECREF(str);
8079 Py_DECREF(substr);
8080 return result;
8081}
8082
Guido van Rossumd57fd912000-03-10 22:53:23 +00008083/* Apply fixfct filter to the Unicode object self and return a
8084 reference to the modified object */
8085
Alexander Belopolsky40018472011-02-26 01:02:56 +00008086static PyObject *
8087fixup(PyUnicodeObject *self,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008088 Py_UCS4 (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008089{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008090 PyObject *u;
8091 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008092
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008093 if (PyUnicode_READY(self) == -1)
8094 return NULL;
8095 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
8096 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
8097 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008098 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008099 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008101 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
8102 PyUnicode_GET_LENGTH(u) * PyUnicode_CHARACTER_SIZE(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008104 /* fix functions return the new maximum character in a string,
8105 if the kind of the resulting unicode object does not change,
8106 everything is fine. Otherwise we need to change the string kind
8107 and re-run the fix function. */
8108 maxchar_new = fixfct((PyUnicodeObject*)u);
8109 if (maxchar_new == 0)
8110 /* do nothing, keep maxchar_new at 0 which means no changes. */;
8111 else if (maxchar_new <= 127)
8112 maxchar_new = 127;
8113 else if (maxchar_new <= 255)
8114 maxchar_new = 255;
8115 else if (maxchar_new <= 65535)
8116 maxchar_new = 65535;
8117 else
8118 maxchar_new = 1114111; /* 0x10ffff */
8119
8120 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008121 /* fixfct should return TRUE if it modified the buffer. If
8122 FALSE, return a reference to the original buffer instead
8123 (to save space, not time) */
8124 Py_INCREF(self);
8125 Py_DECREF(u);
8126 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008127 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008128 else if (maxchar_new == maxchar_old) {
8129 return u;
8130 }
8131 else {
8132 /* In case the maximum character changed, we need to
8133 convert the string to the new category. */
8134 PyObject *v = PyUnicode_New(
8135 PyUnicode_GET_LENGTH(self), maxchar_new);
8136 if (v == NULL) {
8137 Py_DECREF(u);
8138 return NULL;
8139 }
8140 if (maxchar_new > maxchar_old) {
8141 /* If the maxchar increased so that the kind changed, not all
8142 characters are representable anymore and we need to fix the
8143 string again. This only happens in very few cases. */
8144 PyUnicode_CopyCharacters(v, 0, (PyObject*)self, 0, PyUnicode_GET_LENGTH(self));
8145 maxchar_old = fixfct((PyUnicodeObject*)v);
8146 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
8147 }
8148 else
8149 PyUnicode_CopyCharacters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
8150
8151 Py_DECREF(u);
8152 return v;
8153 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008154}
8155
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008156static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008157fixupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008158{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008159 /* No need to call PyUnicode_READY(self) because this function is only
8160 called as a callback from fixup() which does it already. */
8161 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8162 const int kind = PyUnicode_KIND(self);
8163 void *data = PyUnicode_DATA(self);
8164 int touched = 0;
8165 Py_UCS4 maxchar = 0;
8166 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008167
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008168 for (i = 0; i < len; ++i) {
8169 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8170 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
8171 if (up != ch) {
8172 if (up > maxchar)
8173 maxchar = up;
8174 PyUnicode_WRITE(kind, data, i, up);
8175 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008176 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008177 else if (ch > maxchar)
8178 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008179 }
8180
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008181 if (touched)
8182 return maxchar;
8183 else
8184 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008185}
8186
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008187static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008188fixlower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008189{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008190 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8191 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8192 const int kind = PyUnicode_KIND(self);
8193 void *data = PyUnicode_DATA(self);
8194 int touched = 0;
8195 Py_UCS4 maxchar = 0;
8196 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008197
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008198 for(i = 0; i < len; ++i) {
8199 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8200 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
8201 if (lo != ch) {
8202 if (lo > maxchar)
8203 maxchar = lo;
8204 PyUnicode_WRITE(kind, data, i, lo);
8205 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008206 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008207 else if (ch > maxchar)
8208 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008209 }
8210
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008211 if (touched)
8212 return maxchar;
8213 else
8214 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008215}
8216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008217static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008218fixswapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008219{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008220 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8221 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8222 const int kind = PyUnicode_KIND(self);
8223 void *data = PyUnicode_DATA(self);
8224 int touched = 0;
8225 Py_UCS4 maxchar = 0;
8226 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008228 for(i = 0; i < len; ++i) {
8229 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8230 Py_UCS4 nu = 0;
8231
8232 if (Py_UNICODE_ISUPPER(ch))
8233 nu = Py_UNICODE_TOLOWER(ch);
8234 else if (Py_UNICODE_ISLOWER(ch))
8235 nu = Py_UNICODE_TOUPPER(ch);
8236
8237 if (nu != 0) {
8238 if (nu > maxchar)
8239 maxchar = nu;
8240 PyUnicode_WRITE(kind, data, i, nu);
8241 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008242 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008243 else if (ch > maxchar)
8244 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008245 }
8246
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008247 if (touched)
8248 return maxchar;
8249 else
8250 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008251}
8252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008253static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008254fixcapitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008255{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008256 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8257 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8258 const int kind = PyUnicode_KIND(self);
8259 void *data = PyUnicode_DATA(self);
8260 int touched = 0;
8261 Py_UCS4 maxchar = 0;
8262 Py_ssize_t i = 0;
8263 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00008264
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008265 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008266 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008267
8268 ch = PyUnicode_READ(kind, data, i);
8269 if (!Py_UNICODE_ISUPPER(ch)) {
8270 maxchar = Py_UNICODE_TOUPPER(ch);
8271 PyUnicode_WRITE(kind, data, i, maxchar);
8272 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008273 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008274 ++i;
8275 for(; i < len; ++i) {
8276 ch = PyUnicode_READ(kind, data, i);
8277 if (!Py_UNICODE_ISLOWER(ch)) {
8278 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
8279 if (lo > maxchar)
8280 maxchar = lo;
8281 PyUnicode_WRITE(kind, data, i, lo);
8282 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008283 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008284 else if (ch > maxchar)
8285 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008286 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008287
8288 if (touched)
8289 return maxchar;
8290 else
8291 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008292}
8293
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008294static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008295fixtitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008296{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008297 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8298 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8299 const int kind = PyUnicode_KIND(self);
8300 void *data = PyUnicode_DATA(self);
8301 Py_UCS4 maxchar = 0;
8302 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008303 int previous_is_cased;
8304
8305 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008306 if (len == 1) {
8307 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8308 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
8309 if (ti != ch) {
8310 PyUnicode_WRITE(kind, data, i, ti);
8311 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00008312 }
8313 else
8314 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008315 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008316 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008317 for(; i < len; ++i) {
8318 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8319 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00008320
Benjamin Peterson29060642009-01-31 22:14:21 +00008321 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008322 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008324 nu = Py_UNICODE_TOTITLE(ch);
8325
8326 if (nu > maxchar)
8327 maxchar = nu;
8328 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00008329
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 if (Py_UNICODE_ISLOWER(ch) ||
8331 Py_UNICODE_ISUPPER(ch) ||
8332 Py_UNICODE_ISTITLE(ch))
8333 previous_is_cased = 1;
8334 else
8335 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008336 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008337 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008338}
8339
Tim Peters8ce9f162004-08-27 01:49:32 +00008340PyObject *
8341PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008342{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008343 PyObject *sep = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008344 Py_ssize_t seplen = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008345 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00008346 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008347 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
8348 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00008349 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008350 Py_ssize_t sz, i, res_offset;
8351 Py_UCS4 maxchar = 0;
8352 Py_UCS4 item_maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008353
Tim Peters05eba1f2004-08-27 21:32:02 +00008354 fseq = PySequence_Fast(seq, "");
8355 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008356 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00008357 }
8358
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008359 /* NOTE: the following code can't call back into Python code,
8360 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00008361 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008362
Tim Peters05eba1f2004-08-27 21:32:02 +00008363 seqlen = PySequence_Fast_GET_SIZE(fseq);
8364 /* If empty sequence, return u"". */
8365 if (seqlen == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008366 res = PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008367 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00008368 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008369 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00008370 /* If singleton sequence with an exact Unicode, return that. */
8371 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008372 item = items[0];
8373 if (PyUnicode_CheckExact(item)) {
8374 Py_INCREF(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008375 res = item;
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 goto Done;
8377 }
Tim Peters8ce9f162004-08-27 01:49:32 +00008378 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008379 else {
8380 /* Set up sep and seplen */
8381 if (separator == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008382 /* fall back to a blank space separator */
8383 sep = PyUnicode_FromOrdinal(' ');
8384 if (!sep || PyUnicode_READY(sep) == -1)
8385 goto onError;
Tim Peters05eba1f2004-08-27 21:32:02 +00008386 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008387 else {
8388 if (!PyUnicode_Check(separator)) {
8389 PyErr_Format(PyExc_TypeError,
8390 "separator: expected str instance,"
8391 " %.80s found",
8392 Py_TYPE(separator)->tp_name);
8393 goto onError;
8394 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008395 if (PyUnicode_READY(separator) == -1)
8396 goto onError;
8397 sep = separator;
8398 seplen = PyUnicode_GET_LENGTH(separator);
8399 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
8400 /* inc refcount to keep this code path symetric with the
8401 above case of a blank separator */
8402 Py_INCREF(sep);
Tim Peters05eba1f2004-08-27 21:32:02 +00008403 }
8404 }
8405
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008406 /* There are at least two things to join, or else we have a subclass
8407 * of str in the sequence.
8408 * Do a pre-pass to figure out the total amount of space we'll
8409 * need (sz), and see whether all argument are strings.
8410 */
8411 sz = 0;
8412 for (i = 0; i < seqlen; i++) {
8413 const Py_ssize_t old_sz = sz;
8414 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 if (!PyUnicode_Check(item)) {
8416 PyErr_Format(PyExc_TypeError,
8417 "sequence item %zd: expected str instance,"
8418 " %.80s found",
8419 i, Py_TYPE(item)->tp_name);
8420 goto onError;
8421 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008422 if (PyUnicode_READY(item) == -1)
8423 goto onError;
8424 sz += PyUnicode_GET_LENGTH(item);
8425 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
8426 if (item_maxchar > maxchar)
8427 maxchar = item_maxchar;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008428 if (i != 0)
8429 sz += seplen;
8430 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
8431 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00008432 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008433 goto onError;
8434 }
8435 }
Tim Petersced69f82003-09-16 20:30:58 +00008436
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008437 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008438 if (res == NULL)
8439 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00008440
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008441 /* Catenate everything. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008442 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008443 Py_ssize_t itemlen;
8444 item = items[i];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008445 itemlen = PyUnicode_GET_LENGTH(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008446 /* Copy item, and maybe the separator. */
8447 if (i) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008448 PyUnicode_CopyCharacters(res, res_offset,
8449 sep, 0, seplen);
8450 res_offset += seplen;
Benjamin Peterson29060642009-01-31 22:14:21 +00008451 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008452 PyUnicode_CopyCharacters(res, res_offset,
8453 item, 0, itemlen);
8454 res_offset += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00008455 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008456 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00008457
Benjamin Peterson29060642009-01-31 22:14:21 +00008458 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00008459 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008460 Py_XDECREF(sep);
8461 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008462
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00008464 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008465 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00008466 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008467 return NULL;
8468}
8469
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008470#define FILL(kind, data, value, start, length) \
8471 do { \
8472 Py_ssize_t i_ = 0; \
8473 assert(kind != PyUnicode_WCHAR_KIND); \
8474 switch ((kind)) { \
8475 case PyUnicode_1BYTE_KIND: { \
8476 unsigned char * to_ = (unsigned char *)((data)) + (start); \
8477 memset(to_, (unsigned char)value, length); \
8478 break; \
8479 } \
8480 case PyUnicode_2BYTE_KIND: { \
8481 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
8482 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
8483 break; \
8484 } \
8485 default: { \
8486 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
8487 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
8488 break; \
8489 } \
8490 } \
8491 } while (0)
8492
Alexander Belopolsky40018472011-02-26 01:02:56 +00008493static PyUnicodeObject *
8494pad(PyUnicodeObject *self,
8495 Py_ssize_t left,
8496 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008497 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008498{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008499 PyObject *u;
8500 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008501
8502 if (left < 0)
8503 left = 0;
8504 if (right < 0)
8505 right = 0;
8506
Tim Peters7a29bd52001-09-12 03:03:31 +00008507 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008508 Py_INCREF(self);
8509 return self;
8510 }
8511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008512 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
8513 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00008514 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
8515 return NULL;
8516 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008517 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
8518 if (fill > maxchar)
8519 maxchar = fill;
8520 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008521 if (u) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008522 int kind = PyUnicode_KIND(u);
8523 void *data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008524 if (left)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008525 FILL(kind, data, fill, 0, left);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008526 if (right)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008527 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
8528 PyUnicode_CopyCharacters(u, left, (PyObject*)self, 0, _PyUnicode_LENGTH(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +00008529 }
8530
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008531 return (PyUnicodeObject*)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008532}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008533#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00008534
Alexander Belopolsky40018472011-02-26 01:02:56 +00008535PyObject *
8536PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008537{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008538 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008539
8540 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008541 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008542 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008544 switch(PyUnicode_KIND(string)) {
8545 case PyUnicode_1BYTE_KIND:
8546 list = ucs1lib_splitlines(
8547 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
8548 PyUnicode_GET_LENGTH(string), keepends);
8549 break;
8550 case PyUnicode_2BYTE_KIND:
8551 list = ucs2lib_splitlines(
8552 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
8553 PyUnicode_GET_LENGTH(string), keepends);
8554 break;
8555 case PyUnicode_4BYTE_KIND:
8556 list = ucs4lib_splitlines(
8557 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
8558 PyUnicode_GET_LENGTH(string), keepends);
8559 break;
8560 default:
8561 assert(0);
8562 list = 0;
8563 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008564 Py_DECREF(string);
8565 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008566}
8567
Alexander Belopolsky40018472011-02-26 01:02:56 +00008568static PyObject *
8569split(PyUnicodeObject *self,
8570 PyUnicodeObject *substring,
8571 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008572{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008573 int kind1, kind2, kind;
8574 void *buf1, *buf2;
8575 Py_ssize_t len1, len2;
8576 PyObject* out;
8577
Guido van Rossumd57fd912000-03-10 22:53:23 +00008578 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008579 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008580
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008581 if (PyUnicode_READY(self) == -1)
8582 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008583
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008584 if (substring == NULL)
8585 switch(PyUnicode_KIND(self)) {
8586 case PyUnicode_1BYTE_KIND:
8587 return ucs1lib_split_whitespace(
8588 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
8589 PyUnicode_GET_LENGTH(self), maxcount
8590 );
8591 case PyUnicode_2BYTE_KIND:
8592 return ucs2lib_split_whitespace(
8593 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
8594 PyUnicode_GET_LENGTH(self), maxcount
8595 );
8596 case PyUnicode_4BYTE_KIND:
8597 return ucs4lib_split_whitespace(
8598 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
8599 PyUnicode_GET_LENGTH(self), maxcount
8600 );
8601 default:
8602 assert(0);
8603 return NULL;
8604 }
8605
8606 if (PyUnicode_READY(substring) == -1)
8607 return NULL;
8608
8609 kind1 = PyUnicode_KIND(self);
8610 kind2 = PyUnicode_KIND(substring);
8611 kind = kind1 > kind2 ? kind1 : kind2;
8612 buf1 = PyUnicode_DATA(self);
8613 buf2 = PyUnicode_DATA(substring);
8614 if (kind1 != kind)
8615 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
8616 if (!buf1)
8617 return NULL;
8618 if (kind2 != kind)
8619 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
8620 if (!buf2) {
8621 if (kind1 != kind) PyMem_Free(buf1);
8622 return NULL;
8623 }
8624 len1 = PyUnicode_GET_LENGTH(self);
8625 len2 = PyUnicode_GET_LENGTH(substring);
8626
8627 switch(kind) {
8628 case PyUnicode_1BYTE_KIND:
8629 out = ucs1lib_split(
8630 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8631 break;
8632 case PyUnicode_2BYTE_KIND:
8633 out = ucs2lib_split(
8634 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8635 break;
8636 case PyUnicode_4BYTE_KIND:
8637 out = ucs4lib_split(
8638 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8639 break;
8640 default:
8641 out = NULL;
8642 }
8643 if (kind1 != kind)
8644 PyMem_Free(buf1);
8645 if (kind2 != kind)
8646 PyMem_Free(buf2);
8647 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008648}
8649
Alexander Belopolsky40018472011-02-26 01:02:56 +00008650static PyObject *
8651rsplit(PyUnicodeObject *self,
8652 PyUnicodeObject *substring,
8653 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008654{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 int kind1, kind2, kind;
8656 void *buf1, *buf2;
8657 Py_ssize_t len1, len2;
8658 PyObject* out;
8659
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008660 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008661 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008662
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008663 if (PyUnicode_READY(self) == -1)
8664 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666 if (substring == NULL)
8667 switch(PyUnicode_KIND(self)) {
8668 case PyUnicode_1BYTE_KIND:
8669 return ucs1lib_rsplit_whitespace(
8670 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
8671 PyUnicode_GET_LENGTH(self), maxcount
8672 );
8673 case PyUnicode_2BYTE_KIND:
8674 return ucs2lib_rsplit_whitespace(
8675 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
8676 PyUnicode_GET_LENGTH(self), maxcount
8677 );
8678 case PyUnicode_4BYTE_KIND:
8679 return ucs4lib_rsplit_whitespace(
8680 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
8681 PyUnicode_GET_LENGTH(self), maxcount
8682 );
8683 default:
8684 assert(0);
8685 return NULL;
8686 }
8687
8688 if (PyUnicode_READY(substring) == -1)
8689 return NULL;
8690
8691 kind1 = PyUnicode_KIND(self);
8692 kind2 = PyUnicode_KIND(substring);
8693 kind = kind1 > kind2 ? kind1 : kind2;
8694 buf1 = PyUnicode_DATA(self);
8695 buf2 = PyUnicode_DATA(substring);
8696 if (kind1 != kind)
8697 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
8698 if (!buf1)
8699 return NULL;
8700 if (kind2 != kind)
8701 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
8702 if (!buf2) {
8703 if (kind1 != kind) PyMem_Free(buf1);
8704 return NULL;
8705 }
8706 len1 = PyUnicode_GET_LENGTH(self);
8707 len2 = PyUnicode_GET_LENGTH(substring);
8708
8709 switch(kind) {
8710 case PyUnicode_1BYTE_KIND:
8711 out = ucs1lib_rsplit(
8712 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8713 break;
8714 case PyUnicode_2BYTE_KIND:
8715 out = ucs2lib_rsplit(
8716 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8717 break;
8718 case PyUnicode_4BYTE_KIND:
8719 out = ucs4lib_rsplit(
8720 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8721 break;
8722 default:
8723 out = NULL;
8724 }
8725 if (kind1 != kind)
8726 PyMem_Free(buf1);
8727 if (kind2 != kind)
8728 PyMem_Free(buf2);
8729 return out;
8730}
8731
8732static Py_ssize_t
8733anylib_find(int kind, void *buf1, Py_ssize_t len1,
8734 void *buf2, Py_ssize_t len2, Py_ssize_t offset)
8735{
8736 switch(kind) {
8737 case PyUnicode_1BYTE_KIND:
8738 return ucs1lib_find(buf1, len1, buf2, len2, offset);
8739 case PyUnicode_2BYTE_KIND:
8740 return ucs2lib_find(buf1, len1, buf2, len2, offset);
8741 case PyUnicode_4BYTE_KIND:
8742 return ucs4lib_find(buf1, len1, buf2, len2, offset);
8743 }
8744 assert(0);
8745 return -1;
8746}
8747
8748static Py_ssize_t
8749anylib_count(int kind, void* sbuf, Py_ssize_t slen,
8750 void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
8751{
8752 switch(kind) {
8753 case PyUnicode_1BYTE_KIND:
8754 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
8755 case PyUnicode_2BYTE_KIND:
8756 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
8757 case PyUnicode_4BYTE_KIND:
8758 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
8759 }
8760 assert(0);
8761 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008762}
8763
Alexander Belopolsky40018472011-02-26 01:02:56 +00008764static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008765replace(PyObject *self, PyObject *str1,
8766 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008767{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008768 PyObject *u;
8769 char *sbuf = PyUnicode_DATA(self);
8770 char *buf1 = PyUnicode_DATA(str1);
8771 char *buf2 = PyUnicode_DATA(str2);
8772 int srelease = 0, release1 = 0, release2 = 0;
8773 int skind = PyUnicode_KIND(self);
8774 int kind1 = PyUnicode_KIND(str1);
8775 int kind2 = PyUnicode_KIND(str2);
8776 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
8777 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
8778 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008779
8780 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008781 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008782 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008783 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008785 if (skind < kind1)
8786 /* substring too wide to be present */
8787 goto nothing;
8788
8789 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00008790 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008791 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008792 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008793 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008794 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008795 /* replace characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008796 Py_UCS4 u1, u2, maxchar;
8797 int mayshrink, rkind;
8798 u1 = PyUnicode_READ_CHAR(str1, 0);
8799 if (!findchar(sbuf, PyUnicode_KIND(self),
8800 slen, u1, 1))
Thomas Wouters477c8d52006-05-27 19:21:47 +00008801 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008802 u2 = PyUnicode_READ_CHAR(str2, 0);
8803 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
8804 /* Replacing u1 with u2 may cause a maxchar reduction in the
8805 result string. */
8806 mayshrink = maxchar > 127;
8807 if (u2 > maxchar) {
8808 maxchar = u2;
8809 mayshrink = 0;
8810 }
8811 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008812 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008813 goto error;
8814 PyUnicode_CopyCharacters(u, 0,
8815 (PyObject*)self, 0, slen);
8816 rkind = PyUnicode_KIND(u);
8817 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
8818 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008819 if (--maxcount < 0)
8820 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008821 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008822 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008823 if (mayshrink) {
8824 PyObject *tmp = u;
8825 u = PyUnicode_FromKindAndData(rkind, PyUnicode_DATA(tmp),
8826 PyUnicode_GET_LENGTH(tmp));
8827 Py_DECREF(tmp);
8828 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008829 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008830 int rkind = skind;
8831 char *res;
8832 if (kind1 < rkind) {
8833 /* widen substring */
8834 buf1 = _PyUnicode_AsKind(str1, rkind);
8835 if (!buf1) goto error;
8836 release1 = 1;
8837 }
8838 i = anylib_find(rkind, sbuf, slen, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008839 if (i < 0)
8840 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008841 if (rkind > kind2) {
8842 /* widen replacement */
8843 buf2 = _PyUnicode_AsKind(str2, rkind);
8844 if (!buf2) goto error;
8845 release2 = 1;
8846 }
8847 else if (rkind < kind2) {
8848 /* widen self and buf1 */
8849 rkind = kind2;
8850 if (release1) PyMem_Free(buf1);
8851 sbuf = _PyUnicode_AsKind(self, rkind);
8852 if (!sbuf) goto error;
8853 srelease = 1;
8854 buf1 = _PyUnicode_AsKind(str1, rkind);
8855 if (!buf1) goto error;
8856 release1 = 1;
8857 }
8858 res = PyMem_Malloc(PyUnicode_KIND_SIZE(rkind, slen));
8859 if (!res) {
8860 PyErr_NoMemory();
8861 goto error;
8862 }
8863 memcpy(res, sbuf, PyUnicode_KIND_SIZE(rkind, slen));
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008864 /* change everything in-place, starting with this one */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008865 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
8866 buf2,
8867 PyUnicode_KIND_SIZE(rkind, len2));
8868 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008869
8870 while ( --maxcount > 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008871 i = anylib_find(rkind, sbuf+PyUnicode_KIND_SIZE(rkind, i),
8872 slen-i,
8873 buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008874 if (i == -1)
8875 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008876 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
8877 buf2,
8878 PyUnicode_KIND_SIZE(rkind, len2));
8879 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008880 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008881
8882 u = PyUnicode_FromKindAndData(rkind, res, slen);
8883 PyMem_Free(res);
8884 if (!u) goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008885 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008886 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008887
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008888 Py_ssize_t n, i, j, ires;
8889 Py_ssize_t product, new_size;
8890 int rkind = skind;
8891 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008892
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008893 if (kind1 < rkind) {
8894 buf1 = _PyUnicode_AsKind(str1, rkind);
8895 if (!buf1) goto error;
8896 release1 = 1;
8897 }
8898 n = anylib_count(rkind, sbuf, slen, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008899 if (n == 0)
8900 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008901 if (kind2 < rkind) {
8902 buf2 = _PyUnicode_AsKind(str2, rkind);
8903 if (!buf2) goto error;
8904 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008905 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008906 else if (kind2 > rkind) {
8907 rkind = kind2;
8908 sbuf = _PyUnicode_AsKind(self, rkind);
8909 if (!sbuf) goto error;
8910 srelease = 1;
8911 if (release1) PyMem_Free(buf1);
8912 buf1 = _PyUnicode_AsKind(str1, rkind);
8913 if (!buf1) goto error;
8914 release1 = 1;
8915 }
8916 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
8917 PyUnicode_GET_LENGTH(str1))); */
8918 product = n * (len2-len1);
8919 if ((product / (len2-len1)) != n) {
8920 PyErr_SetString(PyExc_OverflowError,
8921 "replace string is too long");
8922 goto error;
8923 }
8924 new_size = slen + product;
8925 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
8926 PyErr_SetString(PyExc_OverflowError,
8927 "replace string is too long");
8928 goto error;
8929 }
8930 res = PyMem_Malloc(PyUnicode_KIND_SIZE(rkind, new_size));
8931 if (!res)
8932 goto error;
8933 ires = i = 0;
8934 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008935 while (n-- > 0) {
8936 /* look for next match */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008937 j = anylib_find(rkind,
8938 sbuf + PyUnicode_KIND_SIZE(rkind, i),
8939 slen-i, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008940 if (j == -1)
8941 break;
8942 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008943 /* copy unchanged part [i:j] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008944 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
8945 sbuf + PyUnicode_KIND_SIZE(rkind, i),
8946 PyUnicode_KIND_SIZE(rkind, j-i));
8947 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008948 }
8949 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008950 if (len2 > 0) {
8951 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
8952 buf2,
8953 PyUnicode_KIND_SIZE(rkind, len2));
8954 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008955 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008956 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008957 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008958 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +00008959 /* copy tail [i:] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008960 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
8961 sbuf + PyUnicode_KIND_SIZE(rkind, i),
8962 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00008963 } else {
8964 /* interleave */
8965 while (n > 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008966 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
8967 buf2,
8968 PyUnicode_KIND_SIZE(rkind, len2));
8969 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008970 if (--n <= 0)
8971 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008972 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
8973 sbuf + PyUnicode_KIND_SIZE(rkind, i),
8974 PyUnicode_KIND_SIZE(rkind, 1));
8975 ires++;
8976 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008977 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008978 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
8979 sbuf + PyUnicode_KIND_SIZE(rkind, i),
8980 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00008981 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008982 u = PyUnicode_FromKindAndData(rkind, res, new_size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008983 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008984 if (srelease)
8985 PyMem_FREE(sbuf);
8986 if (release1)
8987 PyMem_FREE(buf1);
8988 if (release2)
8989 PyMem_FREE(buf2);
8990 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008991
Benjamin Peterson29060642009-01-31 22:14:21 +00008992 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00008993 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008994 if (srelease)
8995 PyMem_FREE(sbuf);
8996 if (release1)
8997 PyMem_FREE(buf1);
8998 if (release2)
8999 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009000 if (PyUnicode_CheckExact(self)) {
9001 Py_INCREF(self);
9002 return (PyObject *) self;
9003 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009004 return PyUnicode_FromKindAndData(PyUnicode_KIND(self),
9005 PyUnicode_DATA(self),
9006 PyUnicode_GET_LENGTH(self));
9007 error:
9008 if (srelease && sbuf)
9009 PyMem_FREE(sbuf);
9010 if (release1 && buf1)
9011 PyMem_FREE(buf1);
9012 if (release2 && buf2)
9013 PyMem_FREE(buf2);
9014 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009015}
9016
9017/* --- Unicode Object Methods --------------------------------------------- */
9018
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009019PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009020 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009021\n\
9022Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009023characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009024
9025static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009026unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009027{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009028 return fixup(self, fixtitle);
9029}
9030
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009031PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009032 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009033\n\
9034Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00009035have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009036
9037static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009038unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009039{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009040 return fixup(self, fixcapitalize);
9041}
9042
9043#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009044PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009045 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009046\n\
9047Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009048normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009049
9050static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009051unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009052{
9053 PyObject *list;
9054 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009055 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009056
Guido van Rossumd57fd912000-03-10 22:53:23 +00009057 /* Split into words */
9058 list = split(self, NULL, -1);
9059 if (!list)
9060 return NULL;
9061
9062 /* Capitalize each word */
9063 for (i = 0; i < PyList_GET_SIZE(list); i++) {
9064 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00009065 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009066 if (item == NULL)
9067 goto onError;
9068 Py_DECREF(PyList_GET_ITEM(list, i));
9069 PyList_SET_ITEM(list, i, item);
9070 }
9071
9072 /* Join the words to form a new string */
9073 item = PyUnicode_Join(NULL, list);
9074
Benjamin Peterson29060642009-01-31 22:14:21 +00009075 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009076 Py_DECREF(list);
9077 return (PyObject *)item;
9078}
9079#endif
9080
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009081/* Argument converter. Coerces to a single unicode character */
9082
9083static int
9084convert_uc(PyObject *obj, void *addr)
9085{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009086 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009087 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009088
Benjamin Peterson14339b62009-01-31 16:36:08 +00009089 uniobj = PyUnicode_FromObject(obj);
9090 if (uniobj == NULL) {
9091 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009092 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009093 return 0;
9094 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009095 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009096 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009097 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009098 Py_DECREF(uniobj);
9099 return 0;
9100 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009101 if (PyUnicode_READY(uniobj)) {
9102 Py_DECREF(uniobj);
9103 return 0;
9104 }
9105 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009106 Py_DECREF(uniobj);
9107 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009108}
9109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009110PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009111 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009112\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00009113Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009114done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009115
9116static PyObject *
9117unicode_center(PyUnicodeObject *self, PyObject *args)
9118{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009119 Py_ssize_t marg, left;
9120 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009121 Py_UCS4 fillchar = ' ';
9122
9123 if (PyUnicode_READY(self) == -1)
9124 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009125
Thomas Woutersde017742006-02-16 19:34:37 +00009126 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009127 return NULL;
9128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009129 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009130 Py_INCREF(self);
9131 return (PyObject*) self;
9132 }
9133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009134 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009135 left = marg / 2 + (marg & width & 1);
9136
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009137 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009138}
9139
Marc-André Lemburge5034372000-08-08 08:04:29 +00009140#if 0
9141
9142/* This code should go into some future Unicode collation support
9143 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00009144 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00009145
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009146/* speedy UTF-16 code point order comparison */
9147/* gleaned from: */
9148/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
9149
Marc-André Lemburge12896e2000-07-07 17:51:08 +00009150static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009151{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009152 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00009153 0, 0, 0, 0, 0, 0, 0, 0,
9154 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00009155 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009156};
9157
Guido van Rossumd57fd912000-03-10 22:53:23 +00009158static int
9159unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
9160{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009161 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009162
Guido van Rossumd57fd912000-03-10 22:53:23 +00009163 Py_UNICODE *s1 = str1->str;
9164 Py_UNICODE *s2 = str2->str;
9165
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009166 len1 = str1->_base._base.length;
9167 len2 = str2->_base._base.length;
Tim Petersced69f82003-09-16 20:30:58 +00009168
Guido van Rossumd57fd912000-03-10 22:53:23 +00009169 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00009170 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009171
9172 c1 = *s1++;
9173 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00009174
Benjamin Peterson29060642009-01-31 22:14:21 +00009175 if (c1 > (1<<11) * 26)
9176 c1 += utf16Fixup[c1>>11];
9177 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009178 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009179 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00009180
9181 if (c1 != c2)
9182 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00009183
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009184 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009185 }
9186
9187 return (len1 < len2) ? -1 : (len1 != len2);
9188}
9189
Marc-André Lemburge5034372000-08-08 08:04:29 +00009190#else
9191
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009192/* This function assumes that str1 and str2 are readied by the caller. */
9193
Marc-André Lemburge5034372000-08-08 08:04:29 +00009194static int
9195unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
9196{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009197 int kind1, kind2;
9198 void *data1, *data2;
9199 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +00009200
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009201 kind1 = PyUnicode_KIND(str1);
9202 kind2 = PyUnicode_KIND(str2);
9203 data1 = PyUnicode_DATA(str1);
9204 data2 = PyUnicode_DATA(str2);
9205 len1 = PyUnicode_GET_LENGTH(str1);
9206 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +00009207
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009208 for (i = 0; i < len1 && i < len2; ++i) {
9209 Py_UCS4 c1, c2;
9210 c1 = PyUnicode_READ(kind1, data1, i);
9211 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +00009212
9213 if (c1 != c2)
9214 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +00009215 }
9216
9217 return (len1 < len2) ? -1 : (len1 != len2);
9218}
9219
9220#endif
9221
Alexander Belopolsky40018472011-02-26 01:02:56 +00009222int
9223PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009224{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009225 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
9226 if (PyUnicode_READY(left) == -1 ||
9227 PyUnicode_READY(right) == -1)
9228 return -1;
Guido van Rossum09dc34f2007-05-04 04:17:33 +00009229 return unicode_compare((PyUnicodeObject *)left,
9230 (PyUnicodeObject *)right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009231 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +00009232 PyErr_Format(PyExc_TypeError,
9233 "Can't compare %.100s and %.100s",
9234 left->ob_type->tp_name,
9235 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009236 return -1;
9237}
9238
Martin v. Löwis5b222132007-06-10 09:51:05 +00009239int
9240PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
9241{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009242 Py_ssize_t i;
9243 int kind;
9244 void *data;
9245 Py_UCS4 chr;
9246
Martin v. Löwis5b222132007-06-10 09:51:05 +00009247 assert(PyUnicode_Check(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009248 if (PyUnicode_READY(uni) == -1)
9249 return -1;
9250 kind = PyUnicode_KIND(uni);
9251 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +00009252 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009253 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
9254 if (chr != str[i])
9255 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00009256 /* This check keeps Python strings that end in '\0' from comparing equal
9257 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009258 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +00009259 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00009260 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00009261 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00009262 return 0;
9263}
9264
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009265
Benjamin Peterson29060642009-01-31 22:14:21 +00009266#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00009267 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009268
Alexander Belopolsky40018472011-02-26 01:02:56 +00009269PyObject *
9270PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009271{
9272 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009273
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009274 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
9275 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009276 if (PyUnicode_READY(left) == -1 ||
9277 PyUnicode_READY(right) == -1)
9278 return NULL;
9279 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
9280 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009281 if (op == Py_EQ) {
9282 Py_INCREF(Py_False);
9283 return Py_False;
9284 }
9285 if (op == Py_NE) {
9286 Py_INCREF(Py_True);
9287 return Py_True;
9288 }
9289 }
9290 if (left == right)
9291 result = 0;
9292 else
9293 result = unicode_compare((PyUnicodeObject *)left,
9294 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009295
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009296 /* Convert the return value to a Boolean */
9297 switch (op) {
9298 case Py_EQ:
9299 v = TEST_COND(result == 0);
9300 break;
9301 case Py_NE:
9302 v = TEST_COND(result != 0);
9303 break;
9304 case Py_LE:
9305 v = TEST_COND(result <= 0);
9306 break;
9307 case Py_GE:
9308 v = TEST_COND(result >= 0);
9309 break;
9310 case Py_LT:
9311 v = TEST_COND(result == -1);
9312 break;
9313 case Py_GT:
9314 v = TEST_COND(result == 1);
9315 break;
9316 default:
9317 PyErr_BadArgument();
9318 return NULL;
9319 }
9320 Py_INCREF(v);
9321 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009322 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00009323
Brian Curtindfc80e32011-08-10 20:28:54 -05009324 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009325}
9326
Alexander Belopolsky40018472011-02-26 01:02:56 +00009327int
9328PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00009329{
Thomas Wouters477c8d52006-05-27 19:21:47 +00009330 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009331 int kind1, kind2, kind;
9332 void *buf1, *buf2;
9333 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009334 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009335
9336 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00009337 sub = PyUnicode_FromObject(element);
9338 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009339 PyErr_Format(PyExc_TypeError,
9340 "'in <string>' requires string as left operand, not %s",
9341 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009342 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009343 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009344 if (PyUnicode_READY(sub) == -1)
9345 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009346
Thomas Wouters477c8d52006-05-27 19:21:47 +00009347 str = PyUnicode_FromObject(container);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 if (!str || PyUnicode_READY(container) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009349 Py_DECREF(sub);
9350 return -1;
9351 }
9352
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009353 kind1 = PyUnicode_KIND(str);
9354 kind2 = PyUnicode_KIND(sub);
9355 kind = kind1 > kind2 ? kind1 : kind2;
9356 buf1 = PyUnicode_DATA(str);
9357 buf2 = PyUnicode_DATA(sub);
9358 if (kind1 != kind)
9359 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
9360 if (!buf1) {
9361 Py_DECREF(sub);
9362 return -1;
9363 }
9364 if (kind2 != kind)
9365 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
9366 if (!buf2) {
9367 Py_DECREF(sub);
9368 if (kind1 != kind) PyMem_Free(buf1);
9369 return -1;
9370 }
9371 len1 = PyUnicode_GET_LENGTH(str);
9372 len2 = PyUnicode_GET_LENGTH(sub);
9373
9374 switch(kind) {
9375 case PyUnicode_1BYTE_KIND:
9376 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
9377 break;
9378 case PyUnicode_2BYTE_KIND:
9379 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
9380 break;
9381 case PyUnicode_4BYTE_KIND:
9382 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
9383 break;
9384 default:
9385 result = -1;
9386 assert(0);
9387 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009388
9389 Py_DECREF(str);
9390 Py_DECREF(sub);
9391
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392 if (kind1 != kind)
9393 PyMem_Free(buf1);
9394 if (kind2 != kind)
9395 PyMem_Free(buf2);
9396
Guido van Rossum403d68b2000-03-13 15:55:09 +00009397 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009398}
9399
Guido van Rossumd57fd912000-03-10 22:53:23 +00009400/* Concat to string or Unicode object giving a new Unicode object. */
9401
Alexander Belopolsky40018472011-02-26 01:02:56 +00009402PyObject *
9403PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009404{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009405 PyObject *u = NULL, *v = NULL, *w;
9406 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009407
9408 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009409 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009410 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009411 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009412 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009413 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009414 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009415
9416 /* Shortcuts */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009417 if (v == (PyObject*)unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009418 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009419 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009420 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009421 if (u == (PyObject*)unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009422 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009423 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009424 }
9425
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009426 if (PyUnicode_READY(u) == -1 || PyUnicode_READY(v) == -1)
9427 goto onError;
9428
9429 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
9430 if (PyUnicode_MAX_CHAR_VALUE(v) > maxchar)
9431 maxchar = PyUnicode_MAX_CHAR_VALUE(v);
9432
Guido van Rossumd57fd912000-03-10 22:53:23 +00009433 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009434 w = PyUnicode_New(
9435 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
9436 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009437 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009438 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009439 PyUnicode_CopyCharacters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
9440 PyUnicode_CopyCharacters(w, PyUnicode_GET_LENGTH(u), v, 0,
9441 PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +00009442 Py_DECREF(u);
9443 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009444 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009445
Benjamin Peterson29060642009-01-31 22:14:21 +00009446 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009447 Py_XDECREF(u);
9448 Py_XDECREF(v);
9449 return NULL;
9450}
9451
Walter Dörwald1ab83302007-05-18 17:15:44 +00009452void
9453PyUnicode_Append(PyObject **pleft, PyObject *right)
9454{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009455 PyObject *new;
9456 if (*pleft == NULL)
9457 return;
9458 if (right == NULL || !PyUnicode_Check(*pleft)) {
9459 Py_DECREF(*pleft);
9460 *pleft = NULL;
9461 return;
9462 }
9463 new = PyUnicode_Concat(*pleft, right);
9464 Py_DECREF(*pleft);
9465 *pleft = new;
Walter Dörwald1ab83302007-05-18 17:15:44 +00009466}
9467
9468void
9469PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
9470{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009471 PyUnicode_Append(pleft, right);
9472 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00009473}
9474
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009475PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009476 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009477\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00009478Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00009479string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009480interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009481
9482static PyObject *
9483unicode_count(PyUnicodeObject *self, PyObject *args)
9484{
9485 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009486 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009487 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009488 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009489 int kind1, kind2, kind;
9490 void *buf1, *buf2;
9491 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009492
Jesus Ceaac451502011-04-20 17:09:23 +02009493 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
9494 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00009495 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +00009496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009497 kind1 = PyUnicode_KIND(self);
9498 kind2 = PyUnicode_KIND(substring);
9499 kind = kind1 > kind2 ? kind1 : kind2;
9500 buf1 = PyUnicode_DATA(self);
9501 buf2 = PyUnicode_DATA(substring);
9502 if (kind1 != kind)
9503 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9504 if (!buf1) {
9505 Py_DECREF(substring);
9506 return NULL;
9507 }
9508 if (kind2 != kind)
9509 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9510 if (!buf2) {
9511 Py_DECREF(substring);
9512 if (kind1 != kind) PyMem_Free(buf1);
9513 return NULL;
9514 }
9515 len1 = PyUnicode_GET_LENGTH(self);
9516 len2 = PyUnicode_GET_LENGTH(substring);
9517
9518 ADJUST_INDICES(start, end, len1);
9519 switch(kind) {
9520 case PyUnicode_1BYTE_KIND:
9521 iresult = ucs1lib_count(
9522 ((Py_UCS1*)buf1) + start, end - start,
9523 buf2, len2, PY_SSIZE_T_MAX
9524 );
9525 break;
9526 case PyUnicode_2BYTE_KIND:
9527 iresult = ucs2lib_count(
9528 ((Py_UCS2*)buf1) + start, end - start,
9529 buf2, len2, PY_SSIZE_T_MAX
9530 );
9531 break;
9532 case PyUnicode_4BYTE_KIND:
9533 iresult = ucs4lib_count(
9534 ((Py_UCS4*)buf1) + start, end - start,
9535 buf2, len2, PY_SSIZE_T_MAX
9536 );
9537 break;
9538 default:
9539 assert(0); iresult = 0;
9540 }
9541
9542 result = PyLong_FromSsize_t(iresult);
9543
9544 if (kind1 != kind)
9545 PyMem_Free(buf1);
9546 if (kind2 != kind)
9547 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009548
9549 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009550
Guido van Rossumd57fd912000-03-10 22:53:23 +00009551 return result;
9552}
9553
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009554PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +00009555 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009556\n\
Victor Stinnere14e2122010-11-07 18:41:46 +00009557Encode S using the codec registered for encoding. Default encoding\n\
9558is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +00009559handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009560a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
9561'xmlcharrefreplace' as well as any other name registered with\n\
9562codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009563
9564static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00009565unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009566{
Benjamin Peterson308d6372009-09-18 21:42:35 +00009567 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +00009568 char *encoding = NULL;
9569 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +00009570
Benjamin Peterson308d6372009-09-18 21:42:35 +00009571 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
9572 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009573 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +00009574 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00009575}
9576
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009577PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009578 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009579\n\
9580Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009581If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009582
9583static PyObject*
9584unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
9585{
9586 Py_UNICODE *e;
9587 Py_UNICODE *p;
9588 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009589 Py_UNICODE *qe;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009590 Py_ssize_t i, j, incr, wstr_length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009591 PyUnicodeObject *u;
9592 int tabsize = 8;
9593
9594 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00009595 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009597 if (PyUnicode_AsUnicodeAndSize((PyObject *)self, &wstr_length) == NULL)
9598 return NULL;
9599
Thomas Wouters7e474022000-07-16 12:04:32 +00009600 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009601 i = 0; /* chars up to and including most recent \n or \r */
9602 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009603 e = _PyUnicode_WSTR(self) + wstr_length; /* end of input */
9604 for (p = _PyUnicode_WSTR(self); p < e; p++)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009605 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009606 if (tabsize > 0) {
9607 incr = tabsize - (j % tabsize); /* cannot overflow */
9608 if (j > PY_SSIZE_T_MAX - incr)
9609 goto overflow1;
9610 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009611 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009612 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009613 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009614 if (j > PY_SSIZE_T_MAX - 1)
9615 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009616 j++;
9617 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009618 if (i > PY_SSIZE_T_MAX - j)
9619 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009620 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009621 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009622 }
9623 }
9624
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009625 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +00009626 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00009627
Guido van Rossumd57fd912000-03-10 22:53:23 +00009628 /* Second pass: create output string and fill it */
9629 u = _PyUnicode_New(i + j);
9630 if (!u)
9631 return NULL;
9632
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009633 j = 0; /* same as in first pass */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009634 q = _PyUnicode_WSTR(u); /* next output char */
9635 qe = _PyUnicode_WSTR(u) + PyUnicode_GET_SIZE(u); /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009636
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009637 for (p = _PyUnicode_WSTR(self); p < e; p++)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009638 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009639 if (tabsize > 0) {
9640 i = tabsize - (j % tabsize);
9641 j += i;
9642 while (i--) {
9643 if (q >= qe)
9644 goto overflow2;
9645 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009646 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009647 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00009648 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009649 else {
9650 if (q >= qe)
9651 goto overflow2;
9652 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009653 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009654 if (*p == '\n' || *p == '\r')
9655 j = 0;
9656 }
9657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009658 if (PyUnicode_READY(u) == -1) {
9659 Py_DECREF(u);
9660 return NULL;
9661 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009662 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009663
9664 overflow2:
9665 Py_DECREF(u);
9666 overflow1:
9667 PyErr_SetString(PyExc_OverflowError, "new string is too long");
9668 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009669}
9670
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009671PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009672 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009673\n\
9674Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08009675such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009676arguments start and end are interpreted as in slice notation.\n\
9677\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009678Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009679
9680static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009681unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009682{
Jesus Ceaac451502011-04-20 17:09:23 +02009683 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00009684 Py_ssize_t start;
9685 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009686 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009687
Jesus Ceaac451502011-04-20 17:09:23 +02009688 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
9689 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009690 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009691
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009692 if (PyUnicode_READY(self) == -1)
9693 return NULL;
9694 if (PyUnicode_READY(substring) == -1)
9695 return NULL;
9696
9697 result = any_find_slice(
9698 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
9699 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00009700 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00009701
9702 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009703
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009704 if (result == -2)
9705 return NULL;
9706
Christian Heimes217cfd12007-12-02 14:31:20 +00009707 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009708}
9709
9710static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00009711unicode_getitem(PyUnicodeObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009712{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009713 Py_UCS4 ch;
9714
9715 if (PyUnicode_READY(self) == -1)
9716 return NULL;
9717 if (index < 0 || index >= _PyUnicode_LENGTH(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009718 PyErr_SetString(PyExc_IndexError, "string index out of range");
9719 return NULL;
9720 }
9721
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009722 ch = PyUnicode_READ(PyUnicode_KIND(self), PyUnicode_DATA(self), index);
9723 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009724}
9725
Guido van Rossumc2504932007-09-18 19:42:40 +00009726/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +01009727 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00009728static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +00009729unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009730{
Guido van Rossumc2504932007-09-18 19:42:40 +00009731 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +01009732 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +00009733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009734 if (_PyUnicode_HASH(self) != -1)
9735 return _PyUnicode_HASH(self);
9736 if (PyUnicode_READY(self) == -1)
9737 return -1;
9738 len = PyUnicode_GET_LENGTH(self);
9739
9740 /* The hash function as a macro, gets expanded three times below. */
9741#define HASH(P) \
9742 x = (Py_uhash_t)*P << 7; \
9743 while (--len >= 0) \
9744 x = (1000003*x) ^ (Py_uhash_t)*P++;
9745
9746 switch (PyUnicode_KIND(self)) {
9747 case PyUnicode_1BYTE_KIND: {
9748 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
9749 HASH(c);
9750 break;
9751 }
9752 case PyUnicode_2BYTE_KIND: {
9753 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
9754 HASH(s);
9755 break;
9756 }
9757 default: {
9758 Py_UCS4 *l;
9759 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
9760 "Impossible switch case in unicode_hash");
9761 l = PyUnicode_4BYTE_DATA(self);
9762 HASH(l);
9763 break;
9764 }
9765 }
9766 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
9767
Guido van Rossumc2504932007-09-18 19:42:40 +00009768 if (x == -1)
9769 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009770 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +00009771 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009772}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009773#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +00009774
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009775PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009776 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009777\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009778Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009779
9780static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009781unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009782{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009783 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +02009784 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00009785 Py_ssize_t start;
9786 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009787
Jesus Ceaac451502011-04-20 17:09:23 +02009788 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
9789 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009790 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009791
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009792 if (PyUnicode_READY(self) == -1)
9793 return NULL;
9794 if (PyUnicode_READY(substring) == -1)
9795 return NULL;
9796
9797 result = any_find_slice(
9798 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
9799 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00009800 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00009801
9802 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009803
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009804 if (result == -2)
9805 return NULL;
9806
Guido van Rossumd57fd912000-03-10 22:53:23 +00009807 if (result < 0) {
9808 PyErr_SetString(PyExc_ValueError, "substring not found");
9809 return NULL;
9810 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009811
Christian Heimes217cfd12007-12-02 14:31:20 +00009812 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009813}
9814
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009815PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009816 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009817\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00009818Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009819at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009820
9821static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009822unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009823{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009824 Py_ssize_t i, length;
9825 int kind;
9826 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009827 int cased;
9828
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009829 if (PyUnicode_READY(self) == -1)
9830 return NULL;
9831 length = PyUnicode_GET_LENGTH(self);
9832 kind = PyUnicode_KIND(self);
9833 data = PyUnicode_DATA(self);
9834
Guido van Rossumd57fd912000-03-10 22:53:23 +00009835 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009836 if (length == 1)
9837 return PyBool_FromLong(
9838 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +00009839
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00009840 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009841 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009842 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00009843
Guido van Rossumd57fd912000-03-10 22:53:23 +00009844 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009845 for (i = 0; i < length; i++) {
9846 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009847
Benjamin Peterson29060642009-01-31 22:14:21 +00009848 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
9849 return PyBool_FromLong(0);
9850 else if (!cased && Py_UNICODE_ISLOWER(ch))
9851 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009852 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00009853 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009854}
9855
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009856PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009857 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009858\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00009859Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009860at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009861
9862static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009863unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009864{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009865 Py_ssize_t i, length;
9866 int kind;
9867 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009868 int cased;
9869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009870 if (PyUnicode_READY(self) == -1)
9871 return NULL;
9872 length = PyUnicode_GET_LENGTH(self);
9873 kind = PyUnicode_KIND(self);
9874 data = PyUnicode_DATA(self);
9875
Guido van Rossumd57fd912000-03-10 22:53:23 +00009876 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009877 if (length == 1)
9878 return PyBool_FromLong(
9879 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009880
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00009881 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009882 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009883 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00009884
Guido van Rossumd57fd912000-03-10 22:53:23 +00009885 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009886 for (i = 0; i < length; i++) {
9887 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009888
Benjamin Peterson29060642009-01-31 22:14:21 +00009889 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
9890 return PyBool_FromLong(0);
9891 else if (!cased && Py_UNICODE_ISUPPER(ch))
9892 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009893 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00009894 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009895}
9896
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009897PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009898 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009899\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00009900Return True if S is a titlecased string and there is at least one\n\
9901character in S, i.e. upper- and titlecase characters may only\n\
9902follow uncased characters and lowercase characters only cased ones.\n\
9903Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009904
9905static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009906unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009907{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009908 Py_ssize_t i, length;
9909 int kind;
9910 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009911 int cased, previous_is_cased;
9912
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009913 if (PyUnicode_READY(self) == -1)
9914 return NULL;
9915 length = PyUnicode_GET_LENGTH(self);
9916 kind = PyUnicode_KIND(self);
9917 data = PyUnicode_DATA(self);
9918
Guido van Rossumd57fd912000-03-10 22:53:23 +00009919 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 if (length == 1) {
9921 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
9922 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
9923 (Py_UNICODE_ISUPPER(ch) != 0));
9924 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009925
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00009926 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009927 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009928 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00009929
Guido van Rossumd57fd912000-03-10 22:53:23 +00009930 cased = 0;
9931 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009932 for (i = 0; i < length; i++) {
9933 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009934
Benjamin Peterson29060642009-01-31 22:14:21 +00009935 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
9936 if (previous_is_cased)
9937 return PyBool_FromLong(0);
9938 previous_is_cased = 1;
9939 cased = 1;
9940 }
9941 else if (Py_UNICODE_ISLOWER(ch)) {
9942 if (!previous_is_cased)
9943 return PyBool_FromLong(0);
9944 previous_is_cased = 1;
9945 cased = 1;
9946 }
9947 else
9948 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009949 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00009950 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009951}
9952
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009953PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009954 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009955\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00009956Return True if all characters in S are whitespace\n\
9957and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009958
9959static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009960unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009961{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009962 Py_ssize_t i, length;
9963 int kind;
9964 void *data;
9965
9966 if (PyUnicode_READY(self) == -1)
9967 return NULL;
9968 length = PyUnicode_GET_LENGTH(self);
9969 kind = PyUnicode_KIND(self);
9970 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009971
Guido van Rossumd57fd912000-03-10 22:53:23 +00009972 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009973 if (length == 1)
9974 return PyBool_FromLong(
9975 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +00009976
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00009977 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009978 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009979 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00009980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981 for (i = 0; i < length; i++) {
9982 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +03009983 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +00009984 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009985 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00009986 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009987}
9988
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009989PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009990 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00009991\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00009992Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009993and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00009994
9995static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009996unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00009997{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009998 Py_ssize_t i, length;
9999 int kind;
10000 void *data;
10001
10002 if (PyUnicode_READY(self) == -1)
10003 return NULL;
10004 length = PyUnicode_GET_LENGTH(self);
10005 kind = PyUnicode_KIND(self);
10006 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010007
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010008 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010009 if (length == 1)
10010 return PyBool_FromLong(
10011 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010012
10013 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010014 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010015 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010016
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010017 for (i = 0; i < length; i++) {
10018 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010019 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010020 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010021 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010022}
10023
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010024PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010025 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010026\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010027Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010028and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010029
10030static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010031unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010032{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010033 int kind;
10034 void *data;
10035 Py_ssize_t len, i;
10036
10037 if (PyUnicode_READY(self) == -1)
10038 return NULL;
10039
10040 kind = PyUnicode_KIND(self);
10041 data = PyUnicode_DATA(self);
10042 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010043
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010044 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010045 if (len == 1) {
10046 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10047 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
10048 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010049
10050 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010052 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010053
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010054 for (i = 0; i < len; i++) {
10055 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010056 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010057 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010058 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010059 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010060}
10061
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010062PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010063 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010064\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010065Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010066False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010067
10068static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010069unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010070{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 Py_ssize_t i, length;
10072 int kind;
10073 void *data;
10074
10075 if (PyUnicode_READY(self) == -1)
10076 return NULL;
10077 length = PyUnicode_GET_LENGTH(self);
10078 kind = PyUnicode_KIND(self);
10079 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010080
Guido van Rossumd57fd912000-03-10 22:53:23 +000010081 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010082 if (length == 1)
10083 return PyBool_FromLong(
10084 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010085
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010086 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010087 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010088 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010089
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090 for (i = 0; i < length; i++) {
10091 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010092 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010093 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010094 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010095}
10096
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010097PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010098 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010099\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010100Return True if all characters in S are digits\n\
10101and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010102
10103static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010104unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010105{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 Py_ssize_t i, length;
10107 int kind;
10108 void *data;
10109
10110 if (PyUnicode_READY(self) == -1)
10111 return NULL;
10112 length = PyUnicode_GET_LENGTH(self);
10113 kind = PyUnicode_KIND(self);
10114 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010115
Guido van Rossumd57fd912000-03-10 22:53:23 +000010116 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 if (length == 1) {
10118 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10119 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
10120 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010121
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010122 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010123 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010124 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010126 for (i = 0; i < length; i++) {
10127 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010128 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010129 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010130 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010131}
10132
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010133PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010134 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010135\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010136Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010137False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010138
10139static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010140unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010141{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 Py_ssize_t i, length;
10143 int kind;
10144 void *data;
10145
10146 if (PyUnicode_READY(self) == -1)
10147 return NULL;
10148 length = PyUnicode_GET_LENGTH(self);
10149 kind = PyUnicode_KIND(self);
10150 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010151
Guido van Rossumd57fd912000-03-10 22:53:23 +000010152 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 if (length == 1)
10154 return PyBool_FromLong(
10155 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010156
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010157 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010159 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010160
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 for (i = 0; i < length; i++) {
10162 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010163 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010164 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010165 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010166}
10167
Martin v. Löwis47383402007-08-15 07:32:56 +000010168int
10169PyUnicode_IsIdentifier(PyObject *self)
10170{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 int kind;
10172 void *data;
10173 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010174 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000010175
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 if (PyUnicode_READY(self) == -1) {
10177 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000010178 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 }
10180
10181 /* Special case for empty strings */
10182 if (PyUnicode_GET_LENGTH(self) == 0)
10183 return 0;
10184 kind = PyUnicode_KIND(self);
10185 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000010186
10187 /* PEP 3131 says that the first character must be in
10188 XID_Start and subsequent characters in XID_Continue,
10189 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000010190 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000010191 letters, digits, underscore). However, given the current
10192 definition of XID_Start and XID_Continue, it is sufficient
10193 to check just for these, except that _ must be allowed
10194 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050010196 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000010197 return 0;
10198
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040010199 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010201 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000010202 return 1;
10203}
10204
10205PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010206 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000010207\n\
10208Return True if S is a valid identifier according\n\
10209to the language definition.");
10210
10211static PyObject*
10212unicode_isidentifier(PyObject *self)
10213{
10214 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
10215}
10216
Georg Brandl559e5d72008-06-11 18:37:52 +000010217PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010218 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000010219\n\
10220Return True if all characters in S are considered\n\
10221printable in repr() or S is empty, False otherwise.");
10222
10223static PyObject*
10224unicode_isprintable(PyObject *self)
10225{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010226 Py_ssize_t i, length;
10227 int kind;
10228 void *data;
10229
10230 if (PyUnicode_READY(self) == -1)
10231 return NULL;
10232 length = PyUnicode_GET_LENGTH(self);
10233 kind = PyUnicode_KIND(self);
10234 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000010235
10236 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 if (length == 1)
10238 return PyBool_FromLong(
10239 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000010240
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 for (i = 0; i < length; i++) {
10242 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000010243 Py_RETURN_FALSE;
10244 }
10245 }
10246 Py_RETURN_TRUE;
10247}
10248
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010249PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000010250 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010251\n\
10252Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000010253iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010254
10255static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010256unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010257{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010258 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010259}
10260
Martin v. Löwis18e16552006-02-15 17:27:45 +000010261static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +000010262unicode_length(PyUnicodeObject *self)
10263{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 if (PyUnicode_READY(self) == -1)
10265 return -1;
10266 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010267}
10268
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010269PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010270 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010271\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000010272Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010273done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010274
10275static PyObject *
10276unicode_ljust(PyUnicodeObject *self, PyObject *args)
10277{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010278 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 Py_UCS4 fillchar = ' ';
10280
10281 if (PyUnicode_READY(self) == -1)
10282 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010283
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010284 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010285 return NULL;
10286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010288 Py_INCREF(self);
10289 return (PyObject*) self;
10290 }
10291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010293}
10294
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010295PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010296 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010297\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010298Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010299
10300static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010301unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010302{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010303 return fixup(self, fixlower);
10304}
10305
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010306#define LEFTSTRIP 0
10307#define RIGHTSTRIP 1
10308#define BOTHSTRIP 2
10309
10310/* Arrays indexed by above */
10311static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
10312
10313#define STRIPNAME(i) (stripformat[i]+3)
10314
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010315/* externally visible for str.strip(unicode) */
10316PyObject *
10317_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
10318{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 void *data;
10320 int kind;
10321 Py_ssize_t i, j, len;
10322 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
10325 return NULL;
10326
10327 kind = PyUnicode_KIND(self);
10328 data = PyUnicode_DATA(self);
10329 len = PyUnicode_GET_LENGTH(self);
10330 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
10331 PyUnicode_DATA(sepobj),
10332 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010333
Benjamin Peterson14339b62009-01-31 16:36:08 +000010334 i = 0;
10335 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336 while (i < len &&
10337 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010338 i++;
10339 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010340 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010341
Benjamin Peterson14339b62009-01-31 16:36:08 +000010342 j = len;
10343 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010344 do {
10345 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346 } while (j >= i &&
10347 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000010348 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010349 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010350
Benjamin Peterson14339b62009-01-31 16:36:08 +000010351 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010352 Py_INCREF(self);
10353 return (PyObject*)self;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010354 }
10355 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010356 return PyUnicode_Substring((PyObject*)self, i, j);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010357}
10358
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010359/* Assumes an already ready self string. */
10360
10361static PyObject *
10362substring(PyUnicodeObject *self, Py_ssize_t start, Py_ssize_t len)
10363{
10364 const int kind = PyUnicode_KIND(self);
10365 void *data = PyUnicode_DATA(self);
10366 Py_UCS4 maxchar = 0;
10367 Py_ssize_t i;
10368 PyObject *unicode;
10369
10370 if (start < 0 || len < 0 || (start + len) > PyUnicode_GET_LENGTH(self)) {
10371 PyErr_BadInternalCall();
10372 return NULL;
10373 }
10374
10375 if (len == PyUnicode_GET_LENGTH(self) && PyUnicode_CheckExact(self)) {
10376 Py_INCREF(self);
10377 return (PyObject*)self;
10378 }
10379
10380 for (i = 0; i < len; ++i) {
10381 const Py_UCS4 ch = PyUnicode_READ(kind, data, start + i);
10382 if (ch > maxchar)
10383 maxchar = ch;
10384 }
10385
10386 unicode = PyUnicode_New(len, maxchar);
10387 if (unicode == NULL)
10388 return NULL;
10389 PyUnicode_CopyCharacters(unicode, 0,
10390 (PyObject*)self, start, len);
10391 return unicode;
10392}
10393
10394PyObject*
10395PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
10396{
10397 unsigned char *data;
10398 int kind;
10399
10400 if (start == 0 && end == PyUnicode_GET_LENGTH(self)
10401 && PyUnicode_CheckExact(self))
10402 {
10403 Py_INCREF(self);
10404 return (PyObject *)self;
10405 }
10406
10407 if ((end - start) == 1)
10408 return unicode_getitem((PyUnicodeObject*)self, start);
10409
10410 if (PyUnicode_READY(self) == -1)
10411 return NULL;
10412 kind = PyUnicode_KIND(self);
10413 data = PyUnicode_1BYTE_DATA(self);
10414 return PyUnicode_FromKindAndData(kind, data + PyUnicode_KIND_SIZE(kind, start),
10415 end-start);
10416}
Guido van Rossumd57fd912000-03-10 22:53:23 +000010417
10418static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010419do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010420{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 int kind;
10422 void *data;
10423 Py_ssize_t len, i, j;
10424
10425 if (PyUnicode_READY(self) == -1)
10426 return NULL;
10427
10428 kind = PyUnicode_KIND(self);
10429 data = PyUnicode_DATA(self);
10430 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010431
Benjamin Peterson14339b62009-01-31 16:36:08 +000010432 i = 0;
10433 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010434 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010435 i++;
10436 }
10437 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010438
Benjamin Peterson14339b62009-01-31 16:36:08 +000010439 j = len;
10440 if (striptype != LEFTSTRIP) {
10441 do {
10442 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000010444 j++;
10445 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010446
Benjamin Peterson14339b62009-01-31 16:36:08 +000010447 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
10448 Py_INCREF(self);
10449 return (PyObject*)self;
10450 }
10451 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 return substring(self, i, j-i);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010453}
10454
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010455
10456static PyObject *
10457do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
10458{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010459 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010460
Benjamin Peterson14339b62009-01-31 16:36:08 +000010461 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
10462 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010463
Benjamin Peterson14339b62009-01-31 16:36:08 +000010464 if (sep != NULL && sep != Py_None) {
10465 if (PyUnicode_Check(sep))
10466 return _PyUnicode_XStrip(self, striptype, sep);
10467 else {
10468 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010469 "%s arg must be None or str",
10470 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000010471 return NULL;
10472 }
10473 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010474
Benjamin Peterson14339b62009-01-31 16:36:08 +000010475 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010476}
10477
10478
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010479PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010480 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010481\n\
10482Return a copy of the string S with leading and trailing\n\
10483whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010484If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010485
10486static PyObject *
10487unicode_strip(PyUnicodeObject *self, PyObject *args)
10488{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010489 if (PyTuple_GET_SIZE(args) == 0)
10490 return do_strip(self, BOTHSTRIP); /* Common case */
10491 else
10492 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010493}
10494
10495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010496PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010497 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010498\n\
10499Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010500If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010501
10502static PyObject *
10503unicode_lstrip(PyUnicodeObject *self, PyObject *args)
10504{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010505 if (PyTuple_GET_SIZE(args) == 0)
10506 return do_strip(self, LEFTSTRIP); /* Common case */
10507 else
10508 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010509}
10510
10511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010512PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010513 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010514\n\
10515Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010516If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010517
10518static PyObject *
10519unicode_rstrip(PyUnicodeObject *self, PyObject *args)
10520{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010521 if (PyTuple_GET_SIZE(args) == 0)
10522 return do_strip(self, RIGHTSTRIP); /* Common case */
10523 else
10524 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010525}
10526
10527
Guido van Rossumd57fd912000-03-10 22:53:23 +000010528static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +000010529unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010530{
10531 PyUnicodeObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 Py_ssize_t nchars, n;
10533 size_t nbytes, char_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010534
Georg Brandl222de0f2009-04-12 12:01:50 +000010535 if (len < 1) {
10536 Py_INCREF(unicode_empty);
10537 return (PyObject *)unicode_empty;
10538 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010539
Tim Peters7a29bd52001-09-12 03:03:31 +000010540 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010541 /* no repeat, return original string */
10542 Py_INCREF(str);
10543 return (PyObject*) str;
10544 }
Tim Peters8f422462000-09-09 06:13:41 +000010545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010546 if (PyUnicode_READY(str) == -1)
10547 return NULL;
10548
Tim Peters8f422462000-09-09 06:13:41 +000010549 /* ensure # of chars needed doesn't overflow int and # of bytes
10550 * needed doesn't overflow size_t
10551 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010552 nchars = len * PyUnicode_GET_LENGTH(str);
10553 if (nchars / len != PyUnicode_GET_LENGTH(str)) {
Tim Peters8f422462000-09-09 06:13:41 +000010554 PyErr_SetString(PyExc_OverflowError,
10555 "repeated string is too long");
10556 return NULL;
10557 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010558 char_size = PyUnicode_CHARACTER_SIZE(str);
10559 nbytes = (nchars + 1) * char_size;
10560 if (nbytes / char_size != (size_t)(nchars + 1)) {
Tim Peters8f422462000-09-09 06:13:41 +000010561 PyErr_SetString(PyExc_OverflowError,
10562 "repeated string is too long");
10563 return NULL;
10564 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010565 u = (PyUnicodeObject *)PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010566 if (!u)
10567 return NULL;
10568
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569 if (PyUnicode_GET_LENGTH(str) == 1) {
10570 const int kind = PyUnicode_KIND(str);
10571 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
10572 void *to = PyUnicode_DATA(u);
10573 for (n = 0; n < len; ++n)
10574 PyUnicode_WRITE(kind, to, n, fill_char);
10575 }
10576 else {
10577 /* number of characters copied this far */
10578 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
10579 const Py_ssize_t char_size = PyUnicode_CHARACTER_SIZE(str);
10580 char *to = (char *) PyUnicode_DATA(u);
10581 Py_MEMCPY(to, PyUnicode_DATA(str),
10582 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000010583 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010584 n = (done <= nchars-done) ? done : nchars-done;
10585 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010586 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000010587 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010588 }
10589
10590 return (PyObject*) u;
10591}
10592
Alexander Belopolsky40018472011-02-26 01:02:56 +000010593PyObject *
10594PyUnicode_Replace(PyObject *obj,
10595 PyObject *subobj,
10596 PyObject *replobj,
10597 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010598{
10599 PyObject *self;
10600 PyObject *str1;
10601 PyObject *str2;
10602 PyObject *result;
10603
10604 self = PyUnicode_FromObject(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 if (self == NULL || PyUnicode_READY(obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000010606 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010607 str1 = PyUnicode_FromObject(subobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 if (str1 == NULL || PyUnicode_READY(obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010609 Py_DECREF(self);
10610 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010611 }
10612 str2 = PyUnicode_FromObject(replobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010613 if (str2 == NULL || PyUnicode_READY(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010614 Py_DECREF(self);
10615 Py_DECREF(str1);
10616 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010617 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010619 Py_DECREF(self);
10620 Py_DECREF(str1);
10621 Py_DECREF(str2);
10622 return result;
10623}
10624
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010625PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000010626 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010627\n\
10628Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000010629old replaced by new. If the optional argument count is\n\
10630given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010631
10632static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010633unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010634{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 PyObject *str1;
10636 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010637 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010638 PyObject *result;
10639
Martin v. Löwis18e16552006-02-15 17:27:45 +000010640 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010641 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010642 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000010643 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010644 str1 = PyUnicode_FromObject(str1);
10645 if (str1 == NULL || PyUnicode_READY(str1) == -1)
10646 return NULL;
10647 str2 = PyUnicode_FromObject(str2);
10648 if (str2 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010649 Py_DECREF(str1);
10650 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000010651 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010652
10653 result = replace(self, str1, str2, maxcount);
10654
10655 Py_DECREF(str1);
10656 Py_DECREF(str2);
10657 return result;
10658}
10659
Alexander Belopolsky40018472011-02-26 01:02:56 +000010660static PyObject *
10661unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010662{
Walter Dörwald79e913e2007-05-12 11:08:06 +000010663 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010664 Py_ssize_t isize;
10665 Py_ssize_t osize, squote, dquote, i, o;
10666 Py_UCS4 max, quote;
10667 int ikind, okind;
10668 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000010669
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010670 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000010671 return NULL;
10672
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010673 isize = PyUnicode_GET_LENGTH(unicode);
10674 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000010675
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010676 /* Compute length of output, quote characters, and
10677 maximum character */
10678 osize = 2; /* quotes */
10679 max = 127;
10680 squote = dquote = 0;
10681 ikind = PyUnicode_KIND(unicode);
10682 for (i = 0; i < isize; i++) {
10683 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
10684 switch (ch) {
10685 case '\'': squote++; osize++; break;
10686 case '"': dquote++; osize++; break;
10687 case '\\': case '\t': case '\r': case '\n':
10688 osize += 2; break;
10689 default:
10690 /* Fast-path ASCII */
10691 if (ch < ' ' || ch == 0x7f)
10692 osize += 4; /* \xHH */
10693 else if (ch < 0x7f)
10694 osize++;
10695 else if (Py_UNICODE_ISPRINTABLE(ch)) {
10696 osize++;
10697 max = ch > max ? ch : max;
10698 }
10699 else if (ch < 0x100)
10700 osize += 4; /* \xHH */
10701 else if (ch < 0x10000)
10702 osize += 6; /* \uHHHH */
10703 else
10704 osize += 10; /* \uHHHHHHHH */
10705 }
10706 }
10707
10708 quote = '\'';
10709 if (squote) {
10710 if (dquote)
10711 /* Both squote and dquote present. Use squote,
10712 and escape them */
10713 osize += squote;
10714 else
10715 quote = '"';
10716 }
10717
10718 repr = PyUnicode_New(osize, max);
10719 if (repr == NULL)
10720 return NULL;
10721 okind = PyUnicode_KIND(repr);
10722 odata = PyUnicode_DATA(repr);
10723
10724 PyUnicode_WRITE(okind, odata, 0, quote);
10725 PyUnicode_WRITE(okind, odata, osize-1, quote);
10726
10727 for (i = 0, o = 1; i < isize; i++) {
10728 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000010729
10730 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010731 if ((ch == quote) || (ch == '\\')) {
10732 PyUnicode_WRITE(okind, odata, o++, '\\');
10733 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000010734 continue;
10735 }
10736
Benjamin Peterson29060642009-01-31 22:14:21 +000010737 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000010738 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010739 PyUnicode_WRITE(okind, odata, o++, '\\');
10740 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000010741 }
10742 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010743 PyUnicode_WRITE(okind, odata, o++, '\\');
10744 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000010745 }
10746 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010747 PyUnicode_WRITE(okind, odata, o++, '\\');
10748 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000010749 }
10750
10751 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000010752 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010753 PyUnicode_WRITE(okind, odata, o++, '\\');
10754 PyUnicode_WRITE(okind, odata, o++, 'x');
10755 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
10756 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000010757 }
10758
Georg Brandl559e5d72008-06-11 18:37:52 +000010759 /* Copy ASCII characters as-is */
10760 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010761 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000010762 }
10763
Benjamin Peterson29060642009-01-31 22:14:21 +000010764 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000010765 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010766 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000010767 (categories Z* and C* except ASCII space)
10768 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010769 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000010770 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010771 if (ch <= 0xff) {
10772 PyUnicode_WRITE(okind, odata, o++, '\\');
10773 PyUnicode_WRITE(okind, odata, o++, 'x');
10774 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
10775 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000010776 }
10777 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010778 else if (ch >= 0x10000) {
10779 PyUnicode_WRITE(okind, odata, o++, '\\');
10780 PyUnicode_WRITE(okind, odata, o++, 'U');
10781 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 28) & 0xF]);
10782 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 24) & 0xF]);
10783 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 20) & 0xF]);
10784 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 16) & 0xF]);
10785 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
10786 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
10787 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
10788 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000010789 }
10790 /* Map 16-bit characters to '\uxxxx' */
10791 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010792 PyUnicode_WRITE(okind, odata, o++, '\\');
10793 PyUnicode_WRITE(okind, odata, o++, 'u');
10794 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
10795 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
10796 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
10797 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000010798 }
10799 }
10800 /* Copy characters as-is */
10801 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010802 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000010803 }
10804 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000010805 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010806 /* Closing quote already added at the beginning */
Walter Dörwald79e913e2007-05-12 11:08:06 +000010807 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010808}
10809
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010810PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010811 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010812\n\
10813Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010814such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010815arguments start and end are interpreted as in slice notation.\n\
10816\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010817Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010818
10819static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010820unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010821{
Jesus Ceaac451502011-04-20 17:09:23 +020010822 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010823 Py_ssize_t start;
10824 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010825 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010826
Jesus Ceaac451502011-04-20 17:09:23 +020010827 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
10828 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000010829 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010831 if (PyUnicode_READY(self) == -1)
10832 return NULL;
10833 if (PyUnicode_READY(substring) == -1)
10834 return NULL;
10835
10836 result = any_find_slice(
10837 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
10838 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010839 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010840
10841 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010842
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010843 if (result == -2)
10844 return NULL;
10845
Christian Heimes217cfd12007-12-02 14:31:20 +000010846 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010847}
10848
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010849PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010850 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010851\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010852Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010853
10854static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010855unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010856{
Jesus Ceaac451502011-04-20 17:09:23 +020010857 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010858 Py_ssize_t start;
10859 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010860 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010861
Jesus Ceaac451502011-04-20 17:09:23 +020010862 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
10863 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000010864 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010865
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010866 if (PyUnicode_READY(self) == -1)
10867 return NULL;
10868 if (PyUnicode_READY(substring) == -1)
10869 return NULL;
10870
10871 result = any_find_slice(
10872 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
10873 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010874 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010875
10876 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010877
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010878 if (result == -2)
10879 return NULL;
10880
Guido van Rossumd57fd912000-03-10 22:53:23 +000010881 if (result < 0) {
10882 PyErr_SetString(PyExc_ValueError, "substring not found");
10883 return NULL;
10884 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010885
Christian Heimes217cfd12007-12-02 14:31:20 +000010886 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010887}
10888
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010889PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010890 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010891\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000010892Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010893done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010894
10895static PyObject *
10896unicode_rjust(PyUnicodeObject *self, PyObject *args)
10897{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010898 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010899 Py_UCS4 fillchar = ' ';
10900
10901 if (PyUnicode_READY(self) == -1)
10902 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010903
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010904 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010905 return NULL;
10906
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010907 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010908 Py_INCREF(self);
10909 return (PyObject*) self;
10910 }
10911
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010912 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010913}
10914
Alexander Belopolsky40018472011-02-26 01:02:56 +000010915PyObject *
10916PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010917{
10918 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000010919
Guido van Rossumd57fd912000-03-10 22:53:23 +000010920 s = PyUnicode_FromObject(s);
10921 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000010922 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000010923 if (sep != NULL) {
10924 sep = PyUnicode_FromObject(sep);
10925 if (sep == NULL) {
10926 Py_DECREF(s);
10927 return NULL;
10928 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010929 }
10930
10931 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
10932
10933 Py_DECREF(s);
10934 Py_XDECREF(sep);
10935 return result;
10936}
10937
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010938PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010939 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010940\n\
10941Return a list of the words in S, using sep as the\n\
10942delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000010943splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000010944whitespace string is a separator and empty strings are\n\
10945removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010946
10947static PyObject*
10948unicode_split(PyUnicodeObject *self, PyObject *args)
10949{
10950 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010951 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010952
Martin v. Löwis18e16552006-02-15 17:27:45 +000010953 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010954 return NULL;
10955
10956 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000010957 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010958 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +000010959 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010960 else
Benjamin Peterson29060642009-01-31 22:14:21 +000010961 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010962}
10963
Thomas Wouters477c8d52006-05-27 19:21:47 +000010964PyObject *
10965PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
10966{
10967 PyObject* str_obj;
10968 PyObject* sep_obj;
10969 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010970 int kind1, kind2, kind;
10971 void *buf1 = NULL, *buf2 = NULL;
10972 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010973
10974 str_obj = PyUnicode_FromObject(str_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010975 if (!str_obj || PyUnicode_READY(str_in) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000010976 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010977 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010978 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010979 Py_DECREF(str_obj);
10980 return NULL;
10981 }
10982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010983 kind1 = PyUnicode_KIND(str_in);
10984 kind2 = PyUnicode_KIND(sep_obj);
10985 kind = kind1 > kind2 ? kind1 : kind2;
10986 buf1 = PyUnicode_DATA(str_in);
10987 if (kind1 != kind)
10988 buf1 = _PyUnicode_AsKind(str_in, kind);
10989 if (!buf1)
10990 goto onError;
10991 buf2 = PyUnicode_DATA(sep_obj);
10992 if (kind2 != kind)
10993 buf2 = _PyUnicode_AsKind(sep_obj, kind);
10994 if (!buf2)
10995 goto onError;
10996 len1 = PyUnicode_GET_LENGTH(str_obj);
10997 len2 = PyUnicode_GET_LENGTH(sep_obj);
10998
10999 switch(PyUnicode_KIND(str_in)) {
11000 case PyUnicode_1BYTE_KIND:
11001 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11002 break;
11003 case PyUnicode_2BYTE_KIND:
11004 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11005 break;
11006 case PyUnicode_4BYTE_KIND:
11007 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11008 break;
11009 default:
11010 assert(0);
11011 out = 0;
11012 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011013
11014 Py_DECREF(sep_obj);
11015 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011016 if (kind1 != kind)
11017 PyMem_Free(buf1);
11018 if (kind2 != kind)
11019 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011020
11021 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011022 onError:
11023 Py_DECREF(sep_obj);
11024 Py_DECREF(str_obj);
11025 if (kind1 != kind && buf1)
11026 PyMem_Free(buf1);
11027 if (kind2 != kind && buf2)
11028 PyMem_Free(buf2);
11029 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011030}
11031
11032
11033PyObject *
11034PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
11035{
11036 PyObject* str_obj;
11037 PyObject* sep_obj;
11038 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011039 int kind1, kind2, kind;
11040 void *buf1 = NULL, *buf2 = NULL;
11041 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011042
11043 str_obj = PyUnicode_FromObject(str_in);
11044 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000011045 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011046 sep_obj = PyUnicode_FromObject(sep_in);
11047 if (!sep_obj) {
11048 Py_DECREF(str_obj);
11049 return NULL;
11050 }
11051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011052 kind1 = PyUnicode_KIND(str_in);
11053 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020011054 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011055 buf1 = PyUnicode_DATA(str_in);
11056 if (kind1 != kind)
11057 buf1 = _PyUnicode_AsKind(str_in, kind);
11058 if (!buf1)
11059 goto onError;
11060 buf2 = PyUnicode_DATA(sep_obj);
11061 if (kind2 != kind)
11062 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11063 if (!buf2)
11064 goto onError;
11065 len1 = PyUnicode_GET_LENGTH(str_obj);
11066 len2 = PyUnicode_GET_LENGTH(sep_obj);
11067
11068 switch(PyUnicode_KIND(str_in)) {
11069 case PyUnicode_1BYTE_KIND:
11070 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11071 break;
11072 case PyUnicode_2BYTE_KIND:
11073 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11074 break;
11075 case PyUnicode_4BYTE_KIND:
11076 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11077 break;
11078 default:
11079 assert(0);
11080 out = 0;
11081 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011082
11083 Py_DECREF(sep_obj);
11084 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011085 if (kind1 != kind)
11086 PyMem_Free(buf1);
11087 if (kind2 != kind)
11088 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011089
11090 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011091 onError:
11092 Py_DECREF(sep_obj);
11093 Py_DECREF(str_obj);
11094 if (kind1 != kind && buf1)
11095 PyMem_Free(buf1);
11096 if (kind2 != kind && buf2)
11097 PyMem_Free(buf2);
11098 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011099}
11100
11101PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011102 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011103\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000011104Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011105the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011106found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000011107
11108static PyObject*
11109unicode_partition(PyUnicodeObject *self, PyObject *separator)
11110{
11111 return PyUnicode_Partition((PyObject *)self, separator);
11112}
11113
11114PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000011115 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011116\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000011117Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011118the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011119separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000011120
11121static PyObject*
11122unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
11123{
11124 return PyUnicode_RPartition((PyObject *)self, separator);
11125}
11126
Alexander Belopolsky40018472011-02-26 01:02:56 +000011127PyObject *
11128PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011129{
11130 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011131
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011132 s = PyUnicode_FromObject(s);
11133 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011134 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011135 if (sep != NULL) {
11136 sep = PyUnicode_FromObject(sep);
11137 if (sep == NULL) {
11138 Py_DECREF(s);
11139 return NULL;
11140 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011141 }
11142
11143 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
11144
11145 Py_DECREF(s);
11146 Py_XDECREF(sep);
11147 return result;
11148}
11149
11150PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011151 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011152\n\
11153Return a list of the words in S, using sep as the\n\
11154delimiter string, starting at the end of the string and\n\
11155working to the front. If maxsplit is given, at most maxsplit\n\
11156splits are done. If sep is not specified, any whitespace string\n\
11157is a separator.");
11158
11159static PyObject*
11160unicode_rsplit(PyUnicodeObject *self, PyObject *args)
11161{
11162 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011163 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011164
Martin v. Löwis18e16552006-02-15 17:27:45 +000011165 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011166 return NULL;
11167
11168 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011169 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011170 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +000011171 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011172 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011173 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011174}
11175
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011176PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011177 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011178\n\
11179Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000011180Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011181is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182
11183static PyObject*
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011184unicode_splitlines(PyUnicodeObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011186 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000011187 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011189 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
11190 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191 return NULL;
11192
Guido van Rossum86662912000-04-11 15:38:46 +000011193 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194}
11195
11196static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000011197PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198{
Walter Dörwald346737f2007-05-31 10:44:43 +000011199 if (PyUnicode_CheckExact(self)) {
11200 Py_INCREF(self);
11201 return self;
11202 } else
11203 /* Subtype -- return genuine unicode string with the same value. */
11204 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(self),
11205 PyUnicode_GET_SIZE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206}
11207
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011208PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011209 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210\n\
11211Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011212and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213
11214static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011215unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011216{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217 return fixup(self, fixswapcase);
11218}
11219
Georg Brandlceee0772007-11-27 23:48:05 +000011220PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011221 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000011222\n\
11223Return a translation table usable for str.translate().\n\
11224If there is only one argument, it must be a dictionary mapping Unicode\n\
11225ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011226Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000011227If there are two arguments, they must be strings of equal length, and\n\
11228in the resulting dictionary, each character in x will be mapped to the\n\
11229character at the same position in y. If there is a third argument, it\n\
11230must be a string, whose characters will be mapped to None in the result.");
11231
11232static PyObject*
11233unicode_maketrans(PyUnicodeObject *null, PyObject *args)
11234{
11235 PyObject *x, *y = NULL, *z = NULL;
11236 PyObject *new = NULL, *key, *value;
11237 Py_ssize_t i = 0;
11238 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011239
Georg Brandlceee0772007-11-27 23:48:05 +000011240 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
11241 return NULL;
11242 new = PyDict_New();
11243 if (!new)
11244 return NULL;
11245 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011246 int x_kind, y_kind, z_kind;
11247 void *x_data, *y_data, *z_data;
11248
Georg Brandlceee0772007-11-27 23:48:05 +000011249 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000011250 if (!PyUnicode_Check(x)) {
11251 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
11252 "be a string if there is a second argument");
11253 goto err;
11254 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011255 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011256 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
11257 "arguments must have equal length");
11258 goto err;
11259 }
11260 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011261 x_kind = PyUnicode_KIND(x);
11262 y_kind = PyUnicode_KIND(y);
11263 x_data = PyUnicode_DATA(x);
11264 y_data = PyUnicode_DATA(y);
11265 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
11266 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
11267 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000011268 if (!key || !value)
11269 goto err;
11270 res = PyDict_SetItem(new, key, value);
11271 Py_DECREF(key);
11272 Py_DECREF(value);
11273 if (res < 0)
11274 goto err;
11275 }
11276 /* create entries for deleting chars in z */
11277 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011278 z_kind = PyUnicode_KIND(z);
11279 z_data = PyUnicode_DATA(z);
Georg Brandlceee0772007-11-27 23:48:05 +000011280 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011281 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000011282 if (!key)
11283 goto err;
11284 res = PyDict_SetItem(new, key, Py_None);
11285 Py_DECREF(key);
11286 if (res < 0)
11287 goto err;
11288 }
11289 }
11290 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011291 int kind;
11292 void *data;
11293
Georg Brandlceee0772007-11-27 23:48:05 +000011294 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000011295 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011296 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
11297 "to maketrans it must be a dict");
11298 goto err;
11299 }
11300 /* copy entries into the new dict, converting string keys to int keys */
11301 while (PyDict_Next(x, &i, &key, &value)) {
11302 if (PyUnicode_Check(key)) {
11303 /* convert string keys to integer keys */
11304 PyObject *newkey;
11305 if (PyUnicode_GET_SIZE(key) != 1) {
11306 PyErr_SetString(PyExc_ValueError, "string keys in translate "
11307 "table must be of length 1");
11308 goto err;
11309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011310 kind = PyUnicode_KIND(key);
11311 data = PyUnicode_DATA(key);
11312 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000011313 if (!newkey)
11314 goto err;
11315 res = PyDict_SetItem(new, newkey, value);
11316 Py_DECREF(newkey);
11317 if (res < 0)
11318 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000011319 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011320 /* just keep integer keys */
11321 if (PyDict_SetItem(new, key, value) < 0)
11322 goto err;
11323 } else {
11324 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
11325 "be strings or integers");
11326 goto err;
11327 }
11328 }
11329 }
11330 return new;
11331 err:
11332 Py_DECREF(new);
11333 return NULL;
11334}
11335
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011336PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011337 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011338\n\
11339Return a copy of the string S, where all characters have been mapped\n\
11340through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011341Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000011342Unmapped characters are left untouched. Characters mapped to None\n\
11343are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344
11345static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011346unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011347{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011348 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349}
11350
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011351PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011352 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011353\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011354Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011355
11356static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011357unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011358{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011359 return fixup(self, fixupper);
11360}
11361
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011362PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011363 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000011365Pad a numeric string S with zeros on the left, to fill a field\n\
11366of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011367
11368static PyObject *
11369unicode_zfill(PyUnicodeObject *self, PyObject *args)
11370{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011371 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011372 PyUnicodeObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011373 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011374 int kind;
11375 void *data;
11376 Py_UCS4 chr;
11377
11378 if (PyUnicode_READY(self) == -1)
11379 return NULL;
11380
Martin v. Löwis18e16552006-02-15 17:27:45 +000011381 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011382 return NULL;
11383
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011384 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000011385 if (PyUnicode_CheckExact(self)) {
11386 Py_INCREF(self);
11387 return (PyObject*) self;
11388 }
11389 else
11390 return PyUnicode_FromUnicode(
11391 PyUnicode_AS_UNICODE(self),
11392 PyUnicode_GET_SIZE(self)
Benjamin Peterson29060642009-01-31 22:14:21 +000011393 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394 }
11395
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011396 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011397
11398 u = pad(self, fill, 0, '0');
11399
Walter Dörwald068325e2002-04-15 13:36:47 +000011400 if (u == NULL)
11401 return NULL;
11402
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011403 kind = PyUnicode_KIND(u);
11404 data = PyUnicode_DATA(u);
11405 chr = PyUnicode_READ(kind, data, fill);
11406
11407 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409 PyUnicode_WRITE(kind, data, 0, chr);
11410 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411 }
11412
11413 return (PyObject*) u;
11414}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415
11416#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011417static PyObject *
11418unicode__decimal2ascii(PyObject *self)
11419{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011420 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011421}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422#endif
11423
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011424PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011425 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000011427Return True if S starts with the specified prefix, False otherwise.\n\
11428With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011429With optional end, stop comparing S at that position.\n\
11430prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431
11432static PyObject *
11433unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000011434 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011436 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011438 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011439 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011440 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441
Jesus Ceaac451502011-04-20 17:09:23 +020011442 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011443 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011444 if (PyTuple_Check(subobj)) {
11445 Py_ssize_t i;
11446 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
11447 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000011448 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011449 if (substring == NULL)
11450 return NULL;
11451 result = tailmatch(self, substring, start, end, -1);
11452 Py_DECREF(substring);
11453 if (result) {
11454 Py_RETURN_TRUE;
11455 }
11456 }
11457 /* nothing matched */
11458 Py_RETURN_FALSE;
11459 }
11460 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030011461 if (substring == NULL) {
11462 if (PyErr_ExceptionMatches(PyExc_TypeError))
11463 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
11464 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000011465 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030011466 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011467 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011469 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011470}
11471
11472
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011473PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011474 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000011476Return True if S ends with the specified suffix, False otherwise.\n\
11477With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011478With optional end, stop comparing S at that position.\n\
11479suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480
11481static PyObject *
11482unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000011483 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011485 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011486 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011487 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011488 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011489 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490
Jesus Ceaac451502011-04-20 17:09:23 +020011491 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011492 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011493 if (PyTuple_Check(subobj)) {
11494 Py_ssize_t i;
11495 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
11496 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000011497 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011498 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011499 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011500 result = tailmatch(self, substring, start, end, +1);
11501 Py_DECREF(substring);
11502 if (result) {
11503 Py_RETURN_TRUE;
11504 }
11505 }
11506 Py_RETURN_FALSE;
11507 }
11508 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030011509 if (substring == NULL) {
11510 if (PyErr_ExceptionMatches(PyExc_TypeError))
11511 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
11512 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000011513 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030011514 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011515 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011517 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518}
11519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011520#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000011521
11522PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011523 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000011524\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000011525Return a formatted version of S, using substitutions from args and kwargs.\n\
11526The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000011527
Eric Smith27bbca62010-11-04 17:06:58 +000011528PyDoc_STRVAR(format_map__doc__,
11529 "S.format_map(mapping) -> str\n\
11530\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000011531Return a formatted version of S, using substitutions from mapping.\n\
11532The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000011533
Eric Smith4a7d76d2008-05-30 18:10:19 +000011534static PyObject *
11535unicode__format__(PyObject* self, PyObject* args)
11536{
11537 PyObject *format_spec;
11538
11539 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
11540 return NULL;
11541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 return _PyUnicode_FormatAdvanced(self, format_spec, 0,
11543 PyUnicode_GET_LENGTH(format_spec));
Eric Smith4a7d76d2008-05-30 18:10:19 +000011544}
11545
Eric Smith8c663262007-08-25 02:26:07 +000011546PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011547 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000011548\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000011549Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000011550
11551static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +000011552unicode__sizeof__(PyUnicodeObject *v)
11553{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011554 Py_ssize_t size;
11555
11556 /* If it's a compact object, account for base structure +
11557 character data. */
11558 if (PyUnicode_IS_COMPACT_ASCII(v))
11559 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
11560 else if (PyUnicode_IS_COMPACT(v))
11561 size = sizeof(PyCompactUnicodeObject) +
11562 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_CHARACTER_SIZE(v);
11563 else {
11564 /* If it is a two-block object, account for base object, and
11565 for character block if present. */
11566 size = sizeof(PyUnicodeObject);
11567 if (v->data.any)
11568 size += (PyUnicode_GET_LENGTH(v) + 1) *
11569 PyUnicode_CHARACTER_SIZE(v);
11570 }
11571 /* If the wstr pointer is present, account for it unless it is shared
11572 with the data pointer. Since PyUnicode_DATA will crash if the object
11573 is not ready, check whether it's either not ready (in which case the
11574 data is entirely in wstr) or if the data is not shared. */
11575 if (_PyUnicode_WSTR(v) &&
11576 (!PyUnicode_IS_READY(v) ||
11577 (PyUnicode_DATA(v) != _PyUnicode_WSTR(v))))
11578 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
11579 if (_PyUnicode_UTF8(v) && _PyUnicode_UTF8(v) != PyUnicode_DATA(v))
11580 size += _PyUnicode_UTF8_LENGTH(v) + 1;
11581
11582 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000011583}
11584
11585PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011586 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000011587
11588static PyObject *
Guido van Rossum5d9113d2003-01-29 17:58:45 +000011589unicode_getnewargs(PyUnicodeObject *v)
11590{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011591 PyObject *copy;
11592 unsigned char *data;
11593 int kind;
11594 if (PyUnicode_READY(v) == -1)
11595 return NULL;
11596 kind = PyUnicode_KIND(v);
11597 data = PyUnicode_1BYTE_DATA(v);
11598 copy = PyUnicode_FromKindAndData(kind, data, PyUnicode_GET_LENGTH(v));
11599 if (!copy)
11600 return NULL;
11601 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000011602}
11603
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604static PyMethodDef unicode_methods[] = {
11605
11606 /* Order is according to common usage: often used methods should
11607 appear first, since lookup is done sequentially. */
11608
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000011609 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011610 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
11611 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011612 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011613 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
11614 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
11615 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
11616 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
11617 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
11618 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
11619 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000011620 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011621 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
11622 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
11623 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011624 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011625 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
11626 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
11627 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011628 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000011629 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011630 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011631 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011632 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
11633 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
11634 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
11635 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
11636 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
11637 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
11638 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
11639 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
11640 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
11641 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
11642 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
11643 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
11644 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
11645 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000011646 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000011647 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011648 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000011649 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000011650 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000011651 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000011652 {"maketrans", (PyCFunction) unicode_maketrans,
11653 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000011654 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000011655#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011656 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000011657#endif
11658
11659#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011660 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011661 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000011662#endif
11663
Benjamin Peterson14339b62009-01-31 16:36:08 +000011664 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665 {NULL, NULL}
11666};
11667
Neil Schemenauerce30bc92002-11-18 16:10:18 +000011668static PyObject *
11669unicode_mod(PyObject *v, PyObject *w)
11670{
Brian Curtindfc80e32011-08-10 20:28:54 -050011671 if (!PyUnicode_Check(v))
11672 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000011673 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000011674}
11675
11676static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011677 0, /*nb_add*/
11678 0, /*nb_subtract*/
11679 0, /*nb_multiply*/
11680 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000011681};
11682
Guido van Rossumd57fd912000-03-10 22:53:23 +000011683static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011684 (lenfunc) unicode_length, /* sq_length */
11685 PyUnicode_Concat, /* sq_concat */
11686 (ssizeargfunc) unicode_repeat, /* sq_repeat */
11687 (ssizeargfunc) unicode_getitem, /* sq_item */
11688 0, /* sq_slice */
11689 0, /* sq_ass_item */
11690 0, /* sq_ass_slice */
11691 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692};
11693
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011694static PyObject*
11695unicode_subscript(PyUnicodeObject* self, PyObject* item)
11696{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011697 if (PyUnicode_READY(self) == -1)
11698 return NULL;
11699
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011700 if (PyIndex_Check(item)) {
11701 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011702 if (i == -1 && PyErr_Occurred())
11703 return NULL;
11704 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 i += PyUnicode_GET_LENGTH(self);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011706 return unicode_getitem(self, i);
11707 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000011708 Py_ssize_t start, stop, step, slicelength, cur, i;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011709 const Py_UNICODE* source_buf;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011710 Py_UNICODE* result_buf;
11711 PyObject* result;
11712
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011713 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000011714 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011715 return NULL;
11716 }
11717
11718 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011719 return PyUnicode_New(0, 0);
11720 } else if (start == 0 && step == 1 &&
11721 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000011722 PyUnicode_CheckExact(self)) {
11723 Py_INCREF(self);
11724 return (PyObject *)self;
11725 } else if (step == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 return substring(self, start, slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011727 } else {
11728 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +000011729 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
11730 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011731
Benjamin Peterson29060642009-01-31 22:14:21 +000011732 if (result_buf == NULL)
11733 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011734
11735 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
11736 result_buf[i] = source_buf[cur];
11737 }
Tim Petersced69f82003-09-16 20:30:58 +000011738
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011739 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +000011740 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011741 return result;
11742 }
11743 } else {
11744 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
11745 return NULL;
11746 }
11747}
11748
11749static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011750 (lenfunc)unicode_length, /* mp_length */
11751 (binaryfunc)unicode_subscript, /* mp_subscript */
11752 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011753};
11754
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756/* Helpers for PyUnicode_Format() */
11757
11758static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000011759getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011761 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011762 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011763 (*p_argidx)++;
11764 if (arglen < 0)
11765 return args;
11766 else
11767 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768 }
11769 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011770 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011771 return NULL;
11772}
11773
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011774/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011776static PyObject *
11777formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011779 char *p;
11780 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011781 double x;
Tim Petersced69f82003-09-16 20:30:58 +000011782
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783 x = PyFloat_AsDouble(v);
11784 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011785 return NULL;
11786
Guido van Rossumd57fd912000-03-10 22:53:23 +000011787 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011788 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000011789
Eric Smith0923d1d2009-04-16 20:16:10 +000011790 p = PyOS_double_to_string(x, type, prec,
11791 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011792 if (p == NULL)
11793 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011794 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000011795 PyMem_Free(p);
11796 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011797}
11798
Tim Peters38fd5b62000-09-21 05:43:11 +000011799static PyObject*
11800formatlong(PyObject *val, int flags, int prec, int type)
11801{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011802 char *buf;
11803 int len;
11804 PyObject *str; /* temporary string object. */
11805 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000011806
Benjamin Peterson14339b62009-01-31 16:36:08 +000011807 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
11808 if (!str)
11809 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011811 Py_DECREF(str);
11812 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000011813}
11814
Guido van Rossumd57fd912000-03-10 22:53:23 +000011815static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816formatchar(Py_UCS4 *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000011817 size_t buflen,
11818 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000011820 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000011821 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011822 if (PyUnicode_GET_LENGTH(v) == 1) {
11823 buf[0] = PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000011824 buf[1] = '\0';
11825 return 1;
11826 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011827 goto onError;
11828 }
11829 else {
11830 /* Integer input truncated to a character */
11831 long x;
11832 x = PyLong_AsLong(v);
11833 if (x == -1 && PyErr_Occurred())
11834 goto onError;
11835
11836 if (x < 0 || x > 0x10ffff) {
11837 PyErr_SetString(PyExc_OverflowError,
11838 "%c arg not in range(0x110000)");
11839 return -1;
11840 }
11841
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011842 buf[0] = (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011843 buf[1] = '\0';
11844 return 1;
11845 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000011846
Benjamin Peterson29060642009-01-31 22:14:21 +000011847 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000011848 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011849 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000011850 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011851}
11852
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000011853/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011854 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000011855*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011856#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000011857
Alexander Belopolsky40018472011-02-26 01:02:56 +000011858PyObject *
11859PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861 void *fmt;
11862 int fmtkind;
11863 PyObject *result;
11864 Py_UCS4 *res, *res0;
11865 Py_UCS4 max;
11866 int kind;
11867 Py_ssize_t fmtcnt, fmtpos, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869 PyObject *dict = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011870 PyUnicodeObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +000011871
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011873 PyErr_BadInternalCall();
11874 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011876 uformat = (PyUnicodeObject*)PyUnicode_FromObject(format);
11877 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011878 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011879 fmt = PyUnicode_DATA(uformat);
11880 fmtkind = PyUnicode_KIND(uformat);
11881 fmtcnt = PyUnicode_GET_LENGTH(uformat);
11882 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883
11884 reslen = rescnt = fmtcnt + 100;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011885 res = res0 = PyMem_Malloc(reslen * sizeof(Py_UCS4));
11886 if (res0 == NULL) {
11887 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000011888 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011890
11891 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011892 arglen = PyTuple_Size(args);
11893 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894 }
11895 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011896 arglen = -1;
11897 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011898 }
Christian Heimes90aa7642007-12-19 02:45:37 +000011899 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000011900 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000011901 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902
11903 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011904 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011905 if (--rescnt < 0) {
11906 rescnt = fmtcnt + 100;
11907 reslen += rescnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011908 res0 = PyMem_Realloc(res0, reslen*sizeof(Py_UCS4));
11909 if (res0 == NULL){
11910 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000011911 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011912 }
11913 res = res0 + reslen - rescnt;
Benjamin Peterson29060642009-01-31 22:14:21 +000011914 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011915 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011916 *res++ = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011917 }
11918 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011919 /* Got a format specifier */
11920 int flags = 0;
11921 Py_ssize_t width = -1;
11922 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011923 Py_UCS4 c = '\0';
11924 Py_UCS4 fill;
Benjamin Peterson29060642009-01-31 22:14:21 +000011925 int isnumok;
11926 PyObject *v = NULL;
11927 PyObject *temp = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011928 void *pbuf;
11929 Py_ssize_t pindex;
Benjamin Peterson29060642009-01-31 22:14:21 +000011930 Py_UNICODE sign;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011931 Py_ssize_t len, len1;
11932 Py_UCS4 formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011934 fmtpos++;
11935 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
11936 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000011937 Py_ssize_t keylen;
11938 PyObject *key;
11939 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000011940
Benjamin Peterson29060642009-01-31 22:14:21 +000011941 if (dict == NULL) {
11942 PyErr_SetString(PyExc_TypeError,
11943 "format requires a mapping");
11944 goto onError;
11945 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011946 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000011947 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011948 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000011949 /* Skip over balanced parentheses */
11950 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011951 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000011952 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000011954 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011955 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000011956 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011957 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011958 if (fmtcnt < 0 || pcount > 0) {
11959 PyErr_SetString(PyExc_ValueError,
11960 "incomplete format key");
11961 goto onError;
11962 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011963 key = substring(uformat, keystart, keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000011964 if (key == NULL)
11965 goto onError;
11966 if (args_owned) {
11967 Py_DECREF(args);
11968 args_owned = 0;
11969 }
11970 args = PyObject_GetItem(dict, key);
11971 Py_DECREF(key);
11972 if (args == NULL) {
11973 goto onError;
11974 }
11975 args_owned = 1;
11976 arglen = -1;
11977 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011978 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011979 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011980 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011981 case '-': flags |= F_LJUST; continue;
11982 case '+': flags |= F_SIGN; continue;
11983 case ' ': flags |= F_BLANK; continue;
11984 case '#': flags |= F_ALT; continue;
11985 case '0': flags |= F_ZERO; continue;
11986 }
11987 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011988 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011989 if (c == '*') {
11990 v = getnextarg(args, arglen, &argidx);
11991 if (v == NULL)
11992 goto onError;
11993 if (!PyLong_Check(v)) {
11994 PyErr_SetString(PyExc_TypeError,
11995 "* wants int");
11996 goto onError;
11997 }
11998 width = PyLong_AsLong(v);
11999 if (width == -1 && PyErr_Occurred())
12000 goto onError;
12001 if (width < 0) {
12002 flags |= F_LJUST;
12003 width = -width;
12004 }
12005 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012006 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012007 }
12008 else if (c >= '0' && c <= '9') {
12009 width = c - '0';
12010 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012012 if (c < '0' || c > '9')
12013 break;
12014 if ((width*10) / 10 != width) {
12015 PyErr_SetString(PyExc_ValueError,
12016 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000012017 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000012018 }
12019 width = width*10 + (c - '0');
12020 }
12021 }
12022 if (c == '.') {
12023 prec = 0;
12024 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012025 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012026 if (c == '*') {
12027 v = getnextarg(args, arglen, &argidx);
12028 if (v == NULL)
12029 goto onError;
12030 if (!PyLong_Check(v)) {
12031 PyErr_SetString(PyExc_TypeError,
12032 "* wants int");
12033 goto onError;
12034 }
12035 prec = PyLong_AsLong(v);
12036 if (prec == -1 && PyErr_Occurred())
12037 goto onError;
12038 if (prec < 0)
12039 prec = 0;
12040 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012041 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012042 }
12043 else if (c >= '0' && c <= '9') {
12044 prec = c - '0';
12045 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012047 if (c < '0' || c > '9')
12048 break;
12049 if ((prec*10) / 10 != prec) {
12050 PyErr_SetString(PyExc_ValueError,
12051 "prec too big");
12052 goto onError;
12053 }
12054 prec = prec*10 + (c - '0');
12055 }
12056 }
12057 } /* prec */
12058 if (fmtcnt >= 0) {
12059 if (c == 'h' || c == 'l' || c == 'L') {
12060 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012061 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012062 }
12063 }
12064 if (fmtcnt < 0) {
12065 PyErr_SetString(PyExc_ValueError,
12066 "incomplete format");
12067 goto onError;
12068 }
12069 if (c != '%') {
12070 v = getnextarg(args, arglen, &argidx);
12071 if (v == NULL)
12072 goto onError;
12073 }
12074 sign = 0;
12075 fill = ' ';
12076 switch (c) {
12077
12078 case '%':
12079 pbuf = formatbuf;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012080 kind = PyUnicode_4BYTE_KIND;
Benjamin Peterson29060642009-01-31 22:14:21 +000012081 /* presume that buffer length is at least 1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012082 PyUnicode_WRITE(kind, pbuf, 0, '%');
Benjamin Peterson29060642009-01-31 22:14:21 +000012083 len = 1;
12084 break;
12085
12086 case 's':
12087 case 'r':
12088 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000012089 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000012090 temp = v;
12091 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012092 }
12093 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012094 if (c == 's')
12095 temp = PyObject_Str(v);
12096 else if (c == 'r')
12097 temp = PyObject_Repr(v);
12098 else
12099 temp = PyObject_ASCII(v);
12100 if (temp == NULL)
12101 goto onError;
12102 if (PyUnicode_Check(temp))
12103 /* nothing to do */;
12104 else {
12105 Py_DECREF(temp);
12106 PyErr_SetString(PyExc_TypeError,
12107 "%s argument has non-string str()");
12108 goto onError;
12109 }
12110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012111 if (PyUnicode_READY(temp) == -1) {
12112 Py_CLEAR(temp);
12113 goto onError;
12114 }
12115 pbuf = PyUnicode_DATA(temp);
12116 kind = PyUnicode_KIND(temp);
12117 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012118 if (prec >= 0 && len > prec)
12119 len = prec;
12120 break;
12121
12122 case 'i':
12123 case 'd':
12124 case 'u':
12125 case 'o':
12126 case 'x':
12127 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000012128 isnumok = 0;
12129 if (PyNumber_Check(v)) {
12130 PyObject *iobj=NULL;
12131
12132 if (PyLong_Check(v)) {
12133 iobj = v;
12134 Py_INCREF(iobj);
12135 }
12136 else {
12137 iobj = PyNumber_Long(v);
12138 }
12139 if (iobj!=NULL) {
12140 if (PyLong_Check(iobj)) {
12141 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070012142 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000012143 Py_DECREF(iobj);
12144 if (!temp)
12145 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012146 if (PyUnicode_READY(temp) == -1) {
12147 Py_CLEAR(temp);
12148 goto onError;
12149 }
12150 pbuf = PyUnicode_DATA(temp);
12151 kind = PyUnicode_KIND(temp);
12152 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012153 sign = 1;
12154 }
12155 else {
12156 Py_DECREF(iobj);
12157 }
12158 }
12159 }
12160 if (!isnumok) {
12161 PyErr_Format(PyExc_TypeError,
12162 "%%%c format: a number is required, "
12163 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
12164 goto onError;
12165 }
12166 if (flags & F_ZERO)
12167 fill = '0';
12168 break;
12169
12170 case 'e':
12171 case 'E':
12172 case 'f':
12173 case 'F':
12174 case 'g':
12175 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012176 temp = formatfloat(v, flags, prec, c);
12177 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000012178 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012179 if (PyUnicode_READY(temp) == -1) {
12180 Py_CLEAR(temp);
12181 goto onError;
12182 }
12183 pbuf = PyUnicode_DATA(temp);
12184 kind = PyUnicode_KIND(temp);
12185 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012186 sign = 1;
12187 if (flags & F_ZERO)
12188 fill = '0';
12189 break;
12190
12191 case 'c':
12192 pbuf = formatbuf;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012193 kind = PyUnicode_4BYTE_KIND;
Benjamin Peterson29060642009-01-31 22:14:21 +000012194 len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
12195 if (len < 0)
12196 goto onError;
12197 break;
12198
12199 default:
12200 PyErr_Format(PyExc_ValueError,
12201 "unsupported format character '%c' (0x%x) "
12202 "at index %zd",
12203 (31<=c && c<=126) ? (char)c : '?',
12204 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012205 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000012206 goto onError;
12207 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012208 /* pbuf is initialized here. */
12209 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000012210 if (sign) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012211 if (PyUnicode_READ(kind, pbuf, pindex) == '-' ||
12212 PyUnicode_READ(kind, pbuf, pindex) == '+') {
12213 sign = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012214 len--;
12215 }
12216 else if (flags & F_SIGN)
12217 sign = '+';
12218 else if (flags & F_BLANK)
12219 sign = ' ';
12220 else
12221 sign = 0;
12222 }
12223 if (width < len)
12224 width = len;
12225 if (rescnt - (sign != 0) < width) {
12226 reslen -= rescnt;
12227 rescnt = width + fmtcnt + 100;
12228 reslen += rescnt;
12229 if (reslen < 0) {
12230 Py_XDECREF(temp);
12231 PyErr_NoMemory();
12232 goto onError;
12233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012234 res0 = PyMem_Realloc(res0, reslen*sizeof(Py_UCS4));
12235 if (res0 == 0) {
12236 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000012237 Py_XDECREF(temp);
12238 goto onError;
12239 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012240 res = res0 + reslen - rescnt;
Benjamin Peterson29060642009-01-31 22:14:21 +000012241 }
12242 if (sign) {
12243 if (fill != ' ')
12244 *res++ = sign;
12245 rescnt--;
12246 if (width > len)
12247 width--;
12248 }
12249 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012250 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
12251 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000012252 if (fill != ' ') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012253 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12254 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012255 }
12256 rescnt -= 2;
12257 width -= 2;
12258 if (width < 0)
12259 width = 0;
12260 len -= 2;
12261 }
12262 if (width > len && !(flags & F_LJUST)) {
12263 do {
12264 --rescnt;
12265 *res++ = fill;
12266 } while (--width > len);
12267 }
12268 if (fill == ' ') {
12269 if (sign)
12270 *res++ = sign;
12271 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012272 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
12273 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
12274 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12275 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012276 }
12277 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012278 /* Copy all characters, preserving len */
12279 len1 = len;
12280 while (len1--) {
12281 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12282 rescnt--;
12283 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012284 while (--width >= len) {
12285 --rescnt;
12286 *res++ = ' ';
12287 }
12288 if (dict && (argidx < arglen) && c != '%') {
12289 PyErr_SetString(PyExc_TypeError,
12290 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +000012291 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012292 goto onError;
12293 }
12294 Py_XDECREF(temp);
12295 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296 } /* until end */
12297 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012298 PyErr_SetString(PyExc_TypeError,
12299 "not all arguments converted during string formatting");
12300 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012301 }
12302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012303
12304 for (max=0, res = res0; res < res0+reslen-rescnt; res++)
12305 if (*res > max)
12306 max = *res;
12307 result = PyUnicode_New(reslen - rescnt, max);
12308 if (!result)
Benjamin Peterson29060642009-01-31 22:14:21 +000012309 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012310 kind = PyUnicode_KIND(result);
12311 for (res = res0; res < res0+reslen-rescnt; res++)
12312 PyUnicode_WRITE(kind, PyUnicode_DATA(result), res-res0, *res);
12313 PyMem_Free(res0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012314 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012315 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012316 }
12317 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012318 return (PyObject *)result;
12319
Benjamin Peterson29060642009-01-31 22:14:21 +000012320 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012321 PyMem_Free(res0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012322 Py_DECREF(uformat);
12323 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012324 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012325 }
12326 return NULL;
12327}
12328
Jeremy Hylton938ace62002-07-17 16:30:39 +000012329static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000012330unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
12331
Tim Peters6d6c1a32001-08-02 04:15:00 +000012332static PyObject *
12333unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
12334{
Benjamin Peterson29060642009-01-31 22:14:21 +000012335 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012336 static char *kwlist[] = {"object", "encoding", "errors", 0};
12337 char *encoding = NULL;
12338 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000012339
Benjamin Peterson14339b62009-01-31 16:36:08 +000012340 if (type != &PyUnicode_Type)
12341 return unicode_subtype_new(type, args, kwds);
12342 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000012343 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012344 return NULL;
12345 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012346 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012347 if (encoding == NULL && errors == NULL)
12348 return PyObject_Str(x);
12349 else
Benjamin Peterson29060642009-01-31 22:14:21 +000012350 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000012351}
12352
Guido van Rossume023fe02001-08-30 03:12:59 +000012353static PyObject *
12354unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
12355{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012356 PyUnicodeObject *tmp, *pnew;
12357 Py_ssize_t n;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012358 PyObject *err = NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000012359
Benjamin Peterson14339b62009-01-31 16:36:08 +000012360 assert(PyType_IsSubtype(type, &PyUnicode_Type));
12361 tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
12362 if (tmp == NULL)
12363 return NULL;
12364 assert(PyUnicode_Check(tmp));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012365 // TODO: Verify the PyUnicode_GET_SIZE does the right thing.
12366 // it seems kind of strange that tp_alloc gets passed the size
12367 // of the unicode string because there will follow another
12368 // malloc.
12369 pnew = (PyUnicodeObject *) type->tp_alloc(type,
12370 n = PyUnicode_GET_SIZE(tmp));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012371 if (pnew == NULL) {
12372 Py_DECREF(tmp);
12373 return NULL;
12374 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012375 _PyUnicode_WSTR(pnew) = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
12376 if (_PyUnicode_WSTR(pnew) == NULL) {
12377 err = PyErr_NoMemory();
12378 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012379 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012380 Py_UNICODE_COPY(_PyUnicode_WSTR(pnew), PyUnicode_AS_UNICODE(tmp), n+1);
12381 _PyUnicode_WSTR_LENGTH(pnew) = n;
12382 _PyUnicode_HASH(pnew) = _PyUnicode_HASH(tmp);
12383 _PyUnicode_STATE(pnew).interned = 0;
12384 _PyUnicode_STATE(pnew).kind = 0;
12385 _PyUnicode_STATE(pnew).compact = 0;
12386 _PyUnicode_STATE(pnew).ready = 0;
12387 _PyUnicode_STATE(pnew).ascii = 0;
12388 pnew->data.any = NULL;
12389 _PyUnicode_LENGTH(pnew) = 0;
12390 pnew->_base.utf8 = NULL;
12391 pnew->_base.utf8_length = 0;
12392
12393 if (PyUnicode_READY(pnew) == -1) {
12394 PyObject_FREE(_PyUnicode_WSTR(pnew));
12395 goto onError;
12396 }
12397
Benjamin Peterson14339b62009-01-31 16:36:08 +000012398 Py_DECREF(tmp);
12399 return (PyObject *)pnew;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012400
12401 onError:
12402 _Py_ForgetReference((PyObject *)pnew);
12403 PyObject_Del(pnew);
12404 Py_DECREF(tmp);
12405 return err;
Guido van Rossume023fe02001-08-30 03:12:59 +000012406}
12407
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012408PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000012409 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000012410\n\
Collin Winterd474ce82007-08-07 19:42:11 +000012411Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000012412encoding defaults to the current default string encoding.\n\
12413errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000012414
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012415static PyObject *unicode_iter(PyObject *seq);
12416
Guido van Rossumd57fd912000-03-10 22:53:23 +000012417PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000012418 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012419 "str", /* tp_name */
12420 sizeof(PyUnicodeObject), /* tp_size */
12421 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012422 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012423 (destructor)unicode_dealloc, /* tp_dealloc */
12424 0, /* tp_print */
12425 0, /* tp_getattr */
12426 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000012427 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012428 unicode_repr, /* tp_repr */
12429 &unicode_as_number, /* tp_as_number */
12430 &unicode_as_sequence, /* tp_as_sequence */
12431 &unicode_as_mapping, /* tp_as_mapping */
12432 (hashfunc) unicode_hash, /* tp_hash*/
12433 0, /* tp_call*/
12434 (reprfunc) unicode_str, /* tp_str */
12435 PyObject_GenericGetAttr, /* tp_getattro */
12436 0, /* tp_setattro */
12437 0, /* tp_as_buffer */
12438 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000012439 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012440 unicode_doc, /* tp_doc */
12441 0, /* tp_traverse */
12442 0, /* tp_clear */
12443 PyUnicode_RichCompare, /* tp_richcompare */
12444 0, /* tp_weaklistoffset */
12445 unicode_iter, /* tp_iter */
12446 0, /* tp_iternext */
12447 unicode_methods, /* tp_methods */
12448 0, /* tp_members */
12449 0, /* tp_getset */
12450 &PyBaseObject_Type, /* tp_base */
12451 0, /* tp_dict */
12452 0, /* tp_descr_get */
12453 0, /* tp_descr_set */
12454 0, /* tp_dictoffset */
12455 0, /* tp_init */
12456 0, /* tp_alloc */
12457 unicode_new, /* tp_new */
12458 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012459};
12460
12461/* Initialize the Unicode implementation */
12462
Thomas Wouters78890102000-07-22 19:25:51 +000012463void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012464{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012465 int i;
12466
Thomas Wouters477c8d52006-05-27 19:21:47 +000012467 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012468 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012469 0x000A, /* LINE FEED */
12470 0x000D, /* CARRIAGE RETURN */
12471 0x001C, /* FILE SEPARATOR */
12472 0x001D, /* GROUP SEPARATOR */
12473 0x001E, /* RECORD SEPARATOR */
12474 0x0085, /* NEXT LINE */
12475 0x2028, /* LINE SEPARATOR */
12476 0x2029, /* PARAGRAPH SEPARATOR */
12477 };
12478
Fred Drakee4315f52000-05-09 19:53:39 +000012479 /* Init the implementation */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012480 unicode_empty = (PyUnicodeObject *) PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012481 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012483
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012484 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000012485 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000012486 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012487 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012488
12489 /* initialize the linebreak bloom filter */
12490 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012491 PyUnicode_2BYTE_KIND, linebreak,
12492 sizeof(linebreak) / sizeof(linebreak[0]));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012493
12494 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495}
12496
12497/* Finalize the Unicode implementation */
12498
Christian Heimesa156e092008-02-16 07:38:31 +000012499int
12500PyUnicode_ClearFreeList(void)
12501{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012502 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000012503}
12504
Guido van Rossumd57fd912000-03-10 22:53:23 +000012505void
Thomas Wouters78890102000-07-22 19:25:51 +000012506_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012507{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012508 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012509
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000012510 Py_XDECREF(unicode_empty);
12511 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000012512
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012513 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012514 if (unicode_latin1[i]) {
12515 Py_DECREF(unicode_latin1[i]);
12516 unicode_latin1[i] = NULL;
12517 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012518 }
Christian Heimesa156e092008-02-16 07:38:31 +000012519 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012520}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000012521
Walter Dörwald16807132007-05-25 13:52:07 +000012522void
12523PyUnicode_InternInPlace(PyObject **p)
12524{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012525 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
12526 PyObject *t;
12527 if (s == NULL || !PyUnicode_Check(s))
12528 Py_FatalError(
12529 "PyUnicode_InternInPlace: unicode strings only please!");
12530 /* If it's a subclass, we don't really know what putting
12531 it in the interned dict might do. */
12532 if (!PyUnicode_CheckExact(s))
12533 return;
12534 if (PyUnicode_CHECK_INTERNED(s))
12535 return;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012536 if (PyUnicode_READY(s) == -1) {
12537 assert(0 && "ready fail in intern...");
12538 return;
12539 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012540 if (interned == NULL) {
12541 interned = PyDict_New();
12542 if (interned == NULL) {
12543 PyErr_Clear(); /* Don't leave an exception */
12544 return;
12545 }
12546 }
12547 /* It might be that the GetItem call fails even
12548 though the key is present in the dictionary,
12549 namely when this happens during a stack overflow. */
12550 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000012551 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012552 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000012553
Benjamin Peterson29060642009-01-31 22:14:21 +000012554 if (t) {
12555 Py_INCREF(t);
12556 Py_DECREF(*p);
12557 *p = t;
12558 return;
12559 }
Walter Dörwald16807132007-05-25 13:52:07 +000012560
Benjamin Peterson14339b62009-01-31 16:36:08 +000012561 PyThreadState_GET()->recursion_critical = 1;
12562 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
12563 PyErr_Clear();
12564 PyThreadState_GET()->recursion_critical = 0;
12565 return;
12566 }
12567 PyThreadState_GET()->recursion_critical = 0;
12568 /* The two references in interned are not counted by refcnt.
12569 The deallocator will take care of this */
12570 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000012572}
12573
12574void
12575PyUnicode_InternImmortal(PyObject **p)
12576{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012577 PyUnicodeObject *u = (PyUnicodeObject *)*p;
12578
Benjamin Peterson14339b62009-01-31 16:36:08 +000012579 PyUnicode_InternInPlace(p);
12580 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012581 _PyUnicode_STATE(u).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012582 Py_INCREF(*p);
12583 }
Walter Dörwald16807132007-05-25 13:52:07 +000012584}
12585
12586PyObject *
12587PyUnicode_InternFromString(const char *cp)
12588{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012589 PyObject *s = PyUnicode_FromString(cp);
12590 if (s == NULL)
12591 return NULL;
12592 PyUnicode_InternInPlace(&s);
12593 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000012594}
12595
Alexander Belopolsky40018472011-02-26 01:02:56 +000012596void
12597_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000012598{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012599 PyObject *keys;
12600 PyUnicodeObject *s;
12601 Py_ssize_t i, n;
12602 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000012603
Benjamin Peterson14339b62009-01-31 16:36:08 +000012604 if (interned == NULL || !PyDict_Check(interned))
12605 return;
12606 keys = PyDict_Keys(interned);
12607 if (keys == NULL || !PyList_Check(keys)) {
12608 PyErr_Clear();
12609 return;
12610 }
Walter Dörwald16807132007-05-25 13:52:07 +000012611
Benjamin Peterson14339b62009-01-31 16:36:08 +000012612 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
12613 detector, interned unicode strings are not forcibly deallocated;
12614 rather, we give them their stolen references back, and then clear
12615 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000012616
Benjamin Peterson14339b62009-01-31 16:36:08 +000012617 n = PyList_GET_SIZE(keys);
12618 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000012619 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012620 for (i = 0; i < n; i++) {
12621 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012622 if (PyUnicode_READY(s) == -1)
12623 fprintf(stderr, "could not ready string\n");
12624 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012625 case SSTATE_NOT_INTERNED:
12626 /* XXX Shouldn't happen */
12627 break;
12628 case SSTATE_INTERNED_IMMORTAL:
12629 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012630 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012631 break;
12632 case SSTATE_INTERNED_MORTAL:
12633 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012635 break;
12636 default:
12637 Py_FatalError("Inconsistent interned string state.");
12638 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012639 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012640 }
12641 fprintf(stderr, "total size of all interned strings: "
12642 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
12643 "mortal/immortal\n", mortal_size, immortal_size);
12644 Py_DECREF(keys);
12645 PyDict_Clear(interned);
12646 Py_DECREF(interned);
12647 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000012648}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012649
12650
12651/********************* Unicode Iterator **************************/
12652
12653typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012654 PyObject_HEAD
12655 Py_ssize_t it_index;
12656 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012657} unicodeiterobject;
12658
12659static void
12660unicodeiter_dealloc(unicodeiterobject *it)
12661{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012662 _PyObject_GC_UNTRACK(it);
12663 Py_XDECREF(it->it_seq);
12664 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012665}
12666
12667static int
12668unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
12669{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012670 Py_VISIT(it->it_seq);
12671 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012672}
12673
12674static PyObject *
12675unicodeiter_next(unicodeiterobject *it)
12676{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012677 PyUnicodeObject *seq;
12678 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012679
Benjamin Peterson14339b62009-01-31 16:36:08 +000012680 assert(it != NULL);
12681 seq = it->it_seq;
12682 if (seq == NULL)
12683 return NULL;
12684 assert(PyUnicode_Check(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012685
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012686 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
12687 int kind = PyUnicode_KIND(seq);
12688 void *data = PyUnicode_DATA(seq);
12689 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
12690 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012691 if (item != NULL)
12692 ++it->it_index;
12693 return item;
12694 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012695
Benjamin Peterson14339b62009-01-31 16:36:08 +000012696 Py_DECREF(seq);
12697 it->it_seq = NULL;
12698 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012699}
12700
12701static PyObject *
12702unicodeiter_len(unicodeiterobject *it)
12703{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012704 Py_ssize_t len = 0;
12705 if (it->it_seq)
12706 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
12707 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012708}
12709
12710PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
12711
12712static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012713 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000012714 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000012715 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012716};
12717
12718PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012719 PyVarObject_HEAD_INIT(&PyType_Type, 0)
12720 "str_iterator", /* tp_name */
12721 sizeof(unicodeiterobject), /* tp_basicsize */
12722 0, /* tp_itemsize */
12723 /* methods */
12724 (destructor)unicodeiter_dealloc, /* tp_dealloc */
12725 0, /* tp_print */
12726 0, /* tp_getattr */
12727 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000012728 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012729 0, /* tp_repr */
12730 0, /* tp_as_number */
12731 0, /* tp_as_sequence */
12732 0, /* tp_as_mapping */
12733 0, /* tp_hash */
12734 0, /* tp_call */
12735 0, /* tp_str */
12736 PyObject_GenericGetAttr, /* tp_getattro */
12737 0, /* tp_setattro */
12738 0, /* tp_as_buffer */
12739 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
12740 0, /* tp_doc */
12741 (traverseproc)unicodeiter_traverse, /* tp_traverse */
12742 0, /* tp_clear */
12743 0, /* tp_richcompare */
12744 0, /* tp_weaklistoffset */
12745 PyObject_SelfIter, /* tp_iter */
12746 (iternextfunc)unicodeiter_next, /* tp_iternext */
12747 unicodeiter_methods, /* tp_methods */
12748 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012749};
12750
12751static PyObject *
12752unicode_iter(PyObject *seq)
12753{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012754 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012755
Benjamin Peterson14339b62009-01-31 16:36:08 +000012756 if (!PyUnicode_Check(seq)) {
12757 PyErr_BadInternalCall();
12758 return NULL;
12759 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012760 if (PyUnicode_READY(seq) == -1)
12761 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012762 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
12763 if (it == NULL)
12764 return NULL;
12765 it->it_index = 0;
12766 Py_INCREF(seq);
12767 it->it_seq = (PyUnicodeObject *)seq;
12768 _PyObject_GC_TRACK(it);
12769 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012770}
12771
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012772#define UNIOP(x) Py_UNICODE_##x
12773#define UNIOP_t Py_UNICODE
12774#include "uniops.h"
12775#undef UNIOP
12776#undef UNIOP_t
12777#define UNIOP(x) Py_UCS4_##x
12778#define UNIOP_t Py_UCS4
12779#include "uniops.h"
12780#undef UNIOP
12781#undef UNIOP_t
Victor Stinner331ea922010-08-10 16:37:20 +000012782
Victor Stinner71133ff2010-09-01 23:43:53 +000012783Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000012784PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000012785{
12786 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
12787 Py_UNICODE *copy;
12788 Py_ssize_t size;
12789
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012790 if (!PyUnicode_Check(unicode)) {
12791 PyErr_BadArgument();
12792 return NULL;
12793 }
Victor Stinner71133ff2010-09-01 23:43:53 +000012794 /* Ensure we won't overflow the size. */
12795 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
12796 PyErr_NoMemory();
12797 return NULL;
12798 }
12799 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
12800 size *= sizeof(Py_UNICODE);
12801 copy = PyMem_Malloc(size);
12802 if (copy == NULL) {
12803 PyErr_NoMemory();
12804 return NULL;
12805 }
12806 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
12807 return copy;
12808}
Martin v. Löwis5b222132007-06-10 09:51:05 +000012809
Georg Brandl66c221e2010-10-14 07:04:07 +000012810/* A _string module, to export formatter_parser and formatter_field_name_split
12811 to the string.Formatter class implemented in Python. */
12812
12813static PyMethodDef _string_methods[] = {
12814 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
12815 METH_O, PyDoc_STR("split the argument as a field name")},
12816 {"formatter_parser", (PyCFunction) formatter_parser,
12817 METH_O, PyDoc_STR("parse the argument as a format string")},
12818 {NULL, NULL}
12819};
12820
12821static struct PyModuleDef _string_module = {
12822 PyModuleDef_HEAD_INIT,
12823 "_string",
12824 PyDoc_STR("string helper module"),
12825 0,
12826 _string_methods,
12827 NULL,
12828 NULL,
12829 NULL,
12830 NULL
12831};
12832
12833PyMODINIT_FUNC
12834PyInit__string(void)
12835{
12836 return PyModule_Create(&_string_module);
12837}
12838
12839
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012840#ifdef __cplusplus
12841}
12842#endif