blob: d0321baa244b6ca609fab62af560c2c19e7c8372 [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,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070045#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000046
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000047#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000048#include <windows.h>
49#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000050
Larry Hastings61272b72014-01-07 12:41:53 -080051/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -080052class str "PyUnicodeObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080053[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080054/*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080055
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000056/* --- Globals ------------------------------------------------------------
57
Serhiy Storchaka05997252013-01-26 12:14:02 +020058NOTE: In the interpreter's initialization phase, some globals are currently
59 initialized dynamically as needed. In the process Unicode objects may
60 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061
62*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000063
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064
65#ifdef __cplusplus
66extern "C" {
67#endif
68
Victor Stinner8faf8212011-12-08 22:14:11 +010069/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
70#define MAX_UNICODE 0x10ffff
71
Victor Stinner910337b2011-10-03 03:20:16 +020072#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020073# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020074#else
75# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
76#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020077
Victor Stinnere90fe6a2011-10-01 16:48:13 +020078#define _PyUnicode_UTF8(op) \
79 (((PyCompactUnicodeObject*)(op))->utf8)
80#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020081 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020082 assert(PyUnicode_IS_READY(op)), \
83 PyUnicode_IS_COMPACT_ASCII(op) ? \
84 ((char*)((PyASCIIObject*)(op) + 1)) : \
85 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020086#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020087 (((PyCompactUnicodeObject*)(op))->utf8_length)
88#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020089 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020090 assert(PyUnicode_IS_READY(op)), \
91 PyUnicode_IS_COMPACT_ASCII(op) ? \
92 ((PyASCIIObject*)(op))->length : \
93 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020094#define _PyUnicode_WSTR(op) \
95 (((PyASCIIObject*)(op))->wstr)
96#define _PyUnicode_WSTR_LENGTH(op) \
97 (((PyCompactUnicodeObject*)(op))->wstr_length)
98#define _PyUnicode_LENGTH(op) \
99 (((PyASCIIObject *)(op))->length)
100#define _PyUnicode_STATE(op) \
101 (((PyASCIIObject *)(op))->state)
102#define _PyUnicode_HASH(op) \
103 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200104#define _PyUnicode_KIND(op) \
105 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200106 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200107#define _PyUnicode_GET_LENGTH(op) \
108 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200109 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200110#define _PyUnicode_DATA_ANY(op) \
111 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200112
Victor Stinner910337b2011-10-03 03:20:16 +0200113#undef PyUnicode_READY
114#define PyUnicode_READY(op) \
115 (assert(_PyUnicode_CHECK(op)), \
116 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200117 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100118 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200119
Victor Stinnerc379ead2011-10-03 12:52:27 +0200120#define _PyUnicode_SHARE_UTF8(op) \
121 (assert(_PyUnicode_CHECK(op)), \
122 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
123 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
124#define _PyUnicode_SHARE_WSTR(op) \
125 (assert(_PyUnicode_CHECK(op)), \
126 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
127
Victor Stinner829c0ad2011-10-03 01:08:02 +0200128/* true if the Unicode object has an allocated UTF-8 memory block
129 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200130#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200131 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200132 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200133 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
134
Victor Stinner03490912011-10-03 23:45:12 +0200135/* true if the Unicode object has an allocated wstr memory block
136 (not shared with other data) */
137#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200138 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200139 (!PyUnicode_IS_READY(op) || \
140 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
141
Victor Stinner910337b2011-10-03 03:20:16 +0200142/* Generic helper macro to convert characters of different types.
143 from_type and to_type have to be valid type names, begin and end
144 are pointers to the source characters which should be of type
145 "from_type *". to is a pointer of type "to_type *" and points to the
146 buffer where the result characters are written to. */
147#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
148 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100149 to_type *_to = (to_type *)(to); \
150 const from_type *_iter = (from_type *)(begin); \
151 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200152 Py_ssize_t n = (_end) - (_iter); \
153 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200154 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200155 while (_iter < (_unrolled_end)) { \
156 _to[0] = (to_type) _iter[0]; \
157 _to[1] = (to_type) _iter[1]; \
158 _to[2] = (to_type) _iter[2]; \
159 _to[3] = (to_type) _iter[3]; \
160 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200161 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200162 while (_iter < (_end)) \
163 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200164 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200165
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200166#ifdef MS_WINDOWS
167 /* On Windows, overallocate by 50% is the best factor */
168# define OVERALLOCATE_FACTOR 2
169#else
170 /* On Linux, overallocate by 25% is the best factor */
171# define OVERALLOCATE_FACTOR 4
172#endif
173
Walter Dörwald16807132007-05-25 13:52:07 +0000174/* This dictionary holds all interned unicode strings. Note that references
175 to strings in this dictionary are *not* counted in the string's ob_refcnt.
176 When the interned string reaches a refcnt of 0 the string deallocation
177 function will delete the reference from this dictionary.
178
179 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000180 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000181*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200182static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000183
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000184/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200185static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200186
Serhiy Storchaka678db842013-01-26 12:16:36 +0200187#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200188 do { \
189 if (unicode_empty != NULL) \
190 Py_INCREF(unicode_empty); \
191 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200192 unicode_empty = PyUnicode_New(0, 0); \
193 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200194 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200195 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
196 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200197 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200198 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000199
Serhiy Storchaka678db842013-01-26 12:16:36 +0200200#define _Py_RETURN_UNICODE_EMPTY() \
201 do { \
202 _Py_INCREF_UNICODE_EMPTY(); \
203 return unicode_empty; \
204 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000205
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200206/* Forward declaration */
207Py_LOCAL_INLINE(int)
208_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
209
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200210/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200211static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200212
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000213/* Single character Unicode strings in the Latin-1 range are being
214 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200215static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000216
Christian Heimes190d79e2008-01-30 11:58:22 +0000217/* Fast detection of the most frequent whitespace characters */
218const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000219 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000220/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000221/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000222/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000223/* case 0x000C: * FORM FEED */
224/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000225 0, 1, 1, 1, 1, 1, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000227/* case 0x001C: * FILE SEPARATOR */
228/* case 0x001D: * GROUP SEPARATOR */
229/* case 0x001E: * RECORD SEPARATOR */
230/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000231 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000232/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000233 1, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000237
Benjamin Peterson14339b62009-01-31 16:36:08 +0000238 0, 0, 0, 0, 0, 0, 0, 0,
239 0, 0, 0, 0, 0, 0, 0, 0,
240 0, 0, 0, 0, 0, 0, 0, 0,
241 0, 0, 0, 0, 0, 0, 0, 0,
242 0, 0, 0, 0, 0, 0, 0, 0,
243 0, 0, 0, 0, 0, 0, 0, 0,
244 0, 0, 0, 0, 0, 0, 0, 0,
245 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000246};
247
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200248/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200249static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200250static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100251static int unicode_modifiable(PyObject *unicode);
252
Victor Stinnerfe226c02011-10-03 03:52:20 +0200253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100255_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200256static PyObject *
257_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
258static PyObject *
259_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
260
261static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000262unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000263 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100264 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000265 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
266
Alexander Belopolsky40018472011-02-26 01:02:56 +0000267static void
268raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300269 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100270 PyObject *unicode,
271 Py_ssize_t startpos, Py_ssize_t endpos,
272 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000273
Christian Heimes190d79e2008-01-30 11:58:22 +0000274/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200275static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000276 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000277/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000278/* 0x000B, * LINE TABULATION */
279/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000280/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000281 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000282 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000283/* 0x001C, * FILE SEPARATOR */
284/* 0x001D, * GROUP SEPARATOR */
285/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000286 0, 0, 0, 0, 1, 1, 1, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000291
Benjamin Peterson14339b62009-01-31 16:36:08 +0000292 0, 0, 0, 0, 0, 0, 0, 0,
293 0, 0, 0, 0, 0, 0, 0, 0,
294 0, 0, 0, 0, 0, 0, 0, 0,
295 0, 0, 0, 0, 0, 0, 0, 0,
296 0, 0, 0, 0, 0, 0, 0, 0,
297 0, 0, 0, 0, 0, 0, 0, 0,
298 0, 0, 0, 0, 0, 0, 0, 0,
299 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000300};
301
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300302#include "clinic/unicodeobject.c.h"
303
Victor Stinner50149202015-09-22 00:26:54 +0200304typedef enum {
305 _Py_ERROR_UNKNOWN=0,
306 _Py_ERROR_STRICT,
307 _Py_ERROR_SURROGATEESCAPE,
308 _Py_ERROR_REPLACE,
309 _Py_ERROR_IGNORE,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200310 _Py_ERROR_BACKSLASHREPLACE,
311 _Py_ERROR_SURROGATEPASS,
Victor Stinner50149202015-09-22 00:26:54 +0200312 _Py_ERROR_XMLCHARREFREPLACE,
313 _Py_ERROR_OTHER
314} _Py_error_handler;
315
316static _Py_error_handler
317get_error_handler(const char *errors)
318{
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200319 if (errors == NULL || strcmp(errors, "strict") == 0)
Victor Stinner50149202015-09-22 00:26:54 +0200320 return _Py_ERROR_STRICT;
321 if (strcmp(errors, "surrogateescape") == 0)
322 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner50149202015-09-22 00:26:54 +0200323 if (strcmp(errors, "replace") == 0)
324 return _Py_ERROR_REPLACE;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200325 if (strcmp(errors, "ignore") == 0)
326 return _Py_ERROR_IGNORE;
327 if (strcmp(errors, "backslashreplace") == 0)
328 return _Py_ERROR_BACKSLASHREPLACE;
329 if (strcmp(errors, "surrogatepass") == 0)
330 return _Py_ERROR_SURROGATEPASS;
Victor Stinner50149202015-09-22 00:26:54 +0200331 if (strcmp(errors, "xmlcharrefreplace") == 0)
332 return _Py_ERROR_XMLCHARREFREPLACE;
333 return _Py_ERROR_OTHER;
334}
335
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300336/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
337 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000338Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000339PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000340{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000341#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000342 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000343#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000344 /* This is actually an illegal character, so it should
345 not be passed to unichr. */
346 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000347#endif
348}
349
Victor Stinner910337b2011-10-03 03:20:16 +0200350#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200351int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100352_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200353{
354 PyASCIIObject *ascii;
355 unsigned int kind;
356
357 assert(PyUnicode_Check(op));
358
359 ascii = (PyASCIIObject *)op;
360 kind = ascii->state.kind;
361
Victor Stinnera3b334d2011-10-03 13:53:37 +0200362 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200363 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200364 assert(ascii->state.ready == 1);
365 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200366 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200367 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200368 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200369
Victor Stinnera41463c2011-10-04 01:05:08 +0200370 if (ascii->state.compact == 1) {
371 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200372 assert(kind == PyUnicode_1BYTE_KIND
373 || kind == PyUnicode_2BYTE_KIND
374 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200375 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200376 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200377 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100378 }
379 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200380 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
381
382 data = unicode->data.any;
383 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100384 assert(ascii->length == 0);
385 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200386 assert(ascii->state.compact == 0);
387 assert(ascii->state.ascii == 0);
388 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100389 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200390 assert(ascii->wstr != NULL);
391 assert(data == NULL);
392 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200393 }
394 else {
395 assert(kind == PyUnicode_1BYTE_KIND
396 || kind == PyUnicode_2BYTE_KIND
397 || kind == PyUnicode_4BYTE_KIND);
398 assert(ascii->state.compact == 0);
399 assert(ascii->state.ready == 1);
400 assert(data != NULL);
401 if (ascii->state.ascii) {
402 assert (compact->utf8 == data);
403 assert (compact->utf8_length == ascii->length);
404 }
405 else
406 assert (compact->utf8 != data);
407 }
408 }
409 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200410 if (
411#if SIZEOF_WCHAR_T == 2
412 kind == PyUnicode_2BYTE_KIND
413#else
414 kind == PyUnicode_4BYTE_KIND
415#endif
416 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200417 {
418 assert(ascii->wstr == data);
419 assert(compact->wstr_length == ascii->length);
420 } else
421 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200422 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200423
424 if (compact->utf8 == NULL)
425 assert(compact->utf8_length == 0);
426 if (ascii->wstr == NULL)
427 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200428 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200429 /* check that the best kind is used */
430 if (check_content && kind != PyUnicode_WCHAR_KIND)
431 {
432 Py_ssize_t i;
433 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200434 void *data;
435 Py_UCS4 ch;
436
437 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200438 for (i=0; i < ascii->length; i++)
439 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200440 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200441 if (ch > maxchar)
442 maxchar = ch;
443 }
444 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100445 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200446 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100447 assert(maxchar <= 255);
448 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200449 else
450 assert(maxchar < 128);
451 }
Victor Stinner77faf692011-11-20 18:56:05 +0100452 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200453 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100454 assert(maxchar <= 0xFFFF);
455 }
456 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200457 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100458 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100459 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200460 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200461 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400462 return 1;
463}
Victor Stinner910337b2011-10-03 03:20:16 +0200464#endif
465
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100466static PyObject*
467unicode_result_wchar(PyObject *unicode)
468{
469#ifndef Py_DEBUG
470 Py_ssize_t len;
471
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100472 len = _PyUnicode_WSTR_LENGTH(unicode);
473 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100474 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200475 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100476 }
477
478 if (len == 1) {
479 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100480 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100481 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
482 Py_DECREF(unicode);
483 return latin1_char;
484 }
485 }
486
487 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200488 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100489 return NULL;
490 }
491#else
Victor Stinneraa771272012-10-04 02:32:58 +0200492 assert(Py_REFCNT(unicode) == 1);
493
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100494 /* don't make the result ready in debug mode to ensure that the caller
495 makes the string ready before using it */
496 assert(_PyUnicode_CheckConsistency(unicode, 1));
497#endif
498 return unicode;
499}
500
501static PyObject*
502unicode_result_ready(PyObject *unicode)
503{
504 Py_ssize_t length;
505
506 length = PyUnicode_GET_LENGTH(unicode);
507 if (length == 0) {
508 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100509 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200510 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100511 }
512 return unicode_empty;
513 }
514
515 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200516 void *data = PyUnicode_DATA(unicode);
517 int kind = PyUnicode_KIND(unicode);
518 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100519 if (ch < 256) {
520 PyObject *latin1_char = unicode_latin1[ch];
521 if (latin1_char != NULL) {
522 if (unicode != latin1_char) {
523 Py_INCREF(latin1_char);
524 Py_DECREF(unicode);
525 }
526 return latin1_char;
527 }
528 else {
529 assert(_PyUnicode_CheckConsistency(unicode, 1));
530 Py_INCREF(unicode);
531 unicode_latin1[ch] = unicode;
532 return unicode;
533 }
534 }
535 }
536
537 assert(_PyUnicode_CheckConsistency(unicode, 1));
538 return unicode;
539}
540
541static PyObject*
542unicode_result(PyObject *unicode)
543{
544 assert(_PyUnicode_CHECK(unicode));
545 if (PyUnicode_IS_READY(unicode))
546 return unicode_result_ready(unicode);
547 else
548 return unicode_result_wchar(unicode);
549}
550
Victor Stinnerc4b49542011-12-11 22:44:26 +0100551static PyObject*
552unicode_result_unchanged(PyObject *unicode)
553{
554 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500555 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100556 return NULL;
557 Py_INCREF(unicode);
558 return unicode;
559 }
560 else
561 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100562 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100563}
564
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200565/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
566 ASCII, Latin1, UTF-8, etc. */
567static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200568backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200569 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
570{
Victor Stinnerad771582015-10-09 12:38:53 +0200571 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200572 Py_UCS4 ch;
573 enum PyUnicode_Kind kind;
574 void *data;
575
576 assert(PyUnicode_IS_READY(unicode));
577 kind = PyUnicode_KIND(unicode);
578 data = PyUnicode_DATA(unicode);
579
580 size = 0;
581 /* determine replacement size */
582 for (i = collstart; i < collend; ++i) {
583 Py_ssize_t incr;
584
585 ch = PyUnicode_READ(kind, data, i);
586 if (ch < 0x100)
587 incr = 2+2;
588 else if (ch < 0x10000)
589 incr = 2+4;
590 else {
591 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200592 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200593 }
594 if (size > PY_SSIZE_T_MAX - incr) {
595 PyErr_SetString(PyExc_OverflowError,
596 "encoded result is too long for a Python string");
597 return NULL;
598 }
599 size += incr;
600 }
601
Victor Stinnerad771582015-10-09 12:38:53 +0200602 str = _PyBytesWriter_Prepare(writer, str, size);
603 if (str == NULL)
604 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200605
606 /* generate replacement */
607 for (i = collstart; i < collend; ++i) {
608 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200609 *str++ = '\\';
610 if (ch >= 0x00010000) {
611 *str++ = 'U';
612 *str++ = Py_hexdigits[(ch>>28)&0xf];
613 *str++ = Py_hexdigits[(ch>>24)&0xf];
614 *str++ = Py_hexdigits[(ch>>20)&0xf];
615 *str++ = Py_hexdigits[(ch>>16)&0xf];
616 *str++ = Py_hexdigits[(ch>>12)&0xf];
617 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200618 }
Victor Stinner797485e2015-10-09 03:17:30 +0200619 else if (ch >= 0x100) {
620 *str++ = 'u';
621 *str++ = Py_hexdigits[(ch>>12)&0xf];
622 *str++ = Py_hexdigits[(ch>>8)&0xf];
623 }
624 else
625 *str++ = 'x';
626 *str++ = Py_hexdigits[(ch>>4)&0xf];
627 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200628 }
629 return str;
630}
631
632/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
633 ASCII, Latin1, UTF-8, etc. */
634static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200635xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200636 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
637{
Victor Stinnerad771582015-10-09 12:38:53 +0200638 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200639 Py_UCS4 ch;
640 enum PyUnicode_Kind kind;
641 void *data;
642
643 assert(PyUnicode_IS_READY(unicode));
644 kind = PyUnicode_KIND(unicode);
645 data = PyUnicode_DATA(unicode);
646
647 size = 0;
648 /* determine replacement size */
649 for (i = collstart; i < collend; ++i) {
650 Py_ssize_t incr;
651
652 ch = PyUnicode_READ(kind, data, i);
653 if (ch < 10)
654 incr = 2+1+1;
655 else if (ch < 100)
656 incr = 2+2+1;
657 else if (ch < 1000)
658 incr = 2+3+1;
659 else if (ch < 10000)
660 incr = 2+4+1;
661 else if (ch < 100000)
662 incr = 2+5+1;
663 else if (ch < 1000000)
664 incr = 2+6+1;
665 else {
666 assert(ch <= MAX_UNICODE);
667 incr = 2+7+1;
668 }
669 if (size > PY_SSIZE_T_MAX - incr) {
670 PyErr_SetString(PyExc_OverflowError,
671 "encoded result is too long for a Python string");
672 return NULL;
673 }
674 size += incr;
675 }
676
Victor Stinnerad771582015-10-09 12:38:53 +0200677 str = _PyBytesWriter_Prepare(writer, str, size);
678 if (str == NULL)
679 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200680
681 /* generate replacement */
682 for (i = collstart; i < collend; ++i) {
683 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
684 }
685 return str;
686}
687
Thomas Wouters477c8d52006-05-27 19:21:47 +0000688/* --- Bloom Filters ----------------------------------------------------- */
689
690/* stuff to implement simple "bloom filters" for Unicode characters.
691 to keep things simple, we use a single bitmask, using the least 5
692 bits from each unicode characters as the bit index. */
693
694/* the linebreak mask is set up by Unicode_Init below */
695
Antoine Pitrouf068f942010-01-13 14:19:12 +0000696#if LONG_BIT >= 128
697#define BLOOM_WIDTH 128
698#elif LONG_BIT >= 64
699#define BLOOM_WIDTH 64
700#elif LONG_BIT >= 32
701#define BLOOM_WIDTH 32
702#else
703#error "LONG_BIT is smaller than 32"
704#endif
705
Thomas Wouters477c8d52006-05-27 19:21:47 +0000706#define BLOOM_MASK unsigned long
707
Serhiy Storchaka05997252013-01-26 12:14:02 +0200708static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000709
Antoine Pitrouf068f942010-01-13 14:19:12 +0000710#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000711
Benjamin Peterson29060642009-01-31 22:14:21 +0000712#define BLOOM_LINEBREAK(ch) \
713 ((ch) < 128U ? ascii_linebreak[(ch)] : \
714 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000715
Alexander Belopolsky40018472011-02-26 01:02:56 +0000716Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200717make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718{
Victor Stinnera85af502013-04-09 21:53:54 +0200719#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
720 do { \
721 TYPE *data = (TYPE *)PTR; \
722 TYPE *end = data + LEN; \
723 Py_UCS4 ch; \
724 for (; data != end; data++) { \
725 ch = *data; \
726 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
727 } \
728 break; \
729 } while (0)
730
Thomas Wouters477c8d52006-05-27 19:21:47 +0000731 /* calculate simple bloom-style bitmask for a given unicode string */
732
Antoine Pitrouf068f942010-01-13 14:19:12 +0000733 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000734
735 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200736 switch (kind) {
737 case PyUnicode_1BYTE_KIND:
738 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
739 break;
740 case PyUnicode_2BYTE_KIND:
741 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
742 break;
743 case PyUnicode_4BYTE_KIND:
744 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
745 break;
746 default:
747 assert(0);
748 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000749 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200750
751#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000752}
753
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200754/* Compilation of templated routines */
755
756#include "stringlib/asciilib.h"
757#include "stringlib/fastsearch.h"
758#include "stringlib/partition.h"
759#include "stringlib/split.h"
760#include "stringlib/count.h"
761#include "stringlib/find.h"
762#include "stringlib/find_max_char.h"
763#include "stringlib/localeutil.h"
764#include "stringlib/undef.h"
765
766#include "stringlib/ucs1lib.h"
767#include "stringlib/fastsearch.h"
768#include "stringlib/partition.h"
769#include "stringlib/split.h"
770#include "stringlib/count.h"
771#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300772#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200773#include "stringlib/find_max_char.h"
774#include "stringlib/localeutil.h"
775#include "stringlib/undef.h"
776
777#include "stringlib/ucs2lib.h"
778#include "stringlib/fastsearch.h"
779#include "stringlib/partition.h"
780#include "stringlib/split.h"
781#include "stringlib/count.h"
782#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300783#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200784#include "stringlib/find_max_char.h"
785#include "stringlib/localeutil.h"
786#include "stringlib/undef.h"
787
788#include "stringlib/ucs4lib.h"
789#include "stringlib/fastsearch.h"
790#include "stringlib/partition.h"
791#include "stringlib/split.h"
792#include "stringlib/count.h"
793#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300794#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200795#include "stringlib/find_max_char.h"
796#include "stringlib/localeutil.h"
797#include "stringlib/undef.h"
798
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200799#include "stringlib/unicodedefs.h"
800#include "stringlib/fastsearch.h"
801#include "stringlib/count.h"
802#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100803#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200804
Guido van Rossumd57fd912000-03-10 22:53:23 +0000805/* --- Unicode Object ----------------------------------------------------- */
806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200807static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200808fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200809
Serhiy Storchakad9d769f2015-03-24 21:55:47 +0200810Py_LOCAL_INLINE(Py_ssize_t) findchar(const void *s, int kind,
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200811 Py_ssize_t size, Py_UCS4 ch,
812 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200813{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200814 switch (kind) {
815 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200816 if ((Py_UCS1) ch != ch)
817 return -1;
818 if (direction > 0)
819 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
820 else
821 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200822 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200823 if ((Py_UCS2) ch != ch)
824 return -1;
825 if (direction > 0)
826 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
827 else
828 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200829 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200830 if (direction > 0)
831 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
832 else
833 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200834 default:
835 assert(0);
836 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200837 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200838}
839
Victor Stinnerafffce42012-10-03 23:03:17 +0200840#ifdef Py_DEBUG
841/* Fill the data of an Unicode string with invalid characters to detect bugs
842 earlier.
843
844 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
845 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
846 invalid character in Unicode 6.0. */
847static void
848unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
849{
850 int kind = PyUnicode_KIND(unicode);
851 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
852 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
853 if (length <= old_length)
854 return;
855 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
856}
857#endif
858
Victor Stinnerfe226c02011-10-03 03:52:20 +0200859static PyObject*
860resize_compact(PyObject *unicode, Py_ssize_t length)
861{
862 Py_ssize_t char_size;
863 Py_ssize_t struct_size;
864 Py_ssize_t new_size;
865 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100866 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200867#ifdef Py_DEBUG
868 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
869#endif
870
Victor Stinner79891572012-05-03 13:43:07 +0200871 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200872 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100873 assert(PyUnicode_IS_COMPACT(unicode));
874
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200875 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100876 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200877 struct_size = sizeof(PyASCIIObject);
878 else
879 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200880 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200881
Victor Stinnerfe226c02011-10-03 03:52:20 +0200882 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
883 PyErr_NoMemory();
884 return NULL;
885 }
886 new_size = (struct_size + (length + 1) * char_size);
887
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200888 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
889 PyObject_DEL(_PyUnicode_UTF8(unicode));
890 _PyUnicode_UTF8(unicode) = NULL;
891 _PyUnicode_UTF8_LENGTH(unicode) = 0;
892 }
Victor Stinner84def372011-12-11 20:04:56 +0100893 _Py_DEC_REFTOTAL;
894 _Py_ForgetReference(unicode);
895
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300896 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100897 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100898 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200899 PyErr_NoMemory();
900 return NULL;
901 }
Victor Stinner84def372011-12-11 20:04:56 +0100902 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200903 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100904
Victor Stinnerfe226c02011-10-03 03:52:20 +0200905 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200906 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200907 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100908 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200909 _PyUnicode_WSTR_LENGTH(unicode) = length;
910 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100911 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
912 PyObject_DEL(_PyUnicode_WSTR(unicode));
913 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100914 if (!PyUnicode_IS_ASCII(unicode))
915 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100916 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200917#ifdef Py_DEBUG
918 unicode_fill_invalid(unicode, old_length);
919#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200920 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
921 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200922 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200923 return unicode;
924}
925
Alexander Belopolsky40018472011-02-26 01:02:56 +0000926static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200927resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000928{
Victor Stinner95663112011-10-04 01:03:50 +0200929 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100930 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200931 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200932 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000933
Victor Stinnerfe226c02011-10-03 03:52:20 +0200934 if (PyUnicode_IS_READY(unicode)) {
935 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200936 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200937 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200938#ifdef Py_DEBUG
939 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
940#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200941
942 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200943 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200944 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
945 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200946
947 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
948 PyErr_NoMemory();
949 return -1;
950 }
951 new_size = (length + 1) * char_size;
952
Victor Stinner7a9105a2011-12-12 00:13:42 +0100953 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
954 {
955 PyObject_DEL(_PyUnicode_UTF8(unicode));
956 _PyUnicode_UTF8(unicode) = NULL;
957 _PyUnicode_UTF8_LENGTH(unicode) = 0;
958 }
959
Victor Stinnerfe226c02011-10-03 03:52:20 +0200960 data = (PyObject *)PyObject_REALLOC(data, new_size);
961 if (data == NULL) {
962 PyErr_NoMemory();
963 return -1;
964 }
965 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200966 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200967 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200968 _PyUnicode_WSTR_LENGTH(unicode) = length;
969 }
970 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200971 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200972 _PyUnicode_UTF8_LENGTH(unicode) = length;
973 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200974 _PyUnicode_LENGTH(unicode) = length;
975 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200976#ifdef Py_DEBUG
977 unicode_fill_invalid(unicode, old_length);
978#endif
Victor Stinner95663112011-10-04 01:03:50 +0200979 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200980 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200981 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200982 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200983 }
Victor Stinner95663112011-10-04 01:03:50 +0200984 assert(_PyUnicode_WSTR(unicode) != NULL);
985
986 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700987 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +0200988 PyErr_NoMemory();
989 return -1;
990 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100991 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200992 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100993 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200994 if (!wstr) {
995 PyErr_NoMemory();
996 return -1;
997 }
998 _PyUnicode_WSTR(unicode) = wstr;
999 _PyUnicode_WSTR(unicode)[length] = 0;
1000 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001001 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001002 return 0;
1003}
1004
Victor Stinnerfe226c02011-10-03 03:52:20 +02001005static PyObject*
1006resize_copy(PyObject *unicode, Py_ssize_t length)
1007{
1008 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001009 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001010 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001011
Benjamin Petersonbac79492012-01-14 13:34:47 -05001012 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +01001013 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001014
1015 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1016 if (copy == NULL)
1017 return NULL;
1018
1019 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001020 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001021 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001022 }
1023 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001024 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001025
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001026 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001027 if (w == NULL)
1028 return NULL;
1029 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1030 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001031 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
1032 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001033 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001034 }
1035}
1036
Guido van Rossumd57fd912000-03-10 22:53:23 +00001037/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001038 Ux0000 terminated; some code (e.g. new_identifier)
1039 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001040
1041 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001042 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001043
1044*/
1045
Alexander Belopolsky40018472011-02-26 01:02:56 +00001046static PyUnicodeObject *
1047_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001048{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001049 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001051
Thomas Wouters477c8d52006-05-27 19:21:47 +00001052 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001053 if (length == 0 && unicode_empty != NULL) {
1054 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001055 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001056 }
1057
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001058 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001059 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001060 return (PyUnicodeObject *)PyErr_NoMemory();
1061 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001062 if (length < 0) {
1063 PyErr_SetString(PyExc_SystemError,
1064 "Negative size passed to _PyUnicode_New");
1065 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001066 }
1067
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001068 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1069 if (unicode == NULL)
1070 return NULL;
1071 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001072
1073 _PyUnicode_WSTR_LENGTH(unicode) = length;
1074 _PyUnicode_HASH(unicode) = -1;
1075 _PyUnicode_STATE(unicode).interned = 0;
1076 _PyUnicode_STATE(unicode).kind = 0;
1077 _PyUnicode_STATE(unicode).compact = 0;
1078 _PyUnicode_STATE(unicode).ready = 0;
1079 _PyUnicode_STATE(unicode).ascii = 0;
1080 _PyUnicode_DATA_ANY(unicode) = NULL;
1081 _PyUnicode_LENGTH(unicode) = 0;
1082 _PyUnicode_UTF8(unicode) = NULL;
1083 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1084
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001085 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1086 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001087 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001088 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001089 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001090 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001091
Jeremy Hyltond8082792003-09-16 19:41:39 +00001092 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001093 * the caller fails before initializing str -- unicode_resize()
1094 * reads str[0], and the Keep-Alive optimization can keep memory
1095 * allocated for str alive across a call to unicode_dealloc(unicode).
1096 * We don't want unicode_resize to read uninitialized memory in
1097 * that case.
1098 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001099 _PyUnicode_WSTR(unicode)[0] = 0;
1100 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001101
Victor Stinner7931d9a2011-11-04 00:22:48 +01001102 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001103 return unicode;
1104}
1105
Victor Stinnerf42dc442011-10-02 23:33:16 +02001106static const char*
1107unicode_kind_name(PyObject *unicode)
1108{
Victor Stinner42dfd712011-10-03 14:41:45 +02001109 /* don't check consistency: unicode_kind_name() is called from
1110 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001111 if (!PyUnicode_IS_COMPACT(unicode))
1112 {
1113 if (!PyUnicode_IS_READY(unicode))
1114 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001115 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001116 {
1117 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001118 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001119 return "legacy ascii";
1120 else
1121 return "legacy latin1";
1122 case PyUnicode_2BYTE_KIND:
1123 return "legacy UCS2";
1124 case PyUnicode_4BYTE_KIND:
1125 return "legacy UCS4";
1126 default:
1127 return "<legacy invalid kind>";
1128 }
1129 }
1130 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001131 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001132 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001133 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001134 return "ascii";
1135 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001136 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001137 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001138 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001139 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001140 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001141 default:
1142 return "<invalid compact kind>";
1143 }
1144}
1145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147/* Functions wrapping macros for use in debugger */
1148char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001149 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150}
1151
1152void *_PyUnicode_compact_data(void *unicode) {
1153 return _PyUnicode_COMPACT_DATA(unicode);
1154}
1155void *_PyUnicode_data(void *unicode){
1156 printf("obj %p\n", unicode);
1157 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1158 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1159 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1160 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1161 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1162 return PyUnicode_DATA(unicode);
1163}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001164
1165void
1166_PyUnicode_Dump(PyObject *op)
1167{
1168 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001169 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1170 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1171 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001172
Victor Stinnera849a4b2011-10-03 12:12:11 +02001173 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001174 {
1175 if (ascii->state.ascii)
1176 data = (ascii + 1);
1177 else
1178 data = (compact + 1);
1179 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001180 else
1181 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001182 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1183 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001184
Victor Stinnera849a4b2011-10-03 12:12:11 +02001185 if (ascii->wstr == data)
1186 printf("shared ");
1187 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001188
Victor Stinnera3b334d2011-10-03 13:53:37 +02001189 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001190 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001191 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1192 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001193 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1194 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001195 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001196 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001197}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001198#endif
1199
1200PyObject *
1201PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1202{
1203 PyObject *obj;
1204 PyCompactUnicodeObject *unicode;
1205 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001206 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001207 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001208 Py_ssize_t char_size;
1209 Py_ssize_t struct_size;
1210
1211 /* Optimization for empty strings */
1212 if (size == 0 && unicode_empty != NULL) {
1213 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001214 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001215 }
1216
Victor Stinner9e9d6892011-10-04 01:02:02 +02001217 is_ascii = 0;
1218 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001219 struct_size = sizeof(PyCompactUnicodeObject);
1220 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001221 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001222 char_size = 1;
1223 is_ascii = 1;
1224 struct_size = sizeof(PyASCIIObject);
1225 }
1226 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001227 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001228 char_size = 1;
1229 }
1230 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001231 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001232 char_size = 2;
1233 if (sizeof(wchar_t) == 2)
1234 is_sharing = 1;
1235 }
1236 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001237 if (maxchar > MAX_UNICODE) {
1238 PyErr_SetString(PyExc_SystemError,
1239 "invalid maximum character passed to PyUnicode_New");
1240 return NULL;
1241 }
Victor Stinner8f825062012-04-27 13:55:39 +02001242 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001243 char_size = 4;
1244 if (sizeof(wchar_t) == 4)
1245 is_sharing = 1;
1246 }
1247
1248 /* Ensure we won't overflow the size. */
1249 if (size < 0) {
1250 PyErr_SetString(PyExc_SystemError,
1251 "Negative size passed to PyUnicode_New");
1252 return NULL;
1253 }
1254 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1255 return PyErr_NoMemory();
1256
1257 /* Duplicated allocation code from _PyObject_New() instead of a call to
1258 * PyObject_New() so we are able to allocate space for the object and
1259 * it's data buffer.
1260 */
1261 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1262 if (obj == NULL)
1263 return PyErr_NoMemory();
1264 obj = PyObject_INIT(obj, &PyUnicode_Type);
1265 if (obj == NULL)
1266 return NULL;
1267
1268 unicode = (PyCompactUnicodeObject *)obj;
1269 if (is_ascii)
1270 data = ((PyASCIIObject*)obj) + 1;
1271 else
1272 data = unicode + 1;
1273 _PyUnicode_LENGTH(unicode) = size;
1274 _PyUnicode_HASH(unicode) = -1;
1275 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001276 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001277 _PyUnicode_STATE(unicode).compact = 1;
1278 _PyUnicode_STATE(unicode).ready = 1;
1279 _PyUnicode_STATE(unicode).ascii = is_ascii;
1280 if (is_ascii) {
1281 ((char*)data)[size] = 0;
1282 _PyUnicode_WSTR(unicode) = NULL;
1283 }
Victor Stinner8f825062012-04-27 13:55:39 +02001284 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001285 ((char*)data)[size] = 0;
1286 _PyUnicode_WSTR(unicode) = NULL;
1287 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001288 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001289 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001290 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001291 else {
1292 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001293 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001294 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001295 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001296 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001297 ((Py_UCS4*)data)[size] = 0;
1298 if (is_sharing) {
1299 _PyUnicode_WSTR_LENGTH(unicode) = size;
1300 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1301 }
1302 else {
1303 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1304 _PyUnicode_WSTR(unicode) = NULL;
1305 }
1306 }
Victor Stinner8f825062012-04-27 13:55:39 +02001307#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001308 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001309#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001310 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001311 return obj;
1312}
1313
1314#if SIZEOF_WCHAR_T == 2
1315/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1316 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001317 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001318
1319 This function assumes that unicode can hold one more code point than wstr
1320 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001321static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001322unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001323 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324{
1325 const wchar_t *iter;
1326 Py_UCS4 *ucs4_out;
1327
Victor Stinner910337b2011-10-03 03:20:16 +02001328 assert(unicode != NULL);
1329 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001330 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1331 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1332
1333 for (iter = begin; iter < end; ) {
1334 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1335 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001336 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1337 && (iter+1) < end
1338 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001339 {
Victor Stinner551ac952011-11-29 22:58:13 +01001340 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001341 iter += 2;
1342 }
1343 else {
1344 *ucs4_out++ = *iter;
1345 iter++;
1346 }
1347 }
1348 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1349 _PyUnicode_GET_LENGTH(unicode)));
1350
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001351}
1352#endif
1353
Victor Stinnercd9950f2011-10-02 00:34:53 +02001354static int
Victor Stinner488fa492011-12-12 00:01:39 +01001355unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001356{
Victor Stinner488fa492011-12-12 00:01:39 +01001357 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001358 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001359 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001360 return -1;
1361 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001362 return 0;
1363}
1364
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001365static int
1366_copy_characters(PyObject *to, Py_ssize_t to_start,
1367 PyObject *from, Py_ssize_t from_start,
1368 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001369{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001370 unsigned int from_kind, to_kind;
1371 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001372
Victor Stinneree4544c2012-05-09 22:24:08 +02001373 assert(0 <= how_many);
1374 assert(0 <= from_start);
1375 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001376 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001377 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001378 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001379
Victor Stinnerd3f08822012-05-29 12:57:52 +02001380 assert(PyUnicode_Check(to));
1381 assert(PyUnicode_IS_READY(to));
1382 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1383
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001384 if (how_many == 0)
1385 return 0;
1386
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001387 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001388 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001389 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001390 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001391
Victor Stinnerf1852262012-06-16 16:38:26 +02001392#ifdef Py_DEBUG
1393 if (!check_maxchar
1394 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1395 {
1396 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1397 Py_UCS4 ch;
1398 Py_ssize_t i;
1399 for (i=0; i < how_many; i++) {
1400 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1401 assert(ch <= to_maxchar);
1402 }
1403 }
1404#endif
1405
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001406 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001407 if (check_maxchar
1408 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1409 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001410 /* Writing Latin-1 characters into an ASCII string requires to
1411 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001412 Py_UCS4 max_char;
1413 max_char = ucs1lib_find_max_char(from_data,
1414 (Py_UCS1*)from_data + how_many);
1415 if (max_char >= 128)
1416 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001417 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001418 Py_MEMCPY((char*)to_data + to_kind * to_start,
1419 (char*)from_data + from_kind * from_start,
1420 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001421 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001422 else if (from_kind == PyUnicode_1BYTE_KIND
1423 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001424 {
1425 _PyUnicode_CONVERT_BYTES(
1426 Py_UCS1, Py_UCS2,
1427 PyUnicode_1BYTE_DATA(from) + from_start,
1428 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1429 PyUnicode_2BYTE_DATA(to) + to_start
1430 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001431 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001432 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001433 && to_kind == PyUnicode_4BYTE_KIND)
1434 {
1435 _PyUnicode_CONVERT_BYTES(
1436 Py_UCS1, Py_UCS4,
1437 PyUnicode_1BYTE_DATA(from) + from_start,
1438 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1439 PyUnicode_4BYTE_DATA(to) + to_start
1440 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001441 }
1442 else if (from_kind == PyUnicode_2BYTE_KIND
1443 && to_kind == PyUnicode_4BYTE_KIND)
1444 {
1445 _PyUnicode_CONVERT_BYTES(
1446 Py_UCS2, Py_UCS4,
1447 PyUnicode_2BYTE_DATA(from) + from_start,
1448 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1449 PyUnicode_4BYTE_DATA(to) + to_start
1450 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001451 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001452 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001453 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1454
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001455 if (!check_maxchar) {
1456 if (from_kind == PyUnicode_2BYTE_KIND
1457 && to_kind == PyUnicode_1BYTE_KIND)
1458 {
1459 _PyUnicode_CONVERT_BYTES(
1460 Py_UCS2, Py_UCS1,
1461 PyUnicode_2BYTE_DATA(from) + from_start,
1462 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1463 PyUnicode_1BYTE_DATA(to) + to_start
1464 );
1465 }
1466 else if (from_kind == PyUnicode_4BYTE_KIND
1467 && to_kind == PyUnicode_1BYTE_KIND)
1468 {
1469 _PyUnicode_CONVERT_BYTES(
1470 Py_UCS4, Py_UCS1,
1471 PyUnicode_4BYTE_DATA(from) + from_start,
1472 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1473 PyUnicode_1BYTE_DATA(to) + to_start
1474 );
1475 }
1476 else if (from_kind == PyUnicode_4BYTE_KIND
1477 && to_kind == PyUnicode_2BYTE_KIND)
1478 {
1479 _PyUnicode_CONVERT_BYTES(
1480 Py_UCS4, Py_UCS2,
1481 PyUnicode_4BYTE_DATA(from) + from_start,
1482 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1483 PyUnicode_2BYTE_DATA(to) + to_start
1484 );
1485 }
1486 else {
1487 assert(0);
1488 return -1;
1489 }
1490 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001491 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001492 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001493 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001494 Py_ssize_t i;
1495
Victor Stinnera0702ab2011-09-29 14:14:38 +02001496 for (i=0; i < how_many; i++) {
1497 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001498 if (ch > to_maxchar)
1499 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001500 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1501 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001502 }
1503 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001504 return 0;
1505}
1506
Victor Stinnerd3f08822012-05-29 12:57:52 +02001507void
1508_PyUnicode_FastCopyCharacters(
1509 PyObject *to, Py_ssize_t to_start,
1510 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001511{
1512 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1513}
1514
1515Py_ssize_t
1516PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1517 PyObject *from, Py_ssize_t from_start,
1518 Py_ssize_t how_many)
1519{
1520 int err;
1521
1522 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1523 PyErr_BadInternalCall();
1524 return -1;
1525 }
1526
Benjamin Petersonbac79492012-01-14 13:34:47 -05001527 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001528 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001529 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001530 return -1;
1531
Victor Stinnerd3f08822012-05-29 12:57:52 +02001532 if (from_start < 0) {
1533 PyErr_SetString(PyExc_IndexError, "string index out of range");
1534 return -1;
1535 }
1536 if (to_start < 0) {
1537 PyErr_SetString(PyExc_IndexError, "string index out of range");
1538 return -1;
1539 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001540 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1541 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1542 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001543 "Cannot write %zi characters at %zi "
1544 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001545 how_many, to_start, PyUnicode_GET_LENGTH(to));
1546 return -1;
1547 }
1548
1549 if (how_many == 0)
1550 return 0;
1551
Victor Stinner488fa492011-12-12 00:01:39 +01001552 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001553 return -1;
1554
1555 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1556 if (err) {
1557 PyErr_Format(PyExc_SystemError,
1558 "Cannot copy %s characters "
1559 "into a string of %s characters",
1560 unicode_kind_name(from),
1561 unicode_kind_name(to));
1562 return -1;
1563 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001564 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001565}
1566
Victor Stinner17222162011-09-28 22:15:37 +02001567/* Find the maximum code point and count the number of surrogate pairs so a
1568 correct string length can be computed before converting a string to UCS4.
1569 This function counts single surrogates as a character and not as a pair.
1570
1571 Return 0 on success, or -1 on error. */
1572static int
1573find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1574 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001575{
1576 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001577 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001578
Victor Stinnerc53be962011-10-02 21:33:54 +02001579 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001580 *num_surrogates = 0;
1581 *maxchar = 0;
1582
1583 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001584#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001585 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1586 && (iter+1) < end
1587 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1588 {
1589 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1590 ++(*num_surrogates);
1591 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 }
1593 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001594#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001595 {
1596 ch = *iter;
1597 iter++;
1598 }
1599 if (ch > *maxchar) {
1600 *maxchar = ch;
1601 if (*maxchar > MAX_UNICODE) {
1602 PyErr_Format(PyExc_ValueError,
1603 "character U+%x is not in range [U+0000; U+10ffff]",
1604 ch);
1605 return -1;
1606 }
1607 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001608 }
1609 return 0;
1610}
1611
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001612int
1613_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001614{
1615 wchar_t *end;
1616 Py_UCS4 maxchar = 0;
1617 Py_ssize_t num_surrogates;
1618#if SIZEOF_WCHAR_T == 2
1619 Py_ssize_t length_wo_surrogates;
1620#endif
1621
Georg Brandl7597add2011-10-05 16:36:47 +02001622 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001623 strings were created using _PyObject_New() and where no canonical
1624 representation (the str field) has been set yet aka strings
1625 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001626 assert(_PyUnicode_CHECK(unicode));
1627 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001628 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001629 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001630 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001631 /* Actually, it should neither be interned nor be anything else: */
1632 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001634 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001635 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001636 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001637 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001638
1639 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001640 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1641 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642 PyErr_NoMemory();
1643 return -1;
1644 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001645 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001646 _PyUnicode_WSTR(unicode), end,
1647 PyUnicode_1BYTE_DATA(unicode));
1648 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1649 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1650 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1651 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001652 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001653 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001654 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001655 }
1656 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001657 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001658 _PyUnicode_UTF8(unicode) = NULL;
1659 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001660 }
1661 PyObject_FREE(_PyUnicode_WSTR(unicode));
1662 _PyUnicode_WSTR(unicode) = NULL;
1663 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1664 }
1665 /* In this case we might have to convert down from 4-byte native
1666 wchar_t to 2-byte unicode. */
1667 else if (maxchar < 65536) {
1668 assert(num_surrogates == 0 &&
1669 "FindMaxCharAndNumSurrogatePairs() messed up");
1670
Victor Stinner506f5922011-09-28 22:34:18 +02001671#if SIZEOF_WCHAR_T == 2
1672 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001673 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001674 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1675 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1676 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001677 _PyUnicode_UTF8(unicode) = NULL;
1678 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001679#else
1680 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001681 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001682 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001683 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001684 PyErr_NoMemory();
1685 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001686 }
Victor Stinner506f5922011-09-28 22:34:18 +02001687 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1688 _PyUnicode_WSTR(unicode), end,
1689 PyUnicode_2BYTE_DATA(unicode));
1690 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1691 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1692 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001693 _PyUnicode_UTF8(unicode) = NULL;
1694 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001695 PyObject_FREE(_PyUnicode_WSTR(unicode));
1696 _PyUnicode_WSTR(unicode) = NULL;
1697 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1698#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001699 }
1700 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1701 else {
1702#if SIZEOF_WCHAR_T == 2
1703 /* in case the native representation is 2-bytes, we need to allocate a
1704 new normalized 4-byte version. */
1705 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001706 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1707 PyErr_NoMemory();
1708 return -1;
1709 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001710 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1711 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001712 PyErr_NoMemory();
1713 return -1;
1714 }
1715 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1716 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001717 _PyUnicode_UTF8(unicode) = NULL;
1718 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001719 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1720 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001721 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001722 PyObject_FREE(_PyUnicode_WSTR(unicode));
1723 _PyUnicode_WSTR(unicode) = NULL;
1724 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1725#else
1726 assert(num_surrogates == 0);
1727
Victor Stinnerc3c74152011-10-02 20:39:55 +02001728 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001729 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001730 _PyUnicode_UTF8(unicode) = NULL;
1731 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001732 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1733#endif
1734 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1735 }
1736 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001737 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001738 return 0;
1739}
1740
Alexander Belopolsky40018472011-02-26 01:02:56 +00001741static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001742unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001743{
Walter Dörwald16807132007-05-25 13:52:07 +00001744 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001745 case SSTATE_NOT_INTERNED:
1746 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001747
Benjamin Peterson29060642009-01-31 22:14:21 +00001748 case SSTATE_INTERNED_MORTAL:
1749 /* revive dead object temporarily for DelItem */
1750 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001751 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001752 Py_FatalError(
1753 "deletion of interned string failed");
1754 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001755
Benjamin Peterson29060642009-01-31 22:14:21 +00001756 case SSTATE_INTERNED_IMMORTAL:
1757 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001758
Benjamin Peterson29060642009-01-31 22:14:21 +00001759 default:
1760 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001761 }
1762
Victor Stinner03490912011-10-03 23:45:12 +02001763 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001765 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001766 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001767 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1768 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001769
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001770 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001771}
1772
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001773#ifdef Py_DEBUG
1774static int
1775unicode_is_singleton(PyObject *unicode)
1776{
1777 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1778 if (unicode == unicode_empty)
1779 return 1;
1780 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1781 {
1782 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1783 if (ch < 256 && unicode_latin1[ch] == unicode)
1784 return 1;
1785 }
1786 return 0;
1787}
1788#endif
1789
Alexander Belopolsky40018472011-02-26 01:02:56 +00001790static int
Victor Stinner488fa492011-12-12 00:01:39 +01001791unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001792{
Victor Stinner488fa492011-12-12 00:01:39 +01001793 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001794 if (Py_REFCNT(unicode) != 1)
1795 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001796 if (_PyUnicode_HASH(unicode) != -1)
1797 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001798 if (PyUnicode_CHECK_INTERNED(unicode))
1799 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001800 if (!PyUnicode_CheckExact(unicode))
1801 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001802#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001803 /* singleton refcount is greater than 1 */
1804 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001805#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001806 return 1;
1807}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001808
Victor Stinnerfe226c02011-10-03 03:52:20 +02001809static int
1810unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1811{
1812 PyObject *unicode;
1813 Py_ssize_t old_length;
1814
1815 assert(p_unicode != NULL);
1816 unicode = *p_unicode;
1817
1818 assert(unicode != NULL);
1819 assert(PyUnicode_Check(unicode));
1820 assert(0 <= length);
1821
Victor Stinner910337b2011-10-03 03:20:16 +02001822 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001823 old_length = PyUnicode_WSTR_LENGTH(unicode);
1824 else
1825 old_length = PyUnicode_GET_LENGTH(unicode);
1826 if (old_length == length)
1827 return 0;
1828
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001829 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001830 _Py_INCREF_UNICODE_EMPTY();
1831 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001832 return -1;
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +02001833 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001834 return 0;
1835 }
1836
Victor Stinner488fa492011-12-12 00:01:39 +01001837 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001838 PyObject *copy = resize_copy(unicode, length);
1839 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001840 return -1;
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +02001841 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001842 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001843 }
1844
Victor Stinnerfe226c02011-10-03 03:52:20 +02001845 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001846 PyObject *new_unicode = resize_compact(unicode, length);
1847 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001848 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001849 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001850 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001851 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001852 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001853}
1854
Alexander Belopolsky40018472011-02-26 01:02:56 +00001855int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001856PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001857{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001858 PyObject *unicode;
1859 if (p_unicode == NULL) {
1860 PyErr_BadInternalCall();
1861 return -1;
1862 }
1863 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001864 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001865 {
1866 PyErr_BadInternalCall();
1867 return -1;
1868 }
1869 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001870}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001871
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001872/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001873
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001874 WARNING: The function doesn't copy the terminating null character and
1875 doesn't check the maximum character (may write a latin1 character in an
1876 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001877static void
1878unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1879 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001880{
1881 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1882 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001883 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001884
1885 switch (kind) {
1886 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001887 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001888#ifdef Py_DEBUG
1889 if (PyUnicode_IS_ASCII(unicode)) {
1890 Py_UCS4 maxchar = ucs1lib_find_max_char(
1891 (const Py_UCS1*)str,
1892 (const Py_UCS1*)str + len);
1893 assert(maxchar < 128);
1894 }
1895#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001896 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001897 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001898 }
1899 case PyUnicode_2BYTE_KIND: {
1900 Py_UCS2 *start = (Py_UCS2 *)data + index;
1901 Py_UCS2 *ucs2 = start;
1902 assert(index <= PyUnicode_GET_LENGTH(unicode));
1903
Victor Stinner184252a2012-06-16 02:57:41 +02001904 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001905 *ucs2 = (Py_UCS2)*str;
1906
1907 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001908 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001909 }
1910 default: {
1911 Py_UCS4 *start = (Py_UCS4 *)data + index;
1912 Py_UCS4 *ucs4 = start;
1913 assert(kind == PyUnicode_4BYTE_KIND);
1914 assert(index <= PyUnicode_GET_LENGTH(unicode));
1915
Victor Stinner184252a2012-06-16 02:57:41 +02001916 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001917 *ucs4 = (Py_UCS4)*str;
1918
1919 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001920 }
1921 }
1922}
1923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001924static PyObject*
1925get_latin1_char(unsigned char ch)
1926{
Victor Stinnera464fc12011-10-02 20:39:30 +02001927 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001928 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001929 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001930 if (!unicode)
1931 return NULL;
1932 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001933 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001934 unicode_latin1[ch] = unicode;
1935 }
1936 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001937 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001938}
1939
Victor Stinner985a82a2014-01-03 12:53:47 +01001940static PyObject*
1941unicode_char(Py_UCS4 ch)
1942{
1943 PyObject *unicode;
1944
1945 assert(ch <= MAX_UNICODE);
1946
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001947 if (ch < 256)
1948 return get_latin1_char(ch);
1949
Victor Stinner985a82a2014-01-03 12:53:47 +01001950 unicode = PyUnicode_New(1, ch);
1951 if (unicode == NULL)
1952 return NULL;
1953 switch (PyUnicode_KIND(unicode)) {
1954 case PyUnicode_1BYTE_KIND:
1955 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1956 break;
1957 case PyUnicode_2BYTE_KIND:
1958 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1959 break;
1960 default:
1961 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1962 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1963 }
1964 assert(_PyUnicode_CheckConsistency(unicode, 1));
1965 return unicode;
1966}
1967
Alexander Belopolsky40018472011-02-26 01:02:56 +00001968PyObject *
1969PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001970{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001971 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001972 Py_UCS4 maxchar = 0;
1973 Py_ssize_t num_surrogates;
1974
1975 if (u == NULL)
1976 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001977
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001978 /* If the Unicode data is known at construction time, we can apply
1979 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001981 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001982 if (size == 0)
1983 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001984
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001985 /* Single character Unicode objects in the Latin-1 range are
1986 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001987 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001988 return get_latin1_char((unsigned char)*u);
1989
1990 /* If not empty and not single character, copy the Unicode data
1991 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001992 if (find_maxchar_surrogates(u, u + size,
1993 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001994 return NULL;
1995
Victor Stinner8faf8212011-12-08 22:14:11 +01001996 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001997 if (!unicode)
1998 return NULL;
1999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 switch (PyUnicode_KIND(unicode)) {
2001 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002002 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2004 break;
2005 case PyUnicode_2BYTE_KIND:
2006#if Py_UNICODE_SIZE == 2
2007 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
2008#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002009 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002010 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2011#endif
2012 break;
2013 case PyUnicode_4BYTE_KIND:
2014#if SIZEOF_WCHAR_T == 2
2015 /* This is the only case which has to process surrogates, thus
2016 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002017 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002018#else
2019 assert(num_surrogates == 0);
2020 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
2021#endif
2022 break;
2023 default:
2024 assert(0 && "Impossible state");
2025 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002026
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002027 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002028}
2029
Alexander Belopolsky40018472011-02-26 01:02:56 +00002030PyObject *
2031PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002032{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002033 if (size < 0) {
2034 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002035 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002036 return NULL;
2037 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002038 if (u != NULL)
2039 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2040 else
2041 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002042}
2043
Alexander Belopolsky40018472011-02-26 01:02:56 +00002044PyObject *
2045PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002046{
2047 size_t size = strlen(u);
2048 if (size > PY_SSIZE_T_MAX) {
2049 PyErr_SetString(PyExc_OverflowError, "input too long");
2050 return NULL;
2051 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002052 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002053}
2054
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002055PyObject *
2056_PyUnicode_FromId(_Py_Identifier *id)
2057{
2058 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002059 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2060 strlen(id->string),
2061 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002062 if (!id->object)
2063 return NULL;
2064 PyUnicode_InternInPlace(&id->object);
2065 assert(!id->next);
2066 id->next = static_strings;
2067 static_strings = id;
2068 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002069 return id->object;
2070}
2071
2072void
2073_PyUnicode_ClearStaticStrings()
2074{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002075 _Py_Identifier *tmp, *s = static_strings;
2076 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002077 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002078 tmp = s->next;
2079 s->next = NULL;
2080 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002081 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002082 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002083}
2084
Benjamin Peterson0df54292012-03-26 14:50:32 -04002085/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002086
Victor Stinnerd3f08822012-05-29 12:57:52 +02002087PyObject*
2088_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002089{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002090 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002091 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002092 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002093#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002094 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002095#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002096 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002097 }
Victor Stinner785938e2011-12-11 20:09:03 +01002098 unicode = PyUnicode_New(size, 127);
2099 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002100 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002101 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2102 assert(_PyUnicode_CheckConsistency(unicode, 1));
2103 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002104}
2105
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002106static Py_UCS4
2107kind_maxchar_limit(unsigned int kind)
2108{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002109 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002110 case PyUnicode_1BYTE_KIND:
2111 return 0x80;
2112 case PyUnicode_2BYTE_KIND:
2113 return 0x100;
2114 case PyUnicode_4BYTE_KIND:
2115 return 0x10000;
2116 default:
2117 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01002118 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002119 }
2120}
2121
Victor Stinnere6abb482012-05-02 01:15:40 +02002122Py_LOCAL_INLINE(Py_UCS4)
2123align_maxchar(Py_UCS4 maxchar)
2124{
2125 if (maxchar <= 127)
2126 return 127;
2127 else if (maxchar <= 255)
2128 return 255;
2129 else if (maxchar <= 65535)
2130 return 65535;
2131 else
2132 return MAX_UNICODE;
2133}
2134
Victor Stinner702c7342011-10-05 13:50:52 +02002135static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002136_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002137{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002138 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002139 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002140
Serhiy Storchaka678db842013-01-26 12:16:36 +02002141 if (size == 0)
2142 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002143 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002144 if (size == 1)
2145 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002146
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002147 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002148 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002149 if (!res)
2150 return NULL;
2151 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002152 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002153 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002154}
2155
Victor Stinnere57b1c02011-09-28 22:20:48 +02002156static PyObject*
2157_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002158{
2159 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002160 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002161
Serhiy Storchaka678db842013-01-26 12:16:36 +02002162 if (size == 0)
2163 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002164 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002165 if (size == 1)
2166 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002167
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002168 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002169 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002170 if (!res)
2171 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002172 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002173 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002174 else {
2175 _PyUnicode_CONVERT_BYTES(
2176 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2177 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002178 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002179 return res;
2180}
2181
Victor Stinnere57b1c02011-09-28 22:20:48 +02002182static PyObject*
2183_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002184{
2185 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002186 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002187
Serhiy Storchaka678db842013-01-26 12:16:36 +02002188 if (size == 0)
2189 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002190 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002191 if (size == 1)
2192 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002193
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002194 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002195 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002196 if (!res)
2197 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002198 if (max_char < 256)
2199 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2200 PyUnicode_1BYTE_DATA(res));
2201 else if (max_char < 0x10000)
2202 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2203 PyUnicode_2BYTE_DATA(res));
2204 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002205 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002206 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002207 return res;
2208}
2209
2210PyObject*
2211PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2212{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002213 if (size < 0) {
2214 PyErr_SetString(PyExc_ValueError, "size must be positive");
2215 return NULL;
2216 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002217 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002219 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002220 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002221 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002222 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002223 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002224 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002225 PyErr_SetString(PyExc_SystemError, "invalid kind");
2226 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002227 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002228}
2229
Victor Stinnerece58de2012-04-23 23:36:38 +02002230Py_UCS4
2231_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2232{
2233 enum PyUnicode_Kind kind;
2234 void *startptr, *endptr;
2235
2236 assert(PyUnicode_IS_READY(unicode));
2237 assert(0 <= start);
2238 assert(end <= PyUnicode_GET_LENGTH(unicode));
2239 assert(start <= end);
2240
2241 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2242 return PyUnicode_MAX_CHAR_VALUE(unicode);
2243
2244 if (start == end)
2245 return 127;
2246
Victor Stinner94d558b2012-04-27 22:26:58 +02002247 if (PyUnicode_IS_ASCII(unicode))
2248 return 127;
2249
Victor Stinnerece58de2012-04-23 23:36:38 +02002250 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002251 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002252 endptr = (char *)startptr + end * kind;
2253 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002254 switch(kind) {
2255 case PyUnicode_1BYTE_KIND:
2256 return ucs1lib_find_max_char(startptr, endptr);
2257 case PyUnicode_2BYTE_KIND:
2258 return ucs2lib_find_max_char(startptr, endptr);
2259 case PyUnicode_4BYTE_KIND:
2260 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002261 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002262 assert(0);
2263 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002264 }
2265}
2266
Victor Stinner25a4b292011-10-06 12:31:55 +02002267/* Ensure that a string uses the most efficient storage, if it is not the
2268 case: create a new string with of the right kind. Write NULL into *p_unicode
2269 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002270static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002271unicode_adjust_maxchar(PyObject **p_unicode)
2272{
2273 PyObject *unicode, *copy;
2274 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002275 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002276 unsigned int kind;
2277
2278 assert(p_unicode != NULL);
2279 unicode = *p_unicode;
2280 assert(PyUnicode_IS_READY(unicode));
2281 if (PyUnicode_IS_ASCII(unicode))
2282 return;
2283
2284 len = PyUnicode_GET_LENGTH(unicode);
2285 kind = PyUnicode_KIND(unicode);
2286 if (kind == PyUnicode_1BYTE_KIND) {
2287 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002288 max_char = ucs1lib_find_max_char(u, u + len);
2289 if (max_char >= 128)
2290 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002291 }
2292 else if (kind == PyUnicode_2BYTE_KIND) {
2293 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002294 max_char = ucs2lib_find_max_char(u, u + len);
2295 if (max_char >= 256)
2296 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002297 }
2298 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002299 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002300 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002301 max_char = ucs4lib_find_max_char(u, u + len);
2302 if (max_char >= 0x10000)
2303 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002304 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002305 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002306 if (copy != NULL)
2307 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002308 Py_DECREF(unicode);
2309 *p_unicode = copy;
2310}
2311
Victor Stinner034f6cf2011-09-30 02:26:44 +02002312PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002313_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002314{
Victor Stinner87af4f22011-11-21 23:03:47 +01002315 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002316 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002317
Victor Stinner034f6cf2011-09-30 02:26:44 +02002318 if (!PyUnicode_Check(unicode)) {
2319 PyErr_BadInternalCall();
2320 return NULL;
2321 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002322 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002323 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002324
Victor Stinner87af4f22011-11-21 23:03:47 +01002325 length = PyUnicode_GET_LENGTH(unicode);
2326 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002327 if (!copy)
2328 return NULL;
2329 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2330
Victor Stinner87af4f22011-11-21 23:03:47 +01002331 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2332 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002333 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002334 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002335}
2336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002337
Victor Stinnerbc603d12011-10-02 01:00:40 +02002338/* Widen Unicode objects to larger buffers. Don't write terminating null
2339 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002340
2341void*
2342_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2343{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002344 Py_ssize_t len;
2345 void *result;
2346 unsigned int skind;
2347
Benjamin Petersonbac79492012-01-14 13:34:47 -05002348 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002349 return NULL;
2350
2351 len = PyUnicode_GET_LENGTH(s);
2352 skind = PyUnicode_KIND(s);
2353 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002354 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002355 return NULL;
2356 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002357 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002358 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002359 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002360 if (!result)
2361 return PyErr_NoMemory();
2362 assert(skind == PyUnicode_1BYTE_KIND);
2363 _PyUnicode_CONVERT_BYTES(
2364 Py_UCS1, Py_UCS2,
2365 PyUnicode_1BYTE_DATA(s),
2366 PyUnicode_1BYTE_DATA(s) + len,
2367 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002368 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002369 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002370 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002371 if (!result)
2372 return PyErr_NoMemory();
2373 if (skind == PyUnicode_2BYTE_KIND) {
2374 _PyUnicode_CONVERT_BYTES(
2375 Py_UCS2, Py_UCS4,
2376 PyUnicode_2BYTE_DATA(s),
2377 PyUnicode_2BYTE_DATA(s) + len,
2378 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002379 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002380 else {
2381 assert(skind == PyUnicode_1BYTE_KIND);
2382 _PyUnicode_CONVERT_BYTES(
2383 Py_UCS1, Py_UCS4,
2384 PyUnicode_1BYTE_DATA(s),
2385 PyUnicode_1BYTE_DATA(s) + len,
2386 result);
2387 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002388 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002389 default:
2390 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002391 }
Victor Stinner01698042011-10-04 00:04:26 +02002392 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002393 return NULL;
2394}
2395
2396static Py_UCS4*
2397as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2398 int copy_null)
2399{
2400 int kind;
2401 void *data;
2402 Py_ssize_t len, targetlen;
2403 if (PyUnicode_READY(string) == -1)
2404 return NULL;
2405 kind = PyUnicode_KIND(string);
2406 data = PyUnicode_DATA(string);
2407 len = PyUnicode_GET_LENGTH(string);
2408 targetlen = len;
2409 if (copy_null)
2410 targetlen++;
2411 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002412 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002413 if (!target) {
2414 PyErr_NoMemory();
2415 return NULL;
2416 }
2417 }
2418 else {
2419 if (targetsize < targetlen) {
2420 PyErr_Format(PyExc_SystemError,
2421 "string is longer than the buffer");
2422 if (copy_null && 0 < targetsize)
2423 target[0] = 0;
2424 return NULL;
2425 }
2426 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002427 if (kind == PyUnicode_1BYTE_KIND) {
2428 Py_UCS1 *start = (Py_UCS1 *) data;
2429 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002430 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002431 else if (kind == PyUnicode_2BYTE_KIND) {
2432 Py_UCS2 *start = (Py_UCS2 *) data;
2433 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2434 }
2435 else {
2436 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002437 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002438 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002439 if (copy_null)
2440 target[len] = 0;
2441 return target;
2442}
2443
2444Py_UCS4*
2445PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2446 int copy_null)
2447{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002448 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002449 PyErr_BadInternalCall();
2450 return NULL;
2451 }
2452 return as_ucs4(string, target, targetsize, copy_null);
2453}
2454
2455Py_UCS4*
2456PyUnicode_AsUCS4Copy(PyObject *string)
2457{
2458 return as_ucs4(string, NULL, 0, 1);
2459}
2460
2461#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002462
Alexander Belopolsky40018472011-02-26 01:02:56 +00002463PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002464PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002465{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002466 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002467 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002468 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002469 PyErr_BadInternalCall();
2470 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002471 }
2472
Martin v. Löwis790465f2008-04-05 20:41:37 +00002473 if (size == -1) {
2474 size = wcslen(w);
2475 }
2476
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002477 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002478}
2479
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002480#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002481
Victor Stinner15a11362012-10-06 23:48:20 +02002482/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002483 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2484 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2485#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002486
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002487static int
2488unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2489 Py_ssize_t width, Py_ssize_t precision)
2490{
2491 Py_ssize_t length, fill, arglen;
2492 Py_UCS4 maxchar;
2493
2494 if (PyUnicode_READY(str) == -1)
2495 return -1;
2496
2497 length = PyUnicode_GET_LENGTH(str);
2498 if ((precision == -1 || precision >= length)
2499 && width <= length)
2500 return _PyUnicodeWriter_WriteStr(writer, str);
2501
2502 if (precision != -1)
2503 length = Py_MIN(precision, length);
2504
2505 arglen = Py_MAX(length, width);
2506 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2507 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2508 else
2509 maxchar = writer->maxchar;
2510
2511 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2512 return -1;
2513
2514 if (width > length) {
2515 fill = width - length;
2516 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2517 return -1;
2518 writer->pos += fill;
2519 }
2520
2521 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2522 str, 0, length);
2523 writer->pos += length;
2524 return 0;
2525}
2526
2527static int
2528unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2529 Py_ssize_t width, Py_ssize_t precision)
2530{
2531 /* UTF-8 */
2532 Py_ssize_t length;
2533 PyObject *unicode;
2534 int res;
2535
2536 length = strlen(str);
2537 if (precision != -1)
2538 length = Py_MIN(length, precision);
2539 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2540 if (unicode == NULL)
2541 return -1;
2542
2543 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2544 Py_DECREF(unicode);
2545 return res;
2546}
2547
Victor Stinner96865452011-03-01 23:44:09 +00002548static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002549unicode_fromformat_arg(_PyUnicodeWriter *writer,
2550 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002551{
Victor Stinnere215d962012-10-06 23:03:36 +02002552 const char *p;
2553 Py_ssize_t len;
2554 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002555 Py_ssize_t width;
2556 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002557 int longflag;
2558 int longlongflag;
2559 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002560 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002561
2562 p = f;
2563 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002564 zeropad = 0;
2565 if (*f == '0') {
2566 zeropad = 1;
2567 f++;
2568 }
Victor Stinner96865452011-03-01 23:44:09 +00002569
2570 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002571 width = -1;
2572 if (Py_ISDIGIT((unsigned)*f)) {
2573 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002574 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002575 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002576 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002577 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002578 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002579 return NULL;
2580 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002581 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002582 f++;
2583 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002584 }
2585 precision = -1;
2586 if (*f == '.') {
2587 f++;
2588 if (Py_ISDIGIT((unsigned)*f)) {
2589 precision = (*f - '0');
2590 f++;
2591 while (Py_ISDIGIT((unsigned)*f)) {
2592 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2593 PyErr_SetString(PyExc_ValueError,
2594 "precision too big");
2595 return NULL;
2596 }
2597 precision = (precision * 10) + (*f - '0');
2598 f++;
2599 }
2600 }
Victor Stinner96865452011-03-01 23:44:09 +00002601 if (*f == '%') {
2602 /* "%.3%s" => f points to "3" */
2603 f--;
2604 }
2605 }
2606 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002607 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002608 f--;
2609 }
Victor Stinner96865452011-03-01 23:44:09 +00002610
2611 /* Handle %ld, %lu, %lld and %llu. */
2612 longflag = 0;
2613 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002614 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002615 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002616 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002617 longflag = 1;
2618 ++f;
2619 }
2620#ifdef HAVE_LONG_LONG
2621 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002622 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002623 longlongflag = 1;
2624 f += 2;
2625 }
2626#endif
2627 }
2628 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002629 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002630 size_tflag = 1;
2631 ++f;
2632 }
Victor Stinnere215d962012-10-06 23:03:36 +02002633
2634 if (f[1] == '\0')
2635 writer->overallocate = 0;
2636
2637 switch (*f) {
2638 case 'c':
2639 {
2640 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002641 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002642 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002643 "character argument not in range(0x110000)");
2644 return NULL;
2645 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002646 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002647 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002648 break;
2649 }
2650
2651 case 'i':
2652 case 'd':
2653 case 'u':
2654 case 'x':
2655 {
2656 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002657 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002658 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002659
2660 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002661 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002662 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002663 va_arg(*vargs, unsigned long));
2664#ifdef HAVE_LONG_LONG
2665 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002666 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002667 va_arg(*vargs, unsigned PY_LONG_LONG));
2668#endif
2669 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002670 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002671 va_arg(*vargs, size_t));
2672 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002673 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002674 va_arg(*vargs, unsigned int));
2675 }
2676 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002677 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002678 }
2679 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002680 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002681 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002682 va_arg(*vargs, long));
2683#ifdef HAVE_LONG_LONG
2684 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002685 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002686 va_arg(*vargs, PY_LONG_LONG));
2687#endif
2688 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002689 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002690 va_arg(*vargs, Py_ssize_t));
2691 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002692 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002693 va_arg(*vargs, int));
2694 }
2695 assert(len >= 0);
2696
Victor Stinnere215d962012-10-06 23:03:36 +02002697 if (precision < len)
2698 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002699
2700 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002701 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2702 return NULL;
2703
Victor Stinnere215d962012-10-06 23:03:36 +02002704 if (width > precision) {
2705 Py_UCS4 fillchar;
2706 fill = width - precision;
2707 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002708 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2709 return NULL;
2710 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002711 }
Victor Stinner15a11362012-10-06 23:48:20 +02002712 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002713 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002714 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2715 return NULL;
2716 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002717 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002718
Victor Stinner4a587072013-11-19 12:54:53 +01002719 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2720 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002721 break;
2722 }
2723
2724 case 'p':
2725 {
2726 char number[MAX_LONG_LONG_CHARS];
2727
2728 len = sprintf(number, "%p", va_arg(*vargs, void*));
2729 assert(len >= 0);
2730
2731 /* %p is ill-defined: ensure leading 0x. */
2732 if (number[1] == 'X')
2733 number[1] = 'x';
2734 else if (number[1] != 'x') {
2735 memmove(number + 2, number,
2736 strlen(number) + 1);
2737 number[0] = '0';
2738 number[1] = 'x';
2739 len += 2;
2740 }
2741
Victor Stinner4a587072013-11-19 12:54:53 +01002742 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002743 return NULL;
2744 break;
2745 }
2746
2747 case 's':
2748 {
2749 /* UTF-8 */
2750 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002751 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002752 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002753 break;
2754 }
2755
2756 case 'U':
2757 {
2758 PyObject *obj = va_arg(*vargs, PyObject *);
2759 assert(obj && _PyUnicode_CHECK(obj));
2760
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002761 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002762 return NULL;
2763 break;
2764 }
2765
2766 case 'V':
2767 {
2768 PyObject *obj = va_arg(*vargs, PyObject *);
2769 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002770 if (obj) {
2771 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002772 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002773 return NULL;
2774 }
2775 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002776 assert(str != NULL);
2777 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002778 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002779 }
2780 break;
2781 }
2782
2783 case 'S':
2784 {
2785 PyObject *obj = va_arg(*vargs, PyObject *);
2786 PyObject *str;
2787 assert(obj);
2788 str = PyObject_Str(obj);
2789 if (!str)
2790 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002791 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002792 Py_DECREF(str);
2793 return NULL;
2794 }
2795 Py_DECREF(str);
2796 break;
2797 }
2798
2799 case 'R':
2800 {
2801 PyObject *obj = va_arg(*vargs, PyObject *);
2802 PyObject *repr;
2803 assert(obj);
2804 repr = PyObject_Repr(obj);
2805 if (!repr)
2806 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002807 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002808 Py_DECREF(repr);
2809 return NULL;
2810 }
2811 Py_DECREF(repr);
2812 break;
2813 }
2814
2815 case 'A':
2816 {
2817 PyObject *obj = va_arg(*vargs, PyObject *);
2818 PyObject *ascii;
2819 assert(obj);
2820 ascii = PyObject_ASCII(obj);
2821 if (!ascii)
2822 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002823 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002824 Py_DECREF(ascii);
2825 return NULL;
2826 }
2827 Py_DECREF(ascii);
2828 break;
2829 }
2830
2831 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002832 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002833 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002834 break;
2835
2836 default:
2837 /* if we stumble upon an unknown formatting code, copy the rest
2838 of the format string to the output string. (we cannot just
2839 skip the code, since there's no way to know what's in the
2840 argument list) */
2841 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002842 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002843 return NULL;
2844 f = p+len;
2845 return f;
2846 }
2847
2848 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002849 return f;
2850}
2851
Walter Dörwaldd2034312007-05-18 16:29:38 +00002852PyObject *
2853PyUnicode_FromFormatV(const char *format, va_list vargs)
2854{
Victor Stinnere215d962012-10-06 23:03:36 +02002855 va_list vargs2;
2856 const char *f;
2857 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002858
Victor Stinner8f674cc2013-04-17 23:02:17 +02002859 _PyUnicodeWriter_Init(&writer);
2860 writer.min_length = strlen(format) + 100;
2861 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002862
2863 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2864 Copy it to be able to pass a reference to a subfunction. */
2865 Py_VA_COPY(vargs2, vargs);
2866
2867 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002868 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002869 f = unicode_fromformat_arg(&writer, f, &vargs2);
2870 if (f == NULL)
2871 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002872 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002873 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002874 const char *p;
2875 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002876
Victor Stinnere215d962012-10-06 23:03:36 +02002877 p = f;
2878 do
2879 {
2880 if ((unsigned char)*p > 127) {
2881 PyErr_Format(PyExc_ValueError,
2882 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2883 "string, got a non-ASCII byte: 0x%02x",
2884 (unsigned char)*p);
2885 return NULL;
2886 }
2887 p++;
2888 }
2889 while (*p != '\0' && *p != '%');
2890 len = p - f;
2891
2892 if (*p == '\0')
2893 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002894
2895 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002896 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002897
2898 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002899 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002900 }
Victor Stinnere215d962012-10-06 23:03:36 +02002901 return _PyUnicodeWriter_Finish(&writer);
2902
2903 fail:
2904 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002905 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002906}
2907
Walter Dörwaldd2034312007-05-18 16:29:38 +00002908PyObject *
2909PyUnicode_FromFormat(const char *format, ...)
2910{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002911 PyObject* ret;
2912 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002913
2914#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002915 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002916#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002917 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002918#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002919 ret = PyUnicode_FromFormatV(format, vargs);
2920 va_end(vargs);
2921 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002922}
2923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002924#ifdef HAVE_WCHAR_H
2925
Victor Stinner5593d8a2010-10-02 11:11:27 +00002926/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2927 convert a Unicode object to a wide character string.
2928
Victor Stinnerd88d9832011-09-06 02:00:05 +02002929 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002930 character) required to convert the unicode object. Ignore size argument.
2931
Victor Stinnerd88d9832011-09-06 02:00:05 +02002932 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002933 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002934 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002935static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002936unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002937 wchar_t *w,
2938 Py_ssize_t size)
2939{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002940 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002941 const wchar_t *wstr;
2942
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002943 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002944 if (wstr == NULL)
2945 return -1;
2946
Victor Stinner5593d8a2010-10-02 11:11:27 +00002947 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002948 if (size > res)
2949 size = res + 1;
2950 else
2951 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002952 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002953 return res;
2954 }
2955 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002956 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002957}
2958
2959Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002960PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002961 wchar_t *w,
2962 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002963{
2964 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002965 PyErr_BadInternalCall();
2966 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002967 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002968 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002969}
2970
Victor Stinner137c34c2010-09-29 10:25:54 +00002971wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002972PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002973 Py_ssize_t *size)
2974{
2975 wchar_t* buffer;
2976 Py_ssize_t buflen;
2977
2978 if (unicode == NULL) {
2979 PyErr_BadInternalCall();
2980 return NULL;
2981 }
2982
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002983 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002984 if (buflen == -1)
2985 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002986 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00002987 if (buffer == NULL) {
2988 PyErr_NoMemory();
2989 return NULL;
2990 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002991 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002992 if (buflen == -1) {
2993 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002994 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002995 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002996 if (size != NULL)
2997 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002998 return buffer;
2999}
3000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003001#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003002
Alexander Belopolsky40018472011-02-26 01:02:56 +00003003PyObject *
3004PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003005{
Victor Stinner8faf8212011-12-08 22:14:11 +01003006 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003007 PyErr_SetString(PyExc_ValueError,
3008 "chr() arg not in range(0x110000)");
3009 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003010 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003011
Victor Stinner985a82a2014-01-03 12:53:47 +01003012 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003013}
3014
Alexander Belopolsky40018472011-02-26 01:02:56 +00003015PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003016PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003017{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003018 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003019 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003020 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003021 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003022 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003023 Py_INCREF(obj);
3024 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003025 }
3026 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003027 /* For a Unicode subtype that's not a Unicode object,
3028 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003029 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003030 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003031 PyErr_Format(PyExc_TypeError,
3032 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003033 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003034 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003035}
3036
Alexander Belopolsky40018472011-02-26 01:02:56 +00003037PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003038PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003039 const char *encoding,
3040 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003041{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003042 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003043 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003044
Guido van Rossumd57fd912000-03-10 22:53:23 +00003045 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003046 PyErr_BadInternalCall();
3047 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003048 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003049
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003050 /* Decoding bytes objects is the most common case and should be fast */
3051 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003052 if (PyBytes_GET_SIZE(obj) == 0)
3053 _Py_RETURN_UNICODE_EMPTY();
3054 v = PyUnicode_Decode(
3055 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3056 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003057 return v;
3058 }
3059
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003060 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003061 PyErr_SetString(PyExc_TypeError,
3062 "decoding str is not supported");
3063 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003064 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003065
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003066 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3067 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3068 PyErr_Format(PyExc_TypeError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02003069 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003070 Py_TYPE(obj)->tp_name);
3071 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003072 }
Tim Petersced69f82003-09-16 20:30:58 +00003073
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003074 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003075 PyBuffer_Release(&buffer);
3076 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003077 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003078
Serhiy Storchaka05997252013-01-26 12:14:02 +02003079 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003080 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003081 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003082}
3083
Victor Stinner600d3be2010-06-10 12:00:55 +00003084/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00003085 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
3086 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003087int
3088_Py_normalize_encoding(const char *encoding,
3089 char *lower,
3090 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003091{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003092 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003093 char *l;
3094 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003095
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003096 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01003097 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01003098 if (lower_len < 6)
3099 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003100 strcpy(lower, "utf-8");
3101 return 1;
3102 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003103 e = encoding;
3104 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003105 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003106 while (*e) {
3107 if (l == l_end)
3108 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003109 if (Py_ISUPPER(*e)) {
3110 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003111 }
3112 else if (*e == '_') {
3113 *l++ = '-';
3114 e++;
3115 }
3116 else {
3117 *l++ = *e++;
3118 }
3119 }
3120 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003121 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003122}
3123
Alexander Belopolsky40018472011-02-26 01:02:56 +00003124PyObject *
3125PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003126 Py_ssize_t size,
3127 const char *encoding,
3128 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003129{
3130 PyObject *buffer = NULL, *unicode;
3131 Py_buffer info;
3132 char lower[11]; /* Enough for any encoding shortcut */
3133
Fred Drakee4315f52000-05-09 19:53:39 +00003134 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003135 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003136 if ((strcmp(lower, "utf-8") == 0) ||
3137 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003138 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003139 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003140 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003141 (strcmp(lower, "iso-8859-1") == 0) ||
3142 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003143 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003144#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003145 else if (strcmp(lower, "mbcs") == 0)
3146 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003147#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003148 else if (strcmp(lower, "ascii") == 0)
3149 return PyUnicode_DecodeASCII(s, size, errors);
3150 else if (strcmp(lower, "utf-16") == 0)
3151 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3152 else if (strcmp(lower, "utf-32") == 0)
3153 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3154 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003155
3156 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003157 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003158 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003159 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003160 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003161 if (buffer == NULL)
3162 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003163 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003164 if (unicode == NULL)
3165 goto onError;
3166 if (!PyUnicode_Check(unicode)) {
3167 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003168 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3169 "use codecs.decode() to decode to arbitrary types",
3170 encoding,
3171 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003172 Py_DECREF(unicode);
3173 goto onError;
3174 }
3175 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003176 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003177
Benjamin Peterson29060642009-01-31 22:14:21 +00003178 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003179 Py_XDECREF(buffer);
3180 return NULL;
3181}
3182
Alexander Belopolsky40018472011-02-26 01:02:56 +00003183PyObject *
3184PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003185 const char *encoding,
3186 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003187{
3188 PyObject *v;
3189
3190 if (!PyUnicode_Check(unicode)) {
3191 PyErr_BadArgument();
3192 goto onError;
3193 }
3194
3195 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003196 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003197
3198 /* Decode via the codec registry */
3199 v = PyCodec_Decode(unicode, encoding, errors);
3200 if (v == NULL)
3201 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003202 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003203
Benjamin Peterson29060642009-01-31 22:14:21 +00003204 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003205 return NULL;
3206}
3207
Alexander Belopolsky40018472011-02-26 01:02:56 +00003208PyObject *
3209PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003210 const char *encoding,
3211 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003212{
3213 PyObject *v;
3214
3215 if (!PyUnicode_Check(unicode)) {
3216 PyErr_BadArgument();
3217 goto onError;
3218 }
3219
3220 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003221 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003222
3223 /* Decode via the codec registry */
3224 v = PyCodec_Decode(unicode, encoding, errors);
3225 if (v == NULL)
3226 goto onError;
3227 if (!PyUnicode_Check(v)) {
3228 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003229 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3230 "use codecs.decode() to decode to arbitrary types",
3231 encoding,
3232 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003233 Py_DECREF(v);
3234 goto onError;
3235 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003236 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003237
Benjamin Peterson29060642009-01-31 22:14:21 +00003238 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003239 return NULL;
3240}
3241
Alexander Belopolsky40018472011-02-26 01:02:56 +00003242PyObject *
3243PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003244 Py_ssize_t size,
3245 const char *encoding,
3246 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003247{
3248 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003249
Guido van Rossumd57fd912000-03-10 22:53:23 +00003250 unicode = PyUnicode_FromUnicode(s, size);
3251 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003252 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003253 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3254 Py_DECREF(unicode);
3255 return v;
3256}
3257
Alexander Belopolsky40018472011-02-26 01:02:56 +00003258PyObject *
3259PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003260 const char *encoding,
3261 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003262{
3263 PyObject *v;
3264
3265 if (!PyUnicode_Check(unicode)) {
3266 PyErr_BadArgument();
3267 goto onError;
3268 }
3269
3270 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003271 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003272
3273 /* Encode via the codec registry */
3274 v = PyCodec_Encode(unicode, encoding, errors);
3275 if (v == NULL)
3276 goto onError;
3277 return v;
3278
Benjamin Peterson29060642009-01-31 22:14:21 +00003279 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003280 return NULL;
3281}
3282
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003283static size_t
3284wcstombs_errorpos(const wchar_t *wstr)
3285{
3286 size_t len;
3287#if SIZEOF_WCHAR_T == 2
3288 wchar_t buf[3];
3289#else
3290 wchar_t buf[2];
3291#endif
3292 char outbuf[MB_LEN_MAX];
3293 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003294
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003295#if SIZEOF_WCHAR_T == 2
3296 buf[2] = 0;
3297#else
3298 buf[1] = 0;
3299#endif
3300 start = wstr;
3301 while (*wstr != L'\0')
3302 {
3303 previous = wstr;
3304#if SIZEOF_WCHAR_T == 2
3305 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3306 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3307 {
3308 buf[0] = wstr[0];
3309 buf[1] = wstr[1];
3310 wstr += 2;
3311 }
3312 else {
3313 buf[0] = *wstr;
3314 buf[1] = 0;
3315 wstr++;
3316 }
3317#else
3318 buf[0] = *wstr;
3319 wstr++;
3320#endif
3321 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003322 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003323 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003324 }
3325
3326 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003327 return 0;
3328}
3329
Victor Stinner1b579672011-12-17 05:47:23 +01003330static int
3331locale_error_handler(const char *errors, int *surrogateescape)
3332{
Victor Stinner50149202015-09-22 00:26:54 +02003333 _Py_error_handler error_handler = get_error_handler(errors);
3334 switch (error_handler)
3335 {
3336 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003337 *surrogateescape = 0;
3338 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003339 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003340 *surrogateescape = 1;
3341 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003342 default:
3343 PyErr_Format(PyExc_ValueError,
3344 "only 'strict' and 'surrogateescape' error handlers "
3345 "are supported, not '%s'",
3346 errors);
3347 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003348 }
Victor Stinner1b579672011-12-17 05:47:23 +01003349}
3350
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003351PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003352PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003353{
3354 Py_ssize_t wlen, wlen2;
3355 wchar_t *wstr;
3356 PyObject *bytes = NULL;
3357 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003358 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003359 PyObject *exc;
3360 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003361 int surrogateescape;
3362
3363 if (locale_error_handler(errors, &surrogateescape) < 0)
3364 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003365
3366 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3367 if (wstr == NULL)
3368 return NULL;
3369
3370 wlen2 = wcslen(wstr);
3371 if (wlen2 != wlen) {
3372 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003373 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003374 return NULL;
3375 }
3376
3377 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003378 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003379 char *str;
3380
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003381 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003382 if (str == NULL) {
3383 if (error_pos == (size_t)-1) {
3384 PyErr_NoMemory();
3385 PyMem_Free(wstr);
3386 return NULL;
3387 }
3388 else {
3389 goto encode_error;
3390 }
3391 }
3392 PyMem_Free(wstr);
3393
3394 bytes = PyBytes_FromString(str);
3395 PyMem_Free(str);
3396 }
3397 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003398 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003399 size_t len, len2;
3400
3401 len = wcstombs(NULL, wstr, 0);
3402 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003403 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003404 goto encode_error;
3405 }
3406
3407 bytes = PyBytes_FromStringAndSize(NULL, len);
3408 if (bytes == NULL) {
3409 PyMem_Free(wstr);
3410 return NULL;
3411 }
3412
3413 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3414 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003415 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003416 goto encode_error;
3417 }
3418 PyMem_Free(wstr);
3419 }
3420 return bytes;
3421
3422encode_error:
3423 errmsg = strerror(errno);
3424 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003425
3426 if (error_pos == (size_t)-1)
3427 error_pos = wcstombs_errorpos(wstr);
3428
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003429 PyMem_Free(wstr);
3430 Py_XDECREF(bytes);
3431
Victor Stinner2f197072011-12-17 07:08:30 +01003432 if (errmsg != NULL) {
3433 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003434 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003435 if (wstr != NULL) {
3436 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003437 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003438 } else
3439 errmsg = NULL;
3440 }
3441 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003442 reason = PyUnicode_FromString(
3443 "wcstombs() encountered an unencodable "
3444 "wide character");
3445 if (reason == NULL)
3446 return NULL;
3447
3448 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3449 "locale", unicode,
3450 (Py_ssize_t)error_pos,
3451 (Py_ssize_t)(error_pos+1),
3452 reason);
3453 Py_DECREF(reason);
3454 if (exc != NULL) {
3455 PyCodec_StrictErrors(exc);
3456 Py_XDECREF(exc);
3457 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003458 return NULL;
3459}
3460
Victor Stinnerad158722010-10-27 00:25:46 +00003461PyObject *
3462PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003463{
Victor Stinner99b95382011-07-04 14:23:54 +02003464#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003465 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003466#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003467 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003468#else
Victor Stinner793b5312011-04-27 00:24:21 +02003469 PyInterpreterState *interp = PyThreadState_GET()->interp;
3470 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3471 cannot use it to encode and decode filenames before it is loaded. Load
3472 the Python codec requires to encode at least its own filename. Use the C
3473 version of the locale codec until the codec registry is initialized and
3474 the Python codec is loaded.
3475
3476 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3477 cannot only rely on it: check also interp->fscodec_initialized for
3478 subinterpreters. */
3479 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003480 return PyUnicode_AsEncodedString(unicode,
3481 Py_FileSystemDefaultEncoding,
3482 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003483 }
3484 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003485 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003486 }
Victor Stinnerad158722010-10-27 00:25:46 +00003487#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003488}
3489
Alexander Belopolsky40018472011-02-26 01:02:56 +00003490PyObject *
3491PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003492 const char *encoding,
3493 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003494{
3495 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003496 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003497
Guido van Rossumd57fd912000-03-10 22:53:23 +00003498 if (!PyUnicode_Check(unicode)) {
3499 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003500 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003501 }
Fred Drakee4315f52000-05-09 19:53:39 +00003502
Fred Drakee4315f52000-05-09 19:53:39 +00003503 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003504 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003505 if ((strcmp(lower, "utf-8") == 0) ||
3506 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003507 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003508 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003509 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003510 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003511 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003512 }
Victor Stinner37296e82010-06-10 13:36:23 +00003513 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003514 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003515 (strcmp(lower, "iso-8859-1") == 0) ||
3516 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003517 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003518#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003519 else if (strcmp(lower, "mbcs") == 0)
3520 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003521#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003522 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003523 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003524 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003525
3526 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003527 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003528 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003529 return NULL;
3530
3531 /* The normal path */
3532 if (PyBytes_Check(v))
3533 return v;
3534
3535 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003536 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003537 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003538 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003539
3540 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003541 "encoder %s returned bytearray instead of bytes; "
3542 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003543 encoding);
3544 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003545 Py_DECREF(v);
3546 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003547 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003548
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003549 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3550 Py_DECREF(v);
3551 return b;
3552 }
3553
3554 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003555 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3556 "use codecs.encode() to encode to arbitrary types",
3557 encoding,
3558 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003559 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003560 return NULL;
3561}
3562
Alexander Belopolsky40018472011-02-26 01:02:56 +00003563PyObject *
3564PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003565 const char *encoding,
3566 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003567{
3568 PyObject *v;
3569
3570 if (!PyUnicode_Check(unicode)) {
3571 PyErr_BadArgument();
3572 goto onError;
3573 }
3574
3575 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003576 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003577
3578 /* Encode via the codec registry */
3579 v = PyCodec_Encode(unicode, encoding, errors);
3580 if (v == NULL)
3581 goto onError;
3582 if (!PyUnicode_Check(v)) {
3583 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003584 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3585 "use codecs.encode() to encode to arbitrary types",
3586 encoding,
3587 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003588 Py_DECREF(v);
3589 goto onError;
3590 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003591 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003592
Benjamin Peterson29060642009-01-31 22:14:21 +00003593 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003594 return NULL;
3595}
3596
Victor Stinner2f197072011-12-17 07:08:30 +01003597static size_t
3598mbstowcs_errorpos(const char *str, size_t len)
3599{
3600#ifdef HAVE_MBRTOWC
3601 const char *start = str;
3602 mbstate_t mbs;
3603 size_t converted;
3604 wchar_t ch;
3605
3606 memset(&mbs, 0, sizeof mbs);
3607 while (len)
3608 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003609 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003610 if (converted == 0)
3611 /* Reached end of string */
3612 break;
3613 if (converted == (size_t)-1 || converted == (size_t)-2) {
3614 /* Conversion error or incomplete character */
3615 return str - start;
3616 }
3617 else {
3618 str += converted;
3619 len -= converted;
3620 }
3621 }
3622 /* failed to find the undecodable byte sequence */
3623 return 0;
3624#endif
3625 return 0;
3626}
3627
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003628PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003629PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003630 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003631{
3632 wchar_t smallbuf[256];
3633 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3634 wchar_t *wstr;
3635 size_t wlen, wlen2;
3636 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003637 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003638 size_t error_pos;
3639 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003640 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3641 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003642
3643 if (locale_error_handler(errors, &surrogateescape) < 0)
3644 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003645
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003646 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3647 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003648 return NULL;
3649 }
3650
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003651 if (surrogateescape) {
3652 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003653 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003654 if (wstr == NULL) {
3655 if (wlen == (size_t)-1)
3656 PyErr_NoMemory();
3657 else
3658 PyErr_SetFromErrno(PyExc_OSError);
3659 return NULL;
3660 }
3661
3662 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003663 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003664 }
3665 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003666 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003667#ifndef HAVE_BROKEN_MBSTOWCS
3668 wlen = mbstowcs(NULL, str, 0);
3669#else
3670 wlen = len;
3671#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003672 if (wlen == (size_t)-1)
3673 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003674 if (wlen+1 <= smallbuf_len) {
3675 wstr = smallbuf;
3676 }
3677 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003678 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003679 if (!wstr)
3680 return PyErr_NoMemory();
3681 }
3682
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003683 wlen2 = mbstowcs(wstr, str, wlen+1);
3684 if (wlen2 == (size_t)-1) {
3685 if (wstr != smallbuf)
3686 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003687 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003688 }
3689#ifdef HAVE_BROKEN_MBSTOWCS
3690 assert(wlen2 == wlen);
3691#endif
3692 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3693 if (wstr != smallbuf)
3694 PyMem_Free(wstr);
3695 }
3696 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003697
3698decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003699 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003700 errmsg = strerror(errno);
3701 assert(errmsg != NULL);
3702
3703 error_pos = mbstowcs_errorpos(str, len);
3704 if (errmsg != NULL) {
3705 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003706 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003707 if (wstr != NULL) {
3708 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003709 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003710 }
Victor Stinner2f197072011-12-17 07:08:30 +01003711 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003712 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003713 reason = PyUnicode_FromString(
3714 "mbstowcs() encountered an invalid multibyte sequence");
3715 if (reason == NULL)
3716 return NULL;
3717
3718 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3719 "locale", str, len,
3720 (Py_ssize_t)error_pos,
3721 (Py_ssize_t)(error_pos+1),
3722 reason);
3723 Py_DECREF(reason);
3724 if (exc != NULL) {
3725 PyCodec_StrictErrors(exc);
3726 Py_XDECREF(exc);
3727 }
3728 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003729}
3730
3731PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003732PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003733{
3734 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003735 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003736}
3737
3738
3739PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003740PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003741 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003742 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3743}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003744
Christian Heimes5894ba72007-11-04 11:43:14 +00003745PyObject*
3746PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3747{
Victor Stinner99b95382011-07-04 14:23:54 +02003748#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003749 return PyUnicode_DecodeMBCS(s, size, NULL);
3750#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003751 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003752#else
Victor Stinner793b5312011-04-27 00:24:21 +02003753 PyInterpreterState *interp = PyThreadState_GET()->interp;
3754 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3755 cannot use it to encode and decode filenames before it is loaded. Load
3756 the Python codec requires to encode at least its own filename. Use the C
3757 version of the locale codec until the codec registry is initialized and
3758 the Python codec is loaded.
3759
3760 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3761 cannot only rely on it: check also interp->fscodec_initialized for
3762 subinterpreters. */
3763 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003764 return PyUnicode_Decode(s, size,
3765 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003766 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003767 }
3768 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003769 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003770 }
Victor Stinnerad158722010-10-27 00:25:46 +00003771#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003772}
3773
Martin v. Löwis011e8422009-05-05 04:43:17 +00003774
3775int
3776PyUnicode_FSConverter(PyObject* arg, void* addr)
3777{
3778 PyObject *output = NULL;
3779 Py_ssize_t size;
3780 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003781 if (arg == NULL) {
3782 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003783 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003784 return 1;
3785 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003786 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003787 output = arg;
3788 Py_INCREF(output);
3789 }
3790 else {
3791 arg = PyUnicode_FromObject(arg);
3792 if (!arg)
3793 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003794 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003795 Py_DECREF(arg);
3796 if (!output)
3797 return 0;
3798 if (!PyBytes_Check(output)) {
3799 Py_DECREF(output);
3800 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3801 return 0;
3802 }
3803 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003804 size = PyBytes_GET_SIZE(output);
3805 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003806 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003807 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003808 Py_DECREF(output);
3809 return 0;
3810 }
3811 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003812 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003813}
3814
3815
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003816int
3817PyUnicode_FSDecoder(PyObject* arg, void* addr)
3818{
3819 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003820 if (arg == NULL) {
3821 Py_DECREF(*(PyObject**)addr);
3822 return 1;
3823 }
3824 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003825 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003826 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003827 output = arg;
3828 Py_INCREF(output);
3829 }
3830 else {
3831 arg = PyBytes_FromObject(arg);
3832 if (!arg)
3833 return 0;
3834 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3835 PyBytes_GET_SIZE(arg));
3836 Py_DECREF(arg);
3837 if (!output)
3838 return 0;
3839 if (!PyUnicode_Check(output)) {
3840 Py_DECREF(output);
3841 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3842 return 0;
3843 }
3844 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003845 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003846 Py_DECREF(output);
3847 return 0;
3848 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003849 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003850 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003851 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003852 Py_DECREF(output);
3853 return 0;
3854 }
3855 *(PyObject**)addr = output;
3856 return Py_CLEANUP_SUPPORTED;
3857}
3858
3859
Martin v. Löwis5b222132007-06-10 09:51:05 +00003860char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003861PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003862{
Christian Heimesf3863112007-11-22 07:46:41 +00003863 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003864
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003865 if (!PyUnicode_Check(unicode)) {
3866 PyErr_BadArgument();
3867 return NULL;
3868 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003869 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003870 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003871
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003872 if (PyUnicode_UTF8(unicode) == NULL) {
3873 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003874 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3875 if (bytes == NULL)
3876 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003877 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3878 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003879 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003880 Py_DECREF(bytes);
3881 return NULL;
3882 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003883 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3884 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3885 PyBytes_AS_STRING(bytes),
3886 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003887 Py_DECREF(bytes);
3888 }
3889
3890 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003891 *psize = PyUnicode_UTF8_LENGTH(unicode);
3892 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003893}
3894
3895char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003896PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003897{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003898 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3899}
3900
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003901Py_UNICODE *
3902PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3903{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003904 const unsigned char *one_byte;
3905#if SIZEOF_WCHAR_T == 4
3906 const Py_UCS2 *two_bytes;
3907#else
3908 const Py_UCS4 *four_bytes;
3909 const Py_UCS4 *ucs4_end;
3910 Py_ssize_t num_surrogates;
3911#endif
3912 wchar_t *w;
3913 wchar_t *wchar_end;
3914
3915 if (!PyUnicode_Check(unicode)) {
3916 PyErr_BadArgument();
3917 return NULL;
3918 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003919 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003920 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003921 assert(_PyUnicode_KIND(unicode) != 0);
3922 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003923
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003924 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003925#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003926 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3927 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003928 num_surrogates = 0;
3929
3930 for (; four_bytes < ucs4_end; ++four_bytes) {
3931 if (*four_bytes > 0xFFFF)
3932 ++num_surrogates;
3933 }
3934
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003935 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3936 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3937 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003938 PyErr_NoMemory();
3939 return NULL;
3940 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003941 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003942
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003943 w = _PyUnicode_WSTR(unicode);
3944 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3945 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003946 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3947 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003948 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003949 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003950 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3951 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003952 }
3953 else
3954 *w = *four_bytes;
3955
3956 if (w > wchar_end) {
3957 assert(0 && "Miscalculated string end");
3958 }
3959 }
3960 *w = 0;
3961#else
3962 /* sizeof(wchar_t) == 4 */
3963 Py_FatalError("Impossible unicode object state, wstr and str "
3964 "should share memory already.");
3965 return NULL;
3966#endif
3967 }
3968 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003969 if ((size_t)_PyUnicode_LENGTH(unicode) >
3970 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3971 PyErr_NoMemory();
3972 return NULL;
3973 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003974 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3975 (_PyUnicode_LENGTH(unicode) + 1));
3976 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003977 PyErr_NoMemory();
3978 return NULL;
3979 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003980 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3981 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3982 w = _PyUnicode_WSTR(unicode);
3983 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003984
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003985 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3986 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003987 for (; w < wchar_end; ++one_byte, ++w)
3988 *w = *one_byte;
3989 /* null-terminate the wstr */
3990 *w = 0;
3991 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003992 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003993#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003994 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003995 for (; w < wchar_end; ++two_bytes, ++w)
3996 *w = *two_bytes;
3997 /* null-terminate the wstr */
3998 *w = 0;
3999#else
4000 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004001 PyObject_FREE(_PyUnicode_WSTR(unicode));
4002 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004003 Py_FatalError("Impossible unicode object state, wstr "
4004 "and str should share memory already.");
4005 return NULL;
4006#endif
4007 }
4008 else {
4009 assert(0 && "This should never happen.");
4010 }
4011 }
4012 }
4013 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004014 *size = PyUnicode_WSTR_LENGTH(unicode);
4015 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004016}
4017
Alexander Belopolsky40018472011-02-26 01:02:56 +00004018Py_UNICODE *
4019PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004020{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004021 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004022}
4023
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004024
Alexander Belopolsky40018472011-02-26 01:02:56 +00004025Py_ssize_t
4026PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004027{
4028 if (!PyUnicode_Check(unicode)) {
4029 PyErr_BadArgument();
4030 goto onError;
4031 }
4032 return PyUnicode_GET_SIZE(unicode);
4033
Benjamin Peterson29060642009-01-31 22:14:21 +00004034 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004035 return -1;
4036}
4037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004038Py_ssize_t
4039PyUnicode_GetLength(PyObject *unicode)
4040{
Victor Stinner07621332012-06-16 04:53:46 +02004041 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004042 PyErr_BadArgument();
4043 return -1;
4044 }
Victor Stinner07621332012-06-16 04:53:46 +02004045 if (PyUnicode_READY(unicode) == -1)
4046 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004047 return PyUnicode_GET_LENGTH(unicode);
4048}
4049
4050Py_UCS4
4051PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4052{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004053 void *data;
4054 int kind;
4055
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004056 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4057 PyErr_BadArgument();
4058 return (Py_UCS4)-1;
4059 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004060 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004061 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004062 return (Py_UCS4)-1;
4063 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004064 data = PyUnicode_DATA(unicode);
4065 kind = PyUnicode_KIND(unicode);
4066 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004067}
4068
4069int
4070PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4071{
4072 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004073 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004074 return -1;
4075 }
Victor Stinner488fa492011-12-12 00:01:39 +01004076 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004077 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004078 PyErr_SetString(PyExc_IndexError, "string index out of range");
4079 return -1;
4080 }
Victor Stinner488fa492011-12-12 00:01:39 +01004081 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004082 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004083 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4084 PyErr_SetString(PyExc_ValueError, "character out of range");
4085 return -1;
4086 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004087 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4088 index, ch);
4089 return 0;
4090}
4091
Alexander Belopolsky40018472011-02-26 01:02:56 +00004092const char *
4093PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004094{
Victor Stinner42cb4622010-09-01 19:39:01 +00004095 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004096}
4097
Victor Stinner554f3f02010-06-16 23:33:54 +00004098/* create or adjust a UnicodeDecodeError */
4099static void
4100make_decode_exception(PyObject **exceptionObject,
4101 const char *encoding,
4102 const char *input, Py_ssize_t length,
4103 Py_ssize_t startpos, Py_ssize_t endpos,
4104 const char *reason)
4105{
4106 if (*exceptionObject == NULL) {
4107 *exceptionObject = PyUnicodeDecodeError_Create(
4108 encoding, input, length, startpos, endpos, reason);
4109 }
4110 else {
4111 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4112 goto onError;
4113 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4114 goto onError;
4115 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4116 goto onError;
4117 }
4118 return;
4119
4120onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004121 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004122}
4123
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004124#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004125/* error handling callback helper:
4126 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004127 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004128 and adjust various state variables.
4129 return 0 on success, -1 on error
4130*/
4131
Alexander Belopolsky40018472011-02-26 01:02:56 +00004132static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004133unicode_decode_call_errorhandler_wchar(
4134 const char *errors, PyObject **errorHandler,
4135 const char *encoding, const char *reason,
4136 const char **input, const char **inend, Py_ssize_t *startinpos,
4137 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4138 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004139{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004140 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004141
4142 PyObject *restuple = NULL;
4143 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004144 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004145 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004146 Py_ssize_t requiredsize;
4147 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004148 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004149 wchar_t *repwstr;
4150 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004151
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004152 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4153 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004154
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004155 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004156 *errorHandler = PyCodec_LookupError(errors);
4157 if (*errorHandler == NULL)
4158 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004159 }
4160
Victor Stinner554f3f02010-06-16 23:33:54 +00004161 make_decode_exception(exceptionObject,
4162 encoding,
4163 *input, *inend - *input,
4164 *startinpos, *endinpos,
4165 reason);
4166 if (*exceptionObject == NULL)
4167 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004168
4169 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4170 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004171 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004172 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004173 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004174 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004175 }
4176 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004177 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004178
4179 /* Copy back the bytes variables, which might have been modified by the
4180 callback */
4181 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4182 if (!inputobj)
4183 goto onError;
4184 if (!PyBytes_Check(inputobj)) {
4185 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4186 }
4187 *input = PyBytes_AS_STRING(inputobj);
4188 insize = PyBytes_GET_SIZE(inputobj);
4189 *inend = *input + insize;
4190 /* we can DECREF safely, as the exception has another reference,
4191 so the object won't go away. */
4192 Py_DECREF(inputobj);
4193
4194 if (newpos<0)
4195 newpos = insize+newpos;
4196 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004197 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004198 goto onError;
4199 }
4200
4201 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4202 if (repwstr == NULL)
4203 goto onError;
4204 /* need more space? (at least enough for what we
4205 have+the replacement+the rest of the string (starting
4206 at the new input position), so we won't have to check space
4207 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004208 requiredsize = *outpos;
4209 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4210 goto overflow;
4211 requiredsize += repwlen;
4212 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4213 goto overflow;
4214 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004215 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004216 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004217 requiredsize = 2*outsize;
4218 if (unicode_resize(output, requiredsize) < 0)
4219 goto onError;
4220 }
4221 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4222 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004223 *endinpos = newpos;
4224 *inptr = *input + newpos;
4225
4226 /* we made it! */
4227 Py_XDECREF(restuple);
4228 return 0;
4229
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004230 overflow:
4231 PyErr_SetString(PyExc_OverflowError,
4232 "decoded result is too long for a Python string");
4233
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004234 onError:
4235 Py_XDECREF(restuple);
4236 return -1;
4237}
4238#endif /* HAVE_MBCS */
4239
4240static int
4241unicode_decode_call_errorhandler_writer(
4242 const char *errors, PyObject **errorHandler,
4243 const char *encoding, const char *reason,
4244 const char **input, const char **inend, Py_ssize_t *startinpos,
4245 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4246 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4247{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004248 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004249
4250 PyObject *restuple = NULL;
4251 PyObject *repunicode = NULL;
4252 Py_ssize_t insize;
4253 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004254 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004255 PyObject *inputobj = NULL;
4256
4257 if (*errorHandler == NULL) {
4258 *errorHandler = PyCodec_LookupError(errors);
4259 if (*errorHandler == NULL)
4260 goto onError;
4261 }
4262
4263 make_decode_exception(exceptionObject,
4264 encoding,
4265 *input, *inend - *input,
4266 *startinpos, *endinpos,
4267 reason);
4268 if (*exceptionObject == NULL)
4269 goto onError;
4270
4271 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4272 if (restuple == NULL)
4273 goto onError;
4274 if (!PyTuple_Check(restuple)) {
4275 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4276 goto onError;
4277 }
4278 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004279 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004280
4281 /* Copy back the bytes variables, which might have been modified by the
4282 callback */
4283 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4284 if (!inputobj)
4285 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004286 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004287 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004288 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004289 *input = PyBytes_AS_STRING(inputobj);
4290 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004291 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004292 /* we can DECREF safely, as the exception has another reference,
4293 so the object won't go away. */
4294 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004295
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004296 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004297 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004298 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004299 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004300 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004301 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004302
Victor Stinner8f674cc2013-04-17 23:02:17 +02004303 if (PyUnicode_READY(repunicode) < 0)
4304 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004305 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004306 if (replen > 1) {
4307 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004308 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004309 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4310 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4311 goto onError;
4312 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004313 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004314 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004315
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004316 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004317 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004318
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004319 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004320 Py_XDECREF(restuple);
4321 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004322
Benjamin Peterson29060642009-01-31 22:14:21 +00004323 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004324 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004325 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004326}
4327
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004328/* --- UTF-7 Codec -------------------------------------------------------- */
4329
Antoine Pitrou244651a2009-05-04 18:56:13 +00004330/* See RFC2152 for details. We encode conservatively and decode liberally. */
4331
4332/* Three simple macros defining base-64. */
4333
4334/* Is c a base-64 character? */
4335
4336#define IS_BASE64(c) \
4337 (((c) >= 'A' && (c) <= 'Z') || \
4338 ((c) >= 'a' && (c) <= 'z') || \
4339 ((c) >= '0' && (c) <= '9') || \
4340 (c) == '+' || (c) == '/')
4341
4342/* given that c is a base-64 character, what is its base-64 value? */
4343
4344#define FROM_BASE64(c) \
4345 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4346 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4347 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4348 (c) == '+' ? 62 : 63)
4349
4350/* What is the base-64 character of the bottom 6 bits of n? */
4351
4352#define TO_BASE64(n) \
4353 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4354
4355/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4356 * decoded as itself. We are permissive on decoding; the only ASCII
4357 * byte not decoding to itself is the + which begins a base64
4358 * string. */
4359
4360#define DECODE_DIRECT(c) \
4361 ((c) <= 127 && (c) != '+')
4362
4363/* The UTF-7 encoder treats ASCII characters differently according to
4364 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4365 * the above). See RFC2152. This array identifies these different
4366 * sets:
4367 * 0 : "Set D"
4368 * alphanumeric and '(),-./:?
4369 * 1 : "Set O"
4370 * !"#$%&*;<=>@[]^_`{|}
4371 * 2 : "whitespace"
4372 * ht nl cr sp
4373 * 3 : special (must be base64 encoded)
4374 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4375 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004376
Tim Petersced69f82003-09-16 20:30:58 +00004377static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004378char utf7_category[128] = {
4379/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4380 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4381/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4382 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4383/* sp ! " # $ % & ' ( ) * + , - . / */
4384 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4385/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4386 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4387/* @ A B C D E F G H I J K L M N O */
4388 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4389/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4390 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4391/* ` a b c d e f g h i j k l m n o */
4392 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4393/* p q r s t u v w x y z { | } ~ del */
4394 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004395};
4396
Antoine Pitrou244651a2009-05-04 18:56:13 +00004397/* ENCODE_DIRECT: this character should be encoded as itself. The
4398 * answer depends on whether we are encoding set O as itself, and also
4399 * on whether we are encoding whitespace as itself. RFC2152 makes it
4400 * clear that the answers to these questions vary between
4401 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004402
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403#define ENCODE_DIRECT(c, directO, directWS) \
4404 ((c) < 128 && (c) > 0 && \
4405 ((utf7_category[(c)] == 0) || \
4406 (directWS && (utf7_category[(c)] == 2)) || \
4407 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004408
Alexander Belopolsky40018472011-02-26 01:02:56 +00004409PyObject *
4410PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004411 Py_ssize_t size,
4412 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004413{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004414 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4415}
4416
Antoine Pitrou244651a2009-05-04 18:56:13 +00004417/* The decoder. The only state we preserve is our read position,
4418 * i.e. how many characters we have consumed. So if we end in the
4419 * middle of a shift sequence we have to back off the read position
4420 * and the output to the beginning of the sequence, otherwise we lose
4421 * all the shift state (seen bits, number of bits seen, high
4422 * surrogate). */
4423
Alexander Belopolsky40018472011-02-26 01:02:56 +00004424PyObject *
4425PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004426 Py_ssize_t size,
4427 const char *errors,
4428 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004429{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004430 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004431 Py_ssize_t startinpos;
4432 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004433 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004434 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004435 const char *errmsg = "";
4436 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004437 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004438 unsigned int base64bits = 0;
4439 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004440 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004441 PyObject *errorHandler = NULL;
4442 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004443
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004444 if (size == 0) {
4445 if (consumed)
4446 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004447 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004448 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004449
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004450 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004451 _PyUnicodeWriter_Init(&writer);
4452 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004453
4454 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004455 e = s + size;
4456
4457 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004458 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004459 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004460 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004461
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462 if (inShift) { /* in a base-64 section */
4463 if (IS_BASE64(ch)) { /* consume a base-64 character */
4464 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4465 base64bits += 6;
4466 s++;
4467 if (base64bits >= 16) {
4468 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004469 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004470 base64bits -= 16;
4471 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004472 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004473 if (surrogate) {
4474 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004475 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4476 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004477 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004478 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004479 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004480 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004481 }
4482 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004483 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004484 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004485 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004486 }
4487 }
Victor Stinner551ac952011-11-29 22:58:13 +01004488 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004489 /* first surrogate */
4490 surrogate = outCh;
4491 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004492 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004493 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004494 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004495 }
4496 }
4497 }
4498 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004499 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004500 if (base64bits > 0) { /* left-over bits */
4501 if (base64bits >= 6) {
4502 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004503 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004504 errmsg = "partial character in shift sequence";
4505 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004506 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004507 else {
4508 /* Some bits remain; they should be zero */
4509 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004510 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004511 errmsg = "non-zero padding bits in shift sequence";
4512 goto utf7Error;
4513 }
4514 }
4515 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004516 if (surrogate && DECODE_DIRECT(ch)) {
4517 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4518 goto onError;
4519 }
4520 surrogate = 0;
4521 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004522 /* '-' is absorbed; other terminating
4523 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004524 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004525 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004526 }
4527 }
4528 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004529 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004530 s++; /* consume '+' */
4531 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004532 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004533 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004534 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004535 }
4536 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004537 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004538 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004539 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004540 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004541 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004542 }
4543 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004544 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004545 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004546 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004547 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004548 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004549 else {
4550 startinpos = s-starts;
4551 s++;
4552 errmsg = "unexpected special character";
4553 goto utf7Error;
4554 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004555 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004556utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004557 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004558 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004559 errors, &errorHandler,
4560 "utf7", errmsg,
4561 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004562 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004563 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004564 }
4565
Antoine Pitrou244651a2009-05-04 18:56:13 +00004566 /* end of string */
4567
4568 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4569 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004570 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004571 if (surrogate ||
4572 (base64bits >= 6) ||
4573 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004575 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004576 errors, &errorHandler,
4577 "utf7", "unterminated shift sequence",
4578 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004579 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 goto onError;
4581 if (s < e)
4582 goto restart;
4583 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004584 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004585
4586 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004587 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004588 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004589 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004590 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004591 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004592 writer.kind, writer.data, shiftOutStart);
4593 Py_XDECREF(errorHandler);
4594 Py_XDECREF(exc);
4595 _PyUnicodeWriter_Dealloc(&writer);
4596 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004597 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004598 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004599 }
4600 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004601 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004602 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004603 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004604
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004605 Py_XDECREF(errorHandler);
4606 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004607 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004608
Benjamin Peterson29060642009-01-31 22:14:21 +00004609 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004610 Py_XDECREF(errorHandler);
4611 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004612 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004613 return NULL;
4614}
4615
4616
Alexander Belopolsky40018472011-02-26 01:02:56 +00004617PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004618_PyUnicode_EncodeUTF7(PyObject *str,
4619 int base64SetO,
4620 int base64WhiteSpace,
4621 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004622{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004623 int kind;
4624 void *data;
4625 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004626 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004627 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004628 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004629 unsigned int base64bits = 0;
4630 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004631 char * out;
4632 char * start;
4633
Benjamin Petersonbac79492012-01-14 13:34:47 -05004634 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004635 return NULL;
4636 kind = PyUnicode_KIND(str);
4637 data = PyUnicode_DATA(str);
4638 len = PyUnicode_GET_LENGTH(str);
4639
4640 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004641 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004642
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004643 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004644 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004645 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004646 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004647 if (v == NULL)
4648 return NULL;
4649
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004650 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004651 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004652 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004653
Antoine Pitrou244651a2009-05-04 18:56:13 +00004654 if (inShift) {
4655 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4656 /* shifting out */
4657 if (base64bits) { /* output remaining bits */
4658 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4659 base64buffer = 0;
4660 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004661 }
4662 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004663 /* Characters not in the BASE64 set implicitly unshift the sequence
4664 so no '-' is required, except if the character is itself a '-' */
4665 if (IS_BASE64(ch) || ch == '-') {
4666 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004667 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004668 *out++ = (char) ch;
4669 }
4670 else {
4671 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004672 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004673 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004674 else { /* not in a shift sequence */
4675 if (ch == '+') {
4676 *out++ = '+';
4677 *out++ = '-';
4678 }
4679 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4680 *out++ = (char) ch;
4681 }
4682 else {
4683 *out++ = '+';
4684 inShift = 1;
4685 goto encode_char;
4686 }
4687 }
4688 continue;
4689encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004690 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004691 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004692
Antoine Pitrou244651a2009-05-04 18:56:13 +00004693 /* code first surrogate */
4694 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004695 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004696 while (base64bits >= 6) {
4697 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4698 base64bits -= 6;
4699 }
4700 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004701 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004702 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004703 base64bits += 16;
4704 base64buffer = (base64buffer << 16) | ch;
4705 while (base64bits >= 6) {
4706 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4707 base64bits -= 6;
4708 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004709 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004710 if (base64bits)
4711 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4712 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004713 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004714 if (_PyBytes_Resize(&v, out - start) < 0)
4715 return NULL;
4716 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004717}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004718PyObject *
4719PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4720 Py_ssize_t size,
4721 int base64SetO,
4722 int base64WhiteSpace,
4723 const char *errors)
4724{
4725 PyObject *result;
4726 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4727 if (tmp == NULL)
4728 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004729 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004730 base64WhiteSpace, errors);
4731 Py_DECREF(tmp);
4732 return result;
4733}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004734
Antoine Pitrou244651a2009-05-04 18:56:13 +00004735#undef IS_BASE64
4736#undef FROM_BASE64
4737#undef TO_BASE64
4738#undef DECODE_DIRECT
4739#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004740
Guido van Rossumd57fd912000-03-10 22:53:23 +00004741/* --- UTF-8 Codec -------------------------------------------------------- */
4742
Alexander Belopolsky40018472011-02-26 01:02:56 +00004743PyObject *
4744PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004745 Py_ssize_t size,
4746 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004747{
Walter Dörwald69652032004-09-07 20:24:22 +00004748 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4749}
4750
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004751#include "stringlib/asciilib.h"
4752#include "stringlib/codecs.h"
4753#include "stringlib/undef.h"
4754
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004755#include "stringlib/ucs1lib.h"
4756#include "stringlib/codecs.h"
4757#include "stringlib/undef.h"
4758
4759#include "stringlib/ucs2lib.h"
4760#include "stringlib/codecs.h"
4761#include "stringlib/undef.h"
4762
4763#include "stringlib/ucs4lib.h"
4764#include "stringlib/codecs.h"
4765#include "stringlib/undef.h"
4766
Antoine Pitrouab868312009-01-10 15:40:25 +00004767/* Mask to quickly check whether a C 'long' contains a
4768 non-ASCII, UTF8-encoded char. */
4769#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004770# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004771#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004772# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004773#else
4774# error C 'long' size should be either 4 or 8!
4775#endif
4776
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004777static Py_ssize_t
4778ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004779{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004780 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004781 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004782
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004783 /*
4784 * Issue #17237: m68k is a bit different from most architectures in
4785 * that objects do not use "natural alignment" - for example, int and
4786 * long are only aligned at 2-byte boundaries. Therefore the assert()
4787 * won't work; also, tests have shown that skipping the "optimised
4788 * version" will even speed up m68k.
4789 */
4790#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004791#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004792 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4793 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004794 /* Fast path, see in STRINGLIB(utf8_decode) for
4795 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004796 /* Help allocation */
4797 const char *_p = p;
4798 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004799 while (_p < aligned_end) {
4800 unsigned long value = *(const unsigned long *) _p;
4801 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004802 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004803 *((unsigned long *)q) = value;
4804 _p += SIZEOF_LONG;
4805 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004806 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004807 p = _p;
4808 while (p < end) {
4809 if ((unsigned char)*p & 0x80)
4810 break;
4811 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004812 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004813 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004814 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004815#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004816#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004817 while (p < end) {
4818 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4819 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004820 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004821 /* Help allocation */
4822 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004823 while (_p < aligned_end) {
4824 unsigned long value = *(unsigned long *) _p;
4825 if (value & ASCII_CHAR_MASK)
4826 break;
4827 _p += SIZEOF_LONG;
4828 }
4829 p = _p;
4830 if (_p == end)
4831 break;
4832 }
4833 if ((unsigned char)*p & 0x80)
4834 break;
4835 ++p;
4836 }
4837 memcpy(dest, start, p - start);
4838 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004839}
Antoine Pitrouab868312009-01-10 15:40:25 +00004840
Victor Stinner785938e2011-12-11 20:09:03 +01004841PyObject *
4842PyUnicode_DecodeUTF8Stateful(const char *s,
4843 Py_ssize_t size,
4844 const char *errors,
4845 Py_ssize_t *consumed)
4846{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004847 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004848 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004849 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004850
4851 Py_ssize_t startinpos;
4852 Py_ssize_t endinpos;
4853 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004854 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004855 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004856 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004857
4858 if (size == 0) {
4859 if (consumed)
4860 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004861 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004862 }
4863
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004864 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4865 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004866 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004867 *consumed = 1;
4868 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004869 }
4870
Victor Stinner8f674cc2013-04-17 23:02:17 +02004871 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004872 writer.min_length = size;
4873 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004874 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004875
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004876 writer.pos = ascii_decode(s, end, writer.data);
4877 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004878 while (s < end) {
4879 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004880 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004881
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004882 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004883 if (PyUnicode_IS_ASCII(writer.buffer))
4884 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004885 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004886 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004887 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004888 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004889 } else {
4890 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004891 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004892 }
4893
4894 switch (ch) {
4895 case 0:
4896 if (s == end || consumed)
4897 goto End;
4898 errmsg = "unexpected end of data";
4899 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004900 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004901 break;
4902 case 1:
4903 errmsg = "invalid start byte";
4904 startinpos = s - starts;
4905 endinpos = startinpos + 1;
4906 break;
4907 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004908 case 3:
4909 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004910 errmsg = "invalid continuation byte";
4911 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004912 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004913 break;
4914 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004915 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004916 goto onError;
4917 continue;
4918 }
4919
Victor Stinner1d65d912015-10-05 13:43:50 +02004920 if (error_handler == _Py_ERROR_UNKNOWN)
4921 error_handler = get_error_handler(errors);
4922
4923 switch (error_handler) {
4924 case _Py_ERROR_IGNORE:
4925 s += (endinpos - startinpos);
4926 break;
4927
4928 case _Py_ERROR_REPLACE:
4929 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4930 goto onError;
4931 s += (endinpos - startinpos);
4932 break;
4933
4934 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004935 {
4936 Py_ssize_t i;
4937
Victor Stinner1d65d912015-10-05 13:43:50 +02004938 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4939 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004940 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004941 ch = (Py_UCS4)(unsigned char)(starts[i]);
4942 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4943 ch + 0xdc00);
4944 writer.pos++;
4945 }
4946 s += (endinpos - startinpos);
4947 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004948 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004949
4950 default:
4951 if (unicode_decode_call_errorhandler_writer(
4952 errors, &error_handler_obj,
4953 "utf-8", errmsg,
4954 &starts, &end, &startinpos, &endinpos, &exc, &s,
4955 &writer))
4956 goto onError;
4957 }
Victor Stinner785938e2011-12-11 20:09:03 +01004958 }
4959
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004960End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004961 if (consumed)
4962 *consumed = s - starts;
4963
Victor Stinner1d65d912015-10-05 13:43:50 +02004964 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004965 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004966 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004967
4968onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004969 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004970 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004971 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004972 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004973}
4974
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004975#ifdef __APPLE__
4976
4977/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004978 used to decode the command line arguments on Mac OS X.
4979
4980 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004981 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004982
4983wchar_t*
4984_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4985{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004986 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004987 wchar_t *unicode;
4988 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004989
4990 /* Note: size will always be longer than the resulting Unicode
4991 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01004992 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004993 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004994 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004995 if (!unicode)
4996 return NULL;
4997
4998 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004999 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005000 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005001 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005002 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005003#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005004 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005005#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005006 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005007#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005008 if (ch > 0xFF) {
5009#if SIZEOF_WCHAR_T == 4
5010 assert(0);
5011#else
5012 assert(Py_UNICODE_IS_SURROGATE(ch));
5013 /* compute and append the two surrogates: */
5014 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5015 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5016#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005017 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005018 else {
5019 if (!ch && s == e)
5020 break;
5021 /* surrogateescape */
5022 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5023 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005024 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005025 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005026 return unicode;
5027}
5028
5029#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005030
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005031/* Primary internal function which creates utf8 encoded bytes objects.
5032
5033 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005034 and allocate exactly as much space needed at the end. Else allocate the
5035 maximum possible needed (4 result bytes per Unicode character), and return
5036 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005037*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005038PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005039_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005040{
Victor Stinner6099a032011-12-18 14:22:26 +01005041 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005042 void *data;
5043 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005044
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005045 if (!PyUnicode_Check(unicode)) {
5046 PyErr_BadArgument();
5047 return NULL;
5048 }
5049
5050 if (PyUnicode_READY(unicode) == -1)
5051 return NULL;
5052
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005053 if (PyUnicode_UTF8(unicode))
5054 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5055 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005056
5057 kind = PyUnicode_KIND(unicode);
5058 data = PyUnicode_DATA(unicode);
5059 size = PyUnicode_GET_LENGTH(unicode);
5060
Benjamin Petersonead6b532011-12-20 17:23:42 -06005061 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005062 default:
5063 assert(0);
5064 case PyUnicode_1BYTE_KIND:
5065 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5066 assert(!PyUnicode_IS_ASCII(unicode));
5067 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5068 case PyUnicode_2BYTE_KIND:
5069 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5070 case PyUnicode_4BYTE_KIND:
5071 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005072 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005073}
5074
Alexander Belopolsky40018472011-02-26 01:02:56 +00005075PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005076PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5077 Py_ssize_t size,
5078 const char *errors)
5079{
5080 PyObject *v, *unicode;
5081
5082 unicode = PyUnicode_FromUnicode(s, size);
5083 if (unicode == NULL)
5084 return NULL;
5085 v = _PyUnicode_AsUTF8String(unicode, errors);
5086 Py_DECREF(unicode);
5087 return v;
5088}
5089
5090PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005091PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005092{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005093 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005094}
5095
Walter Dörwald41980ca2007-08-16 21:55:45 +00005096/* --- UTF-32 Codec ------------------------------------------------------- */
5097
5098PyObject *
5099PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005100 Py_ssize_t size,
5101 const char *errors,
5102 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005103{
5104 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5105}
5106
5107PyObject *
5108PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005109 Py_ssize_t size,
5110 const char *errors,
5111 int *byteorder,
5112 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005113{
5114 const char *starts = s;
5115 Py_ssize_t startinpos;
5116 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005117 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005118 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005119 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005120 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005121 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005122 PyObject *errorHandler = NULL;
5123 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005124
Walter Dörwald41980ca2007-08-16 21:55:45 +00005125 q = (unsigned char *)s;
5126 e = q + size;
5127
5128 if (byteorder)
5129 bo = *byteorder;
5130
5131 /* Check for BOM marks (U+FEFF) in the input and adjust current
5132 byte order setting accordingly. In native mode, the leading BOM
5133 mark is skipped, in all other modes, it is copied to the output
5134 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005135 if (bo == 0 && size >= 4) {
5136 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5137 if (bom == 0x0000FEFF) {
5138 bo = -1;
5139 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005140 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005141 else if (bom == 0xFFFE0000) {
5142 bo = 1;
5143 q += 4;
5144 }
5145 if (byteorder)
5146 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005147 }
5148
Victor Stinnere64322e2012-10-30 23:12:47 +01005149 if (q == e) {
5150 if (consumed)
5151 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005152 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005153 }
5154
Victor Stinnere64322e2012-10-30 23:12:47 +01005155#ifdef WORDS_BIGENDIAN
5156 le = bo < 0;
5157#else
5158 le = bo <= 0;
5159#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005160 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005161
Victor Stinner8f674cc2013-04-17 23:02:17 +02005162 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005163 writer.min_length = (e - q + 3) / 4;
5164 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005165 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005166
Victor Stinnere64322e2012-10-30 23:12:47 +01005167 while (1) {
5168 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005169 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005170
Victor Stinnere64322e2012-10-30 23:12:47 +01005171 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005172 enum PyUnicode_Kind kind = writer.kind;
5173 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005174 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005175 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005176 if (le) {
5177 do {
5178 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5179 if (ch > maxch)
5180 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005181 if (kind != PyUnicode_1BYTE_KIND &&
5182 Py_UNICODE_IS_SURROGATE(ch))
5183 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005184 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005185 q += 4;
5186 } while (q <= last);
5187 }
5188 else {
5189 do {
5190 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5191 if (ch > maxch)
5192 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005193 if (kind != PyUnicode_1BYTE_KIND &&
5194 Py_UNICODE_IS_SURROGATE(ch))
5195 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005196 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005197 q += 4;
5198 } while (q <= last);
5199 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005200 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005201 }
5202
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005203 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005204 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005205 startinpos = ((const char *)q) - starts;
5206 endinpos = startinpos + 4;
5207 }
5208 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005209 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005210 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005211 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005212 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005213 startinpos = ((const char *)q) - starts;
5214 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005215 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005216 else {
5217 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005218 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005219 goto onError;
5220 q += 4;
5221 continue;
5222 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005223 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005224 startinpos = ((const char *)q) - starts;
5225 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005226 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005227
5228 /* The remaining input chars are ignored if the callback
5229 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005230 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005231 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005232 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005233 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005234 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005235 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005236 }
5237
Walter Dörwald41980ca2007-08-16 21:55:45 +00005238 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005239 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005240
Walter Dörwald41980ca2007-08-16 21:55:45 +00005241 Py_XDECREF(errorHandler);
5242 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005243 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005244
Benjamin Peterson29060642009-01-31 22:14:21 +00005245 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005246 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005247 Py_XDECREF(errorHandler);
5248 Py_XDECREF(exc);
5249 return NULL;
5250}
5251
5252PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005253_PyUnicode_EncodeUTF32(PyObject *str,
5254 const char *errors,
5255 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005256{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005257 enum PyUnicode_Kind kind;
5258 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005259 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005260 PyObject *v;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005261 PY_UINT32_T *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005262#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005263 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005264#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005265 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005266#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005267 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005268 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005269 PyObject *errorHandler = NULL;
5270 PyObject *exc = NULL;
5271 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005272
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005273 if (!PyUnicode_Check(str)) {
5274 PyErr_BadArgument();
5275 return NULL;
5276 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005277 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005278 return NULL;
5279 kind = PyUnicode_KIND(str);
5280 data = PyUnicode_DATA(str);
5281 len = PyUnicode_GET_LENGTH(str);
5282
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005283 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005284 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005285 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005286 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005287 if (v == NULL)
5288 return NULL;
5289
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005290 /* output buffer is 4-bytes aligned */
5291 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
5292 out = (PY_UINT32_T *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005293 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005294 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005295 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005296 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005297
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005298 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005299 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005300 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005301 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005302 else
5303 encoding = "utf-32";
5304
5305 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005306 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5307 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005308 }
5309
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005310 pos = 0;
5311 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005312 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005313
5314 if (kind == PyUnicode_2BYTE_KIND) {
5315 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5316 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005317 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005318 else {
5319 assert(kind == PyUnicode_4BYTE_KIND);
5320 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5321 &out, native_ordering);
5322 }
5323 if (pos == len)
5324 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005325
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005326 rep = unicode_encode_call_errorhandler(
5327 errors, &errorHandler,
5328 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005329 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005330 if (!rep)
5331 goto error;
5332
5333 if (PyBytes_Check(rep)) {
5334 repsize = PyBytes_GET_SIZE(rep);
5335 if (repsize & 3) {
5336 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005337 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005338 "surrogates not allowed");
5339 goto error;
5340 }
5341 moreunits = repsize / 4;
5342 }
5343 else {
5344 assert(PyUnicode_Check(rep));
5345 if (PyUnicode_READY(rep) < 0)
5346 goto error;
5347 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5348 if (!PyUnicode_IS_ASCII(rep)) {
5349 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005350 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005351 "surrogates not allowed");
5352 goto error;
5353 }
5354 }
5355
5356 /* four bytes are reserved for each surrogate */
5357 if (moreunits > 1) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005358 Py_ssize_t outpos = out - (PY_UINT32_T*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005359 Py_ssize_t morebytes = 4 * (moreunits - 1);
5360 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5361 /* integer overflow */
5362 PyErr_NoMemory();
5363 goto error;
5364 }
5365 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5366 goto error;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005367 out = (PY_UINT32_T*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005368 }
5369
5370 if (PyBytes_Check(rep)) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005371 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5372 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005373 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005374 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005375 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5376 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005377 }
5378
5379 Py_CLEAR(rep);
5380 }
5381
5382 /* Cut back to size actually needed. This is necessary for, for example,
5383 encoding of a string containing isolated surrogates and the 'ignore'
5384 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005385 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005386 if (nsize != PyBytes_GET_SIZE(v))
5387 _PyBytes_Resize(&v, nsize);
5388 Py_XDECREF(errorHandler);
5389 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005390 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005391 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005392 error:
5393 Py_XDECREF(rep);
5394 Py_XDECREF(errorHandler);
5395 Py_XDECREF(exc);
5396 Py_XDECREF(v);
5397 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005398}
5399
Alexander Belopolsky40018472011-02-26 01:02:56 +00005400PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005401PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5402 Py_ssize_t size,
5403 const char *errors,
5404 int byteorder)
5405{
5406 PyObject *result;
5407 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5408 if (tmp == NULL)
5409 return NULL;
5410 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5411 Py_DECREF(tmp);
5412 return result;
5413}
5414
5415PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005416PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005417{
Victor Stinnerb960b342011-11-20 19:12:52 +01005418 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005419}
5420
Guido van Rossumd57fd912000-03-10 22:53:23 +00005421/* --- UTF-16 Codec ------------------------------------------------------- */
5422
Tim Peters772747b2001-08-09 22:21:55 +00005423PyObject *
5424PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005425 Py_ssize_t size,
5426 const char *errors,
5427 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428{
Walter Dörwald69652032004-09-07 20:24:22 +00005429 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5430}
5431
5432PyObject *
5433PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005434 Py_ssize_t size,
5435 const char *errors,
5436 int *byteorder,
5437 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005438{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005439 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005440 Py_ssize_t startinpos;
5441 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005442 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005443 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005444 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005445 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005446 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005447 PyObject *errorHandler = NULL;
5448 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005449 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005450
Tim Peters772747b2001-08-09 22:21:55 +00005451 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005452 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005453
5454 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005455 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005456
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005457 /* Check for BOM marks (U+FEFF) in the input and adjust current
5458 byte order setting accordingly. In native mode, the leading BOM
5459 mark is skipped, in all other modes, it is copied to the output
5460 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005461 if (bo == 0 && size >= 2) {
5462 const Py_UCS4 bom = (q[1] << 8) | q[0];
5463 if (bom == 0xFEFF) {
5464 q += 2;
5465 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005466 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005467 else if (bom == 0xFFFE) {
5468 q += 2;
5469 bo = 1;
5470 }
5471 if (byteorder)
5472 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005473 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005474
Antoine Pitrou63065d72012-05-15 23:48:04 +02005475 if (q == e) {
5476 if (consumed)
5477 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005478 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005479 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005480
Christian Heimes743e0cd2012-10-17 23:52:17 +02005481#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005482 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005483 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005484#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005485 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005486 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005487#endif
Tim Peters772747b2001-08-09 22:21:55 +00005488
Antoine Pitrou63065d72012-05-15 23:48:04 +02005489 /* Note: size will always be longer than the resulting Unicode
5490 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005491 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005492 writer.min_length = (e - q + 1) / 2;
5493 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005494 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005495
Antoine Pitrou63065d72012-05-15 23:48:04 +02005496 while (1) {
5497 Py_UCS4 ch = 0;
5498 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005499 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005500 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005501 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005502 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005503 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005504 native_ordering);
5505 else
5506 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005507 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005508 native_ordering);
5509 } else if (kind == PyUnicode_2BYTE_KIND) {
5510 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005511 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005512 native_ordering);
5513 } else {
5514 assert(kind == PyUnicode_4BYTE_KIND);
5515 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005516 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005517 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005518 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005519 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005520
Antoine Pitrou63065d72012-05-15 23:48:04 +02005521 switch (ch)
5522 {
5523 case 0:
5524 /* remaining byte at the end? (size should be even) */
5525 if (q == e || consumed)
5526 goto End;
5527 errmsg = "truncated data";
5528 startinpos = ((const char *)q) - starts;
5529 endinpos = ((const char *)e) - starts;
5530 break;
5531 /* The remaining input chars are ignored if the callback
5532 chooses to skip the input */
5533 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005534 q -= 2;
5535 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005536 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005537 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005538 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005539 endinpos = ((const char *)e) - starts;
5540 break;
5541 case 2:
5542 errmsg = "illegal encoding";
5543 startinpos = ((const char *)q) - 2 - starts;
5544 endinpos = startinpos + 2;
5545 break;
5546 case 3:
5547 errmsg = "illegal UTF-16 surrogate";
5548 startinpos = ((const char *)q) - 4 - starts;
5549 endinpos = startinpos + 2;
5550 break;
5551 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005552 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005553 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005554 continue;
5555 }
5556
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005557 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005558 errors,
5559 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005560 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005561 &starts,
5562 (const char **)&e,
5563 &startinpos,
5564 &endinpos,
5565 &exc,
5566 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005567 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005568 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005569 }
5570
Antoine Pitrou63065d72012-05-15 23:48:04 +02005571End:
Walter Dörwald69652032004-09-07 20:24:22 +00005572 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005573 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005574
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005575 Py_XDECREF(errorHandler);
5576 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005577 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005578
Benjamin Peterson29060642009-01-31 22:14:21 +00005579 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005580 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005581 Py_XDECREF(errorHandler);
5582 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005583 return NULL;
5584}
5585
Tim Peters772747b2001-08-09 22:21:55 +00005586PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005587_PyUnicode_EncodeUTF16(PyObject *str,
5588 const char *errors,
5589 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005590{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005591 enum PyUnicode_Kind kind;
5592 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005593 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005594 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005595 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005596 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005597#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005598 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005599#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005600 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005601#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005602 const char *encoding;
5603 Py_ssize_t nsize, pos;
5604 PyObject *errorHandler = NULL;
5605 PyObject *exc = NULL;
5606 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005607
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005608 if (!PyUnicode_Check(str)) {
5609 PyErr_BadArgument();
5610 return NULL;
5611 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005612 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005613 return NULL;
5614 kind = PyUnicode_KIND(str);
5615 data = PyUnicode_DATA(str);
5616 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005617
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005618 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005619 if (kind == PyUnicode_4BYTE_KIND) {
5620 const Py_UCS4 *in = (const Py_UCS4 *)data;
5621 const Py_UCS4 *end = in + len;
5622 while (in < end)
5623 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005624 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005625 }
5626 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005627 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005628 nsize = len + pairs + (byteorder == 0);
5629 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630 if (v == NULL)
5631 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005632
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005633 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005634 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005635 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005636 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005637 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005638 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005639 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005640
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005641 if (kind == PyUnicode_1BYTE_KIND) {
5642 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5643 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005644 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005645
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005646 if (byteorder < 0)
5647 encoding = "utf-16-le";
5648 else if (byteorder > 0)
5649 encoding = "utf-16-be";
5650 else
5651 encoding = "utf-16";
5652
5653 pos = 0;
5654 while (pos < len) {
5655 Py_ssize_t repsize, moreunits;
5656
5657 if (kind == PyUnicode_2BYTE_KIND) {
5658 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5659 &out, native_ordering);
5660 }
5661 else {
5662 assert(kind == PyUnicode_4BYTE_KIND);
5663 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5664 &out, native_ordering);
5665 }
5666 if (pos == len)
5667 break;
5668
5669 rep = unicode_encode_call_errorhandler(
5670 errors, &errorHandler,
5671 encoding, "surrogates not allowed",
5672 str, &exc, pos, pos + 1, &pos);
5673 if (!rep)
5674 goto error;
5675
5676 if (PyBytes_Check(rep)) {
5677 repsize = PyBytes_GET_SIZE(rep);
5678 if (repsize & 1) {
5679 raise_encode_exception(&exc, encoding,
5680 str, pos - 1, pos,
5681 "surrogates not allowed");
5682 goto error;
5683 }
5684 moreunits = repsize / 2;
5685 }
5686 else {
5687 assert(PyUnicode_Check(rep));
5688 if (PyUnicode_READY(rep) < 0)
5689 goto error;
5690 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5691 if (!PyUnicode_IS_ASCII(rep)) {
5692 raise_encode_exception(&exc, encoding,
5693 str, pos - 1, pos,
5694 "surrogates not allowed");
5695 goto error;
5696 }
5697 }
5698
5699 /* two bytes are reserved for each surrogate */
5700 if (moreunits > 1) {
5701 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5702 Py_ssize_t morebytes = 2 * (moreunits - 1);
5703 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5704 /* integer overflow */
5705 PyErr_NoMemory();
5706 goto error;
5707 }
5708 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5709 goto error;
5710 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5711 }
5712
5713 if (PyBytes_Check(rep)) {
5714 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5715 out += moreunits;
5716 } else /* rep is unicode */ {
5717 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5718 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5719 &out, native_ordering);
5720 }
5721
5722 Py_CLEAR(rep);
5723 }
5724
5725 /* Cut back to size actually needed. This is necessary for, for example,
5726 encoding of a string containing isolated surrogates and the 'ignore' handler
5727 is used. */
5728 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5729 if (nsize != PyBytes_GET_SIZE(v))
5730 _PyBytes_Resize(&v, nsize);
5731 Py_XDECREF(errorHandler);
5732 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005733 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005734 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005735 error:
5736 Py_XDECREF(rep);
5737 Py_XDECREF(errorHandler);
5738 Py_XDECREF(exc);
5739 Py_XDECREF(v);
5740 return NULL;
5741#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742}
5743
Alexander Belopolsky40018472011-02-26 01:02:56 +00005744PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005745PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5746 Py_ssize_t size,
5747 const char *errors,
5748 int byteorder)
5749{
5750 PyObject *result;
5751 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5752 if (tmp == NULL)
5753 return NULL;
5754 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5755 Py_DECREF(tmp);
5756 return result;
5757}
5758
5759PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005760PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005761{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005762 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005763}
5764
5765/* --- Unicode Escape Codec ----------------------------------------------- */
5766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005767/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5768 if all the escapes in the string make it still a valid ASCII string.
5769 Returns -1 if any escapes were found which cause the string to
5770 pop out of ASCII range. Otherwise returns the length of the
5771 required buffer to hold the string.
5772 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005773static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005774length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5775{
5776 const unsigned char *p = (const unsigned char *)s;
5777 const unsigned char *end = p + size;
5778 Py_ssize_t length = 0;
5779
5780 if (size < 0)
5781 return -1;
5782
5783 for (; p < end; ++p) {
5784 if (*p > 127) {
5785 /* Non-ASCII */
5786 return -1;
5787 }
5788 else if (*p != '\\') {
5789 /* Normal character */
5790 ++length;
5791 }
5792 else {
5793 /* Backslash-escape, check next char */
5794 ++p;
5795 /* Escape sequence reaches till end of string or
5796 non-ASCII follow-up. */
5797 if (p >= end || *p > 127)
5798 return -1;
5799 switch (*p) {
5800 case '\n':
5801 /* backslash + \n result in zero characters */
5802 break;
5803 case '\\': case '\'': case '\"':
5804 case 'b': case 'f': case 't':
5805 case 'n': case 'r': case 'v': case 'a':
5806 ++length;
5807 break;
5808 case '0': case '1': case '2': case '3':
5809 case '4': case '5': case '6': case '7':
5810 case 'x': case 'u': case 'U': case 'N':
5811 /* these do not guarantee ASCII characters */
5812 return -1;
5813 default:
5814 /* count the backslash + the other character */
5815 length += 2;
5816 }
5817 }
5818 }
5819 return length;
5820}
5821
Fredrik Lundh06d12682001-01-24 07:59:11 +00005822static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005823
Alexander Belopolsky40018472011-02-26 01:02:56 +00005824PyObject *
5825PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005826 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005827 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005828{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005829 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005830 Py_ssize_t startinpos;
5831 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005832 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005833 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005834 char* message;
5835 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005836 PyObject *errorHandler = NULL;
5837 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005838 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005839
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005840 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005841 if (len == 0)
5842 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005843
5844 /* After length_of_escaped_ascii_string() there are two alternatives,
5845 either the string is pure ASCII with named escapes like \n, etc.
5846 and we determined it's exact size (common case)
5847 or it contains \x, \u, ... escape sequences. then we create a
5848 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005849 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005850 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005851 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005852 }
5853 else {
5854 /* Escaped strings will always be longer than the resulting
5855 Unicode string, so we start with size here and then reduce the
5856 length after conversion to the true value.
5857 (but if the error callback returns a long replacement string
5858 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005859 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005860 }
5861
Guido van Rossumd57fd912000-03-10 22:53:23 +00005862 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005863 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005864 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005865
Guido van Rossumd57fd912000-03-10 22:53:23 +00005866 while (s < end) {
5867 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005868 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005869 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870
5871 /* Non-escape characters are interpreted as Unicode ordinals */
5872 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005873 x = (unsigned char)*s;
5874 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005875 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005876 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005877 continue;
5878 }
5879
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005880 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881 /* \ - Escapes */
5882 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005883 c = *s++;
5884 if (s > end)
5885 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005886
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005887 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005888
Benjamin Peterson29060642009-01-31 22:14:21 +00005889 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005890#define WRITECHAR(ch) \
5891 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005892 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005893 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005894 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005895
Guido van Rossumd57fd912000-03-10 22:53:23 +00005896 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005897 case '\\': WRITECHAR('\\'); break;
5898 case '\'': WRITECHAR('\''); break;
5899 case '\"': WRITECHAR('\"'); break;
5900 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005901 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005902 case 'f': WRITECHAR('\014'); break;
5903 case 't': WRITECHAR('\t'); break;
5904 case 'n': WRITECHAR('\n'); break;
5905 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005906 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005907 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005908 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005909 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910
Benjamin Peterson29060642009-01-31 22:14:21 +00005911 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005912 case '0': case '1': case '2': case '3':
5913 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005914 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005915 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005916 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005917 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005918 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005920 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005921 break;
5922
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 /* hex escapes */
5924 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005926 digits = 2;
5927 message = "truncated \\xXX escape";
5928 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929
Benjamin Peterson29060642009-01-31 22:14:21 +00005930 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005931 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005932 digits = 4;
5933 message = "truncated \\uXXXX escape";
5934 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935
Benjamin Peterson29060642009-01-31 22:14:21 +00005936 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005937 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005938 digits = 8;
5939 message = "truncated \\UXXXXXXXX escape";
5940 hexescape:
5941 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005942 if (end - s < digits) {
5943 /* count only hex digits */
5944 for (; s < end; ++s) {
5945 c = (unsigned char)*s;
5946 if (!Py_ISXDIGIT(c))
5947 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005948 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005949 goto error;
5950 }
5951 for (; digits--; ++s) {
5952 c = (unsigned char)*s;
5953 if (!Py_ISXDIGIT(c))
5954 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005955 chr = (chr<<4) & ~0xF;
5956 if (c >= '0' && c <= '9')
5957 chr += c - '0';
5958 else if (c >= 'a' && c <= 'f')
5959 chr += 10 + c - 'a';
5960 else
5961 chr += 10 + c - 'A';
5962 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005963 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005964 /* _decoding_error will have already written into the
5965 target buffer. */
5966 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005967 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005968 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005969 message = "illegal Unicode character";
5970 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005971 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005972 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005973 break;
5974
Benjamin Peterson29060642009-01-31 22:14:21 +00005975 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005976 case 'N':
5977 message = "malformed \\N character escape";
5978 if (ucnhash_CAPI == NULL) {
5979 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005980 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5981 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005982 if (ucnhash_CAPI == NULL)
5983 goto ucnhashError;
5984 }
5985 if (*s == '{') {
5986 const char *start = s+1;
5987 /* look for the closing brace */
5988 while (*s != '}' && s < end)
5989 s++;
5990 if (s > start && s < end && *s == '}') {
5991 /* found a name. look it up in the unicode database */
5992 message = "unknown Unicode character name";
5993 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005994 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005995 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005996 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005997 goto store;
5998 }
5999 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006000 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006001
6002 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00006003 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006004 message = "\\ at end of string";
6005 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02006006 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00006007 }
6008 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006009 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02006010 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00006011 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006012 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006013 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006014 continue;
6015
6016 error:
6017 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006018 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006019 errors, &errorHandler,
6020 "unicodeescape", message,
6021 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006022 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02006023 goto onError;
6024 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006025 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006026#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006027
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006028 Py_XDECREF(errorHandler);
6029 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006030 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006031
Benjamin Peterson29060642009-01-31 22:14:21 +00006032 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00006033 PyErr_SetString(
6034 PyExc_UnicodeError,
6035 "\\N escapes not supported (can't load unicodedata module)"
6036 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006037 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006038 Py_XDECREF(errorHandler);
6039 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00006040 return NULL;
6041
Benjamin Peterson29060642009-01-31 22:14:21 +00006042 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006043 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006044 Py_XDECREF(errorHandler);
6045 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006046 return NULL;
6047}
6048
6049/* Return a Unicode-Escape string version of the Unicode object.
6050
6051 If quotes is true, the string is enclosed in u"" or u'' quotes as
6052 appropriate.
6053
6054*/
6055
Alexander Belopolsky40018472011-02-26 01:02:56 +00006056PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006057PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006058{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006059 Py_ssize_t i, len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006060 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006061 int kind;
6062 void *data;
Victor Stinner358af132015-10-12 22:36:57 +02006063 _PyBytesWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006064
Ezio Melottie7f90372012-10-05 03:33:31 +03006065 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006066 escape.
6067
Ezio Melottie7f90372012-10-05 03:33:31 +03006068 For UCS1 strings it's '\xxx', 4 bytes per source character.
6069 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6070 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006071 */
6072
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006073 if (!PyUnicode_Check(unicode)) {
6074 PyErr_BadArgument();
6075 return NULL;
6076 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006077 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006078 return NULL;
Victor Stinner358af132015-10-12 22:36:57 +02006079
6080 _PyBytesWriter_Init(&writer);
6081
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006082 len = PyUnicode_GET_LENGTH(unicode);
6083 kind = PyUnicode_KIND(unicode);
6084 data = PyUnicode_DATA(unicode);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006085
Victor Stinner358af132015-10-12 22:36:57 +02006086 p = _PyBytesWriter_Alloc(&writer, len);
6087 if (p == NULL)
6088 goto error;
6089 writer.overallocate = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006090
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006091 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006092 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006093
Walter Dörwald79e913e2007-05-12 11:08:06 +00006094 /* Escape backslashes */
6095 if (ch == '\\') {
Victor Stinner358af132015-10-12 22:36:57 +02006096 /* -1: substract 1 preallocated byte */
6097 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6098 if (p == NULL)
6099 goto error;
6100
Guido van Rossumd57fd912000-03-10 22:53:23 +00006101 *p++ = '\\';
6102 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006103 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006104 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006105
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006106 /* Map 21-bit characters to '\U00xxxxxx' */
6107 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006108 assert(ch <= MAX_UNICODE);
Victor Stinner358af132015-10-12 22:36:57 +02006109
6110 p = _PyBytesWriter_Prepare(&writer, p, 10-1);
6111 if (p == NULL)
6112 goto error;
6113
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006114 *p++ = '\\';
6115 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006116 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6117 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6118 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6119 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6120 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6121 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6122 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6123 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006124 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006125 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006126
Guido van Rossumd57fd912000-03-10 22:53:23 +00006127 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006128 if (ch >= 256) {
Victor Stinner358af132015-10-12 22:36:57 +02006129 p = _PyBytesWriter_Prepare(&writer, p, 6-1);
6130 if (p == NULL)
6131 goto error;
6132
Guido van Rossumd57fd912000-03-10 22:53:23 +00006133 *p++ = '\\';
6134 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006135 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6136 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6137 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6138 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006139 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006140
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006141 /* Map special whitespace to '\t', \n', '\r' */
6142 else if (ch == '\t') {
Victor Stinner358af132015-10-12 22:36:57 +02006143 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6144 if (p == NULL)
6145 goto error;
6146
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006147 *p++ = '\\';
6148 *p++ = 't';
6149 }
6150 else if (ch == '\n') {
Victor Stinner358af132015-10-12 22:36:57 +02006151 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6152 if (p == NULL)
6153 goto error;
6154
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006155 *p++ = '\\';
6156 *p++ = 'n';
6157 }
6158 else if (ch == '\r') {
Victor Stinner358af132015-10-12 22:36:57 +02006159 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6160 if (p == NULL)
6161 goto error;
6162
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006163 *p++ = '\\';
6164 *p++ = 'r';
6165 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006166
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006167 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006168 else if (ch < ' ' || ch >= 0x7F) {
Victor Stinner358af132015-10-12 22:36:57 +02006169 /* -1: substract 1 preallocated byte */
6170 p = _PyBytesWriter_Prepare(&writer, p, 4-1);
6171 if (p == NULL)
6172 goto error;
6173
Guido van Rossumd57fd912000-03-10 22:53:23 +00006174 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006175 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006176 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6177 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006178 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006179
Guido van Rossumd57fd912000-03-10 22:53:23 +00006180 /* Copy everything else as-is */
6181 else
6182 *p++ = (char) ch;
6183 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006184
Victor Stinner358af132015-10-12 22:36:57 +02006185 return _PyBytesWriter_Finish(&writer, p);
6186
6187error:
6188 _PyBytesWriter_Dealloc(&writer);
6189 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006190}
6191
Alexander Belopolsky40018472011-02-26 01:02:56 +00006192PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006193PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6194 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006195{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006196 PyObject *result;
6197 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6198 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006199 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006200 result = PyUnicode_AsUnicodeEscapeString(tmp);
6201 Py_DECREF(tmp);
6202 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006203}
6204
6205/* --- Raw Unicode Escape Codec ------------------------------------------- */
6206
Alexander Belopolsky40018472011-02-26 01:02:56 +00006207PyObject *
6208PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006209 Py_ssize_t size,
6210 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006211{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006212 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006213 Py_ssize_t startinpos;
6214 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006215 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216 const char *end;
6217 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006218 PyObject *errorHandler = NULL;
6219 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006220
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006221 if (size == 0)
6222 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006223
Guido van Rossumd57fd912000-03-10 22:53:23 +00006224 /* Escaped strings will always be longer than the resulting
6225 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006226 length after conversion to the true value. (But decoding error
6227 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006228 _PyUnicodeWriter_Init(&writer);
6229 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006230
Guido van Rossumd57fd912000-03-10 22:53:23 +00006231 end = s + size;
6232 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006233 unsigned char c;
6234 Py_UCS4 x;
6235 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006236 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006237
Benjamin Peterson29060642009-01-31 22:14:21 +00006238 /* Non-escape characters are interpreted as Unicode ordinals */
6239 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006240 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006241 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006242 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006243 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006244 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006245 startinpos = s-starts;
6246
6247 /* \u-escapes are only interpreted iff the number of leading
6248 backslashes if odd */
6249 bs = s;
6250 for (;s < end;) {
6251 if (*s != '\\')
6252 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006253 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006254 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006255 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006256 }
6257 if (((s - bs) & 1) == 0 ||
6258 s >= end ||
6259 (*s != 'u' && *s != 'U')) {
6260 continue;
6261 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006262 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006263 count = *s=='u' ? 4 : 8;
6264 s++;
6265
6266 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006267 for (x = 0, i = 0; i < count; ++i, ++s) {
6268 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006269 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006270 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006271 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006272 errors, &errorHandler,
6273 "rawunicodeescape", "truncated \\uXXXX",
6274 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006275 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006276 goto onError;
6277 goto nextByte;
6278 }
6279 x = (x<<4) & ~0xF;
6280 if (c >= '0' && c <= '9')
6281 x += c - '0';
6282 else if (c >= 'a' && c <= 'f')
6283 x += 10 + c - 'a';
6284 else
6285 x += 10 + c - 'A';
6286 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006287 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006288 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006289 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006290 }
6291 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006292 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006293 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006294 errors, &errorHandler,
6295 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006296 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006297 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006298 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006299 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006300 nextByte:
6301 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006302 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006303 Py_XDECREF(errorHandler);
6304 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006305 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006306
Benjamin Peterson29060642009-01-31 22:14:21 +00006307 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006308 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006309 Py_XDECREF(errorHandler);
6310 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006311 return NULL;
6312}
6313
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006314
Alexander Belopolsky40018472011-02-26 01:02:56 +00006315PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006316PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006317{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006318 char *p;
Victor Stinner358af132015-10-12 22:36:57 +02006319 Py_ssize_t pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006320 int kind;
6321 void *data;
6322 Py_ssize_t len;
Victor Stinner358af132015-10-12 22:36:57 +02006323 _PyBytesWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006324
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006325 if (!PyUnicode_Check(unicode)) {
6326 PyErr_BadArgument();
6327 return NULL;
6328 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006329 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006330 return NULL;
Victor Stinner358af132015-10-12 22:36:57 +02006331
6332 _PyBytesWriter_Init(&writer);
6333
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006334 kind = PyUnicode_KIND(unicode);
6335 data = PyUnicode_DATA(unicode);
6336 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner0e368262011-11-10 20:12:49 +01006337
Victor Stinner358af132015-10-12 22:36:57 +02006338 p = _PyBytesWriter_Alloc(&writer, len);
6339 if (p == NULL)
6340 goto error;
6341 writer.overallocate = 1;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006342
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006343 for (pos = 0; pos < len; pos++) {
6344 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006345 /* Map 32-bit characters to '\Uxxxxxxxx' */
6346 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006347 assert(ch <= MAX_UNICODE);
Victor Stinner358af132015-10-12 22:36:57 +02006348
6349 /* -1: substract 1 preallocated byte */
6350 p = _PyBytesWriter_Prepare(&writer, p, 10-1);
6351 if (p == NULL)
6352 goto error;
6353
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006354 *p++ = '\\';
6355 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006356 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6357 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6358 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6359 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6360 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6361 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6362 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6363 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006364 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006365 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006366 else if (ch >= 256) {
Victor Stinner358af132015-10-12 22:36:57 +02006367 /* -1: substract 1 preallocated byte */
6368 p = _PyBytesWriter_Prepare(&writer, p, 6-1);
6369 if (p == NULL)
6370 goto error;
6371
Guido van Rossumd57fd912000-03-10 22:53:23 +00006372 *p++ = '\\';
6373 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006374 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6375 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6376 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6377 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006378 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006379 /* Copy everything else as-is */
6380 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006381 *p++ = (char) ch;
6382 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006383
Victor Stinner358af132015-10-12 22:36:57 +02006384 return _PyBytesWriter_Finish(&writer, p);
6385
6386error:
6387 _PyBytesWriter_Dealloc(&writer);
6388 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006389}
6390
Alexander Belopolsky40018472011-02-26 01:02:56 +00006391PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006392PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6393 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006394{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006395 PyObject *result;
6396 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6397 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006398 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006399 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6400 Py_DECREF(tmp);
6401 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006402}
6403
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006404/* --- Unicode Internal Codec ------------------------------------------- */
6405
Alexander Belopolsky40018472011-02-26 01:02:56 +00006406PyObject *
6407_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006408 Py_ssize_t size,
6409 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006410{
6411 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006412 Py_ssize_t startinpos;
6413 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006414 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006415 const char *end;
6416 const char *reason;
6417 PyObject *errorHandler = NULL;
6418 PyObject *exc = NULL;
6419
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006420 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006421 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006422 1))
6423 return NULL;
6424
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006425 if (size == 0)
6426 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006427
Victor Stinner8f674cc2013-04-17 23:02:17 +02006428 _PyUnicodeWriter_Init(&writer);
6429 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6430 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006431 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006432 }
6433 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006434
Victor Stinner8f674cc2013-04-17 23:02:17 +02006435 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006436 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006437 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006438 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006439 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006440 endinpos = end-starts;
6441 reason = "truncated input";
6442 goto error;
6443 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006444 /* We copy the raw representation one byte at a time because the
6445 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006446 ((char *) &uch)[0] = s[0];
6447 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006448#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006449 ((char *) &uch)[2] = s[2];
6450 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006451#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006452 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006453#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006454 /* We have to sanity check the raw data, otherwise doom looms for
6455 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006456 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006457 endinpos = s - starts + Py_UNICODE_SIZE;
6458 reason = "illegal code point (> 0x10FFFF)";
6459 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006460 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006461#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006462 s += Py_UNICODE_SIZE;
6463#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006464 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006465 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006466 Py_UNICODE uch2;
6467 ((char *) &uch2)[0] = s[0];
6468 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006469 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006470 {
Victor Stinner551ac952011-11-29 22:58:13 +01006471 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006472 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006473 }
6474 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006475#endif
6476
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006477 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006478 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006479 continue;
6480
6481 error:
6482 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006483 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006484 errors, &errorHandler,
6485 "unicode_internal", reason,
6486 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006487 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006488 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006489 }
6490
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006491 Py_XDECREF(errorHandler);
6492 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006493 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006494
Benjamin Peterson29060642009-01-31 22:14:21 +00006495 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006496 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006497 Py_XDECREF(errorHandler);
6498 Py_XDECREF(exc);
6499 return NULL;
6500}
6501
Guido van Rossumd57fd912000-03-10 22:53:23 +00006502/* --- Latin-1 Codec ------------------------------------------------------ */
6503
Alexander Belopolsky40018472011-02-26 01:02:56 +00006504PyObject *
6505PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006506 Py_ssize_t size,
6507 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006508{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006509 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006510 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006511}
6512
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006513/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006514static void
6515make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006516 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006517 PyObject *unicode,
6518 Py_ssize_t startpos, Py_ssize_t endpos,
6519 const char *reason)
6520{
6521 if (*exceptionObject == NULL) {
6522 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006523 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006524 encoding, unicode, startpos, endpos, reason);
6525 }
6526 else {
6527 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6528 goto onError;
6529 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6530 goto onError;
6531 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6532 goto onError;
6533 return;
6534 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006535 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006536 }
6537}
6538
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006539/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006540static void
6541raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006542 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006543 PyObject *unicode,
6544 Py_ssize_t startpos, Py_ssize_t endpos,
6545 const char *reason)
6546{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006547 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006548 encoding, unicode, startpos, endpos, reason);
6549 if (*exceptionObject != NULL)
6550 PyCodec_StrictErrors(*exceptionObject);
6551}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006552
6553/* error handling callback helper:
6554 build arguments, call the callback and check the arguments,
6555 put the result into newpos and return the replacement string, which
6556 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006557static PyObject *
6558unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006559 PyObject **errorHandler,
6560 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006561 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006562 Py_ssize_t startpos, Py_ssize_t endpos,
6563 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006564{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006565 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006566 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006567 PyObject *restuple;
6568 PyObject *resunicode;
6569
6570 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006571 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006572 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006573 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006574 }
6575
Benjamin Petersonbac79492012-01-14 13:34:47 -05006576 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006577 return NULL;
6578 len = PyUnicode_GET_LENGTH(unicode);
6579
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006580 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006581 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006582 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006583 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006584
6585 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006586 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006587 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006588 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006589 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006590 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006591 Py_DECREF(restuple);
6592 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006593 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006594 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006595 &resunicode, newpos)) {
6596 Py_DECREF(restuple);
6597 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006598 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006599 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6600 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6601 Py_DECREF(restuple);
6602 return NULL;
6603 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006604 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006605 *newpos = len + *newpos;
6606 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006607 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006608 Py_DECREF(restuple);
6609 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006610 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006611 Py_INCREF(resunicode);
6612 Py_DECREF(restuple);
6613 return resunicode;
6614}
6615
Alexander Belopolsky40018472011-02-26 01:02:56 +00006616static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006617unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006618 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006619 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006620{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006621 /* input state */
6622 Py_ssize_t pos=0, size;
6623 int kind;
6624 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006625 /* pointer into the output */
6626 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006627 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6628 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006629 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006630 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006631 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006632 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006633 /* output object */
6634 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006635
Benjamin Petersonbac79492012-01-14 13:34:47 -05006636 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006637 return NULL;
6638 size = PyUnicode_GET_LENGTH(unicode);
6639 kind = PyUnicode_KIND(unicode);
6640 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006641 /* allocate enough for a simple encoding without
6642 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006643 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006644 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006645
6646 _PyBytesWriter_Init(&writer);
6647 str = _PyBytesWriter_Alloc(&writer, size);
6648 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006649 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006650
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006651 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006652 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006653
Benjamin Peterson29060642009-01-31 22:14:21 +00006654 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006655 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006656 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006657 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006658 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006659 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006660 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006661 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006662 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006663 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006664 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006665 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006666
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006667 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006668 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006669
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006670 /* Only overallocate the buffer if it's not the last write */
6671 writer.overallocate = (collend < size);
6672
Benjamin Peterson29060642009-01-31 22:14:21 +00006673 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006674 if (error_handler == _Py_ERROR_UNKNOWN)
6675 error_handler = get_error_handler(errors);
6676
6677 switch (error_handler) {
6678 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006679 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006680 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006681
6682 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006683 memset(str, '?', collend - collstart);
6684 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006685 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006686 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006687 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006688 break;
Victor Stinner50149202015-09-22 00:26:54 +02006689
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006690 case _Py_ERROR_BACKSLASHREPLACE:
Victor Stinnerad771582015-10-09 12:38:53 +02006691 /* substract preallocated bytes */
6692 writer.min_size -= (collend - collstart);
6693 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006694 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006695 if (str == NULL)
6696 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006697 pos = collend;
6698 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006699
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006700 case _Py_ERROR_XMLCHARREFREPLACE:
Victor Stinnerad771582015-10-09 12:38:53 +02006701 /* substract preallocated bytes */
6702 writer.min_size -= (collend - collstart);
6703 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006704 unicode, collstart, collend);
6705 if (str == NULL)
6706 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006707 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006708 break;
Victor Stinner50149202015-09-22 00:26:54 +02006709
Victor Stinnerc3713e92015-09-29 12:32:13 +02006710 case _Py_ERROR_SURROGATEESCAPE:
6711 for (i = collstart; i < collend; ++i) {
6712 ch = PyUnicode_READ(kind, data, i);
6713 if (ch < 0xdc80 || 0xdcff < ch) {
6714 /* Not a UTF-8b surrogate */
6715 break;
6716 }
6717 *str++ = (char)(ch - 0xdc00);
6718 ++pos;
6719 }
6720 if (i >= collend)
6721 break;
6722 collstart = pos;
6723 assert(collstart != collend);
6724 /* fallback to general error handling */
6725
Benjamin Peterson29060642009-01-31 22:14:21 +00006726 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006727 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6728 encoding, reason, unicode, &exc,
6729 collstart, collend, &newpos);
6730 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006732
Victor Stinnerad771582015-10-09 12:38:53 +02006733 /* substract preallocated bytes */
6734 writer.min_size -= 1;
6735
Victor Stinner6bd525b2015-10-09 13:10:05 +02006736 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006737 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006738 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006739 PyBytes_AS_STRING(rep),
6740 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006741 if (str == NULL)
6742 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006743 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006744 else {
6745 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006746
Victor Stinner6bd525b2015-10-09 13:10:05 +02006747 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006749
6750 if (PyUnicode_IS_ASCII(rep)) {
6751 /* Fast path: all characters are smaller than limit */
6752 assert(limit >= 128);
6753 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6754 str = _PyBytesWriter_WriteBytes(&writer, str,
6755 PyUnicode_DATA(rep),
6756 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006757 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006758 else {
6759 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6760
6761 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6762 if (str == NULL)
6763 goto onError;
6764
6765 /* check if there is anything unencodable in the
6766 replacement and copy it to the output */
6767 for (i = 0; repsize-->0; ++i, ++str) {
6768 ch = PyUnicode_READ_CHAR(rep, i);
6769 if (ch >= limit) {
6770 raise_encode_exception(&exc, encoding, unicode,
6771 pos, pos+1, reason);
6772 goto onError;
6773 }
6774 *str = (char)ch;
6775 }
6776 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006777 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006778 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006779 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006780 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006781
6782 /* If overallocation was disabled, ensure that it was the last
6783 write. Otherwise, we missed an optimization */
6784 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006785 }
6786 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006787
Victor Stinner50149202015-09-22 00:26:54 +02006788 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006789 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006790 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006791
6792 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006793 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006794 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006795 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006796 Py_XDECREF(exc);
6797 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006798}
6799
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006800/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006801PyObject *
6802PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006803 Py_ssize_t size,
6804 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006805{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006806 PyObject *result;
6807 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6808 if (unicode == NULL)
6809 return NULL;
6810 result = unicode_encode_ucs1(unicode, errors, 256);
6811 Py_DECREF(unicode);
6812 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006813}
6814
Alexander Belopolsky40018472011-02-26 01:02:56 +00006815PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006816_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006817{
6818 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006819 PyErr_BadArgument();
6820 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006821 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006822 if (PyUnicode_READY(unicode) == -1)
6823 return NULL;
6824 /* Fast path: if it is a one-byte string, construct
6825 bytes object directly. */
6826 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6827 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6828 PyUnicode_GET_LENGTH(unicode));
6829 /* Non-Latin-1 characters present. Defer to above function to
6830 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006831 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006832}
6833
6834PyObject*
6835PyUnicode_AsLatin1String(PyObject *unicode)
6836{
6837 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006838}
6839
6840/* --- 7-bit ASCII Codec -------------------------------------------------- */
6841
Alexander Belopolsky40018472011-02-26 01:02:56 +00006842PyObject *
6843PyUnicode_DecodeASCII(const char *s,
6844 Py_ssize_t size,
6845 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006846{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006847 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006848 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006849 int kind;
6850 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006851 Py_ssize_t startinpos;
6852 Py_ssize_t endinpos;
6853 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006854 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006855 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006856 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006857 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006858
Guido van Rossumd57fd912000-03-10 22:53:23 +00006859 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006860 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006861
Guido van Rossumd57fd912000-03-10 22:53:23 +00006862 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006863 if (size == 1 && (unsigned char)s[0] < 128)
6864 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006865
Victor Stinner8f674cc2013-04-17 23:02:17 +02006866 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006867 writer.min_length = size;
6868 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006869 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006870
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006871 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006872 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006873 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006874 writer.pos = outpos;
6875 if (writer.pos == size)
6876 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006877
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006878 s += writer.pos;
6879 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006880 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006881 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006882 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006883 PyUnicode_WRITE(kind, data, writer.pos, c);
6884 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006885 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006886 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006887 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006888
6889 /* byte outsize range 0x00..0x7f: call the error handler */
6890
6891 if (error_handler == _Py_ERROR_UNKNOWN)
6892 error_handler = get_error_handler(errors);
6893
6894 switch (error_handler)
6895 {
6896 case _Py_ERROR_REPLACE:
6897 case _Py_ERROR_SURROGATEESCAPE:
6898 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006899 but we may switch to UCS2 at the first write */
6900 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6901 goto onError;
6902 kind = writer.kind;
6903 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006904
6905 if (error_handler == _Py_ERROR_REPLACE)
6906 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6907 else
6908 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6909 writer.pos++;
6910 ++s;
6911 break;
6912
6913 case _Py_ERROR_IGNORE:
6914 ++s;
6915 break;
6916
6917 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006918 startinpos = s-starts;
6919 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006920 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006921 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006922 "ascii", "ordinal not in range(128)",
6923 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006924 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006925 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006926 kind = writer.kind;
6927 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006928 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006929 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006930 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006931 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006932 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006933
Benjamin Peterson29060642009-01-31 22:14:21 +00006934 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006935 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006936 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006937 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006938 return NULL;
6939}
6940
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006941/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006942PyObject *
6943PyUnicode_EncodeASCII(const Py_UNICODE *p,
6944 Py_ssize_t size,
6945 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006946{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006947 PyObject *result;
6948 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6949 if (unicode == NULL)
6950 return NULL;
6951 result = unicode_encode_ucs1(unicode, errors, 128);
6952 Py_DECREF(unicode);
6953 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006954}
6955
Alexander Belopolsky40018472011-02-26 01:02:56 +00006956PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006957_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006958{
6959 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006960 PyErr_BadArgument();
6961 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006962 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006963 if (PyUnicode_READY(unicode) == -1)
6964 return NULL;
6965 /* Fast path: if it is an ASCII-only string, construct bytes object
6966 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006967 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006968 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6969 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006970 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006971}
6972
6973PyObject *
6974PyUnicode_AsASCIIString(PyObject *unicode)
6975{
6976 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006977}
6978
Victor Stinner99b95382011-07-04 14:23:54 +02006979#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006980
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006981/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006982
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006983#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006984#define NEED_RETRY
6985#endif
6986
Victor Stinner3a50e702011-10-18 21:21:00 +02006987#ifndef WC_ERR_INVALID_CHARS
6988# define WC_ERR_INVALID_CHARS 0x0080
6989#endif
6990
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02006991static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02006992code_page_name(UINT code_page, PyObject **obj)
6993{
6994 *obj = NULL;
6995 if (code_page == CP_ACP)
6996 return "mbcs";
6997 if (code_page == CP_UTF7)
6998 return "CP_UTF7";
6999 if (code_page == CP_UTF8)
7000 return "CP_UTF8";
7001
7002 *obj = PyBytes_FromFormat("cp%u", code_page);
7003 if (*obj == NULL)
7004 return NULL;
7005 return PyBytes_AS_STRING(*obj);
7006}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007007
Victor Stinner3a50e702011-10-18 21:21:00 +02007008static DWORD
7009decode_code_page_flags(UINT code_page)
7010{
7011 if (code_page == CP_UTF7) {
7012 /* The CP_UTF7 decoder only supports flags=0 */
7013 return 0;
7014 }
7015 else
7016 return MB_ERR_INVALID_CHARS;
7017}
7018
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007019/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007020 * Decode a byte string from a Windows code page into unicode object in strict
7021 * mode.
7022 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007023 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7024 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007025 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007026static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007027decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007028 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007029 const char *in,
7030 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007031{
Victor Stinner3a50e702011-10-18 21:21:00 +02007032 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007033 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007034 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007035
7036 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007037 assert(insize > 0);
7038 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7039 if (outsize <= 0)
7040 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007041
7042 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007043 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007044 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007045 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007046 if (*v == NULL)
7047 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007048 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007049 }
7050 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007051 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007052 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007053 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007054 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007055 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007056 }
7057
7058 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007059 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7060 if (outsize <= 0)
7061 goto error;
7062 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007063
Victor Stinner3a50e702011-10-18 21:21:00 +02007064error:
7065 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7066 return -2;
7067 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007068 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007069}
7070
Victor Stinner3a50e702011-10-18 21:21:00 +02007071/*
7072 * Decode a byte string from a code page into unicode object with an error
7073 * handler.
7074 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007075 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007076 * UnicodeDecodeError exception and returns -1 on error.
7077 */
7078static int
7079decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007080 PyObject **v,
7081 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007082 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007083{
7084 const char *startin = in;
7085 const char *endin = in + size;
7086 const DWORD flags = decode_code_page_flags(code_page);
7087 /* Ideally, we should get reason from FormatMessage. This is the Windows
7088 2000 English version of the message. */
7089 const char *reason = "No mapping for the Unicode character exists "
7090 "in the target code page.";
7091 /* each step cannot decode more than 1 character, but a character can be
7092 represented as a surrogate pair */
7093 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007094 int insize;
7095 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007096 PyObject *errorHandler = NULL;
7097 PyObject *exc = NULL;
7098 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007099 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007100 DWORD err;
7101 int ret = -1;
7102
7103 assert(size > 0);
7104
7105 encoding = code_page_name(code_page, &encoding_obj);
7106 if (encoding == NULL)
7107 return -1;
7108
Victor Stinner7d00cc12014-03-17 23:08:06 +01007109 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007110 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7111 UnicodeDecodeError. */
7112 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7113 if (exc != NULL) {
7114 PyCodec_StrictErrors(exc);
7115 Py_CLEAR(exc);
7116 }
7117 goto error;
7118 }
7119
7120 if (*v == NULL) {
7121 /* Create unicode object */
7122 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7123 PyErr_NoMemory();
7124 goto error;
7125 }
Victor Stinnerab595942011-12-17 04:59:06 +01007126 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007127 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007128 if (*v == NULL)
7129 goto error;
7130 startout = PyUnicode_AS_UNICODE(*v);
7131 }
7132 else {
7133 /* Extend unicode object */
7134 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7135 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7136 PyErr_NoMemory();
7137 goto error;
7138 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007139 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007140 goto error;
7141 startout = PyUnicode_AS_UNICODE(*v) + n;
7142 }
7143
7144 /* Decode the byte string character per character */
7145 out = startout;
7146 while (in < endin)
7147 {
7148 /* Decode a character */
7149 insize = 1;
7150 do
7151 {
7152 outsize = MultiByteToWideChar(code_page, flags,
7153 in, insize,
7154 buffer, Py_ARRAY_LENGTH(buffer));
7155 if (outsize > 0)
7156 break;
7157 err = GetLastError();
7158 if (err != ERROR_NO_UNICODE_TRANSLATION
7159 && err != ERROR_INSUFFICIENT_BUFFER)
7160 {
7161 PyErr_SetFromWindowsErr(0);
7162 goto error;
7163 }
7164 insize++;
7165 }
7166 /* 4=maximum length of a UTF-8 sequence */
7167 while (insize <= 4 && (in + insize) <= endin);
7168
7169 if (outsize <= 0) {
7170 Py_ssize_t startinpos, endinpos, outpos;
7171
Victor Stinner7d00cc12014-03-17 23:08:06 +01007172 /* last character in partial decode? */
7173 if (in + insize >= endin && !final)
7174 break;
7175
Victor Stinner3a50e702011-10-18 21:21:00 +02007176 startinpos = in - startin;
7177 endinpos = startinpos + 1;
7178 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007179 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007180 errors, &errorHandler,
7181 encoding, reason,
7182 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007183 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007184 {
7185 goto error;
7186 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007187 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007188 }
7189 else {
7190 in += insize;
7191 memcpy(out, buffer, outsize * sizeof(wchar_t));
7192 out += outsize;
7193 }
7194 }
7195
7196 /* write a NUL character at the end */
7197 *out = 0;
7198
7199 /* Extend unicode object */
7200 outsize = out - startout;
7201 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007202 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007203 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007204 /* (in - startin) <= size and size is an int */
7205 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007206
7207error:
7208 Py_XDECREF(encoding_obj);
7209 Py_XDECREF(errorHandler);
7210 Py_XDECREF(exc);
7211 return ret;
7212}
7213
Victor Stinner3a50e702011-10-18 21:21:00 +02007214static PyObject *
7215decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007216 const char *s, Py_ssize_t size,
7217 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007218{
Victor Stinner76a31a62011-11-04 00:05:13 +01007219 PyObject *v = NULL;
7220 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007221
Victor Stinner3a50e702011-10-18 21:21:00 +02007222 if (code_page < 0) {
7223 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7224 return NULL;
7225 }
7226
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007227 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007228 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007229
Victor Stinner76a31a62011-11-04 00:05:13 +01007230 do
7231 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007232#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007233 if (size > INT_MAX) {
7234 chunk_size = INT_MAX;
7235 final = 0;
7236 done = 0;
7237 }
7238 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007239#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007240 {
7241 chunk_size = (int)size;
7242 final = (consumed == NULL);
7243 done = 1;
7244 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007245
Victor Stinner76a31a62011-11-04 00:05:13 +01007246 if (chunk_size == 0 && done) {
7247 if (v != NULL)
7248 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007249 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007250 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007251
Victor Stinner76a31a62011-11-04 00:05:13 +01007252 converted = decode_code_page_strict(code_page, &v,
7253 s, chunk_size);
7254 if (converted == -2)
7255 converted = decode_code_page_errors(code_page, &v,
7256 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007257 errors, final);
7258 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007259
7260 if (converted < 0) {
7261 Py_XDECREF(v);
7262 return NULL;
7263 }
7264
7265 if (consumed)
7266 *consumed += converted;
7267
7268 s += converted;
7269 size -= converted;
7270 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007271
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007272 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007273}
7274
Alexander Belopolsky40018472011-02-26 01:02:56 +00007275PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007276PyUnicode_DecodeCodePageStateful(int code_page,
7277 const char *s,
7278 Py_ssize_t size,
7279 const char *errors,
7280 Py_ssize_t *consumed)
7281{
7282 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7283}
7284
7285PyObject *
7286PyUnicode_DecodeMBCSStateful(const char *s,
7287 Py_ssize_t size,
7288 const char *errors,
7289 Py_ssize_t *consumed)
7290{
7291 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7292}
7293
7294PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007295PyUnicode_DecodeMBCS(const char *s,
7296 Py_ssize_t size,
7297 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007298{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007299 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7300}
7301
Victor Stinner3a50e702011-10-18 21:21:00 +02007302static DWORD
7303encode_code_page_flags(UINT code_page, const char *errors)
7304{
7305 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007306 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007307 }
7308 else if (code_page == CP_UTF7) {
7309 /* CP_UTF7 only supports flags=0 */
7310 return 0;
7311 }
7312 else {
7313 if (errors != NULL && strcmp(errors, "replace") == 0)
7314 return 0;
7315 else
7316 return WC_NO_BEST_FIT_CHARS;
7317 }
7318}
7319
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007320/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007321 * Encode a Unicode string to a Windows code page into a byte string in strict
7322 * mode.
7323 *
7324 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007325 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007326 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007327static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007328encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007329 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007330 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007331{
Victor Stinner554f3f02010-06-16 23:33:54 +00007332 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007333 BOOL *pusedDefaultChar = &usedDefaultChar;
7334 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007335 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007336 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007337 const DWORD flags = encode_code_page_flags(code_page, NULL);
7338 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007339 /* Create a substring so that we can get the UTF-16 representation
7340 of just the slice under consideration. */
7341 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007342
Martin v. Löwis3d325192011-11-04 18:23:06 +01007343 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007344
Victor Stinner3a50e702011-10-18 21:21:00 +02007345 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007346 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007347 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007348 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007349
Victor Stinner2fc507f2011-11-04 20:06:39 +01007350 substring = PyUnicode_Substring(unicode, offset, offset+len);
7351 if (substring == NULL)
7352 return -1;
7353 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7354 if (p == NULL) {
7355 Py_DECREF(substring);
7356 return -1;
7357 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007358 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007359
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007360 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007361 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007362 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007363 NULL, 0,
7364 NULL, pusedDefaultChar);
7365 if (outsize <= 0)
7366 goto error;
7367 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007368 if (pusedDefaultChar && *pusedDefaultChar) {
7369 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007370 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007371 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007372
Victor Stinner3a50e702011-10-18 21:21:00 +02007373 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007374 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007375 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007376 if (*outbytes == NULL) {
7377 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007378 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007379 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007380 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007381 }
7382 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007383 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007384 const Py_ssize_t n = PyBytes_Size(*outbytes);
7385 if (outsize > PY_SSIZE_T_MAX - n) {
7386 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007387 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007388 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007389 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007390 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7391 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007393 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007394 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007395 }
7396
7397 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007398 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007399 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007400 out, outsize,
7401 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007402 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007403 if (outsize <= 0)
7404 goto error;
7405 if (pusedDefaultChar && *pusedDefaultChar)
7406 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007407 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007408
Victor Stinner3a50e702011-10-18 21:21:00 +02007409error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007410 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007411 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7412 return -2;
7413 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007414 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007415}
7416
Victor Stinner3a50e702011-10-18 21:21:00 +02007417/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007418 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007419 * error handler.
7420 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007421 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007422 * -1 on other error.
7423 */
7424static int
7425encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007426 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007427 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007428{
Victor Stinner3a50e702011-10-18 21:21:00 +02007429 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007430 Py_ssize_t pos = unicode_offset;
7431 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007432 /* Ideally, we should get reason from FormatMessage. This is the Windows
7433 2000 English version of the message. */
7434 const char *reason = "invalid character";
7435 /* 4=maximum length of a UTF-8 sequence */
7436 char buffer[4];
7437 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7438 Py_ssize_t outsize;
7439 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 PyObject *errorHandler = NULL;
7441 PyObject *exc = NULL;
7442 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007443 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007444 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 PyObject *rep;
7446 int ret = -1;
7447
7448 assert(insize > 0);
7449
7450 encoding = code_page_name(code_page, &encoding_obj);
7451 if (encoding == NULL)
7452 return -1;
7453
7454 if (errors == NULL || strcmp(errors, "strict") == 0) {
7455 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7456 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007457 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007458 if (exc != NULL) {
7459 PyCodec_StrictErrors(exc);
7460 Py_DECREF(exc);
7461 }
7462 Py_XDECREF(encoding_obj);
7463 return -1;
7464 }
7465
7466 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7467 pusedDefaultChar = &usedDefaultChar;
7468 else
7469 pusedDefaultChar = NULL;
7470
7471 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7472 PyErr_NoMemory();
7473 goto error;
7474 }
7475 outsize = insize * Py_ARRAY_LENGTH(buffer);
7476
7477 if (*outbytes == NULL) {
7478 /* Create string object */
7479 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7480 if (*outbytes == NULL)
7481 goto error;
7482 out = PyBytes_AS_STRING(*outbytes);
7483 }
7484 else {
7485 /* Extend string object */
7486 Py_ssize_t n = PyBytes_Size(*outbytes);
7487 if (n > PY_SSIZE_T_MAX - outsize) {
7488 PyErr_NoMemory();
7489 goto error;
7490 }
7491 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7492 goto error;
7493 out = PyBytes_AS_STRING(*outbytes) + n;
7494 }
7495
7496 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007497 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007498 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007499 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7500 wchar_t chars[2];
7501 int charsize;
7502 if (ch < 0x10000) {
7503 chars[0] = (wchar_t)ch;
7504 charsize = 1;
7505 }
7506 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007507 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7508 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007509 charsize = 2;
7510 }
7511
Victor Stinner3a50e702011-10-18 21:21:00 +02007512 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007513 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007514 buffer, Py_ARRAY_LENGTH(buffer),
7515 NULL, pusedDefaultChar);
7516 if (outsize > 0) {
7517 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7518 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007519 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007520 memcpy(out, buffer, outsize);
7521 out += outsize;
7522 continue;
7523 }
7524 }
7525 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7526 PyErr_SetFromWindowsErr(0);
7527 goto error;
7528 }
7529
Victor Stinner3a50e702011-10-18 21:21:00 +02007530 rep = unicode_encode_call_errorhandler(
7531 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007532 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007533 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007534 if (rep == NULL)
7535 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007536 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007537
7538 if (PyBytes_Check(rep)) {
7539 outsize = PyBytes_GET_SIZE(rep);
7540 if (outsize != 1) {
7541 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7542 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7543 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7544 Py_DECREF(rep);
7545 goto error;
7546 }
7547 out = PyBytes_AS_STRING(*outbytes) + offset;
7548 }
7549 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7550 out += outsize;
7551 }
7552 else {
7553 Py_ssize_t i;
7554 enum PyUnicode_Kind kind;
7555 void *data;
7556
Benjamin Petersonbac79492012-01-14 13:34:47 -05007557 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007558 Py_DECREF(rep);
7559 goto error;
7560 }
7561
7562 outsize = PyUnicode_GET_LENGTH(rep);
7563 if (outsize != 1) {
7564 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7565 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7566 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7567 Py_DECREF(rep);
7568 goto error;
7569 }
7570 out = PyBytes_AS_STRING(*outbytes) + offset;
7571 }
7572 kind = PyUnicode_KIND(rep);
7573 data = PyUnicode_DATA(rep);
7574 for (i=0; i < outsize; i++) {
7575 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7576 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007577 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007578 encoding, unicode,
7579 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007580 "unable to encode error handler result to ASCII");
7581 Py_DECREF(rep);
7582 goto error;
7583 }
7584 *out = (unsigned char)ch;
7585 out++;
7586 }
7587 }
7588 Py_DECREF(rep);
7589 }
7590 /* write a NUL byte */
7591 *out = 0;
7592 outsize = out - PyBytes_AS_STRING(*outbytes);
7593 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7594 if (_PyBytes_Resize(outbytes, outsize) < 0)
7595 goto error;
7596 ret = 0;
7597
7598error:
7599 Py_XDECREF(encoding_obj);
7600 Py_XDECREF(errorHandler);
7601 Py_XDECREF(exc);
7602 return ret;
7603}
7604
Victor Stinner3a50e702011-10-18 21:21:00 +02007605static PyObject *
7606encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007607 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007608 const char *errors)
7609{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007610 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007611 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007612 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007613 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007614
Victor Stinner29dacf22015-01-26 16:41:32 +01007615 if (!PyUnicode_Check(unicode)) {
7616 PyErr_BadArgument();
7617 return NULL;
7618 }
7619
Benjamin Petersonbac79492012-01-14 13:34:47 -05007620 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007621 return NULL;
7622 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007623
Victor Stinner3a50e702011-10-18 21:21:00 +02007624 if (code_page < 0) {
7625 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7626 return NULL;
7627 }
7628
Martin v. Löwis3d325192011-11-04 18:23:06 +01007629 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007630 return PyBytes_FromStringAndSize(NULL, 0);
7631
Victor Stinner7581cef2011-11-03 22:32:33 +01007632 offset = 0;
7633 do
7634 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007635#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007636 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007637 chunks. */
7638 if (len > INT_MAX/2) {
7639 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007640 done = 0;
7641 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007642 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007643#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007644 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007645 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007646 done = 1;
7647 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007648
Victor Stinner76a31a62011-11-04 00:05:13 +01007649 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007650 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007651 errors);
7652 if (ret == -2)
7653 ret = encode_code_page_errors(code_page, &outbytes,
7654 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007655 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007656 if (ret < 0) {
7657 Py_XDECREF(outbytes);
7658 return NULL;
7659 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007660
Victor Stinner7581cef2011-11-03 22:32:33 +01007661 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007662 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007663 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007664
Victor Stinner3a50e702011-10-18 21:21:00 +02007665 return outbytes;
7666}
7667
7668PyObject *
7669PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7670 Py_ssize_t size,
7671 const char *errors)
7672{
Victor Stinner7581cef2011-11-03 22:32:33 +01007673 PyObject *unicode, *res;
7674 unicode = PyUnicode_FromUnicode(p, size);
7675 if (unicode == NULL)
7676 return NULL;
7677 res = encode_code_page(CP_ACP, unicode, errors);
7678 Py_DECREF(unicode);
7679 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007680}
7681
7682PyObject *
7683PyUnicode_EncodeCodePage(int code_page,
7684 PyObject *unicode,
7685 const char *errors)
7686{
Victor Stinner7581cef2011-11-03 22:32:33 +01007687 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007688}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007689
Alexander Belopolsky40018472011-02-26 01:02:56 +00007690PyObject *
7691PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007692{
Victor Stinner7581cef2011-11-03 22:32:33 +01007693 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007694}
7695
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007696#undef NEED_RETRY
7697
Victor Stinner99b95382011-07-04 14:23:54 +02007698#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007699
Guido van Rossumd57fd912000-03-10 22:53:23 +00007700/* --- Character Mapping Codec -------------------------------------------- */
7701
Victor Stinnerfb161b12013-04-18 01:44:27 +02007702static int
7703charmap_decode_string(const char *s,
7704 Py_ssize_t size,
7705 PyObject *mapping,
7706 const char *errors,
7707 _PyUnicodeWriter *writer)
7708{
7709 const char *starts = s;
7710 const char *e;
7711 Py_ssize_t startinpos, endinpos;
7712 PyObject *errorHandler = NULL, *exc = NULL;
7713 Py_ssize_t maplen;
7714 enum PyUnicode_Kind mapkind;
7715 void *mapdata;
7716 Py_UCS4 x;
7717 unsigned char ch;
7718
7719 if (PyUnicode_READY(mapping) == -1)
7720 return -1;
7721
7722 maplen = PyUnicode_GET_LENGTH(mapping);
7723 mapdata = PyUnicode_DATA(mapping);
7724 mapkind = PyUnicode_KIND(mapping);
7725
7726 e = s + size;
7727
7728 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7729 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7730 * is disabled in encoding aliases, latin1 is preferred because
7731 * its implementation is faster. */
7732 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7733 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7734 Py_UCS4 maxchar = writer->maxchar;
7735
7736 assert (writer->kind == PyUnicode_1BYTE_KIND);
7737 while (s < e) {
7738 ch = *s;
7739 x = mapdata_ucs1[ch];
7740 if (x > maxchar) {
7741 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7742 goto onError;
7743 maxchar = writer->maxchar;
7744 outdata = (Py_UCS1 *)writer->data;
7745 }
7746 outdata[writer->pos] = x;
7747 writer->pos++;
7748 ++s;
7749 }
7750 return 0;
7751 }
7752
7753 while (s < e) {
7754 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7755 enum PyUnicode_Kind outkind = writer->kind;
7756 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7757 if (outkind == PyUnicode_1BYTE_KIND) {
7758 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7759 Py_UCS4 maxchar = writer->maxchar;
7760 while (s < e) {
7761 ch = *s;
7762 x = mapdata_ucs2[ch];
7763 if (x > maxchar)
7764 goto Error;
7765 outdata[writer->pos] = x;
7766 writer->pos++;
7767 ++s;
7768 }
7769 break;
7770 }
7771 else if (outkind == PyUnicode_2BYTE_KIND) {
7772 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7773 while (s < e) {
7774 ch = *s;
7775 x = mapdata_ucs2[ch];
7776 if (x == 0xFFFE)
7777 goto Error;
7778 outdata[writer->pos] = x;
7779 writer->pos++;
7780 ++s;
7781 }
7782 break;
7783 }
7784 }
7785 ch = *s;
7786
7787 if (ch < maplen)
7788 x = PyUnicode_READ(mapkind, mapdata, ch);
7789 else
7790 x = 0xfffe; /* invalid value */
7791Error:
7792 if (x == 0xfffe)
7793 {
7794 /* undefined mapping */
7795 startinpos = s-starts;
7796 endinpos = startinpos+1;
7797 if (unicode_decode_call_errorhandler_writer(
7798 errors, &errorHandler,
7799 "charmap", "character maps to <undefined>",
7800 &starts, &e, &startinpos, &endinpos, &exc, &s,
7801 writer)) {
7802 goto onError;
7803 }
7804 continue;
7805 }
7806
7807 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7808 goto onError;
7809 ++s;
7810 }
7811 Py_XDECREF(errorHandler);
7812 Py_XDECREF(exc);
7813 return 0;
7814
7815onError:
7816 Py_XDECREF(errorHandler);
7817 Py_XDECREF(exc);
7818 return -1;
7819}
7820
7821static int
7822charmap_decode_mapping(const char *s,
7823 Py_ssize_t size,
7824 PyObject *mapping,
7825 const char *errors,
7826 _PyUnicodeWriter *writer)
7827{
7828 const char *starts = s;
7829 const char *e;
7830 Py_ssize_t startinpos, endinpos;
7831 PyObject *errorHandler = NULL, *exc = NULL;
7832 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007833 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007834
7835 e = s + size;
7836
7837 while (s < e) {
7838 ch = *s;
7839
7840 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7841 key = PyLong_FromLong((long)ch);
7842 if (key == NULL)
7843 goto onError;
7844
7845 item = PyObject_GetItem(mapping, key);
7846 Py_DECREF(key);
7847 if (item == NULL) {
7848 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7849 /* No mapping found means: mapping is undefined. */
7850 PyErr_Clear();
7851 goto Undefined;
7852 } else
7853 goto onError;
7854 }
7855
7856 /* Apply mapping */
7857 if (item == Py_None)
7858 goto Undefined;
7859 if (PyLong_Check(item)) {
7860 long value = PyLong_AS_LONG(item);
7861 if (value == 0xFFFE)
7862 goto Undefined;
7863 if (value < 0 || value > MAX_UNICODE) {
7864 PyErr_Format(PyExc_TypeError,
7865 "character mapping must be in range(0x%lx)",
7866 (unsigned long)MAX_UNICODE + 1);
7867 goto onError;
7868 }
7869
7870 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7871 goto onError;
7872 }
7873 else if (PyUnicode_Check(item)) {
7874 if (PyUnicode_READY(item) == -1)
7875 goto onError;
7876 if (PyUnicode_GET_LENGTH(item) == 1) {
7877 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7878 if (value == 0xFFFE)
7879 goto Undefined;
7880 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7881 goto onError;
7882 }
7883 else {
7884 writer->overallocate = 1;
7885 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7886 goto onError;
7887 }
7888 }
7889 else {
7890 /* wrong return value */
7891 PyErr_SetString(PyExc_TypeError,
7892 "character mapping must return integer, None or str");
7893 goto onError;
7894 }
7895 Py_CLEAR(item);
7896 ++s;
7897 continue;
7898
7899Undefined:
7900 /* undefined mapping */
7901 Py_CLEAR(item);
7902 startinpos = s-starts;
7903 endinpos = startinpos+1;
7904 if (unicode_decode_call_errorhandler_writer(
7905 errors, &errorHandler,
7906 "charmap", "character maps to <undefined>",
7907 &starts, &e, &startinpos, &endinpos, &exc, &s,
7908 writer)) {
7909 goto onError;
7910 }
7911 }
7912 Py_XDECREF(errorHandler);
7913 Py_XDECREF(exc);
7914 return 0;
7915
7916onError:
7917 Py_XDECREF(item);
7918 Py_XDECREF(errorHandler);
7919 Py_XDECREF(exc);
7920 return -1;
7921}
7922
Alexander Belopolsky40018472011-02-26 01:02:56 +00007923PyObject *
7924PyUnicode_DecodeCharmap(const char *s,
7925 Py_ssize_t size,
7926 PyObject *mapping,
7927 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007928{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007929 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007930
Guido van Rossumd57fd912000-03-10 22:53:23 +00007931 /* Default to Latin-1 */
7932 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007933 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007934
Guido van Rossumd57fd912000-03-10 22:53:23 +00007935 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007936 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007937 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007938 writer.min_length = size;
7939 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007940 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007941
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007942 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007943 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7944 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007945 }
7946 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007947 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7948 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007949 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007950 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007951
Benjamin Peterson29060642009-01-31 22:14:21 +00007952 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007953 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007954 return NULL;
7955}
7956
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007957/* Charmap encoding: the lookup table */
7958
Alexander Belopolsky40018472011-02-26 01:02:56 +00007959struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007960 PyObject_HEAD
7961 unsigned char level1[32];
7962 int count2, count3;
7963 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007964};
7965
7966static PyObject*
7967encoding_map_size(PyObject *obj, PyObject* args)
7968{
7969 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007970 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007971 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007972}
7973
7974static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007975 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007976 PyDoc_STR("Return the size (in bytes) of this object") },
7977 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007978};
7979
7980static void
7981encoding_map_dealloc(PyObject* o)
7982{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007983 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007984}
7985
7986static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007987 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007988 "EncodingMap", /*tp_name*/
7989 sizeof(struct encoding_map), /*tp_basicsize*/
7990 0, /*tp_itemsize*/
7991 /* methods */
7992 encoding_map_dealloc, /*tp_dealloc*/
7993 0, /*tp_print*/
7994 0, /*tp_getattr*/
7995 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007996 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007997 0, /*tp_repr*/
7998 0, /*tp_as_number*/
7999 0, /*tp_as_sequence*/
8000 0, /*tp_as_mapping*/
8001 0, /*tp_hash*/
8002 0, /*tp_call*/
8003 0, /*tp_str*/
8004 0, /*tp_getattro*/
8005 0, /*tp_setattro*/
8006 0, /*tp_as_buffer*/
8007 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8008 0, /*tp_doc*/
8009 0, /*tp_traverse*/
8010 0, /*tp_clear*/
8011 0, /*tp_richcompare*/
8012 0, /*tp_weaklistoffset*/
8013 0, /*tp_iter*/
8014 0, /*tp_iternext*/
8015 encoding_map_methods, /*tp_methods*/
8016 0, /*tp_members*/
8017 0, /*tp_getset*/
8018 0, /*tp_base*/
8019 0, /*tp_dict*/
8020 0, /*tp_descr_get*/
8021 0, /*tp_descr_set*/
8022 0, /*tp_dictoffset*/
8023 0, /*tp_init*/
8024 0, /*tp_alloc*/
8025 0, /*tp_new*/
8026 0, /*tp_free*/
8027 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008028};
8029
8030PyObject*
8031PyUnicode_BuildEncodingMap(PyObject* string)
8032{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008033 PyObject *result;
8034 struct encoding_map *mresult;
8035 int i;
8036 int need_dict = 0;
8037 unsigned char level1[32];
8038 unsigned char level2[512];
8039 unsigned char *mlevel1, *mlevel2, *mlevel3;
8040 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008041 int kind;
8042 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008043 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008044 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008045
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008046 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008047 PyErr_BadArgument();
8048 return NULL;
8049 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008050 kind = PyUnicode_KIND(string);
8051 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008052 length = PyUnicode_GET_LENGTH(string);
8053 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008054 memset(level1, 0xFF, sizeof level1);
8055 memset(level2, 0xFF, sizeof level2);
8056
8057 /* If there isn't a one-to-one mapping of NULL to \0,
8058 or if there are non-BMP characters, we need to use
8059 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008060 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008061 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008062 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008063 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008064 ch = PyUnicode_READ(kind, data, i);
8065 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008066 need_dict = 1;
8067 break;
8068 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008069 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008070 /* unmapped character */
8071 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008072 l1 = ch >> 11;
8073 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008074 if (level1[l1] == 0xFF)
8075 level1[l1] = count2++;
8076 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008077 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008078 }
8079
8080 if (count2 >= 0xFF || count3 >= 0xFF)
8081 need_dict = 1;
8082
8083 if (need_dict) {
8084 PyObject *result = PyDict_New();
8085 PyObject *key, *value;
8086 if (!result)
8087 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008088 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008089 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008090 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008091 if (!key || !value)
8092 goto failed1;
8093 if (PyDict_SetItem(result, key, value) == -1)
8094 goto failed1;
8095 Py_DECREF(key);
8096 Py_DECREF(value);
8097 }
8098 return result;
8099 failed1:
8100 Py_XDECREF(key);
8101 Py_XDECREF(value);
8102 Py_DECREF(result);
8103 return NULL;
8104 }
8105
8106 /* Create a three-level trie */
8107 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8108 16*count2 + 128*count3 - 1);
8109 if (!result)
8110 return PyErr_NoMemory();
8111 PyObject_Init(result, &EncodingMapType);
8112 mresult = (struct encoding_map*)result;
8113 mresult->count2 = count2;
8114 mresult->count3 = count3;
8115 mlevel1 = mresult->level1;
8116 mlevel2 = mresult->level23;
8117 mlevel3 = mresult->level23 + 16*count2;
8118 memcpy(mlevel1, level1, 32);
8119 memset(mlevel2, 0xFF, 16*count2);
8120 memset(mlevel3, 0, 128*count3);
8121 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008122 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008123 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008124 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8125 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008126 /* unmapped character */
8127 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008128 o1 = ch>>11;
8129 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008130 i2 = 16*mlevel1[o1] + o2;
8131 if (mlevel2[i2] == 0xFF)
8132 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008133 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134 i3 = 128*mlevel2[i2] + o3;
8135 mlevel3[i3] = i;
8136 }
8137 return result;
8138}
8139
8140static int
Victor Stinner22168992011-11-20 17:09:18 +01008141encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008142{
8143 struct encoding_map *map = (struct encoding_map*)mapping;
8144 int l1 = c>>11;
8145 int l2 = (c>>7) & 0xF;
8146 int l3 = c & 0x7F;
8147 int i;
8148
Victor Stinner22168992011-11-20 17:09:18 +01008149 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008150 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008151 if (c == 0)
8152 return 0;
8153 /* level 1*/
8154 i = map->level1[l1];
8155 if (i == 0xFF) {
8156 return -1;
8157 }
8158 /* level 2*/
8159 i = map->level23[16*i+l2];
8160 if (i == 0xFF) {
8161 return -1;
8162 }
8163 /* level 3 */
8164 i = map->level23[16*map->count2 + 128*i + l3];
8165 if (i == 0) {
8166 return -1;
8167 }
8168 return i;
8169}
8170
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008171/* Lookup the character ch in the mapping. If the character
8172 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008173 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008174static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008175charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008176{
Christian Heimes217cfd12007-12-02 14:31:20 +00008177 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008178 PyObject *x;
8179
8180 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008181 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008182 x = PyObject_GetItem(mapping, w);
8183 Py_DECREF(w);
8184 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008185 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8186 /* No mapping found means: mapping is undefined. */
8187 PyErr_Clear();
8188 x = Py_None;
8189 Py_INCREF(x);
8190 return x;
8191 } else
8192 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008193 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008194 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008195 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008196 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008197 long value = PyLong_AS_LONG(x);
8198 if (value < 0 || value > 255) {
8199 PyErr_SetString(PyExc_TypeError,
8200 "character mapping must be in range(256)");
8201 Py_DECREF(x);
8202 return NULL;
8203 }
8204 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008205 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008206 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008207 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008208 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008209 /* wrong return value */
8210 PyErr_Format(PyExc_TypeError,
8211 "character mapping must return integer, bytes or None, not %.400s",
8212 x->ob_type->tp_name);
8213 Py_DECREF(x);
8214 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008215 }
8216}
8217
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008218static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008219charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008220{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008221 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8222 /* exponentially overallocate to minimize reallocations */
8223 if (requiredsize < 2*outsize)
8224 requiredsize = 2*outsize;
8225 if (_PyBytes_Resize(outobj, requiredsize))
8226 return -1;
8227 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008228}
8229
Benjamin Peterson14339b62009-01-31 16:36:08 +00008230typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008231 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008232} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008233/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008234 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008235 space is available. Return a new reference to the object that
8236 was put in the output buffer, or Py_None, if the mapping was undefined
8237 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008238 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008239static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008240charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008241 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008242{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008243 PyObject *rep;
8244 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008245 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008246
Christian Heimes90aa7642007-12-19 02:45:37 +00008247 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008248 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008249 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008250 if (res == -1)
8251 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008252 if (outsize<requiredsize)
8253 if (charmapencode_resize(outobj, outpos, requiredsize))
8254 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008255 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008256 outstart[(*outpos)++] = (char)res;
8257 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008258 }
8259
8260 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008262 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008263 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 Py_DECREF(rep);
8265 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008266 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008267 if (PyLong_Check(rep)) {
8268 Py_ssize_t requiredsize = *outpos+1;
8269 if (outsize<requiredsize)
8270 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8271 Py_DECREF(rep);
8272 return enc_EXCEPTION;
8273 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008274 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008275 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008276 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008277 else {
8278 const char *repchars = PyBytes_AS_STRING(rep);
8279 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8280 Py_ssize_t requiredsize = *outpos+repsize;
8281 if (outsize<requiredsize)
8282 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8283 Py_DECREF(rep);
8284 return enc_EXCEPTION;
8285 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008286 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008287 memcpy(outstart + *outpos, repchars, repsize);
8288 *outpos += repsize;
8289 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008291 Py_DECREF(rep);
8292 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008293}
8294
8295/* handle an error in PyUnicode_EncodeCharmap
8296 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008297static int
8298charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008299 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008300 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008301 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008302 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008303{
8304 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008305 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008306 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008307 enum PyUnicode_Kind kind;
8308 void *data;
8309 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008310 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008311 Py_ssize_t collstartpos = *inpos;
8312 Py_ssize_t collendpos = *inpos+1;
8313 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008314 char *encoding = "charmap";
8315 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008316 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008317 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008318 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008319
Benjamin Petersonbac79492012-01-14 13:34:47 -05008320 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008321 return -1;
8322 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008323 /* find all unencodable characters */
8324 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008325 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008326 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008327 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008328 val = encoding_map_lookup(ch, mapping);
8329 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 break;
8331 ++collendpos;
8332 continue;
8333 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008334
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008335 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8336 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008337 if (rep==NULL)
8338 return -1;
8339 else if (rep!=Py_None) {
8340 Py_DECREF(rep);
8341 break;
8342 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008343 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008345 }
8346 /* cache callback name lookup
8347 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008348 if (*error_handler == _Py_ERROR_UNKNOWN)
8349 *error_handler = get_error_handler(errors);
8350
8351 switch (*error_handler) {
8352 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008353 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008354 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008355
8356 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008357 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 x = charmapencode_output('?', mapping, res, respos);
8359 if (x==enc_EXCEPTION) {
8360 return -1;
8361 }
8362 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008363 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008364 return -1;
8365 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008366 }
8367 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008368 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008369 *inpos = collendpos;
8370 break;
Victor Stinner50149202015-09-22 00:26:54 +02008371
8372 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008373 /* generate replacement (temporarily (mis)uses p) */
8374 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 char buffer[2+29+1+1];
8376 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008377 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 for (cp = buffer; *cp; ++cp) {
8379 x = charmapencode_output(*cp, mapping, res, respos);
8380 if (x==enc_EXCEPTION)
8381 return -1;
8382 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008383 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 return -1;
8385 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008386 }
8387 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008388 *inpos = collendpos;
8389 break;
Victor Stinner50149202015-09-22 00:26:54 +02008390
Benjamin Peterson14339b62009-01-31 16:36:08 +00008391 default:
Victor Stinner50149202015-09-22 00:26:54 +02008392 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008393 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008394 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008395 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008397 if (PyBytes_Check(repunicode)) {
8398 /* Directly copy bytes result to output. */
8399 Py_ssize_t outsize = PyBytes_Size(*res);
8400 Py_ssize_t requiredsize;
8401 repsize = PyBytes_Size(repunicode);
8402 requiredsize = *respos + repsize;
8403 if (requiredsize > outsize)
8404 /* Make room for all additional bytes. */
8405 if (charmapencode_resize(res, respos, requiredsize)) {
8406 Py_DECREF(repunicode);
8407 return -1;
8408 }
8409 memcpy(PyBytes_AsString(*res) + *respos,
8410 PyBytes_AsString(repunicode), repsize);
8411 *respos += repsize;
8412 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008413 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008414 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008415 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008416 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008417 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008418 Py_DECREF(repunicode);
8419 return -1;
8420 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008421 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008422 data = PyUnicode_DATA(repunicode);
8423 kind = PyUnicode_KIND(repunicode);
8424 for (index = 0; index < repsize; index++) {
8425 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8426 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008427 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008428 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008429 return -1;
8430 }
8431 else if (x==enc_FAILED) {
8432 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008433 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008434 return -1;
8435 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008436 }
8437 *inpos = newpos;
8438 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008439 }
8440 return 0;
8441}
8442
Alexander Belopolsky40018472011-02-26 01:02:56 +00008443PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008444_PyUnicode_EncodeCharmap(PyObject *unicode,
8445 PyObject *mapping,
8446 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008447{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008448 /* output object */
8449 PyObject *res = NULL;
8450 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008451 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008452 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008453 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008454 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008455 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008456 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008457 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008458 void *data;
8459 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008460
Benjamin Petersonbac79492012-01-14 13:34:47 -05008461 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008462 return NULL;
8463 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008464 data = PyUnicode_DATA(unicode);
8465 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008466
Guido van Rossumd57fd912000-03-10 22:53:23 +00008467 /* Default to Latin-1 */
8468 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008469 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008470
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008471 /* allocate enough for a simple encoding without
8472 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008473 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474 if (res == NULL)
8475 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008476 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008477 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008478
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008479 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008480 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008482 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008483 if (x==enc_EXCEPTION) /* error */
8484 goto onError;
8485 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008486 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008488 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008489 &res, &respos)) {
8490 goto onError;
8491 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008492 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 else
8494 /* done with this character => adjust input position */
8495 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008496 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008497
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008498 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008499 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008500 if (_PyBytes_Resize(&res, respos) < 0)
8501 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008502
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008503 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008504 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008505 return res;
8506
Benjamin Peterson29060642009-01-31 22:14:21 +00008507 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008508 Py_XDECREF(res);
8509 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008510 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008511 return NULL;
8512}
8513
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008514/* Deprecated */
8515PyObject *
8516PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8517 Py_ssize_t size,
8518 PyObject *mapping,
8519 const char *errors)
8520{
8521 PyObject *result;
8522 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8523 if (unicode == NULL)
8524 return NULL;
8525 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8526 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008527 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008528}
8529
Alexander Belopolsky40018472011-02-26 01:02:56 +00008530PyObject *
8531PyUnicode_AsCharmapString(PyObject *unicode,
8532 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008533{
8534 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 PyErr_BadArgument();
8536 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008537 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008538 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008539}
8540
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008542static void
8543make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008544 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008545 Py_ssize_t startpos, Py_ssize_t endpos,
8546 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008547{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008548 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008549 *exceptionObject = _PyUnicodeTranslateError_Create(
8550 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008551 }
8552 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008553 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8554 goto onError;
8555 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8556 goto onError;
8557 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8558 goto onError;
8559 return;
8560 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008561 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008562 }
8563}
8564
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008565/* error handling callback helper:
8566 build arguments, call the callback and check the arguments,
8567 put the result into newpos and return the replacement string, which
8568 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008569static PyObject *
8570unicode_translate_call_errorhandler(const char *errors,
8571 PyObject **errorHandler,
8572 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008573 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008574 Py_ssize_t startpos, Py_ssize_t endpos,
8575 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008576{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02008577 static const char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008578
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008579 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008580 PyObject *restuple;
8581 PyObject *resunicode;
8582
8583 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008584 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008585 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008586 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008587 }
8588
8589 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008592 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008593
8594 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008595 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008596 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008597 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008598 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008599 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008600 Py_DECREF(restuple);
8601 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008602 }
8603 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008604 &resunicode, &i_newpos)) {
8605 Py_DECREF(restuple);
8606 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008607 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008608 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008609 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008610 else
8611 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008613 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008614 Py_DECREF(restuple);
8615 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008616 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008617 Py_INCREF(resunicode);
8618 Py_DECREF(restuple);
8619 return resunicode;
8620}
8621
8622/* Lookup the character ch in the mapping and put the result in result,
8623 which must be decrefed by the caller.
8624 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008625static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008626charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008627{
Christian Heimes217cfd12007-12-02 14:31:20 +00008628 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008629 PyObject *x;
8630
8631 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008632 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008633 x = PyObject_GetItem(mapping, w);
8634 Py_DECREF(w);
8635 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008636 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8637 /* No mapping found means: use 1:1 mapping. */
8638 PyErr_Clear();
8639 *result = NULL;
8640 return 0;
8641 } else
8642 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008643 }
8644 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008645 *result = x;
8646 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008647 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008648 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008649 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008650 if (value < 0 || value > MAX_UNICODE) {
8651 PyErr_Format(PyExc_ValueError,
8652 "character mapping must be in range(0x%x)",
8653 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 Py_DECREF(x);
8655 return -1;
8656 }
8657 *result = x;
8658 return 0;
8659 }
8660 else if (PyUnicode_Check(x)) {
8661 *result = x;
8662 return 0;
8663 }
8664 else {
8665 /* wrong return value */
8666 PyErr_SetString(PyExc_TypeError,
8667 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008668 Py_DECREF(x);
8669 return -1;
8670 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008671}
Victor Stinner1194ea02014-04-04 19:37:40 +02008672
8673/* lookup the character, write the result into the writer.
8674 Return 1 if the result was written into the writer, return 0 if the mapping
8675 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008676static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008677charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8678 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008679{
Victor Stinner1194ea02014-04-04 19:37:40 +02008680 PyObject *item;
8681
8682 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008683 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008684
8685 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008687 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008688 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008689 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008690 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008691 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008692
8693 if (item == Py_None) {
8694 Py_DECREF(item);
8695 return 0;
8696 }
8697
8698 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008699 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8700 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8701 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008702 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8703 Py_DECREF(item);
8704 return -1;
8705 }
8706 Py_DECREF(item);
8707 return 1;
8708 }
8709
8710 if (!PyUnicode_Check(item)) {
8711 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008712 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008713 }
8714
8715 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8716 Py_DECREF(item);
8717 return -1;
8718 }
8719
8720 Py_DECREF(item);
8721 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008722}
8723
Victor Stinner89a76ab2014-04-05 11:44:04 +02008724static int
8725unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8726 Py_UCS1 *translate)
8727{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008728 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008729 int ret = 0;
8730
Victor Stinner89a76ab2014-04-05 11:44:04 +02008731 if (charmaptranslate_lookup(ch, mapping, &item)) {
8732 return -1;
8733 }
8734
8735 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008736 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008737 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008738 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008739 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008740 /* not found => default to 1:1 mapping */
8741 translate[ch] = ch;
8742 return 1;
8743 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008744 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008745 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008746 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8747 used it */
8748 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008749 /* invalid character or character outside ASCII:
8750 skip the fast translate */
8751 goto exit;
8752 }
8753 translate[ch] = (Py_UCS1)replace;
8754 }
8755 else if (PyUnicode_Check(item)) {
8756 Py_UCS4 replace;
8757
8758 if (PyUnicode_READY(item) == -1) {
8759 Py_DECREF(item);
8760 return -1;
8761 }
8762 if (PyUnicode_GET_LENGTH(item) != 1)
8763 goto exit;
8764
8765 replace = PyUnicode_READ_CHAR(item, 0);
8766 if (replace > 127)
8767 goto exit;
8768 translate[ch] = (Py_UCS1)replace;
8769 }
8770 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008771 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008772 goto exit;
8773 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008774 ret = 1;
8775
Benjamin Peterson1365de72014-04-07 20:15:41 -04008776 exit:
8777 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008778 return ret;
8779}
8780
8781/* Fast path for ascii => ascii translation. Return 1 if the whole string
8782 was translated into writer, return 0 if the input string was partially
8783 translated into writer, raise an exception and return -1 on error. */
8784static int
8785unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008786 _PyUnicodeWriter *writer, int ignore,
8787 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008788{
Victor Stinner872b2912014-04-05 14:27:07 +02008789 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008790 Py_ssize_t len;
8791 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008792 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008793
Victor Stinner89a76ab2014-04-05 11:44:04 +02008794 len = PyUnicode_GET_LENGTH(input);
8795
Victor Stinner872b2912014-04-05 14:27:07 +02008796 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008797
8798 in = PyUnicode_1BYTE_DATA(input);
8799 end = in + len;
8800
8801 assert(PyUnicode_IS_ASCII(writer->buffer));
8802 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8803 out = PyUnicode_1BYTE_DATA(writer->buffer);
8804
Victor Stinner872b2912014-04-05 14:27:07 +02008805 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008806 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008807 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008808 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008809 int translate = unicode_fast_translate_lookup(mapping, ch,
8810 ascii_table);
8811 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008812 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008813 if (translate == 0)
8814 goto exit;
8815 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008816 }
Victor Stinner872b2912014-04-05 14:27:07 +02008817 if (ch2 == 0xfe) {
8818 if (ignore)
8819 continue;
8820 goto exit;
8821 }
8822 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008823 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008824 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008825 }
Victor Stinner872b2912014-04-05 14:27:07 +02008826 res = 1;
8827
8828exit:
8829 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008830 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008831 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008832}
8833
Victor Stinner3222da22015-10-01 22:07:32 +02008834static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008835_PyUnicode_TranslateCharmap(PyObject *input,
8836 PyObject *mapping,
8837 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008838{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008839 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008840 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008841 Py_ssize_t size, i;
8842 int kind;
8843 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008844 _PyUnicodeWriter writer;
8845 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008846 char *reason = "character maps to <undefined>";
8847 PyObject *errorHandler = NULL;
8848 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008849 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008850 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008851
Guido van Rossumd57fd912000-03-10 22:53:23 +00008852 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008853 PyErr_BadArgument();
8854 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008855 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008856
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008857 if (PyUnicode_READY(input) == -1)
8858 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008859 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008860 kind = PyUnicode_KIND(input);
8861 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008862
8863 if (size == 0) {
8864 Py_INCREF(input);
8865 return input;
8866 }
8867
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008868 /* allocate enough for a simple 1:1 translation without
8869 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008870 _PyUnicodeWriter_Init(&writer);
8871 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008872 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008873
Victor Stinner872b2912014-04-05 14:27:07 +02008874 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8875
Victor Stinner33798672016-03-01 21:59:58 +01008876 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008877 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008878 if (PyUnicode_IS_ASCII(input)) {
8879 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8880 if (res < 0) {
8881 _PyUnicodeWriter_Dealloc(&writer);
8882 return NULL;
8883 }
8884 if (res == 1)
8885 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008886 }
Victor Stinner33798672016-03-01 21:59:58 +01008887 else {
8888 i = 0;
8889 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008890
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008891 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008892 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008893 int translate;
8894 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8895 Py_ssize_t newpos;
8896 /* startpos for collecting untranslatable chars */
8897 Py_ssize_t collstart;
8898 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008899 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008900
Victor Stinner1194ea02014-04-04 19:37:40 +02008901 ch = PyUnicode_READ(kind, data, i);
8902 translate = charmaptranslate_output(ch, mapping, &writer);
8903 if (translate < 0)
8904 goto onError;
8905
8906 if (translate != 0) {
8907 /* it worked => adjust input pointer */
8908 ++i;
8909 continue;
8910 }
8911
8912 /* untranslatable character */
8913 collstart = i;
8914 collend = i+1;
8915
8916 /* find all untranslatable characters */
8917 while (collend < size) {
8918 PyObject *x;
8919 ch = PyUnicode_READ(kind, data, collend);
8920 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008921 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008922 Py_XDECREF(x);
8923 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008924 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008925 ++collend;
8926 }
8927
8928 if (ignore) {
8929 i = collend;
8930 }
8931 else {
8932 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8933 reason, input, &exc,
8934 collstart, collend, &newpos);
8935 if (repunicode == NULL)
8936 goto onError;
8937 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008938 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008939 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008940 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008941 Py_DECREF(repunicode);
8942 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008943 }
8944 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008945 Py_XDECREF(exc);
8946 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008947 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008948
Benjamin Peterson29060642009-01-31 22:14:21 +00008949 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008950 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008951 Py_XDECREF(exc);
8952 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008953 return NULL;
8954}
8955
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008956/* Deprecated. Use PyUnicode_Translate instead. */
8957PyObject *
8958PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8959 Py_ssize_t size,
8960 PyObject *mapping,
8961 const char *errors)
8962{
Christian Heimes5f520f42012-09-11 14:03:25 +02008963 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008964 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8965 if (!unicode)
8966 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008967 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8968 Py_DECREF(unicode);
8969 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008970}
8971
Alexander Belopolsky40018472011-02-26 01:02:56 +00008972PyObject *
8973PyUnicode_Translate(PyObject *str,
8974 PyObject *mapping,
8975 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008976{
8977 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008978
Guido van Rossumd57fd912000-03-10 22:53:23 +00008979 str = PyUnicode_FromObject(str);
8980 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008981 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008982 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008983 Py_DECREF(str);
8984 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008985}
Tim Petersced69f82003-09-16 20:30:58 +00008986
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008987static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008988fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008989{
8990 /* No need to call PyUnicode_READY(self) because this function is only
8991 called as a callback from fixup() which does it already. */
8992 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8993 const int kind = PyUnicode_KIND(self);
8994 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008995 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008996 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008997 Py_ssize_t i;
8998
8999 for (i = 0; i < len; ++i) {
9000 ch = PyUnicode_READ(kind, data, i);
9001 fixed = 0;
9002 if (ch > 127) {
9003 if (Py_UNICODE_ISSPACE(ch))
9004 fixed = ' ';
9005 else {
9006 const int decimal = Py_UNICODE_TODECIMAL(ch);
9007 if (decimal >= 0)
9008 fixed = '0' + decimal;
9009 }
9010 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009011 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009012 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009013 PyUnicode_WRITE(kind, data, i, fixed);
9014 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009015 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009016 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009017 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009018 }
9019
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009020 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009021}
9022
9023PyObject *
9024_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9025{
9026 if (!PyUnicode_Check(unicode)) {
9027 PyErr_BadInternalCall();
9028 return NULL;
9029 }
9030 if (PyUnicode_READY(unicode) == -1)
9031 return NULL;
9032 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9033 /* If the string is already ASCII, just return the same string */
9034 Py_INCREF(unicode);
9035 return unicode;
9036 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009037 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009038}
9039
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009040PyObject *
9041PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9042 Py_ssize_t length)
9043{
Victor Stinnerf0124502011-11-21 23:12:56 +01009044 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009045 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009046 Py_UCS4 maxchar;
9047 enum PyUnicode_Kind kind;
9048 void *data;
9049
Victor Stinner99d7ad02012-02-22 13:37:39 +01009050 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009051 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009052 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009053 if (ch > 127) {
9054 int decimal = Py_UNICODE_TODECIMAL(ch);
9055 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009056 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009057 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009058 }
9059 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009060
9061 /* Copy to a new string */
9062 decimal = PyUnicode_New(length, maxchar);
9063 if (decimal == NULL)
9064 return decimal;
9065 kind = PyUnicode_KIND(decimal);
9066 data = PyUnicode_DATA(decimal);
9067 /* Iterate over code points */
9068 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009069 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009070 if (ch > 127) {
9071 int decimal = Py_UNICODE_TODECIMAL(ch);
9072 if (decimal >= 0)
9073 ch = '0' + decimal;
9074 }
9075 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009076 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009077 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009078}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009079/* --- Decimal Encoder ---------------------------------------------------- */
9080
Alexander Belopolsky40018472011-02-26 01:02:56 +00009081int
9082PyUnicode_EncodeDecimal(Py_UNICODE *s,
9083 Py_ssize_t length,
9084 char *output,
9085 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009086{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009087 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009088 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009089 enum PyUnicode_Kind kind;
9090 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009091
9092 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009093 PyErr_BadArgument();
9094 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009095 }
9096
Victor Stinner42bf7752011-11-21 22:52:58 +01009097 unicode = PyUnicode_FromUnicode(s, length);
9098 if (unicode == NULL)
9099 return -1;
9100
Benjamin Petersonbac79492012-01-14 13:34:47 -05009101 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009102 Py_DECREF(unicode);
9103 return -1;
9104 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009105 kind = PyUnicode_KIND(unicode);
9106 data = PyUnicode_DATA(unicode);
9107
Victor Stinnerb84d7232011-11-22 01:50:07 +01009108 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009109 PyObject *exc;
9110 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009111 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009112 Py_ssize_t startpos;
9113
9114 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009115
Benjamin Peterson29060642009-01-31 22:14:21 +00009116 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009117 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009118 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009119 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009120 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009121 decimal = Py_UNICODE_TODECIMAL(ch);
9122 if (decimal >= 0) {
9123 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009124 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009125 continue;
9126 }
9127 if (0 < ch && ch < 256) {
9128 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009129 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009130 continue;
9131 }
Victor Stinner6345be92011-11-25 20:09:01 +01009132
Victor Stinner42bf7752011-11-21 22:52:58 +01009133 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009134 exc = NULL;
9135 raise_encode_exception(&exc, "decimal", unicode,
9136 startpos, startpos+1,
9137 "invalid decimal Unicode string");
9138 Py_XDECREF(exc);
9139 Py_DECREF(unicode);
9140 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009141 }
9142 /* 0-terminate the output string */
9143 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009144 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009145 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009146}
9147
Guido van Rossumd57fd912000-03-10 22:53:23 +00009148/* --- Helpers ------------------------------------------------------------ */
9149
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009150/* helper macro to fixup start/end slice values */
9151#define ADJUST_INDICES(start, end, len) \
9152 if (end > len) \
9153 end = len; \
9154 else if (end < 0) { \
9155 end += len; \
9156 if (end < 0) \
9157 end = 0; \
9158 } \
9159 if (start < 0) { \
9160 start += len; \
9161 if (start < 0) \
9162 start = 0; \
9163 }
9164
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009165static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009166any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009167 Py_ssize_t start,
9168 Py_ssize_t end)
9169{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009170 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009171 void *buf1, *buf2;
9172 Py_ssize_t len1, len2, result;
9173
9174 kind1 = PyUnicode_KIND(s1);
9175 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009176 if (kind1 < kind2)
9177 return -1;
9178
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009179 len1 = PyUnicode_GET_LENGTH(s1);
9180 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009181 ADJUST_INDICES(start, end, len1);
9182 if (end - start < len2)
9183 return -1;
9184
9185 buf1 = PyUnicode_DATA(s1);
9186 buf2 = PyUnicode_DATA(s2);
9187 if (len2 == 1) {
9188 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9189 result = findchar((const char *)buf1 + kind1*start,
9190 kind1, end - start, ch, direction);
9191 if (result == -1)
9192 return -1;
9193 else
9194 return start + result;
9195 }
9196
9197 if (kind2 != kind1) {
9198 buf2 = _PyUnicode_AsKind(s2, kind1);
9199 if (!buf2)
9200 return -2;
9201 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009202
Victor Stinner794d5672011-10-10 03:21:36 +02009203 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009204 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009205 case PyUnicode_1BYTE_KIND:
9206 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9207 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9208 else
9209 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9210 break;
9211 case PyUnicode_2BYTE_KIND:
9212 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9213 break;
9214 case PyUnicode_4BYTE_KIND:
9215 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9216 break;
9217 default:
9218 assert(0); result = -2;
9219 }
9220 }
9221 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009222 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009223 case PyUnicode_1BYTE_KIND:
9224 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9225 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9226 else
9227 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9228 break;
9229 case PyUnicode_2BYTE_KIND:
9230 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9231 break;
9232 case PyUnicode_4BYTE_KIND:
9233 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9234 break;
9235 default:
9236 assert(0); result = -2;
9237 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009238 }
9239
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009240 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009241 PyMem_Free(buf2);
9242
9243 return result;
9244}
9245
9246Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009247_PyUnicode_InsertThousandsGrouping(
9248 PyObject *unicode, Py_ssize_t index,
9249 Py_ssize_t n_buffer,
9250 void *digits, Py_ssize_t n_digits,
9251 Py_ssize_t min_width,
9252 const char *grouping, PyObject *thousands_sep,
9253 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009254{
Victor Stinner41a863c2012-02-24 00:37:51 +01009255 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009256 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009257 Py_ssize_t thousands_sep_len;
9258 Py_ssize_t len;
9259
9260 if (unicode != NULL) {
9261 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009262 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009263 }
9264 else {
9265 kind = PyUnicode_1BYTE_KIND;
9266 data = NULL;
9267 }
9268 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9269 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9270 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9271 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009272 if (thousands_sep_kind < kind) {
9273 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9274 if (!thousands_sep_data)
9275 return -1;
9276 }
9277 else {
9278 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9279 if (!data)
9280 return -1;
9281 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009282 }
9283
Benjamin Petersonead6b532011-12-20 17:23:42 -06009284 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009285 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009286 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009287 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009288 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009289 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009290 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009291 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009292 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009293 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009294 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009295 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009296 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009298 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009299 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009300 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009301 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009302 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009303 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009304 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009305 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009306 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009307 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009308 break;
9309 default:
9310 assert(0);
9311 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009312 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009313 if (unicode != NULL && thousands_sep_kind != kind) {
9314 if (thousands_sep_kind < kind)
9315 PyMem_Free(thousands_sep_data);
9316 else
9317 PyMem_Free(data);
9318 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009319 if (unicode == NULL) {
9320 *maxchar = 127;
9321 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009322 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009323 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009324 }
9325 }
9326 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009327}
9328
9329
Alexander Belopolsky40018472011-02-26 01:02:56 +00009330Py_ssize_t
9331PyUnicode_Count(PyObject *str,
9332 PyObject *substr,
9333 Py_ssize_t start,
9334 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009335{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009336 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009337 PyObject* str_obj;
9338 PyObject* sub_obj;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009339 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009340 void *buf1 = NULL, *buf2 = NULL;
9341 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009342
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009343 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009344 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009345 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009346 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009347 if (!sub_obj) {
9348 Py_DECREF(str_obj);
9349 return -1;
9350 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009351 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009352 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009353 Py_DECREF(str_obj);
9354 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009355 }
Tim Petersced69f82003-09-16 20:30:58 +00009356
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009357 kind1 = PyUnicode_KIND(str_obj);
9358 kind2 = PyUnicode_KIND(sub_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009359 if (kind1 < kind2) {
9360 Py_DECREF(sub_obj);
9361 Py_DECREF(str_obj);
9362 return 0;
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009363 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009364
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009365 len1 = PyUnicode_GET_LENGTH(str_obj);
9366 len2 = PyUnicode_GET_LENGTH(sub_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009367 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009368 if (end - start < len2) {
9369 Py_DECREF(sub_obj);
9370 Py_DECREF(str_obj);
9371 return 0;
9372 }
9373
9374 buf1 = PyUnicode_DATA(str_obj);
9375 buf2 = PyUnicode_DATA(sub_obj);
9376 if (kind2 != kind1) {
9377 buf2 = _PyUnicode_AsKind(sub_obj, kind1);
9378 if (!buf2)
9379 goto onError;
9380 }
9381
9382 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009383 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009384 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9385 result = asciilib_count(
9386 ((Py_UCS1*)buf1) + start, end - start,
9387 buf2, len2, PY_SSIZE_T_MAX
9388 );
9389 else
9390 result = ucs1lib_count(
9391 ((Py_UCS1*)buf1) + start, end - start,
9392 buf2, len2, PY_SSIZE_T_MAX
9393 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009394 break;
9395 case PyUnicode_2BYTE_KIND:
9396 result = ucs2lib_count(
9397 ((Py_UCS2*)buf1) + start, end - start,
9398 buf2, len2, PY_SSIZE_T_MAX
9399 );
9400 break;
9401 case PyUnicode_4BYTE_KIND:
9402 result = ucs4lib_count(
9403 ((Py_UCS4*)buf1) + start, end - start,
9404 buf2, len2, PY_SSIZE_T_MAX
9405 );
9406 break;
9407 default:
9408 assert(0); result = 0;
9409 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009410
9411 Py_DECREF(sub_obj);
9412 Py_DECREF(str_obj);
9413
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009414 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009415 PyMem_Free(buf2);
9416
Guido van Rossumd57fd912000-03-10 22:53:23 +00009417 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009418 onError:
9419 Py_DECREF(sub_obj);
9420 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009421 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009422 PyMem_Free(buf2);
9423 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009424}
9425
Alexander Belopolsky40018472011-02-26 01:02:56 +00009426Py_ssize_t
9427PyUnicode_Find(PyObject *str,
9428 PyObject *sub,
9429 Py_ssize_t start,
9430 Py_ssize_t end,
9431 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009432{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009433 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009434
Guido van Rossumd57fd912000-03-10 22:53:23 +00009435 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009436 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009437 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009438 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009439 if (!sub) {
9440 Py_DECREF(str);
9441 return -2;
9442 }
9443 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9444 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009445 Py_DECREF(str);
9446 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009447 }
Tim Petersced69f82003-09-16 20:30:58 +00009448
Victor Stinner794d5672011-10-10 03:21:36 +02009449 result = any_find_slice(direction,
9450 str, sub, start, end
9451 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009452
Guido van Rossumd57fd912000-03-10 22:53:23 +00009453 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009454 Py_DECREF(sub);
9455
Guido van Rossumd57fd912000-03-10 22:53:23 +00009456 return result;
9457}
9458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009459Py_ssize_t
9460PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9461 Py_ssize_t start, Py_ssize_t end,
9462 int direction)
9463{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009464 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009465 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466 if (PyUnicode_READY(str) == -1)
9467 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009468 if (start < 0 || end < 0) {
9469 PyErr_SetString(PyExc_IndexError, "string index out of range");
9470 return -2;
9471 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009472 if (end > PyUnicode_GET_LENGTH(str))
9473 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009474 if (start >= end)
9475 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009477 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9478 kind, end-start, ch, direction);
9479 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009480 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009481 else
9482 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009483}
9484
Alexander Belopolsky40018472011-02-26 01:02:56 +00009485static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009486tailmatch(PyObject *self,
9487 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009488 Py_ssize_t start,
9489 Py_ssize_t end,
9490 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492 int kind_self;
9493 int kind_sub;
9494 void *data_self;
9495 void *data_sub;
9496 Py_ssize_t offset;
9497 Py_ssize_t i;
9498 Py_ssize_t end_sub;
9499
9500 if (PyUnicode_READY(self) == -1 ||
9501 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009502 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009504 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9505 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009506 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009507 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009508
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009509 if (PyUnicode_GET_LENGTH(substring) == 0)
9510 return 1;
9511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009512 kind_self = PyUnicode_KIND(self);
9513 data_self = PyUnicode_DATA(self);
9514 kind_sub = PyUnicode_KIND(substring);
9515 data_sub = PyUnicode_DATA(substring);
9516 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9517
9518 if (direction > 0)
9519 offset = end;
9520 else
9521 offset = start;
9522
9523 if (PyUnicode_READ(kind_self, data_self, offset) ==
9524 PyUnicode_READ(kind_sub, data_sub, 0) &&
9525 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9526 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9527 /* If both are of the same kind, memcmp is sufficient */
9528 if (kind_self == kind_sub) {
9529 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009530 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009531 data_sub,
9532 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009533 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009534 }
9535 /* otherwise we have to compare each character by first accesing it */
9536 else {
9537 /* We do not need to compare 0 and len(substring)-1 because
9538 the if statement above ensured already that they are equal
9539 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009540 for (i = 1; i < end_sub; ++i) {
9541 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9542 PyUnicode_READ(kind_sub, data_sub, i))
9543 return 0;
9544 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009545 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009547 }
9548
9549 return 0;
9550}
9551
Alexander Belopolsky40018472011-02-26 01:02:56 +00009552Py_ssize_t
9553PyUnicode_Tailmatch(PyObject *str,
9554 PyObject *substr,
9555 Py_ssize_t start,
9556 Py_ssize_t end,
9557 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009558{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009559 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009560
Guido van Rossumd57fd912000-03-10 22:53:23 +00009561 str = PyUnicode_FromObject(str);
9562 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009563 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009564 substr = PyUnicode_FromObject(substr);
9565 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009566 Py_DECREF(str);
9567 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009568 }
Tim Petersced69f82003-09-16 20:30:58 +00009569
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009570 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009571 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009572 Py_DECREF(str);
9573 Py_DECREF(substr);
9574 return result;
9575}
9576
Guido van Rossumd57fd912000-03-10 22:53:23 +00009577/* Apply fixfct filter to the Unicode object self and return a
9578 reference to the modified object */
9579
Alexander Belopolsky40018472011-02-26 01:02:56 +00009580static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009581fixup(PyObject *self,
9582 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009583{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009584 PyObject *u;
9585 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009586 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009587
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009588 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009589 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009590 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009591 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009592
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009593 /* fix functions return the new maximum character in a string,
9594 if the kind of the resulting unicode object does not change,
9595 everything is fine. Otherwise we need to change the string kind
9596 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009597 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009598
9599 if (maxchar_new == 0) {
9600 /* no changes */;
9601 if (PyUnicode_CheckExact(self)) {
9602 Py_DECREF(u);
9603 Py_INCREF(self);
9604 return self;
9605 }
9606 else
9607 return u;
9608 }
9609
Victor Stinnere6abb482012-05-02 01:15:40 +02009610 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009611
Victor Stinnereaab6042011-12-11 22:22:39 +01009612 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009613 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009614
9615 /* In case the maximum character changed, we need to
9616 convert the string to the new category. */
9617 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9618 if (v == NULL) {
9619 Py_DECREF(u);
9620 return NULL;
9621 }
9622 if (maxchar_new > maxchar_old) {
9623 /* If the maxchar increased so that the kind changed, not all
9624 characters are representable anymore and we need to fix the
9625 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009626 _PyUnicode_FastCopyCharacters(v, 0,
9627 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009628 maxchar_old = fixfct(v);
9629 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009630 }
9631 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009632 _PyUnicode_FastCopyCharacters(v, 0,
9633 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009634 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009635 Py_DECREF(u);
9636 assert(_PyUnicode_CheckConsistency(v, 1));
9637 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009638}
9639
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009640static PyObject *
9641ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009642{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009643 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9644 char *resdata, *data = PyUnicode_DATA(self);
9645 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009646
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009647 res = PyUnicode_New(len, 127);
9648 if (res == NULL)
9649 return NULL;
9650 resdata = PyUnicode_DATA(res);
9651 if (lower)
9652 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009654 _Py_bytes_upper(resdata, data, len);
9655 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009656}
9657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009658static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009659handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009660{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009661 Py_ssize_t j;
9662 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009663 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009664 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009665
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009666 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9667
9668 where ! is a negation and \p{xxx} is a character with property xxx.
9669 */
9670 for (j = i - 1; j >= 0; j--) {
9671 c = PyUnicode_READ(kind, data, j);
9672 if (!_PyUnicode_IsCaseIgnorable(c))
9673 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009674 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009675 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9676 if (final_sigma) {
9677 for (j = i + 1; j < length; j++) {
9678 c = PyUnicode_READ(kind, data, j);
9679 if (!_PyUnicode_IsCaseIgnorable(c))
9680 break;
9681 }
9682 final_sigma = j == length || !_PyUnicode_IsCased(c);
9683 }
9684 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009685}
9686
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009687static int
9688lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9689 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009690{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009691 /* Obscure special case. */
9692 if (c == 0x3A3) {
9693 mapped[0] = handle_capital_sigma(kind, data, length, i);
9694 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009695 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009696 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009697}
9698
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009699static Py_ssize_t
9700do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009701{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009702 Py_ssize_t i, k = 0;
9703 int n_res, j;
9704 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009705
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009706 c = PyUnicode_READ(kind, data, 0);
9707 n_res = _PyUnicode_ToUpperFull(c, mapped);
9708 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009709 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009710 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009711 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009712 for (i = 1; i < length; i++) {
9713 c = PyUnicode_READ(kind, data, i);
9714 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9715 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009716 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009717 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009718 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009719 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009720 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009721}
9722
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009723static Py_ssize_t
9724do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9725 Py_ssize_t i, k = 0;
9726
9727 for (i = 0; i < length; i++) {
9728 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9729 int n_res, j;
9730 if (Py_UNICODE_ISUPPER(c)) {
9731 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9732 }
9733 else if (Py_UNICODE_ISLOWER(c)) {
9734 n_res = _PyUnicode_ToUpperFull(c, mapped);
9735 }
9736 else {
9737 n_res = 1;
9738 mapped[0] = c;
9739 }
9740 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009741 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009742 res[k++] = mapped[j];
9743 }
9744 }
9745 return k;
9746}
9747
9748static Py_ssize_t
9749do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9750 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009751{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009752 Py_ssize_t i, k = 0;
9753
9754 for (i = 0; i < length; i++) {
9755 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9756 int n_res, j;
9757 if (lower)
9758 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9759 else
9760 n_res = _PyUnicode_ToUpperFull(c, mapped);
9761 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009762 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009763 res[k++] = mapped[j];
9764 }
9765 }
9766 return k;
9767}
9768
9769static Py_ssize_t
9770do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9771{
9772 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9773}
9774
9775static Py_ssize_t
9776do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9777{
9778 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9779}
9780
Benjamin Petersone51757f2012-01-12 21:10:29 -05009781static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009782do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9783{
9784 Py_ssize_t i, k = 0;
9785
9786 for (i = 0; i < length; i++) {
9787 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9788 Py_UCS4 mapped[3];
9789 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9790 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009791 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009792 res[k++] = mapped[j];
9793 }
9794 }
9795 return k;
9796}
9797
9798static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009799do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9800{
9801 Py_ssize_t i, k = 0;
9802 int previous_is_cased;
9803
9804 previous_is_cased = 0;
9805 for (i = 0; i < length; i++) {
9806 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9807 Py_UCS4 mapped[3];
9808 int n_res, j;
9809
9810 if (previous_is_cased)
9811 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9812 else
9813 n_res = _PyUnicode_ToTitleFull(c, mapped);
9814
9815 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009816 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009817 res[k++] = mapped[j];
9818 }
9819
9820 previous_is_cased = _PyUnicode_IsCased(c);
9821 }
9822 return k;
9823}
9824
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009825static PyObject *
9826case_operation(PyObject *self,
9827 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9828{
9829 PyObject *res = NULL;
9830 Py_ssize_t length, newlength = 0;
9831 int kind, outkind;
9832 void *data, *outdata;
9833 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9834
Benjamin Petersoneea48462012-01-16 14:28:50 -05009835 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009836
9837 kind = PyUnicode_KIND(self);
9838 data = PyUnicode_DATA(self);
9839 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009840 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009841 PyErr_SetString(PyExc_OverflowError, "string is too long");
9842 return NULL;
9843 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009844 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009845 if (tmp == NULL)
9846 return PyErr_NoMemory();
9847 newlength = perform(kind, data, length, tmp, &maxchar);
9848 res = PyUnicode_New(newlength, maxchar);
9849 if (res == NULL)
9850 goto leave;
9851 tmpend = tmp + newlength;
9852 outdata = PyUnicode_DATA(res);
9853 outkind = PyUnicode_KIND(res);
9854 switch (outkind) {
9855 case PyUnicode_1BYTE_KIND:
9856 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9857 break;
9858 case PyUnicode_2BYTE_KIND:
9859 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9860 break;
9861 case PyUnicode_4BYTE_KIND:
9862 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9863 break;
9864 default:
9865 assert(0);
9866 break;
9867 }
9868 leave:
9869 PyMem_FREE(tmp);
9870 return res;
9871}
9872
Tim Peters8ce9f162004-08-27 01:49:32 +00009873PyObject *
9874PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009875{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009876 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009877 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009878 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009879 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009880 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9881 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009882 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009883 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009884 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009885 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009886 int use_memcpy;
9887 unsigned char *res_data = NULL, *sep_data = NULL;
9888 PyObject *last_obj;
9889 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009890
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009891 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009892 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009893 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009894 }
9895
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009896 /* NOTE: the following code can't call back into Python code,
9897 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009898 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009899
Tim Peters05eba1f2004-08-27 21:32:02 +00009900 seqlen = PySequence_Fast_GET_SIZE(fseq);
9901 /* If empty sequence, return u"". */
9902 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009903 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009904 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009905 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009906
Tim Peters05eba1f2004-08-27 21:32:02 +00009907 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009908 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009909 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009910 if (seqlen == 1) {
9911 if (PyUnicode_CheckExact(items[0])) {
9912 res = items[0];
9913 Py_INCREF(res);
9914 Py_DECREF(fseq);
9915 return res;
9916 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009917 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009918 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009919 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009920 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009921 /* Set up sep and seplen */
9922 if (separator == NULL) {
9923 /* fall back to a blank space separator */
9924 sep = PyUnicode_FromOrdinal(' ');
9925 if (!sep)
9926 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009927 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009928 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009929 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009930 else {
9931 if (!PyUnicode_Check(separator)) {
9932 PyErr_Format(PyExc_TypeError,
9933 "separator: expected str instance,"
9934 " %.80s found",
9935 Py_TYPE(separator)->tp_name);
9936 goto onError;
9937 }
9938 if (PyUnicode_READY(separator))
9939 goto onError;
9940 sep = separator;
9941 seplen = PyUnicode_GET_LENGTH(separator);
9942 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9943 /* inc refcount to keep this code path symmetric with the
9944 above case of a blank separator */
9945 Py_INCREF(sep);
9946 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009947 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009948 }
9949
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009950 /* There are at least two things to join, or else we have a subclass
9951 * of str in the sequence.
9952 * Do a pre-pass to figure out the total amount of space we'll
9953 * need (sz), and see whether all argument are strings.
9954 */
9955 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009956#ifdef Py_DEBUG
9957 use_memcpy = 0;
9958#else
9959 use_memcpy = 1;
9960#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009961 for (i = 0; i < seqlen; i++) {
9962 const Py_ssize_t old_sz = sz;
9963 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009964 if (!PyUnicode_Check(item)) {
9965 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009966 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009967 " %.80s found",
9968 i, Py_TYPE(item)->tp_name);
9969 goto onError;
9970 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009971 if (PyUnicode_READY(item) == -1)
9972 goto onError;
9973 sz += PyUnicode_GET_LENGTH(item);
9974 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009975 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009976 if (i != 0)
9977 sz += seplen;
9978 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9979 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009980 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009981 goto onError;
9982 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009983 if (use_memcpy && last_obj != NULL) {
9984 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9985 use_memcpy = 0;
9986 }
9987 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009988 }
Tim Petersced69f82003-09-16 20:30:58 +00009989
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009990 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009991 if (res == NULL)
9992 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009993
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009994 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009995#ifdef Py_DEBUG
9996 use_memcpy = 0;
9997#else
9998 if (use_memcpy) {
9999 res_data = PyUnicode_1BYTE_DATA(res);
10000 kind = PyUnicode_KIND(res);
10001 if (seplen != 0)
10002 sep_data = PyUnicode_1BYTE_DATA(sep);
10003 }
10004#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010005 if (use_memcpy) {
10006 for (i = 0; i < seqlen; ++i) {
10007 Py_ssize_t itemlen;
10008 item = items[i];
10009
10010 /* Copy item, and maybe the separator. */
10011 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +020010012 Py_MEMCPY(res_data,
10013 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010014 kind * seplen);
10015 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010016 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010017
10018 itemlen = PyUnicode_GET_LENGTH(item);
10019 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +020010020 Py_MEMCPY(res_data,
10021 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010022 kind * itemlen);
10023 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010024 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010025 }
10026 assert(res_data == PyUnicode_1BYTE_DATA(res)
10027 + kind * PyUnicode_GET_LENGTH(res));
10028 }
10029 else {
10030 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10031 Py_ssize_t itemlen;
10032 item = items[i];
10033
10034 /* Copy item, and maybe the separator. */
10035 if (i && seplen != 0) {
10036 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10037 res_offset += seplen;
10038 }
10039
10040 itemlen = PyUnicode_GET_LENGTH(item);
10041 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010042 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010043 res_offset += itemlen;
10044 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010045 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010046 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010047 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010048
Tim Peters05eba1f2004-08-27 21:32:02 +000010049 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010050 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010051 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010052 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010053
Benjamin Peterson29060642009-01-31 22:14:21 +000010054 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +000010055 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010056 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010057 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010058 return NULL;
10059}
10060
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010061#define FILL(kind, data, value, start, length) \
10062 do { \
10063 Py_ssize_t i_ = 0; \
10064 assert(kind != PyUnicode_WCHAR_KIND); \
10065 switch ((kind)) { \
10066 case PyUnicode_1BYTE_KIND: { \
10067 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010068 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010069 break; \
10070 } \
10071 case PyUnicode_2BYTE_KIND: { \
10072 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10073 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10074 break; \
10075 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010076 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010077 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10078 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10079 break; \
10080 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010081 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010082 } \
10083 } while (0)
10084
Victor Stinnerd3f08822012-05-29 12:57:52 +020010085void
10086_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10087 Py_UCS4 fill_char)
10088{
10089 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10090 const void *data = PyUnicode_DATA(unicode);
10091 assert(PyUnicode_IS_READY(unicode));
10092 assert(unicode_modifiable(unicode));
10093 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10094 assert(start >= 0);
10095 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10096 FILL(kind, data, fill_char, start, length);
10097}
10098
Victor Stinner3fe55312012-01-04 00:33:50 +010010099Py_ssize_t
10100PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10101 Py_UCS4 fill_char)
10102{
10103 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010104
10105 if (!PyUnicode_Check(unicode)) {
10106 PyErr_BadInternalCall();
10107 return -1;
10108 }
10109 if (PyUnicode_READY(unicode) == -1)
10110 return -1;
10111 if (unicode_check_modifiable(unicode))
10112 return -1;
10113
Victor Stinnerd3f08822012-05-29 12:57:52 +020010114 if (start < 0) {
10115 PyErr_SetString(PyExc_IndexError, "string index out of range");
10116 return -1;
10117 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010118 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10119 PyErr_SetString(PyExc_ValueError,
10120 "fill character is bigger than "
10121 "the string maximum character");
10122 return -1;
10123 }
10124
10125 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10126 length = Py_MIN(maxlen, length);
10127 if (length <= 0)
10128 return 0;
10129
Victor Stinnerd3f08822012-05-29 12:57:52 +020010130 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010131 return length;
10132}
10133
Victor Stinner9310abb2011-10-05 00:59:23 +020010134static PyObject *
10135pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010136 Py_ssize_t left,
10137 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010139{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 PyObject *u;
10141 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010142 int kind;
10143 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010144
10145 if (left < 0)
10146 left = 0;
10147 if (right < 0)
10148 right = 0;
10149
Victor Stinnerc4b49542011-12-11 22:44:26 +010010150 if (left == 0 && right == 0)
10151 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010152
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10154 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010155 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10156 return NULL;
10157 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010159 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010161 if (!u)
10162 return NULL;
10163
10164 kind = PyUnicode_KIND(u);
10165 data = PyUnicode_DATA(u);
10166 if (left)
10167 FILL(kind, data, fill, 0, left);
10168 if (right)
10169 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010170 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010171 assert(_PyUnicode_CheckConsistency(u, 1));
10172 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010173}
10174
Alexander Belopolsky40018472011-02-26 01:02:56 +000010175PyObject *
10176PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010177{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010178 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010179
10180 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010181 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010182 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060010183 if (PyUnicode_READY(string) == -1) {
10184 Py_DECREF(string);
10185 return NULL;
10186 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010187
Benjamin Petersonead6b532011-12-20 17:23:42 -060010188 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010189 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010190 if (PyUnicode_IS_ASCII(string))
10191 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010192 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010193 PyUnicode_GET_LENGTH(string), keepends);
10194 else
10195 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010196 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010197 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 break;
10199 case PyUnicode_2BYTE_KIND:
10200 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010201 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202 PyUnicode_GET_LENGTH(string), keepends);
10203 break;
10204 case PyUnicode_4BYTE_KIND:
10205 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010206 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 PyUnicode_GET_LENGTH(string), keepends);
10208 break;
10209 default:
10210 assert(0);
10211 list = 0;
10212 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010213 Py_DECREF(string);
10214 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010215}
10216
Alexander Belopolsky40018472011-02-26 01:02:56 +000010217static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010218split(PyObject *self,
10219 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010220 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010221{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010222 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 void *buf1, *buf2;
10224 Py_ssize_t len1, len2;
10225 PyObject* out;
10226
Guido van Rossumd57fd912000-03-10 22:53:23 +000010227 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010228 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010229
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 if (PyUnicode_READY(self) == -1)
10231 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010232
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010234 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010236 if (PyUnicode_IS_ASCII(self))
10237 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010238 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010239 PyUnicode_GET_LENGTH(self), maxcount
10240 );
10241 else
10242 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010243 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010244 PyUnicode_GET_LENGTH(self), maxcount
10245 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 case PyUnicode_2BYTE_KIND:
10247 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010248 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249 PyUnicode_GET_LENGTH(self), maxcount
10250 );
10251 case PyUnicode_4BYTE_KIND:
10252 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010253 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 PyUnicode_GET_LENGTH(self), maxcount
10255 );
10256 default:
10257 assert(0);
10258 return NULL;
10259 }
10260
10261 if (PyUnicode_READY(substring) == -1)
10262 return NULL;
10263
10264 kind1 = PyUnicode_KIND(self);
10265 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266 len1 = PyUnicode_GET_LENGTH(self);
10267 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010268 if (kind1 < kind2 || len1 < len2) {
10269 out = PyList_New(1);
10270 if (out == NULL)
10271 return NULL;
10272 Py_INCREF(self);
10273 PyList_SET_ITEM(out, 0, self);
10274 return out;
10275 }
10276 buf1 = PyUnicode_DATA(self);
10277 buf2 = PyUnicode_DATA(substring);
10278 if (kind2 != kind1) {
10279 buf2 = _PyUnicode_AsKind(substring, kind1);
10280 if (!buf2)
10281 return NULL;
10282 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010284 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010286 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10287 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010288 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010289 else
10290 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010291 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 break;
10293 case PyUnicode_2BYTE_KIND:
10294 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010295 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 break;
10297 case PyUnicode_4BYTE_KIND:
10298 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010299 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 break;
10301 default:
10302 out = NULL;
10303 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010304 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 PyMem_Free(buf2);
10306 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010307}
10308
Alexander Belopolsky40018472011-02-26 01:02:56 +000010309static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010310rsplit(PyObject *self,
10311 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010312 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010313{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010314 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 void *buf1, *buf2;
10316 Py_ssize_t len1, len2;
10317 PyObject* out;
10318
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010319 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010320 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010321
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 if (PyUnicode_READY(self) == -1)
10323 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010325 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010326 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010328 if (PyUnicode_IS_ASCII(self))
10329 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010330 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010331 PyUnicode_GET_LENGTH(self), maxcount
10332 );
10333 else
10334 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010335 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010336 PyUnicode_GET_LENGTH(self), maxcount
10337 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 case PyUnicode_2BYTE_KIND:
10339 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010340 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010341 PyUnicode_GET_LENGTH(self), maxcount
10342 );
10343 case PyUnicode_4BYTE_KIND:
10344 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010345 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346 PyUnicode_GET_LENGTH(self), maxcount
10347 );
10348 default:
10349 assert(0);
10350 return NULL;
10351 }
10352
10353 if (PyUnicode_READY(substring) == -1)
10354 return NULL;
10355
10356 kind1 = PyUnicode_KIND(self);
10357 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358 len1 = PyUnicode_GET_LENGTH(self);
10359 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010360 if (kind1 < kind2 || len1 < len2) {
10361 out = PyList_New(1);
10362 if (out == NULL)
10363 return NULL;
10364 Py_INCREF(self);
10365 PyList_SET_ITEM(out, 0, self);
10366 return out;
10367 }
10368 buf1 = PyUnicode_DATA(self);
10369 buf2 = PyUnicode_DATA(substring);
10370 if (kind2 != kind1) {
10371 buf2 = _PyUnicode_AsKind(substring, kind1);
10372 if (!buf2)
10373 return NULL;
10374 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010376 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010378 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10379 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010380 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010381 else
10382 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010383 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 break;
10385 case PyUnicode_2BYTE_KIND:
10386 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010387 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 break;
10389 case PyUnicode_4BYTE_KIND:
10390 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010391 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 break;
10393 default:
10394 out = NULL;
10395 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010396 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397 PyMem_Free(buf2);
10398 return out;
10399}
10400
10401static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010402anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10403 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010405 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010406 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010407 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10408 return asciilib_find(buf1, len1, buf2, len2, offset);
10409 else
10410 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 case PyUnicode_2BYTE_KIND:
10412 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10413 case PyUnicode_4BYTE_KIND:
10414 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10415 }
10416 assert(0);
10417 return -1;
10418}
10419
10420static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010421anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10422 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010423{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010424 switch (kind) {
10425 case PyUnicode_1BYTE_KIND:
10426 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10427 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10428 else
10429 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10430 case PyUnicode_2BYTE_KIND:
10431 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10432 case PyUnicode_4BYTE_KIND:
10433 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10434 }
10435 assert(0);
10436 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010437}
10438
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010439static void
10440replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10441 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10442{
10443 int kind = PyUnicode_KIND(u);
10444 void *data = PyUnicode_DATA(u);
10445 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10446 if (kind == PyUnicode_1BYTE_KIND) {
10447 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10448 (Py_UCS1 *)data + len,
10449 u1, u2, maxcount);
10450 }
10451 else if (kind == PyUnicode_2BYTE_KIND) {
10452 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10453 (Py_UCS2 *)data + len,
10454 u1, u2, maxcount);
10455 }
10456 else {
10457 assert(kind == PyUnicode_4BYTE_KIND);
10458 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10459 (Py_UCS4 *)data + len,
10460 u1, u2, maxcount);
10461 }
10462}
10463
Alexander Belopolsky40018472011-02-26 01:02:56 +000010464static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465replace(PyObject *self, PyObject *str1,
10466 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010467{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 PyObject *u;
10469 char *sbuf = PyUnicode_DATA(self);
10470 char *buf1 = PyUnicode_DATA(str1);
10471 char *buf2 = PyUnicode_DATA(str2);
10472 int srelease = 0, release1 = 0, release2 = 0;
10473 int skind = PyUnicode_KIND(self);
10474 int kind1 = PyUnicode_KIND(str1);
10475 int kind2 = PyUnicode_KIND(str2);
10476 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10477 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10478 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010479 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010480 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010481
10482 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010483 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010485 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010486
Victor Stinner59de0ee2011-10-07 10:01:28 +020010487 if (str1 == str2)
10488 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010489
Victor Stinner49a0a212011-10-12 23:46:10 +020010490 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010491 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10492 if (maxchar < maxchar_str1)
10493 /* substring too wide to be present */
10494 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010495 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10496 /* Replacing str1 with str2 may cause a maxchar reduction in the
10497 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010498 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010499 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010502 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010504 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010505 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010506 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010507 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010508 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010509
Victor Stinner69ed0f42013-04-09 21:48:24 +020010510 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010511 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010512 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010513 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010514 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010515 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010516 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010518
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010519 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10520 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010521 }
10522 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 int rkind = skind;
10524 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010525 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010527 if (kind1 < rkind) {
10528 /* widen substring */
10529 buf1 = _PyUnicode_AsKind(str1, rkind);
10530 if (!buf1) goto error;
10531 release1 = 1;
10532 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010533 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010534 if (i < 0)
10535 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 if (rkind > kind2) {
10537 /* widen replacement */
10538 buf2 = _PyUnicode_AsKind(str2, rkind);
10539 if (!buf2) goto error;
10540 release2 = 1;
10541 }
10542 else if (rkind < kind2) {
10543 /* widen self and buf1 */
10544 rkind = kind2;
10545 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010546 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010547 sbuf = _PyUnicode_AsKind(self, rkind);
10548 if (!sbuf) goto error;
10549 srelease = 1;
10550 buf1 = _PyUnicode_AsKind(str1, rkind);
10551 if (!buf1) goto error;
10552 release1 = 1;
10553 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010554 u = PyUnicode_New(slen, maxchar);
10555 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010557 assert(PyUnicode_KIND(u) == rkind);
10558 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010559
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010560 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010561 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010562 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010564 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010565 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010566
10567 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010568 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010569 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010570 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010571 if (i == -1)
10572 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010573 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010575 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010576 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010577 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010578 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010579 }
10580 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010582 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010583 int rkind = skind;
10584 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010585
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010587 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 buf1 = _PyUnicode_AsKind(str1, rkind);
10589 if (!buf1) goto error;
10590 release1 = 1;
10591 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010592 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010593 if (n == 0)
10594 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010596 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 buf2 = _PyUnicode_AsKind(str2, rkind);
10598 if (!buf2) goto error;
10599 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010600 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010602 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 rkind = kind2;
10604 sbuf = _PyUnicode_AsKind(self, rkind);
10605 if (!sbuf) goto error;
10606 srelease = 1;
10607 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010608 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010609 buf1 = _PyUnicode_AsKind(str1, rkind);
10610 if (!buf1) goto error;
10611 release1 = 1;
10612 }
10613 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10614 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010615 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010616 PyErr_SetString(PyExc_OverflowError,
10617 "replace string is too long");
10618 goto error;
10619 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010620 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010621 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010622 _Py_INCREF_UNICODE_EMPTY();
10623 if (!unicode_empty)
10624 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010625 u = unicode_empty;
10626 goto done;
10627 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010628 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 PyErr_SetString(PyExc_OverflowError,
10630 "replace string is too long");
10631 goto error;
10632 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010633 u = PyUnicode_New(new_size, maxchar);
10634 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010636 assert(PyUnicode_KIND(u) == rkind);
10637 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010638 ires = i = 0;
10639 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010640 while (n-- > 0) {
10641 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010642 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010643 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010644 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010645 if (j == -1)
10646 break;
10647 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010648 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010649 memcpy(res + rkind * ires,
10650 sbuf + rkind * i,
10651 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010652 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010653 }
10654 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010656 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010657 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010658 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010659 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010660 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010662 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010664 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010665 memcpy(res + rkind * ires,
10666 sbuf + rkind * i,
10667 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010668 }
10669 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010670 /* interleave */
10671 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010672 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010673 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010674 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010675 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010676 if (--n <= 0)
10677 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010678 memcpy(res + rkind * ires,
10679 sbuf + rkind * i,
10680 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010681 ires++;
10682 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010683 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010684 memcpy(res + rkind * ires,
10685 sbuf + rkind * i,
10686 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010687 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010688 }
10689
10690 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010691 unicode_adjust_maxchar(&u);
10692 if (u == NULL)
10693 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010694 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010695
10696 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010697 if (srelease)
10698 PyMem_FREE(sbuf);
10699 if (release1)
10700 PyMem_FREE(buf1);
10701 if (release2)
10702 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010703 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010704 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010705
Benjamin Peterson29060642009-01-31 22:14:21 +000010706 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010707 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010708 if (srelease)
10709 PyMem_FREE(sbuf);
10710 if (release1)
10711 PyMem_FREE(buf1);
10712 if (release2)
10713 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010714 return unicode_result_unchanged(self);
10715
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010716 error:
10717 if (srelease && sbuf)
10718 PyMem_FREE(sbuf);
10719 if (release1 && buf1)
10720 PyMem_FREE(buf1);
10721 if (release2 && buf2)
10722 PyMem_FREE(buf2);
10723 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010724}
10725
10726/* --- Unicode Object Methods --------------------------------------------- */
10727
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010728PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010729 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010730\n\
10731Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010732characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010733
10734static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010735unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010736{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010737 if (PyUnicode_READY(self) == -1)
10738 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010739 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010740}
10741
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010742PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010743 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010744\n\
10745Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010746have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010747
10748static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010749unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010751 if (PyUnicode_READY(self) == -1)
10752 return NULL;
10753 if (PyUnicode_GET_LENGTH(self) == 0)
10754 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010755 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756}
10757
Benjamin Petersond5890c82012-01-14 13:23:30 -050010758PyDoc_STRVAR(casefold__doc__,
10759 "S.casefold() -> str\n\
10760\n\
10761Return a version of S suitable for caseless comparisons.");
10762
10763static PyObject *
10764unicode_casefold(PyObject *self)
10765{
10766 if (PyUnicode_READY(self) == -1)
10767 return NULL;
10768 if (PyUnicode_IS_ASCII(self))
10769 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010770 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010771}
10772
10773
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010774/* Argument converter. Coerces to a single unicode character */
10775
10776static int
10777convert_uc(PyObject *obj, void *addr)
10778{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010779 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010780 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010781
Benjamin Peterson14339b62009-01-31 16:36:08 +000010782 uniobj = PyUnicode_FromObject(obj);
10783 if (uniobj == NULL) {
10784 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010785 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010786 return 0;
10787 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010788 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010789 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010790 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010791 Py_DECREF(uniobj);
10792 return 0;
10793 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010794 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010795 Py_DECREF(uniobj);
10796 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010797}
10798
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010799PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010800 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010801\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010802Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010803done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010804
10805static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010806unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010807{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010808 Py_ssize_t marg, left;
10809 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010810 Py_UCS4 fillchar = ' ';
10811
Victor Stinnere9a29352011-10-01 02:14:59 +020010812 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010813 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010814
Benjamin Petersonbac79492012-01-14 13:34:47 -050010815 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010816 return NULL;
10817
Victor Stinnerc4b49542011-12-11 22:44:26 +010010818 if (PyUnicode_GET_LENGTH(self) >= width)
10819 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010820
Victor Stinnerc4b49542011-12-11 22:44:26 +010010821 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010822 left = marg / 2 + (marg & width & 1);
10823
Victor Stinner9310abb2011-10-05 00:59:23 +020010824 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010825}
10826
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010827/* This function assumes that str1 and str2 are readied by the caller. */
10828
Marc-André Lemburge5034372000-08-08 08:04:29 +000010829static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010830unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010831{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010832#define COMPARE(TYPE1, TYPE2) \
10833 do { \
10834 TYPE1* p1 = (TYPE1 *)data1; \
10835 TYPE2* p2 = (TYPE2 *)data2; \
10836 TYPE1* end = p1 + len; \
10837 Py_UCS4 c1, c2; \
10838 for (; p1 != end; p1++, p2++) { \
10839 c1 = *p1; \
10840 c2 = *p2; \
10841 if (c1 != c2) \
10842 return (c1 < c2) ? -1 : 1; \
10843 } \
10844 } \
10845 while (0)
10846
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010847 int kind1, kind2;
10848 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010849 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010850
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010851 kind1 = PyUnicode_KIND(str1);
10852 kind2 = PyUnicode_KIND(str2);
10853 data1 = PyUnicode_DATA(str1);
10854 data2 = PyUnicode_DATA(str2);
10855 len1 = PyUnicode_GET_LENGTH(str1);
10856 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010857 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010858
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010859 switch(kind1) {
10860 case PyUnicode_1BYTE_KIND:
10861 {
10862 switch(kind2) {
10863 case PyUnicode_1BYTE_KIND:
10864 {
10865 int cmp = memcmp(data1, data2, len);
10866 /* normalize result of memcmp() into the range [-1; 1] */
10867 if (cmp < 0)
10868 return -1;
10869 if (cmp > 0)
10870 return 1;
10871 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010872 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010873 case PyUnicode_2BYTE_KIND:
10874 COMPARE(Py_UCS1, Py_UCS2);
10875 break;
10876 case PyUnicode_4BYTE_KIND:
10877 COMPARE(Py_UCS1, Py_UCS4);
10878 break;
10879 default:
10880 assert(0);
10881 }
10882 break;
10883 }
10884 case PyUnicode_2BYTE_KIND:
10885 {
10886 switch(kind2) {
10887 case PyUnicode_1BYTE_KIND:
10888 COMPARE(Py_UCS2, Py_UCS1);
10889 break;
10890 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010891 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010892 COMPARE(Py_UCS2, Py_UCS2);
10893 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010894 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010895 case PyUnicode_4BYTE_KIND:
10896 COMPARE(Py_UCS2, Py_UCS4);
10897 break;
10898 default:
10899 assert(0);
10900 }
10901 break;
10902 }
10903 case PyUnicode_4BYTE_KIND:
10904 {
10905 switch(kind2) {
10906 case PyUnicode_1BYTE_KIND:
10907 COMPARE(Py_UCS4, Py_UCS1);
10908 break;
10909 case PyUnicode_2BYTE_KIND:
10910 COMPARE(Py_UCS4, Py_UCS2);
10911 break;
10912 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010913 {
10914#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10915 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10916 /* normalize result of wmemcmp() into the range [-1; 1] */
10917 if (cmp < 0)
10918 return -1;
10919 if (cmp > 0)
10920 return 1;
10921#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010922 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010923#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010924 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010925 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010926 default:
10927 assert(0);
10928 }
10929 break;
10930 }
10931 default:
10932 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010933 }
10934
Victor Stinner770e19e2012-10-04 22:59:45 +020010935 if (len1 == len2)
10936 return 0;
10937 if (len1 < len2)
10938 return -1;
10939 else
10940 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010941
10942#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010943}
10944
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010945Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010946unicode_compare_eq(PyObject *str1, PyObject *str2)
10947{
10948 int kind;
10949 void *data1, *data2;
10950 Py_ssize_t len;
10951 int cmp;
10952
Victor Stinnere5567ad2012-10-23 02:48:49 +020010953 len = PyUnicode_GET_LENGTH(str1);
10954 if (PyUnicode_GET_LENGTH(str2) != len)
10955 return 0;
10956 kind = PyUnicode_KIND(str1);
10957 if (PyUnicode_KIND(str2) != kind)
10958 return 0;
10959 data1 = PyUnicode_DATA(str1);
10960 data2 = PyUnicode_DATA(str2);
10961
10962 cmp = memcmp(data1, data2, len * kind);
10963 return (cmp == 0);
10964}
10965
10966
Alexander Belopolsky40018472011-02-26 01:02:56 +000010967int
10968PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010969{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010970 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10971 if (PyUnicode_READY(left) == -1 ||
10972 PyUnicode_READY(right) == -1)
10973 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010974
10975 /* a string is equal to itself */
10976 if (left == right)
10977 return 0;
10978
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010979 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010980 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010981 PyErr_Format(PyExc_TypeError,
10982 "Can't compare %.100s and %.100s",
10983 left->ob_type->tp_name,
10984 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010985 return -1;
10986}
10987
Martin v. Löwis5b222132007-06-10 09:51:05 +000010988int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010989_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10990{
10991 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10992 if (right_str == NULL)
10993 return -1;
10994 return PyUnicode_Compare(left, right_str);
10995}
10996
10997int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010998PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10999{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011000 Py_ssize_t i;
11001 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011002 Py_UCS4 chr;
11003
Victor Stinner910337b2011-10-03 03:20:16 +020011004 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011005 if (PyUnicode_READY(uni) == -1)
11006 return -1;
11007 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011008 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011009 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011010 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011011 size_t len, len2 = strlen(str);
11012 int cmp;
11013
11014 len = Py_MIN(len1, len2);
11015 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011016 if (cmp != 0) {
11017 if (cmp < 0)
11018 return -1;
11019 else
11020 return 1;
11021 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011022 if (len1 > len2)
11023 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011024 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011025 return -1; /* str is longer */
11026 return 0;
11027 }
11028 else {
11029 void *data = PyUnicode_DATA(uni);
11030 /* Compare Unicode string and source character set string */
11031 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011032 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011033 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11034 /* This check keeps Python strings that end in '\0' from comparing equal
11035 to C strings identical up to that point. */
11036 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11037 return 1; /* uni is longer */
11038 if (str[i])
11039 return -1; /* str is longer */
11040 return 0;
11041 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011042}
11043
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011044
Benjamin Peterson29060642009-01-31 22:14:21 +000011045#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011046 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011047
Alexander Belopolsky40018472011-02-26 01:02:56 +000011048PyObject *
11049PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011050{
11051 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011052 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011053
Victor Stinnere5567ad2012-10-23 02:48:49 +020011054 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11055 Py_RETURN_NOTIMPLEMENTED;
11056
11057 if (PyUnicode_READY(left) == -1 ||
11058 PyUnicode_READY(right) == -1)
11059 return NULL;
11060
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011061 if (left == right) {
11062 switch (op) {
11063 case Py_EQ:
11064 case Py_LE:
11065 case Py_GE:
11066 /* a string is equal to itself */
11067 v = Py_True;
11068 break;
11069 case Py_NE:
11070 case Py_LT:
11071 case Py_GT:
11072 v = Py_False;
11073 break;
11074 default:
11075 PyErr_BadArgument();
11076 return NULL;
11077 }
11078 }
11079 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011080 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011081 result ^= (op == Py_NE);
11082 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011083 }
11084 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011085 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011086
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011087 /* Convert the return value to a Boolean */
11088 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011089 case Py_LE:
11090 v = TEST_COND(result <= 0);
11091 break;
11092 case Py_GE:
11093 v = TEST_COND(result >= 0);
11094 break;
11095 case Py_LT:
11096 v = TEST_COND(result == -1);
11097 break;
11098 case Py_GT:
11099 v = TEST_COND(result == 1);
11100 break;
11101 default:
11102 PyErr_BadArgument();
11103 return NULL;
11104 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011105 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011106 Py_INCREF(v);
11107 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011108}
11109
Alexander Belopolsky40018472011-02-26 01:02:56 +000011110int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011111_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11112{
11113 return unicode_eq(aa, bb);
11114}
11115
11116int
Alexander Belopolsky40018472011-02-26 01:02:56 +000011117PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011118{
Thomas Wouters477c8d52006-05-27 19:21:47 +000011119 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020011120 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011121 void *buf1, *buf2;
11122 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011123 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011124
11125 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000011126 sub = PyUnicode_FromObject(element);
11127 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011128 PyErr_Format(PyExc_TypeError,
11129 "'in <string>' requires string as left operand, not %s",
11130 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011131 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011132 }
11133
Thomas Wouters477c8d52006-05-27 19:21:47 +000011134 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011135 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011136 Py_DECREF(sub);
11137 return -1;
11138 }
11139
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011140 kind1 = PyUnicode_KIND(str);
11141 kind2 = PyUnicode_KIND(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011142 if (kind1 < kind2) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011143 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050011144 Py_DECREF(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011145 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011146 }
11147 len1 = PyUnicode_GET_LENGTH(str);
11148 len2 = PyUnicode_GET_LENGTH(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011149 if (len1 < len2) {
11150 Py_DECREF(sub);
11151 Py_DECREF(str);
11152 return 0;
11153 }
11154 buf1 = PyUnicode_DATA(str);
11155 buf2 = PyUnicode_DATA(sub);
11156 if (len2 == 1) {
11157 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11158 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
11159 Py_DECREF(sub);
11160 Py_DECREF(str);
11161 return result;
11162 }
11163 if (kind2 != kind1) {
11164 buf2 = _PyUnicode_AsKind(sub, kind1);
11165 if (!buf2) {
11166 Py_DECREF(sub);
11167 Py_DECREF(str);
11168 return -1;
11169 }
11170 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011171
Victor Stinner77282cb2013-04-14 19:22:47 +020011172 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011173 case PyUnicode_1BYTE_KIND:
11174 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11175 break;
11176 case PyUnicode_2BYTE_KIND:
11177 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11178 break;
11179 case PyUnicode_4BYTE_KIND:
11180 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11181 break;
11182 default:
11183 result = -1;
11184 assert(0);
11185 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011186
11187 Py_DECREF(str);
11188 Py_DECREF(sub);
11189
Victor Stinner77282cb2013-04-14 19:22:47 +020011190 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011191 PyMem_Free(buf2);
11192
Guido van Rossum403d68b2000-03-13 15:55:09 +000011193 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011194}
11195
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196/* Concat to string or Unicode object giving a new Unicode object. */
11197
Alexander Belopolsky40018472011-02-26 01:02:56 +000011198PyObject *
11199PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011201 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020011202 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010011203 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204
11205 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011206 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011208 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011209 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011211 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212
11213 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020011214 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011215 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011216 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011218 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011219 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011220 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221 }
11222
Victor Stinner488fa492011-12-12 00:01:39 +010011223 u_len = PyUnicode_GET_LENGTH(u);
11224 v_len = PyUnicode_GET_LENGTH(v);
11225 if (u_len > PY_SSIZE_T_MAX - v_len) {
11226 PyErr_SetString(PyExc_OverflowError,
11227 "strings are too large to concat");
11228 goto onError;
11229 }
11230 new_len = u_len + v_len;
11231
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011232 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011233 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011234 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011235
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011237 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011239 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011240 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11241 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011242 Py_DECREF(u);
11243 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011244 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011245 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011246
Benjamin Peterson29060642009-01-31 22:14:21 +000011247 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011248 Py_XDECREF(u);
11249 Py_XDECREF(v);
11250 return NULL;
11251}
11252
Walter Dörwald1ab83302007-05-18 17:15:44 +000011253void
Victor Stinner23e56682011-10-03 03:54:37 +020011254PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011255{
Victor Stinner23e56682011-10-03 03:54:37 +020011256 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011257 Py_UCS4 maxchar, maxchar2;
11258 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011259
11260 if (p_left == NULL) {
11261 if (!PyErr_Occurred())
11262 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011263 return;
11264 }
Victor Stinner23e56682011-10-03 03:54:37 +020011265 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011266 if (right == NULL || left == NULL
11267 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011268 if (!PyErr_Occurred())
11269 PyErr_BadInternalCall();
11270 goto error;
11271 }
11272
Benjamin Petersonbac79492012-01-14 13:34:47 -050011273 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011274 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011275 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011276 goto error;
11277
Victor Stinner488fa492011-12-12 00:01:39 +010011278 /* Shortcuts */
11279 if (left == unicode_empty) {
11280 Py_DECREF(left);
11281 Py_INCREF(right);
11282 *p_left = right;
11283 return;
11284 }
11285 if (right == unicode_empty)
11286 return;
11287
11288 left_len = PyUnicode_GET_LENGTH(left);
11289 right_len = PyUnicode_GET_LENGTH(right);
11290 if (left_len > PY_SSIZE_T_MAX - right_len) {
11291 PyErr_SetString(PyExc_OverflowError,
11292 "strings are too large to concat");
11293 goto error;
11294 }
11295 new_len = left_len + right_len;
11296
11297 if (unicode_modifiable(left)
11298 && PyUnicode_CheckExact(right)
11299 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011300 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11301 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011302 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011303 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011304 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11305 {
11306 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011307 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011308 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011309
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011310 /* copy 'right' into the newly allocated area of 'left' */
11311 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011312 }
Victor Stinner488fa492011-12-12 00:01:39 +010011313 else {
11314 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11315 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011316 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011317
Victor Stinner488fa492011-12-12 00:01:39 +010011318 /* Concat the two Unicode strings */
11319 res = PyUnicode_New(new_len, maxchar);
11320 if (res == NULL)
11321 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011322 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11323 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011324 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011325 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011326 }
11327 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011328 return;
11329
11330error:
Victor Stinner488fa492011-12-12 00:01:39 +010011331 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011332}
11333
11334void
11335PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11336{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011337 PyUnicode_Append(pleft, right);
11338 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011339}
11340
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011341PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011342 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011344Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011345string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011346interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011347
11348static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011349unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011351 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011352 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011353 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011355 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011356 void *buf1, *buf2;
11357 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011358
Jesus Ceaac451502011-04-20 17:09:23 +020011359 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11360 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011361 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011362
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011363 kind1 = PyUnicode_KIND(self);
11364 kind2 = PyUnicode_KIND(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011365 if (kind1 < kind2) {
Christian Heimesd47802e2013-06-29 21:33:36 +020011366 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011367 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011368 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011369 len1 = PyUnicode_GET_LENGTH(self);
11370 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011372 if (end - start < len2) {
11373 Py_DECREF(substring);
11374 return PyLong_FromLong(0);
11375 }
11376 buf1 = PyUnicode_DATA(self);
11377 buf2 = PyUnicode_DATA(substring);
11378 if (kind2 != kind1) {
11379 buf2 = _PyUnicode_AsKind(substring, kind1);
11380 if (!buf2) {
11381 Py_DECREF(substring);
11382 return NULL;
11383 }
11384 }
11385 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011386 case PyUnicode_1BYTE_KIND:
11387 iresult = ucs1lib_count(
11388 ((Py_UCS1*)buf1) + start, end - start,
11389 buf2, len2, PY_SSIZE_T_MAX
11390 );
11391 break;
11392 case PyUnicode_2BYTE_KIND:
11393 iresult = ucs2lib_count(
11394 ((Py_UCS2*)buf1) + start, end - start,
11395 buf2, len2, PY_SSIZE_T_MAX
11396 );
11397 break;
11398 case PyUnicode_4BYTE_KIND:
11399 iresult = ucs4lib_count(
11400 ((Py_UCS4*)buf1) + start, end - start,
11401 buf2, len2, PY_SSIZE_T_MAX
11402 );
11403 break;
11404 default:
11405 assert(0); iresult = 0;
11406 }
11407
11408 result = PyLong_FromSsize_t(iresult);
11409
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011410 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011411 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011412
11413 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011414
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415 return result;
11416}
11417
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011418PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011419 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011421Encode S using the codec registered for encoding. Default encoding\n\
11422is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011423handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011424a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11425'xmlcharrefreplace' as well as any other name registered with\n\
11426codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011427
11428static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011429unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011431 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432 char *encoding = NULL;
11433 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011434
Benjamin Peterson308d6372009-09-18 21:42:35 +000011435 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11436 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011438 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011439}
11440
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011441PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011442 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443\n\
11444Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011445If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446
11447static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011448unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011450 Py_ssize_t i, j, line_pos, src_len, incr;
11451 Py_UCS4 ch;
11452 PyObject *u;
11453 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011454 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011456 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011457 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458
Ezio Melotti745d54d2013-11-16 19:10:57 +020011459 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11460 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011461 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
Antoine Pitrou22425222011-10-04 19:10:51 +020011463 if (PyUnicode_READY(self) == -1)
11464 return NULL;
11465
Thomas Wouters7e474022000-07-16 12:04:32 +000011466 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011467 src_len = PyUnicode_GET_LENGTH(self);
11468 i = j = line_pos = 0;
11469 kind = PyUnicode_KIND(self);
11470 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011471 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011472 for (; i < src_len; i++) {
11473 ch = PyUnicode_READ(kind, src_data, i);
11474 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011475 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011476 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011477 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011479 goto overflow;
11480 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011482 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011483 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011485 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011486 goto overflow;
11487 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011489 if (ch == '\n' || ch == '\r')
11490 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011492 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011493 if (!found)
11494 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011495
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011497 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498 if (!u)
11499 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011500 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011501
Antoine Pitroue71d5742011-10-04 15:55:09 +020011502 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503
Antoine Pitroue71d5742011-10-04 15:55:09 +020011504 for (; i < src_len; i++) {
11505 ch = PyUnicode_READ(kind, src_data, i);
11506 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011507 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011508 incr = tabsize - (line_pos % tabsize);
11509 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011510 FILL(kind, dest_data, ' ', j, incr);
11511 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011513 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011514 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011515 line_pos++;
11516 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011517 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011518 if (ch == '\n' || ch == '\r')
11519 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011521 }
11522 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011523 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011524
Antoine Pitroue71d5742011-10-04 15:55:09 +020011525 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011526 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11527 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528}
11529
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011530PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011531 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532\n\
11533Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011534such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535arguments start and end are interpreted as in slice notation.\n\
11536\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011537Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538
11539static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011540unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011542 /* initialize variables to prevent gcc warning */
11543 PyObject *substring = NULL;
11544 Py_ssize_t start = 0;
11545 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011546 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547
Jesus Ceaac451502011-04-20 17:09:23 +020011548 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11549 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011550 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551
Christian Heimesd47802e2013-06-29 21:33:36 +020011552 if (PyUnicode_READY(self) == -1) {
11553 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011554 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011555 }
11556 if (PyUnicode_READY(substring) == -1) {
11557 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011558 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011559 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560
Victor Stinner7931d9a2011-11-04 00:22:48 +010011561 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562
11563 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011564
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011565 if (result == -2)
11566 return NULL;
11567
Christian Heimes217cfd12007-12-02 14:31:20 +000011568 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569}
11570
11571static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011572unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011574 void *data;
11575 enum PyUnicode_Kind kind;
11576 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011577
11578 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11579 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011580 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011581 }
11582 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11583 PyErr_SetString(PyExc_IndexError, "string index out of range");
11584 return NULL;
11585 }
11586 kind = PyUnicode_KIND(self);
11587 data = PyUnicode_DATA(self);
11588 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011589 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590}
11591
Guido van Rossumc2504932007-09-18 19:42:40 +000011592/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011593 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011594static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011595unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596{
Guido van Rossumc2504932007-09-18 19:42:40 +000011597 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011598 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011599
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011600#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011601 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011602#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603 if (_PyUnicode_HASH(self) != -1)
11604 return _PyUnicode_HASH(self);
11605 if (PyUnicode_READY(self) == -1)
11606 return -1;
11607 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011608 /*
11609 We make the hash of the empty string be 0, rather than using
11610 (prefix ^ suffix), since this slightly obfuscates the hash secret
11611 */
11612 if (len == 0) {
11613 _PyUnicode_HASH(self) = 0;
11614 return 0;
11615 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011616 x = _Py_HashBytes(PyUnicode_DATA(self),
11617 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011618 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011619 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011620}
11621
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011622PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011623 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011625Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626
11627static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011628unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011629{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011630 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011631 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011632 PyObject *substring = NULL;
11633 Py_ssize_t start = 0;
11634 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011635
Jesus Ceaac451502011-04-20 17:09:23 +020011636 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11637 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011638 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011639
Christian Heimesd47a0452013-06-29 21:21:37 +020011640 if (PyUnicode_READY(self) == -1) {
11641 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011642 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011643 }
11644 if (PyUnicode_READY(substring) == -1) {
11645 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011646 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011647 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648
Victor Stinner7931d9a2011-11-04 00:22:48 +010011649 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011650
11651 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 if (result == -2)
11654 return NULL;
11655
Guido van Rossumd57fd912000-03-10 22:53:23 +000011656 if (result < 0) {
11657 PyErr_SetString(PyExc_ValueError, "substring not found");
11658 return NULL;
11659 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011660
Christian Heimes217cfd12007-12-02 14:31:20 +000011661 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011662}
11663
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011664PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011665 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011666\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011667Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011668at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011669
11670static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011671unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011672{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011673 Py_ssize_t i, length;
11674 int kind;
11675 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011676 int cased;
11677
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011678 if (PyUnicode_READY(self) == -1)
11679 return NULL;
11680 length = PyUnicode_GET_LENGTH(self);
11681 kind = PyUnicode_KIND(self);
11682 data = PyUnicode_DATA(self);
11683
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011685 if (length == 1)
11686 return PyBool_FromLong(
11687 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011689 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011691 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011692
Guido van Rossumd57fd912000-03-10 22:53:23 +000011693 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011694 for (i = 0; i < length; i++) {
11695 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011696
Benjamin Peterson29060642009-01-31 22:14:21 +000011697 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11698 return PyBool_FromLong(0);
11699 else if (!cased && Py_UNICODE_ISLOWER(ch))
11700 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011702 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703}
11704
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011705PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011706 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011708Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011709at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710
11711static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011712unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011713{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011714 Py_ssize_t i, length;
11715 int kind;
11716 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717 int cased;
11718
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011719 if (PyUnicode_READY(self) == -1)
11720 return NULL;
11721 length = PyUnicode_GET_LENGTH(self);
11722 kind = PyUnicode_KIND(self);
11723 data = PyUnicode_DATA(self);
11724
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 if (length == 1)
11727 return PyBool_FromLong(
11728 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011730 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011731 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011732 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011733
Guido van Rossumd57fd912000-03-10 22:53:23 +000011734 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 for (i = 0; i < length; i++) {
11736 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011737
Benjamin Peterson29060642009-01-31 22:14:21 +000011738 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11739 return PyBool_FromLong(0);
11740 else if (!cased && Py_UNICODE_ISUPPER(ch))
11741 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011743 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744}
11745
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011746PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011747 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011748\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011749Return True if S is a titlecased string and there is at least one\n\
11750character in S, i.e. upper- and titlecase characters may only\n\
11751follow uncased characters and lowercase characters only cased ones.\n\
11752Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011753
11754static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011755unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011757 Py_ssize_t i, length;
11758 int kind;
11759 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760 int cased, previous_is_cased;
11761
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011762 if (PyUnicode_READY(self) == -1)
11763 return NULL;
11764 length = PyUnicode_GET_LENGTH(self);
11765 kind = PyUnicode_KIND(self);
11766 data = PyUnicode_DATA(self);
11767
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011769 if (length == 1) {
11770 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11771 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11772 (Py_UNICODE_ISUPPER(ch) != 0));
11773 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011775 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011777 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011778
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779 cased = 0;
11780 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011781 for (i = 0; i < length; i++) {
11782 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011783
Benjamin Peterson29060642009-01-31 22:14:21 +000011784 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11785 if (previous_is_cased)
11786 return PyBool_FromLong(0);
11787 previous_is_cased = 1;
11788 cased = 1;
11789 }
11790 else if (Py_UNICODE_ISLOWER(ch)) {
11791 if (!previous_is_cased)
11792 return PyBool_FromLong(0);
11793 previous_is_cased = 1;
11794 cased = 1;
11795 }
11796 else
11797 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011799 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011800}
11801
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011802PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011803 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011805Return True if all characters in S are whitespace\n\
11806and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807
11808static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011809unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011810{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 Py_ssize_t i, length;
11812 int kind;
11813 void *data;
11814
11815 if (PyUnicode_READY(self) == -1)
11816 return NULL;
11817 length = PyUnicode_GET_LENGTH(self);
11818 kind = PyUnicode_KIND(self);
11819 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820
Guido van Rossumd57fd912000-03-10 22:53:23 +000011821 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011822 if (length == 1)
11823 return PyBool_FromLong(
11824 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011825
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011826 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011827 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011828 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011829
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011830 for (i = 0; i < length; i++) {
11831 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011832 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011833 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011835 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836}
11837
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011838PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011839 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011840\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011841Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011842and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011843
11844static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011845unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011846{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011847 Py_ssize_t i, length;
11848 int kind;
11849 void *data;
11850
11851 if (PyUnicode_READY(self) == -1)
11852 return NULL;
11853 length = PyUnicode_GET_LENGTH(self);
11854 kind = PyUnicode_KIND(self);
11855 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011856
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011857 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011858 if (length == 1)
11859 return PyBool_FromLong(
11860 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011861
11862 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011863 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011864 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011865
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011866 for (i = 0; i < length; i++) {
11867 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011868 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011869 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011870 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011871}
11872
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011873PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011874 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011875\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011876Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011877and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011878
11879static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011880unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011881{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011882 int kind;
11883 void *data;
11884 Py_ssize_t len, i;
11885
11886 if (PyUnicode_READY(self) == -1)
11887 return NULL;
11888
11889 kind = PyUnicode_KIND(self);
11890 data = PyUnicode_DATA(self);
11891 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011892
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011893 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011894 if (len == 1) {
11895 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11896 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11897 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011898
11899 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011900 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011901 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011902
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011903 for (i = 0; i < len; i++) {
11904 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011905 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011906 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011907 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011908 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011909}
11910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011911PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011912 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011913\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011914Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011915False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011916
11917static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011918unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011920 Py_ssize_t i, length;
11921 int kind;
11922 void *data;
11923
11924 if (PyUnicode_READY(self) == -1)
11925 return NULL;
11926 length = PyUnicode_GET_LENGTH(self);
11927 kind = PyUnicode_KIND(self);
11928 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011929
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011931 if (length == 1)
11932 return PyBool_FromLong(
11933 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011935 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011936 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011937 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011938
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011939 for (i = 0; i < length; i++) {
11940 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011941 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011943 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011944}
11945
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011946PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011947 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011949Return True if all characters in S are digits\n\
11950and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011951
11952static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011953unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011954{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011955 Py_ssize_t i, length;
11956 int kind;
11957 void *data;
11958
11959 if (PyUnicode_READY(self) == -1)
11960 return NULL;
11961 length = PyUnicode_GET_LENGTH(self);
11962 kind = PyUnicode_KIND(self);
11963 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011964
Guido van Rossumd57fd912000-03-10 22:53:23 +000011965 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011966 if (length == 1) {
11967 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11968 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11969 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011970
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011971 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011973 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011975 for (i = 0; i < length; i++) {
11976 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011977 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011978 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011979 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011980}
11981
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011982PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011983 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011984\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011985Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011986False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011987
11988static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011989unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011990{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011991 Py_ssize_t i, length;
11992 int kind;
11993 void *data;
11994
11995 if (PyUnicode_READY(self) == -1)
11996 return NULL;
11997 length = PyUnicode_GET_LENGTH(self);
11998 kind = PyUnicode_KIND(self);
11999 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012000
Guido van Rossumd57fd912000-03-10 22:53:23 +000012001 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 if (length == 1)
12003 return PyBool_FromLong(
12004 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012005
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012006 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012008 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012009
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012010 for (i = 0; i < length; i++) {
12011 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012012 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012013 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012014 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012015}
12016
Martin v. Löwis47383402007-08-15 07:32:56 +000012017int
12018PyUnicode_IsIdentifier(PyObject *self)
12019{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012020 int kind;
12021 void *data;
12022 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012023 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012024
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012025 if (PyUnicode_READY(self) == -1) {
12026 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012027 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012028 }
12029
12030 /* Special case for empty strings */
12031 if (PyUnicode_GET_LENGTH(self) == 0)
12032 return 0;
12033 kind = PyUnicode_KIND(self);
12034 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012035
12036 /* PEP 3131 says that the first character must be in
12037 XID_Start and subsequent characters in XID_Continue,
12038 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012039 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012040 letters, digits, underscore). However, given the current
12041 definition of XID_Start and XID_Continue, it is sufficient
12042 to check just for these, except that _ must be allowed
12043 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012044 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012045 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012046 return 0;
12047
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012048 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012049 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012050 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012051 return 1;
12052}
12053
12054PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012055 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000012056\n\
12057Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012058to the language definition.\n\
12059\n\
12060Use keyword.iskeyword() to test for reserved identifiers\n\
12061such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012062
12063static PyObject*
12064unicode_isidentifier(PyObject *self)
12065{
12066 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12067}
12068
Georg Brandl559e5d72008-06-11 18:37:52 +000012069PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012070 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012071\n\
12072Return True if all characters in S are considered\n\
12073printable in repr() or S is empty, False otherwise.");
12074
12075static PyObject*
12076unicode_isprintable(PyObject *self)
12077{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012078 Py_ssize_t i, length;
12079 int kind;
12080 void *data;
12081
12082 if (PyUnicode_READY(self) == -1)
12083 return NULL;
12084 length = PyUnicode_GET_LENGTH(self);
12085 kind = PyUnicode_KIND(self);
12086 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012087
12088 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012089 if (length == 1)
12090 return PyBool_FromLong(
12091 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012092
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012093 for (i = 0; i < length; i++) {
12094 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012095 Py_RETURN_FALSE;
12096 }
12097 }
12098 Py_RETURN_TRUE;
12099}
12100
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012101PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012102 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012103\n\
12104Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012105iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012106
12107static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012108unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012110 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012111}
12112
Martin v. Löwis18e16552006-02-15 17:27:45 +000012113static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012114unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012115{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012116 if (PyUnicode_READY(self) == -1)
12117 return -1;
12118 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119}
12120
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012121PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012122 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012123\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012124Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012125done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012126
12127static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012128unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012129{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012130 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012131 Py_UCS4 fillchar = ' ';
12132
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012133 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134 return NULL;
12135
Benjamin Petersonbac79492012-01-14 13:34:47 -050012136 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012137 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012138
Victor Stinnerc4b49542011-12-11 22:44:26 +010012139 if (PyUnicode_GET_LENGTH(self) >= width)
12140 return unicode_result_unchanged(self);
12141
12142 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143}
12144
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012145PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012146 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012148Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012149
12150static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012151unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012152{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012153 if (PyUnicode_READY(self) == -1)
12154 return NULL;
12155 if (PyUnicode_IS_ASCII(self))
12156 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012157 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012158}
12159
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012160#define LEFTSTRIP 0
12161#define RIGHTSTRIP 1
12162#define BOTHSTRIP 2
12163
12164/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012165static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012166
12167#define STRIPNAME(i) (stripformat[i]+3)
12168
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012169/* externally visible for str.strip(unicode) */
12170PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012171_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012172{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012173 void *data;
12174 int kind;
12175 Py_ssize_t i, j, len;
12176 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012177 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012178
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012179 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12180 return NULL;
12181
12182 kind = PyUnicode_KIND(self);
12183 data = PyUnicode_DATA(self);
12184 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012185 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012186 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12187 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012188 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012189
Benjamin Peterson14339b62009-01-31 16:36:08 +000012190 i = 0;
12191 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012192 while (i < len) {
12193 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12194 if (!BLOOM(sepmask, ch))
12195 break;
12196 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12197 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012198 i++;
12199 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012200 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012201
Benjamin Peterson14339b62009-01-31 16:36:08 +000012202 j = len;
12203 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012204 j--;
12205 while (j >= i) {
12206 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12207 if (!BLOOM(sepmask, ch))
12208 break;
12209 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12210 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012211 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012212 }
12213
Benjamin Peterson29060642009-01-31 22:14:21 +000012214 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012215 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012216
Victor Stinner7931d9a2011-11-04 00:22:48 +010012217 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012218}
12219
12220PyObject*
12221PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12222{
12223 unsigned char *data;
12224 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012225 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012226
Victor Stinnerde636f32011-10-01 03:55:54 +020012227 if (PyUnicode_READY(self) == -1)
12228 return NULL;
12229
Victor Stinner684d5fd2012-05-03 02:32:34 +020012230 length = PyUnicode_GET_LENGTH(self);
12231 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012232
Victor Stinner684d5fd2012-05-03 02:32:34 +020012233 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012234 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012235
Victor Stinnerde636f32011-10-01 03:55:54 +020012236 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012237 PyErr_SetString(PyExc_IndexError, "string index out of range");
12238 return NULL;
12239 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012240 if (start >= length || end < start)
12241 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012242
Victor Stinner684d5fd2012-05-03 02:32:34 +020012243 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012244 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012245 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012246 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012247 }
12248 else {
12249 kind = PyUnicode_KIND(self);
12250 data = PyUnicode_1BYTE_DATA(self);
12251 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012252 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012253 length);
12254 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012255}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256
12257static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012258do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012259{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012260 Py_ssize_t len, i, j;
12261
12262 if (PyUnicode_READY(self) == -1)
12263 return NULL;
12264
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012265 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012266
Victor Stinnercc7af722013-04-09 22:39:24 +020012267 if (PyUnicode_IS_ASCII(self)) {
12268 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12269
12270 i = 0;
12271 if (striptype != RIGHTSTRIP) {
12272 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012273 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012274 if (!_Py_ascii_whitespace[ch])
12275 break;
12276 i++;
12277 }
12278 }
12279
12280 j = len;
12281 if (striptype != LEFTSTRIP) {
12282 j--;
12283 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012284 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012285 if (!_Py_ascii_whitespace[ch])
12286 break;
12287 j--;
12288 }
12289 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012290 }
12291 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012292 else {
12293 int kind = PyUnicode_KIND(self);
12294 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012295
Victor Stinnercc7af722013-04-09 22:39:24 +020012296 i = 0;
12297 if (striptype != RIGHTSTRIP) {
12298 while (i < len) {
12299 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12300 if (!Py_UNICODE_ISSPACE(ch))
12301 break;
12302 i++;
12303 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012304 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012305
12306 j = len;
12307 if (striptype != LEFTSTRIP) {
12308 j--;
12309 while (j >= i) {
12310 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12311 if (!Py_UNICODE_ISSPACE(ch))
12312 break;
12313 j--;
12314 }
12315 j++;
12316 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012317 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012318
Victor Stinner7931d9a2011-11-04 00:22:48 +010012319 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012320}
12321
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012322
12323static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012324do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012325{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012326 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012327
Serhiy Storchakac6792272013-10-19 21:03:34 +030012328 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012329 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012330
Benjamin Peterson14339b62009-01-31 16:36:08 +000012331 if (sep != NULL && sep != Py_None) {
12332 if (PyUnicode_Check(sep))
12333 return _PyUnicode_XStrip(self, striptype, sep);
12334 else {
12335 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012336 "%s arg must be None or str",
12337 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012338 return NULL;
12339 }
12340 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012341
Benjamin Peterson14339b62009-01-31 16:36:08 +000012342 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012343}
12344
12345
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012346PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012347 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012348\n\
12349Return a copy of the string S with leading and trailing\n\
12350whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012351If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012352
12353static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012354unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012355{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012356 if (PyTuple_GET_SIZE(args) == 0)
12357 return do_strip(self, BOTHSTRIP); /* Common case */
12358 else
12359 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012360}
12361
12362
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012363PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012364 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012365\n\
12366Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012367If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012368
12369static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012370unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012371{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012372 if (PyTuple_GET_SIZE(args) == 0)
12373 return do_strip(self, LEFTSTRIP); /* Common case */
12374 else
12375 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012376}
12377
12378
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012379PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012380 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012381\n\
12382Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012383If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012384
12385static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012386unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012387{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012388 if (PyTuple_GET_SIZE(args) == 0)
12389 return do_strip(self, RIGHTSTRIP); /* Common case */
12390 else
12391 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012392}
12393
12394
Guido van Rossumd57fd912000-03-10 22:53:23 +000012395static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012396unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012397{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012398 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012399 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012400
Serhiy Storchaka05997252013-01-26 12:14:02 +020012401 if (len < 1)
12402 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012403
Victor Stinnerc4b49542011-12-11 22:44:26 +010012404 /* no repeat, return original string */
12405 if (len == 1)
12406 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012407
Benjamin Petersonbac79492012-01-14 13:34:47 -050012408 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012409 return NULL;
12410
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012411 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012412 PyErr_SetString(PyExc_OverflowError,
12413 "repeated string is too long");
12414 return NULL;
12415 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012416 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012417
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012418 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012419 if (!u)
12420 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012421 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012423 if (PyUnicode_GET_LENGTH(str) == 1) {
12424 const int kind = PyUnicode_KIND(str);
12425 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012426 if (kind == PyUnicode_1BYTE_KIND) {
12427 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012428 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012429 }
12430 else if (kind == PyUnicode_2BYTE_KIND) {
12431 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012432 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012433 ucs2[n] = fill_char;
12434 } else {
12435 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12436 assert(kind == PyUnicode_4BYTE_KIND);
12437 for (n = 0; n < len; ++n)
12438 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012439 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012440 }
12441 else {
12442 /* number of characters copied this far */
12443 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012444 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012445 char *to = (char *) PyUnicode_DATA(u);
12446 Py_MEMCPY(to, PyUnicode_DATA(str),
12447 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012448 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012449 n = (done <= nchars-done) ? done : nchars-done;
12450 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012451 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012452 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012453 }
12454
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012455 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012456 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012457}
12458
Alexander Belopolsky40018472011-02-26 01:02:56 +000012459PyObject *
12460PyUnicode_Replace(PyObject *obj,
12461 PyObject *subobj,
12462 PyObject *replobj,
12463 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012464{
12465 PyObject *self;
12466 PyObject *str1;
12467 PyObject *str2;
12468 PyObject *result;
12469
12470 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012471 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012472 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012473 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012474 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012475 Py_DECREF(self);
12476 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012477 }
12478 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012479 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012480 Py_DECREF(self);
12481 Py_DECREF(str1);
12482 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012483 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012484 if (PyUnicode_READY(self) == -1 ||
12485 PyUnicode_READY(str1) == -1 ||
12486 PyUnicode_READY(str2) == -1)
12487 result = NULL;
12488 else
12489 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012490 Py_DECREF(self);
12491 Py_DECREF(str1);
12492 Py_DECREF(str2);
12493 return result;
12494}
12495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012496PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012497 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498\n\
12499Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012500old replaced by new. If the optional argument count is\n\
12501given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012502
12503static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012504unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012505{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012506 PyObject *str1;
12507 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012508 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012509 PyObject *result;
12510
Martin v. Löwis18e16552006-02-15 17:27:45 +000012511 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012512 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012513 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012514 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012515 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012516 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012517 return NULL;
12518 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012519 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012520 Py_DECREF(str1);
12521 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012522 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012523 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12524 result = NULL;
12525 else
12526 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012527
12528 Py_DECREF(str1);
12529 Py_DECREF(str2);
12530 return result;
12531}
12532
Alexander Belopolsky40018472011-02-26 01:02:56 +000012533static PyObject *
12534unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012536 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012537 Py_ssize_t isize;
12538 Py_ssize_t osize, squote, dquote, i, o;
12539 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012540 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012541 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012543 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012544 return NULL;
12545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012546 isize = PyUnicode_GET_LENGTH(unicode);
12547 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012549 /* Compute length of output, quote characters, and
12550 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012551 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012552 max = 127;
12553 squote = dquote = 0;
12554 ikind = PyUnicode_KIND(unicode);
12555 for (i = 0; i < isize; i++) {
12556 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012557 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012558 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012559 case '\'': squote++; break;
12560 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012561 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012562 incr = 2;
12563 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012564 default:
12565 /* Fast-path ASCII */
12566 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012567 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012568 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012569 ;
12570 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012572 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012573 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012575 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012576 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012577 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012579 if (osize > PY_SSIZE_T_MAX - incr) {
12580 PyErr_SetString(PyExc_OverflowError,
12581 "string is too long to generate repr");
12582 return NULL;
12583 }
12584 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012585 }
12586
12587 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012588 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012590 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012591 if (dquote)
12592 /* Both squote and dquote present. Use squote,
12593 and escape them */
12594 osize += squote;
12595 else
12596 quote = '"';
12597 }
Victor Stinner55c08782013-04-14 18:45:39 +020012598 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012599
12600 repr = PyUnicode_New(osize, max);
12601 if (repr == NULL)
12602 return NULL;
12603 okind = PyUnicode_KIND(repr);
12604 odata = PyUnicode_DATA(repr);
12605
12606 PyUnicode_WRITE(okind, odata, 0, quote);
12607 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012608 if (unchanged) {
12609 _PyUnicode_FastCopyCharacters(repr, 1,
12610 unicode, 0,
12611 isize);
12612 }
12613 else {
12614 for (i = 0, o = 1; i < isize; i++) {
12615 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012616
Victor Stinner55c08782013-04-14 18:45:39 +020012617 /* Escape quotes and backslashes */
12618 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012619 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012620 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012621 continue;
12622 }
12623
12624 /* Map special whitespace to '\t', \n', '\r' */
12625 if (ch == '\t') {
12626 PyUnicode_WRITE(okind, odata, o++, '\\');
12627 PyUnicode_WRITE(okind, odata, o++, 't');
12628 }
12629 else if (ch == '\n') {
12630 PyUnicode_WRITE(okind, odata, o++, '\\');
12631 PyUnicode_WRITE(okind, odata, o++, 'n');
12632 }
12633 else if (ch == '\r') {
12634 PyUnicode_WRITE(okind, odata, o++, '\\');
12635 PyUnicode_WRITE(okind, odata, o++, 'r');
12636 }
12637
12638 /* Map non-printable US ASCII to '\xhh' */
12639 else if (ch < ' ' || ch == 0x7F) {
12640 PyUnicode_WRITE(okind, odata, o++, '\\');
12641 PyUnicode_WRITE(okind, odata, o++, 'x');
12642 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12643 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12644 }
12645
12646 /* Copy ASCII characters as-is */
12647 else if (ch < 0x7F) {
12648 PyUnicode_WRITE(okind, odata, o++, ch);
12649 }
12650
12651 /* Non-ASCII characters */
12652 else {
12653 /* Map Unicode whitespace and control characters
12654 (categories Z* and C* except ASCII space)
12655 */
12656 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12657 PyUnicode_WRITE(okind, odata, o++, '\\');
12658 /* Map 8-bit characters to '\xhh' */
12659 if (ch <= 0xff) {
12660 PyUnicode_WRITE(okind, odata, o++, 'x');
12661 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12662 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12663 }
12664 /* Map 16-bit characters to '\uxxxx' */
12665 else if (ch <= 0xffff) {
12666 PyUnicode_WRITE(okind, odata, o++, 'u');
12667 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12668 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12669 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12670 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12671 }
12672 /* Map 21-bit characters to '\U00xxxxxx' */
12673 else {
12674 PyUnicode_WRITE(okind, odata, o++, 'U');
12675 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12676 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12677 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12678 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12679 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12680 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12681 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12682 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12683 }
12684 }
12685 /* Copy characters as-is */
12686 else {
12687 PyUnicode_WRITE(okind, odata, o++, ch);
12688 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012689 }
12690 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012691 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012692 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012693 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012694 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012695}
12696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012697PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012698 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699\n\
12700Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012701such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702arguments start and end are interpreted as in slice notation.\n\
12703\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012704Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705
12706static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012707unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012709 /* initialize variables to prevent gcc warning */
12710 PyObject *substring = NULL;
12711 Py_ssize_t start = 0;
12712 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012713 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714
Jesus Ceaac451502011-04-20 17:09:23 +020012715 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12716 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012717 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718
Christian Heimesea71a522013-06-29 21:17:34 +020012719 if (PyUnicode_READY(self) == -1) {
12720 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012721 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012722 }
12723 if (PyUnicode_READY(substring) == -1) {
12724 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012725 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012726 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012727
Victor Stinner7931d9a2011-11-04 00:22:48 +010012728 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012729
12730 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012732 if (result == -2)
12733 return NULL;
12734
Christian Heimes217cfd12007-12-02 14:31:20 +000012735 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012736}
12737
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012738PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012739 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012740\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012741Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012742
12743static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012744unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012746 /* initialize variables to prevent gcc warning */
12747 PyObject *substring = NULL;
12748 Py_ssize_t start = 0;
12749 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012750 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012751
Jesus Ceaac451502011-04-20 17:09:23 +020012752 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12753 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012754 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012755
Christian Heimesea71a522013-06-29 21:17:34 +020012756 if (PyUnicode_READY(self) == -1) {
12757 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012758 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012759 }
12760 if (PyUnicode_READY(substring) == -1) {
12761 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012762 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012763 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012764
Victor Stinner7931d9a2011-11-04 00:22:48 +010012765 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012766
12767 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012768
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012769 if (result == -2)
12770 return NULL;
12771
Guido van Rossumd57fd912000-03-10 22:53:23 +000012772 if (result < 0) {
12773 PyErr_SetString(PyExc_ValueError, "substring not found");
12774 return NULL;
12775 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012776
Christian Heimes217cfd12007-12-02 14:31:20 +000012777 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778}
12779
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012780PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012781 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012782\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012783Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012784done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012785
12786static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012787unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012788{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012789 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012790 Py_UCS4 fillchar = ' ';
12791
Victor Stinnere9a29352011-10-01 02:14:59 +020012792 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012793 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012794
Benjamin Petersonbac79492012-01-14 13:34:47 -050012795 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796 return NULL;
12797
Victor Stinnerc4b49542011-12-11 22:44:26 +010012798 if (PyUnicode_GET_LENGTH(self) >= width)
12799 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012800
Victor Stinnerc4b49542011-12-11 22:44:26 +010012801 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012802}
12803
Alexander Belopolsky40018472011-02-26 01:02:56 +000012804PyObject *
12805PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806{
12807 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012808
Guido van Rossumd57fd912000-03-10 22:53:23 +000012809 s = PyUnicode_FromObject(s);
12810 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012811 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012812 if (sep != NULL) {
12813 sep = PyUnicode_FromObject(sep);
12814 if (sep == NULL) {
12815 Py_DECREF(s);
12816 return NULL;
12817 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012818 }
12819
Victor Stinner9310abb2011-10-05 00:59:23 +020012820 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012821
12822 Py_DECREF(s);
12823 Py_XDECREF(sep);
12824 return result;
12825}
12826
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012827PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012828 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012829\n\
12830Return a list of the words in S, using sep as the\n\
12831delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012832splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012833whitespace string is a separator and empty strings are\n\
12834removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012835
12836static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012837unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012838{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012839 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012840 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012841 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012842
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012843 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12844 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012845 return NULL;
12846
12847 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012848 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012849 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012850 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012851 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012852 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012853}
12854
Thomas Wouters477c8d52006-05-27 19:21:47 +000012855PyObject *
12856PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12857{
12858 PyObject* str_obj;
12859 PyObject* sep_obj;
12860 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012861 int kind1, kind2;
12862 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012863 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012864
12865 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012866 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012867 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012868 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012869 if (!sep_obj) {
12870 Py_DECREF(str_obj);
12871 return NULL;
12872 }
12873 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12874 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012875 Py_DECREF(str_obj);
12876 return NULL;
12877 }
12878
Victor Stinner14f8f022011-10-05 20:58:25 +020012879 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012880 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012881 len1 = PyUnicode_GET_LENGTH(str_obj);
12882 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012883 if (kind1 < kind2 || len1 < len2) {
12884 _Py_INCREF_UNICODE_EMPTY();
12885 if (!unicode_empty)
12886 out = NULL;
12887 else {
12888 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12889 Py_DECREF(unicode_empty);
12890 }
12891 Py_DECREF(sep_obj);
12892 Py_DECREF(str_obj);
12893 return out;
12894 }
12895 buf1 = PyUnicode_DATA(str_obj);
12896 buf2 = PyUnicode_DATA(sep_obj);
12897 if (kind2 != kind1) {
12898 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12899 if (!buf2)
12900 goto onError;
12901 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012902
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012903 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012904 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012905 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12906 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12907 else
12908 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012909 break;
12910 case PyUnicode_2BYTE_KIND:
12911 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12912 break;
12913 case PyUnicode_4BYTE_KIND:
12914 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12915 break;
12916 default:
12917 assert(0);
12918 out = 0;
12919 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012920
12921 Py_DECREF(sep_obj);
12922 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012923 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012924 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012925
12926 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012927 onError:
12928 Py_DECREF(sep_obj);
12929 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012930 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012931 PyMem_Free(buf2);
12932 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012933}
12934
12935
12936PyObject *
12937PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12938{
12939 PyObject* str_obj;
12940 PyObject* sep_obj;
12941 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012942 int kind1, kind2;
12943 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012944 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012945
12946 str_obj = PyUnicode_FromObject(str_in);
12947 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012948 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012949 sep_obj = PyUnicode_FromObject(sep_in);
12950 if (!sep_obj) {
12951 Py_DECREF(str_obj);
12952 return NULL;
12953 }
12954
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012955 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012956 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012957 len1 = PyUnicode_GET_LENGTH(str_obj);
12958 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012959 if (kind1 < kind2 || len1 < len2) {
12960 _Py_INCREF_UNICODE_EMPTY();
12961 if (!unicode_empty)
12962 out = NULL;
12963 else {
12964 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12965 Py_DECREF(unicode_empty);
12966 }
12967 Py_DECREF(sep_obj);
12968 Py_DECREF(str_obj);
12969 return out;
12970 }
12971 buf1 = PyUnicode_DATA(str_obj);
12972 buf2 = PyUnicode_DATA(sep_obj);
12973 if (kind2 != kind1) {
12974 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12975 if (!buf2)
12976 goto onError;
12977 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012978
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012979 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012980 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012981 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12982 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12983 else
12984 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012985 break;
12986 case PyUnicode_2BYTE_KIND:
12987 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12988 break;
12989 case PyUnicode_4BYTE_KIND:
12990 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12991 break;
12992 default:
12993 assert(0);
12994 out = 0;
12995 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012996
12997 Py_DECREF(sep_obj);
12998 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012999 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013000 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013001
13002 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013003 onError:
13004 Py_DECREF(sep_obj);
13005 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013006 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013007 PyMem_Free(buf2);
13008 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013009}
13010
13011PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013012 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013013\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000013014Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013015the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000013016found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013017
13018static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013019unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013020{
Victor Stinner9310abb2011-10-05 00:59:23 +020013021 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013022}
13023
13024PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000013025 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013026\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000013027Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013028the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000013029separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013030
13031static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013032unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013033{
Victor Stinner9310abb2011-10-05 00:59:23 +020013034 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013035}
13036
Alexander Belopolsky40018472011-02-26 01:02:56 +000013037PyObject *
13038PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013039{
13040 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013041
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013042 s = PyUnicode_FromObject(s);
13043 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013044 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013045 if (sep != NULL) {
13046 sep = PyUnicode_FromObject(sep);
13047 if (sep == NULL) {
13048 Py_DECREF(s);
13049 return NULL;
13050 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013051 }
13052
Victor Stinner9310abb2011-10-05 00:59:23 +020013053 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013054
13055 Py_DECREF(s);
13056 Py_XDECREF(sep);
13057 return result;
13058}
13059
13060PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013061 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013062\n\
13063Return a list of the words in S, using sep as the\n\
13064delimiter string, starting at the end of the string and\n\
13065working to the front. If maxsplit is given, at most maxsplit\n\
13066splits are done. If sep is not specified, any whitespace string\n\
13067is a separator.");
13068
13069static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013070unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013071{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013072 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013073 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013074 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013075
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013076 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
13077 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013078 return NULL;
13079
13080 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000013081 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013082 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020013083 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013084 else
Victor Stinner9310abb2011-10-05 00:59:23 +020013085 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013086}
13087
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013088PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013089 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090\n\
13091Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000013092Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013093is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013094
13095static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013096unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013098 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000013099 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013100
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013101 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
13102 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013103 return NULL;
13104
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013105 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013106}
13107
13108static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013109PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013111 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112}
13113
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013114PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013115 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116\n\
13117Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013118and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013119
13120static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013121unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013122{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013123 if (PyUnicode_READY(self) == -1)
13124 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013125 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013126}
13127
Larry Hastings61272b72014-01-07 12:41:53 -080013128/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013129
Larry Hastings31826802013-10-19 00:09:25 -070013130@staticmethod
13131str.maketrans as unicode_maketrans
13132
13133 x: object
13134
13135 y: unicode=NULL
13136
13137 z: unicode=NULL
13138
13139 /
13140
13141Return a translation table usable for str.translate().
13142
13143If there is only one argument, it must be a dictionary mapping Unicode
13144ordinals (integers) or characters to Unicode ordinals, strings or None.
13145Character keys will be then converted to ordinals.
13146If there are two arguments, they must be strings of equal length, and
13147in the resulting dictionary, each character in x will be mapped to the
13148character at the same position in y. If there is a third argument, it
13149must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013150[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013151
Larry Hastings31826802013-10-19 00:09:25 -070013152static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013153unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013154/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013155{
Georg Brandlceee0772007-11-27 23:48:05 +000013156 PyObject *new = NULL, *key, *value;
13157 Py_ssize_t i = 0;
13158 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013159
Georg Brandlceee0772007-11-27 23:48:05 +000013160 new = PyDict_New();
13161 if (!new)
13162 return NULL;
13163 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013164 int x_kind, y_kind, z_kind;
13165 void *x_data, *y_data, *z_data;
13166
Georg Brandlceee0772007-11-27 23:48:05 +000013167 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013168 if (!PyUnicode_Check(x)) {
13169 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13170 "be a string if there is a second argument");
13171 goto err;
13172 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013173 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013174 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13175 "arguments must have equal length");
13176 goto err;
13177 }
13178 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013179 x_kind = PyUnicode_KIND(x);
13180 y_kind = PyUnicode_KIND(y);
13181 x_data = PyUnicode_DATA(x);
13182 y_data = PyUnicode_DATA(y);
13183 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13184 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013185 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013186 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013187 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013188 if (!value) {
13189 Py_DECREF(key);
13190 goto err;
13191 }
Georg Brandlceee0772007-11-27 23:48:05 +000013192 res = PyDict_SetItem(new, key, value);
13193 Py_DECREF(key);
13194 Py_DECREF(value);
13195 if (res < 0)
13196 goto err;
13197 }
13198 /* create entries for deleting chars in z */
13199 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013200 z_kind = PyUnicode_KIND(z);
13201 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013202 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013203 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013204 if (!key)
13205 goto err;
13206 res = PyDict_SetItem(new, key, Py_None);
13207 Py_DECREF(key);
13208 if (res < 0)
13209 goto err;
13210 }
13211 }
13212 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013213 int kind;
13214 void *data;
13215
Georg Brandlceee0772007-11-27 23:48:05 +000013216 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013217 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013218 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13219 "to maketrans it must be a dict");
13220 goto err;
13221 }
13222 /* copy entries into the new dict, converting string keys to int keys */
13223 while (PyDict_Next(x, &i, &key, &value)) {
13224 if (PyUnicode_Check(key)) {
13225 /* convert string keys to integer keys */
13226 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013227 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013228 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13229 "table must be of length 1");
13230 goto err;
13231 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013232 kind = PyUnicode_KIND(key);
13233 data = PyUnicode_DATA(key);
13234 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013235 if (!newkey)
13236 goto err;
13237 res = PyDict_SetItem(new, newkey, value);
13238 Py_DECREF(newkey);
13239 if (res < 0)
13240 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013241 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013242 /* just keep integer keys */
13243 if (PyDict_SetItem(new, key, value) < 0)
13244 goto err;
13245 } else {
13246 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13247 "be strings or integers");
13248 goto err;
13249 }
13250 }
13251 }
13252 return new;
13253 err:
13254 Py_DECREF(new);
13255 return NULL;
13256}
13257
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013258PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013259 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013260\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013261Return a copy of the string S in which each character has been mapped\n\
13262through the given translation table. The table must implement\n\
13263lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13264mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13265this operation raises LookupError, the character is left untouched.\n\
13266Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013267
13268static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013269unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013270{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013271 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013272}
13273
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013274PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013275 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013276\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013277Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013278
13279static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013280unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013281{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013282 if (PyUnicode_READY(self) == -1)
13283 return NULL;
13284 if (PyUnicode_IS_ASCII(self))
13285 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013286 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013287}
13288
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013289PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013290 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013291\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013292Pad a numeric string S with zeros on the left, to fill a field\n\
13293of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013294
13295static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013296unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013297{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013298 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013299 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013300 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013301 int kind;
13302 void *data;
13303 Py_UCS4 chr;
13304
Martin v. Löwis18e16552006-02-15 17:27:45 +000013305 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013306 return NULL;
13307
Benjamin Petersonbac79492012-01-14 13:34:47 -050013308 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013309 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013310
Victor Stinnerc4b49542011-12-11 22:44:26 +010013311 if (PyUnicode_GET_LENGTH(self) >= width)
13312 return unicode_result_unchanged(self);
13313
13314 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013315
13316 u = pad(self, fill, 0, '0');
13317
Walter Dörwald068325e2002-04-15 13:36:47 +000013318 if (u == NULL)
13319 return NULL;
13320
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013321 kind = PyUnicode_KIND(u);
13322 data = PyUnicode_DATA(u);
13323 chr = PyUnicode_READ(kind, data, fill);
13324
13325 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013326 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013327 PyUnicode_WRITE(kind, data, 0, chr);
13328 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013329 }
13330
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013331 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013332 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013333}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013334
13335#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013336static PyObject *
13337unicode__decimal2ascii(PyObject *self)
13338{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013339 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013340}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013341#endif
13342
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013343PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013344 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013345\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013346Return True if S starts with the specified prefix, False otherwise.\n\
13347With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013348With optional end, stop comparing S at that position.\n\
13349prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013350
13351static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013352unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013353 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013354{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013355 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013356 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013357 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013358 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013359 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013360
Jesus Ceaac451502011-04-20 17:09:23 +020013361 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013362 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013363 if (PyTuple_Check(subobj)) {
13364 Py_ssize_t i;
13365 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013366 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013367 if (substring == NULL)
13368 return NULL;
13369 result = tailmatch(self, substring, start, end, -1);
13370 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013371 if (result == -1)
13372 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013373 if (result) {
13374 Py_RETURN_TRUE;
13375 }
13376 }
13377 /* nothing matched */
13378 Py_RETURN_FALSE;
13379 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013380 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013381 if (substring == NULL) {
13382 if (PyErr_ExceptionMatches(PyExc_TypeError))
13383 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13384 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013385 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013386 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013387 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013388 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013389 if (result == -1)
13390 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013391 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013392}
13393
13394
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013395PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013396 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013397\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013398Return True if S ends with the specified suffix, False otherwise.\n\
13399With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013400With optional end, stop comparing S at that position.\n\
13401suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013402
13403static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013404unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013405 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013406{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013407 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013408 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013409 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013410 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013411 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013412
Jesus Ceaac451502011-04-20 17:09:23 +020013413 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013414 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013415 if (PyTuple_Check(subobj)) {
13416 Py_ssize_t i;
13417 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013418 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013419 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013420 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013421 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013422 result = tailmatch(self, substring, start, end, +1);
13423 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013424 if (result == -1)
13425 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013426 if (result) {
13427 Py_RETURN_TRUE;
13428 }
13429 }
13430 Py_RETURN_FALSE;
13431 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013432 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013433 if (substring == NULL) {
13434 if (PyErr_ExceptionMatches(PyExc_TypeError))
13435 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13436 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013437 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013438 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013439 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013440 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013441 if (result == -1)
13442 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013443 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013444}
13445
Victor Stinner202fdca2012-05-07 12:47:02 +020013446Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013447_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013448{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013449 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13450 writer->data = PyUnicode_DATA(writer->buffer);
13451
13452 if (!writer->readonly) {
13453 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013454 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013455 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013456 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013457 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13458 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13459 writer->kind = PyUnicode_WCHAR_KIND;
13460 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13461
Victor Stinner8f674cc2013-04-17 23:02:17 +020013462 /* Copy-on-write mode: set buffer size to 0 so
13463 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13464 * next write. */
13465 writer->size = 0;
13466 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013467}
13468
Victor Stinnerd3f08822012-05-29 12:57:52 +020013469void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013470_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013471{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013472 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013473
13474 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013475 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013476
13477 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13478 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13479 writer->kind = PyUnicode_WCHAR_KIND;
13480 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013481}
13482
Victor Stinnerd3f08822012-05-29 12:57:52 +020013483int
13484_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13485 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013486{
13487 Py_ssize_t newlen;
13488 PyObject *newbuffer;
13489
Victor Stinnerca9381e2015-09-22 00:58:32 +020013490 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013491 assert((maxchar > writer->maxchar && length >= 0)
13492 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013493
Victor Stinner202fdca2012-05-07 12:47:02 +020013494 if (length > PY_SSIZE_T_MAX - writer->pos) {
13495 PyErr_NoMemory();
13496 return -1;
13497 }
13498 newlen = writer->pos + length;
13499
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013500 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013501
Victor Stinnerd3f08822012-05-29 12:57:52 +020013502 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013503 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013504 if (writer->overallocate
13505 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13506 /* overallocate to limit the number of realloc() */
13507 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013508 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013509 if (newlen < writer->min_length)
13510 newlen = writer->min_length;
13511
Victor Stinnerd3f08822012-05-29 12:57:52 +020013512 writer->buffer = PyUnicode_New(newlen, maxchar);
13513 if (writer->buffer == NULL)
13514 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013515 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013516 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013517 if (writer->overallocate
13518 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13519 /* overallocate to limit the number of realloc() */
13520 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013521 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013522 if (newlen < writer->min_length)
13523 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013524
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013525 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013526 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013527 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013528 newbuffer = PyUnicode_New(newlen, maxchar);
13529 if (newbuffer == NULL)
13530 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013531 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13532 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013533 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013534 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013535 }
13536 else {
13537 newbuffer = resize_compact(writer->buffer, newlen);
13538 if (newbuffer == NULL)
13539 return -1;
13540 }
13541 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013542 }
13543 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013544 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013545 newbuffer = PyUnicode_New(writer->size, maxchar);
13546 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013547 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013548 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13549 writer->buffer, 0, writer->pos);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +020013550 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013551 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013552 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013553 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013554
13555#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013556}
13557
Victor Stinnerca9381e2015-09-22 00:58:32 +020013558int
13559_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13560 enum PyUnicode_Kind kind)
13561{
13562 Py_UCS4 maxchar;
13563
13564 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13565 assert(writer->kind < kind);
13566
13567 switch (kind)
13568 {
13569 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13570 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13571 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13572 default:
13573 assert(0 && "invalid kind");
13574 return -1;
13575 }
13576
13577 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13578}
13579
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013580Py_LOCAL_INLINE(int)
13581_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013582{
13583 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13584 return -1;
13585 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13586 writer->pos++;
13587 return 0;
13588}
13589
13590int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013591_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13592{
13593 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13594}
13595
13596int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013597_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13598{
13599 Py_UCS4 maxchar;
13600 Py_ssize_t len;
13601
13602 if (PyUnicode_READY(str) == -1)
13603 return -1;
13604 len = PyUnicode_GET_LENGTH(str);
13605 if (len == 0)
13606 return 0;
13607 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13608 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013609 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013610 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013611 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013612 Py_INCREF(str);
13613 writer->buffer = str;
13614 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013615 writer->pos += len;
13616 return 0;
13617 }
13618 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13619 return -1;
13620 }
13621 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13622 str, 0, len);
13623 writer->pos += len;
13624 return 0;
13625}
13626
Victor Stinnere215d962012-10-06 23:03:36 +020013627int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013628_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13629 Py_ssize_t start, Py_ssize_t end)
13630{
13631 Py_UCS4 maxchar;
13632 Py_ssize_t len;
13633
13634 if (PyUnicode_READY(str) == -1)
13635 return -1;
13636
13637 assert(0 <= start);
13638 assert(end <= PyUnicode_GET_LENGTH(str));
13639 assert(start <= end);
13640
13641 if (end == 0)
13642 return 0;
13643
13644 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13645 return _PyUnicodeWriter_WriteStr(writer, str);
13646
13647 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13648 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13649 else
13650 maxchar = writer->maxchar;
13651 len = end - start;
13652
13653 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13654 return -1;
13655
13656 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13657 str, start, len);
13658 writer->pos += len;
13659 return 0;
13660}
13661
13662int
Victor Stinner4a587072013-11-19 12:54:53 +010013663_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13664 const char *ascii, Py_ssize_t len)
13665{
13666 if (len == -1)
13667 len = strlen(ascii);
13668
13669 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13670
13671 if (writer->buffer == NULL && !writer->overallocate) {
13672 PyObject *str;
13673
13674 str = _PyUnicode_FromASCII(ascii, len);
13675 if (str == NULL)
13676 return -1;
13677
13678 writer->readonly = 1;
13679 writer->buffer = str;
13680 _PyUnicodeWriter_Update(writer);
13681 writer->pos += len;
13682 return 0;
13683 }
13684
13685 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13686 return -1;
13687
13688 switch (writer->kind)
13689 {
13690 case PyUnicode_1BYTE_KIND:
13691 {
13692 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13693 Py_UCS1 *data = writer->data;
13694
13695 Py_MEMCPY(data + writer->pos, str, len);
13696 break;
13697 }
13698 case PyUnicode_2BYTE_KIND:
13699 {
13700 _PyUnicode_CONVERT_BYTES(
13701 Py_UCS1, Py_UCS2,
13702 ascii, ascii + len,
13703 (Py_UCS2 *)writer->data + writer->pos);
13704 break;
13705 }
13706 case PyUnicode_4BYTE_KIND:
13707 {
13708 _PyUnicode_CONVERT_BYTES(
13709 Py_UCS1, Py_UCS4,
13710 ascii, ascii + len,
13711 (Py_UCS4 *)writer->data + writer->pos);
13712 break;
13713 }
13714 default:
13715 assert(0);
13716 }
13717
13718 writer->pos += len;
13719 return 0;
13720}
13721
13722int
13723_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13724 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013725{
13726 Py_UCS4 maxchar;
13727
13728 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13729 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13730 return -1;
13731 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13732 writer->pos += len;
13733 return 0;
13734}
13735
Victor Stinnerd3f08822012-05-29 12:57:52 +020013736PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013737_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013738{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013739 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013740 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013741 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013742 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013743 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013744 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013745 str = writer->buffer;
13746 writer->buffer = NULL;
13747 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13748 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013749 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013750 if (writer->pos == 0) {
13751 Py_CLEAR(writer->buffer);
13752
13753 /* Get the empty Unicode string singleton ('') */
13754 _Py_INCREF_UNICODE_EMPTY();
13755 str = unicode_empty;
Victor Stinner202fdca2012-05-07 12:47:02 +020013756 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013757 else {
13758 str = writer->buffer;
13759 writer->buffer = NULL;
13760
13761 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13762 PyObject *str2;
13763 str2 = resize_compact(str, writer->pos);
13764 if (str2 == NULL)
13765 return NULL;
13766 str = str2;
13767 }
13768 }
13769
Victor Stinner15a0bd32013-07-08 22:29:55 +020013770 assert(_PyUnicode_CheckConsistency(str, 1));
13771 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013772}
13773
Victor Stinnerd3f08822012-05-29 12:57:52 +020013774void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013775_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013776{
13777 Py_CLEAR(writer->buffer);
13778}
13779
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013780#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013781
13782PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013783 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013784\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013785Return a formatted version of S, using substitutions from args and kwargs.\n\
13786The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013787
Eric Smith27bbca62010-11-04 17:06:58 +000013788PyDoc_STRVAR(format_map__doc__,
13789 "S.format_map(mapping) -> str\n\
13790\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013791Return a formatted version of S, using substitutions from mapping.\n\
13792The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013793
Eric Smith4a7d76d2008-05-30 18:10:19 +000013794static PyObject *
13795unicode__format__(PyObject* self, PyObject* args)
13796{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013797 PyObject *format_spec;
13798 _PyUnicodeWriter writer;
13799 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013800
13801 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13802 return NULL;
13803
Victor Stinnerd3f08822012-05-29 12:57:52 +020013804 if (PyUnicode_READY(self) == -1)
13805 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013806 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013807 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13808 self, format_spec, 0,
13809 PyUnicode_GET_LENGTH(format_spec));
13810 if (ret == -1) {
13811 _PyUnicodeWriter_Dealloc(&writer);
13812 return NULL;
13813 }
13814 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013815}
13816
Eric Smith8c663262007-08-25 02:26:07 +000013817PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013818 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013819\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013820Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013821
13822static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013823unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013824{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013825 Py_ssize_t size;
13826
13827 /* If it's a compact object, account for base structure +
13828 character data. */
13829 if (PyUnicode_IS_COMPACT_ASCII(v))
13830 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13831 else if (PyUnicode_IS_COMPACT(v))
13832 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013833 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013834 else {
13835 /* If it is a two-block object, account for base object, and
13836 for character block if present. */
13837 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013838 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013839 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013840 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013841 }
13842 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013843 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013844 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013845 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013846 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013847 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013848
13849 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013850}
13851
13852PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013853 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013854
13855static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013856unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013857{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013858 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013859 if (!copy)
13860 return NULL;
13861 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013862}
13863
Guido van Rossumd57fd912000-03-10 22:53:23 +000013864static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013865 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013866 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013867 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13868 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013869 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13870 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013871 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013872 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13873 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13874 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013875 {"expandtabs", (PyCFunction) unicode_expandtabs,
13876 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013877 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013878 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013879 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13880 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13881 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013882 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013883 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13884 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13885 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013886 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013887 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013888 {"splitlines", (PyCFunction) unicode_splitlines,
13889 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013890 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013891 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13892 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13893 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13894 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13895 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13896 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13897 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13898 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13899 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13900 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13901 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13902 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13903 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13904 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013905 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013906 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013907 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013908 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013909 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013910 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013911 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013912 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013913#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013914 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013915 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013916#endif
13917
Benjamin Peterson14339b62009-01-31 16:36:08 +000013918 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013919 {NULL, NULL}
13920};
13921
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013922static PyObject *
13923unicode_mod(PyObject *v, PyObject *w)
13924{
Brian Curtindfc80e32011-08-10 20:28:54 -050013925 if (!PyUnicode_Check(v))
13926 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013927 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013928}
13929
13930static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013931 0, /*nb_add*/
13932 0, /*nb_subtract*/
13933 0, /*nb_multiply*/
13934 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013935};
13936
Guido van Rossumd57fd912000-03-10 22:53:23 +000013937static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013938 (lenfunc) unicode_length, /* sq_length */
13939 PyUnicode_Concat, /* sq_concat */
13940 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13941 (ssizeargfunc) unicode_getitem, /* sq_item */
13942 0, /* sq_slice */
13943 0, /* sq_ass_item */
13944 0, /* sq_ass_slice */
13945 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013946};
13947
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013948static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013949unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013950{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013951 if (PyUnicode_READY(self) == -1)
13952 return NULL;
13953
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013954 if (PyIndex_Check(item)) {
13955 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013956 if (i == -1 && PyErr_Occurred())
13957 return NULL;
13958 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013959 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013960 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013961 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013962 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013963 PyObject *result;
13964 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013965 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013966 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013967
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013968 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013969 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013970 return NULL;
13971 }
13972
13973 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013974 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013975 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013976 slicelength == PyUnicode_GET_LENGTH(self)) {
13977 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013978 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013979 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013980 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013981 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013982 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013983 src_kind = PyUnicode_KIND(self);
13984 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013985 if (!PyUnicode_IS_ASCII(self)) {
13986 kind_limit = kind_maxchar_limit(src_kind);
13987 max_char = 0;
13988 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13989 ch = PyUnicode_READ(src_kind, src_data, cur);
13990 if (ch > max_char) {
13991 max_char = ch;
13992 if (max_char >= kind_limit)
13993 break;
13994 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013995 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013996 }
Victor Stinner55c99112011-10-13 01:17:06 +020013997 else
13998 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013999 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014000 if (result == NULL)
14001 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014002 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014003 dest_data = PyUnicode_DATA(result);
14004
14005 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014006 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14007 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014008 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014009 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014010 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014011 } else {
14012 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
14013 return NULL;
14014 }
14015}
14016
14017static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014018 (lenfunc)unicode_length, /* mp_length */
14019 (binaryfunc)unicode_subscript, /* mp_subscript */
14020 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014021};
14022
Guido van Rossumd57fd912000-03-10 22:53:23 +000014023
Guido van Rossumd57fd912000-03-10 22:53:23 +000014024/* Helpers for PyUnicode_Format() */
14025
Victor Stinnera47082312012-10-04 02:19:54 +020014026struct unicode_formatter_t {
14027 PyObject *args;
14028 int args_owned;
14029 Py_ssize_t arglen, argidx;
14030 PyObject *dict;
14031
14032 enum PyUnicode_Kind fmtkind;
14033 Py_ssize_t fmtcnt, fmtpos;
14034 void *fmtdata;
14035 PyObject *fmtstr;
14036
14037 _PyUnicodeWriter writer;
14038};
14039
14040struct unicode_format_arg_t {
14041 Py_UCS4 ch;
14042 int flags;
14043 Py_ssize_t width;
14044 int prec;
14045 int sign;
14046};
14047
Guido van Rossumd57fd912000-03-10 22:53:23 +000014048static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014049unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014050{
Victor Stinnera47082312012-10-04 02:19:54 +020014051 Py_ssize_t argidx = ctx->argidx;
14052
14053 if (argidx < ctx->arglen) {
14054 ctx->argidx++;
14055 if (ctx->arglen < 0)
14056 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014057 else
Victor Stinnera47082312012-10-04 02:19:54 +020014058 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014059 }
14060 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014061 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014062 return NULL;
14063}
14064
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014065/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014066
Victor Stinnera47082312012-10-04 02:19:54 +020014067/* Format a float into the writer if the writer is not NULL, or into *p_output
14068 otherwise.
14069
14070 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014071static int
Victor Stinnera47082312012-10-04 02:19:54 +020014072formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14073 PyObject **p_output,
14074 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014075{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014076 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014077 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014078 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014079 int prec;
14080 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014081
Guido van Rossumd57fd912000-03-10 22:53:23 +000014082 x = PyFloat_AsDouble(v);
14083 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014084 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014085
Victor Stinnera47082312012-10-04 02:19:54 +020014086 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014087 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014088 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014089
Victor Stinnera47082312012-10-04 02:19:54 +020014090 if (arg->flags & F_ALT)
14091 dtoa_flags = Py_DTSF_ALT;
14092 else
14093 dtoa_flags = 0;
14094 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014095 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014096 return -1;
14097 len = strlen(p);
14098 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014099 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014100 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014101 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014102 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014103 }
14104 else
14105 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014106 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014107 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014108}
14109
Victor Stinnerd0880d52012-04-27 23:40:13 +020014110/* formatlong() emulates the format codes d, u, o, x and X, and
14111 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14112 * Python's regular ints.
14113 * Return value: a new PyUnicodeObject*, or NULL if error.
14114 * The output string is of the form
14115 * "-"? ("0x" | "0X")? digit+
14116 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14117 * set in flags. The case of hex digits will be correct,
14118 * There will be at least prec digits, zero-filled on the left if
14119 * necessary to get that many.
14120 * val object to be converted
14121 * flags bitmask of format flags; only F_ALT is looked at
14122 * prec minimum number of digits; 0-fill on left if needed
14123 * type a character in [duoxX]; u acts the same as d
14124 *
14125 * CAUTION: o, x and X conversions on regular ints can never
14126 * produce a '-' sign, but can for Python's unbounded ints.
14127 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014128PyObject *
14129_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014130{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014131 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014132 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014133 Py_ssize_t i;
14134 int sign; /* 1 if '-', else 0 */
14135 int len; /* number of characters */
14136 Py_ssize_t llen;
14137 int numdigits; /* len == numnondigits + numdigits */
14138 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014139
Victor Stinnerd0880d52012-04-27 23:40:13 +020014140 /* Avoid exceeding SSIZE_T_MAX */
14141 if (prec > INT_MAX-3) {
14142 PyErr_SetString(PyExc_OverflowError,
14143 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014144 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014145 }
14146
14147 assert(PyLong_Check(val));
14148
14149 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014150 default:
14151 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014152 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014153 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014154 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014155 /* int and int subclasses should print numerically when a numeric */
14156 /* format code is used (see issue18780) */
14157 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014158 break;
14159 case 'o':
14160 numnondigits = 2;
14161 result = PyNumber_ToBase(val, 8);
14162 break;
14163 case 'x':
14164 case 'X':
14165 numnondigits = 2;
14166 result = PyNumber_ToBase(val, 16);
14167 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014168 }
14169 if (!result)
14170 return NULL;
14171
14172 assert(unicode_modifiable(result));
14173 assert(PyUnicode_IS_READY(result));
14174 assert(PyUnicode_IS_ASCII(result));
14175
14176 /* To modify the string in-place, there can only be one reference. */
14177 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014178 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014179 PyErr_BadInternalCall();
14180 return NULL;
14181 }
14182 buf = PyUnicode_DATA(result);
14183 llen = PyUnicode_GET_LENGTH(result);
14184 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014185 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014186 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014187 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014188 return NULL;
14189 }
14190 len = (int)llen;
14191 sign = buf[0] == '-';
14192 numnondigits += sign;
14193 numdigits = len - numnondigits;
14194 assert(numdigits > 0);
14195
14196 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014197 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014198 (type == 'o' || type == 'x' || type == 'X'))) {
14199 assert(buf[sign] == '0');
14200 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14201 buf[sign+1] == 'o');
14202 numnondigits -= 2;
14203 buf += 2;
14204 len -= 2;
14205 if (sign)
14206 buf[0] = '-';
14207 assert(len == numnondigits + numdigits);
14208 assert(numdigits > 0);
14209 }
14210
14211 /* Fill with leading zeroes to meet minimum width. */
14212 if (prec > numdigits) {
14213 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14214 numnondigits + prec);
14215 char *b1;
14216 if (!r1) {
14217 Py_DECREF(result);
14218 return NULL;
14219 }
14220 b1 = PyBytes_AS_STRING(r1);
14221 for (i = 0; i < numnondigits; ++i)
14222 *b1++ = *buf++;
14223 for (i = 0; i < prec - numdigits; i++)
14224 *b1++ = '0';
14225 for (i = 0; i < numdigits; i++)
14226 *b1++ = *buf++;
14227 *b1 = '\0';
14228 Py_DECREF(result);
14229 result = r1;
14230 buf = PyBytes_AS_STRING(result);
14231 len = numnondigits + prec;
14232 }
14233
14234 /* Fix up case for hex conversions. */
14235 if (type == 'X') {
14236 /* Need to convert all lower case letters to upper case.
14237 and need to convert 0x to 0X (and -0x to -0X). */
14238 for (i = 0; i < len; i++)
14239 if (buf[i] >= 'a' && buf[i] <= 'x')
14240 buf[i] -= 'a'-'A';
14241 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014242 if (!PyUnicode_Check(result)
14243 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014244 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014245 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014246 Py_DECREF(result);
14247 result = unicode;
14248 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014249 else if (len != PyUnicode_GET_LENGTH(result)) {
14250 if (PyUnicode_Resize(&result, len) < 0)
14251 Py_CLEAR(result);
14252 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014253 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014254}
14255
Ethan Furmandf3ed242014-01-05 06:50:30 -080014256/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014257 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014258 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014259 * -1 and raise an exception on error */
14260static int
Victor Stinnera47082312012-10-04 02:19:54 +020014261mainformatlong(PyObject *v,
14262 struct unicode_format_arg_t *arg,
14263 PyObject **p_output,
14264 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014265{
14266 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014267 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014268
14269 if (!PyNumber_Check(v))
14270 goto wrongtype;
14271
Ethan Furman9ab74802014-03-21 06:38:46 -070014272 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014273 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014274 if (type == 'o' || type == 'x' || type == 'X') {
14275 iobj = PyNumber_Index(v);
14276 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014277 if (PyErr_ExceptionMatches(PyExc_TypeError))
14278 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014279 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014280 }
14281 }
14282 else {
14283 iobj = PyNumber_Long(v);
14284 if (iobj == NULL ) {
14285 if (PyErr_ExceptionMatches(PyExc_TypeError))
14286 goto wrongtype;
14287 return -1;
14288 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014289 }
14290 assert(PyLong_Check(iobj));
14291 }
14292 else {
14293 iobj = v;
14294 Py_INCREF(iobj);
14295 }
14296
14297 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014298 && arg->width == -1 && arg->prec == -1
14299 && !(arg->flags & (F_SIGN | F_BLANK))
14300 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014301 {
14302 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014303 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014304 int base;
14305
Victor Stinnera47082312012-10-04 02:19:54 +020014306 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014307 {
14308 default:
14309 assert(0 && "'type' not in [diuoxX]");
14310 case 'd':
14311 case 'i':
14312 case 'u':
14313 base = 10;
14314 break;
14315 case 'o':
14316 base = 8;
14317 break;
14318 case 'x':
14319 case 'X':
14320 base = 16;
14321 break;
14322 }
14323
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014324 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14325 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014326 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014327 }
14328 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014329 return 1;
14330 }
14331
Ethan Furmanb95b5612015-01-23 20:05:18 -080014332 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014333 Py_DECREF(iobj);
14334 if (res == NULL)
14335 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014336 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014337 return 0;
14338
14339wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014340 switch(type)
14341 {
14342 case 'o':
14343 case 'x':
14344 case 'X':
14345 PyErr_Format(PyExc_TypeError,
14346 "%%%c format: an integer is required, "
14347 "not %.200s",
14348 type, Py_TYPE(v)->tp_name);
14349 break;
14350 default:
14351 PyErr_Format(PyExc_TypeError,
14352 "%%%c format: a number is required, "
14353 "not %.200s",
14354 type, Py_TYPE(v)->tp_name);
14355 break;
14356 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014357 return -1;
14358}
14359
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014360static Py_UCS4
14361formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014362{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014363 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014364 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014365 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014366 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014367 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014368 goto onError;
14369 }
14370 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014371 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014372 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014373 /* make sure number is a type of integer */
14374 if (!PyLong_Check(v)) {
14375 iobj = PyNumber_Index(v);
14376 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014377 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014378 }
14379 v = iobj;
14380 Py_DECREF(iobj);
14381 }
14382 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014383 x = PyLong_AsLong(v);
14384 if (x == -1 && PyErr_Occurred())
14385 goto onError;
14386
Victor Stinner8faf8212011-12-08 22:14:11 +010014387 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014388 PyErr_SetString(PyExc_OverflowError,
14389 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014390 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014391 }
14392
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014393 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014394 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014395
Benjamin Peterson29060642009-01-31 22:14:21 +000014396 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014397 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014398 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014399 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014400}
14401
Victor Stinnera47082312012-10-04 02:19:54 +020014402/* Parse options of an argument: flags, width, precision.
14403 Handle also "%(name)" syntax.
14404
14405 Return 0 if the argument has been formatted into arg->str.
14406 Return 1 if the argument has been written into ctx->writer,
14407 Raise an exception and return -1 on error. */
14408static int
14409unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14410 struct unicode_format_arg_t *arg)
14411{
14412#define FORMAT_READ(ctx) \
14413 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14414
14415 PyObject *v;
14416
Victor Stinnera47082312012-10-04 02:19:54 +020014417 if (arg->ch == '(') {
14418 /* Get argument value from a dictionary. Example: "%(name)s". */
14419 Py_ssize_t keystart;
14420 Py_ssize_t keylen;
14421 PyObject *key;
14422 int pcount = 1;
14423
14424 if (ctx->dict == NULL) {
14425 PyErr_SetString(PyExc_TypeError,
14426 "format requires a mapping");
14427 return -1;
14428 }
14429 ++ctx->fmtpos;
14430 --ctx->fmtcnt;
14431 keystart = ctx->fmtpos;
14432 /* Skip over balanced parentheses */
14433 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14434 arg->ch = FORMAT_READ(ctx);
14435 if (arg->ch == ')')
14436 --pcount;
14437 else if (arg->ch == '(')
14438 ++pcount;
14439 ctx->fmtpos++;
14440 }
14441 keylen = ctx->fmtpos - keystart - 1;
14442 if (ctx->fmtcnt < 0 || pcount > 0) {
14443 PyErr_SetString(PyExc_ValueError,
14444 "incomplete format key");
14445 return -1;
14446 }
14447 key = PyUnicode_Substring(ctx->fmtstr,
14448 keystart, keystart + keylen);
14449 if (key == NULL)
14450 return -1;
14451 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014452 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014453 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014454 }
14455 ctx->args = PyObject_GetItem(ctx->dict, key);
14456 Py_DECREF(key);
14457 if (ctx->args == NULL)
14458 return -1;
14459 ctx->args_owned = 1;
14460 ctx->arglen = -1;
14461 ctx->argidx = -2;
14462 }
14463
14464 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014465 while (--ctx->fmtcnt >= 0) {
14466 arg->ch = FORMAT_READ(ctx);
14467 ctx->fmtpos++;
14468 switch (arg->ch) {
14469 case '-': arg->flags |= F_LJUST; continue;
14470 case '+': arg->flags |= F_SIGN; continue;
14471 case ' ': arg->flags |= F_BLANK; continue;
14472 case '#': arg->flags |= F_ALT; continue;
14473 case '0': arg->flags |= F_ZERO; continue;
14474 }
14475 break;
14476 }
14477
14478 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014479 if (arg->ch == '*') {
14480 v = unicode_format_getnextarg(ctx);
14481 if (v == NULL)
14482 return -1;
14483 if (!PyLong_Check(v)) {
14484 PyErr_SetString(PyExc_TypeError,
14485 "* wants int");
14486 return -1;
14487 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014488 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014489 if (arg->width == -1 && PyErr_Occurred())
14490 return -1;
14491 if (arg->width < 0) {
14492 arg->flags |= F_LJUST;
14493 arg->width = -arg->width;
14494 }
14495 if (--ctx->fmtcnt >= 0) {
14496 arg->ch = FORMAT_READ(ctx);
14497 ctx->fmtpos++;
14498 }
14499 }
14500 else if (arg->ch >= '0' && arg->ch <= '9') {
14501 arg->width = arg->ch - '0';
14502 while (--ctx->fmtcnt >= 0) {
14503 arg->ch = FORMAT_READ(ctx);
14504 ctx->fmtpos++;
14505 if (arg->ch < '0' || arg->ch > '9')
14506 break;
14507 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14508 mixing signed and unsigned comparison. Since arg->ch is between
14509 '0' and '9', casting to int is safe. */
14510 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14511 PyErr_SetString(PyExc_ValueError,
14512 "width too big");
14513 return -1;
14514 }
14515 arg->width = arg->width*10 + (arg->ch - '0');
14516 }
14517 }
14518
14519 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014520 if (arg->ch == '.') {
14521 arg->prec = 0;
14522 if (--ctx->fmtcnt >= 0) {
14523 arg->ch = FORMAT_READ(ctx);
14524 ctx->fmtpos++;
14525 }
14526 if (arg->ch == '*') {
14527 v = unicode_format_getnextarg(ctx);
14528 if (v == NULL)
14529 return -1;
14530 if (!PyLong_Check(v)) {
14531 PyErr_SetString(PyExc_TypeError,
14532 "* wants int");
14533 return -1;
14534 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014535 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014536 if (arg->prec == -1 && PyErr_Occurred())
14537 return -1;
14538 if (arg->prec < 0)
14539 arg->prec = 0;
14540 if (--ctx->fmtcnt >= 0) {
14541 arg->ch = FORMAT_READ(ctx);
14542 ctx->fmtpos++;
14543 }
14544 }
14545 else if (arg->ch >= '0' && arg->ch <= '9') {
14546 arg->prec = arg->ch - '0';
14547 while (--ctx->fmtcnt >= 0) {
14548 arg->ch = FORMAT_READ(ctx);
14549 ctx->fmtpos++;
14550 if (arg->ch < '0' || arg->ch > '9')
14551 break;
14552 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14553 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014554 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014555 return -1;
14556 }
14557 arg->prec = arg->prec*10 + (arg->ch - '0');
14558 }
14559 }
14560 }
14561
14562 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14563 if (ctx->fmtcnt >= 0) {
14564 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14565 if (--ctx->fmtcnt >= 0) {
14566 arg->ch = FORMAT_READ(ctx);
14567 ctx->fmtpos++;
14568 }
14569 }
14570 }
14571 if (ctx->fmtcnt < 0) {
14572 PyErr_SetString(PyExc_ValueError,
14573 "incomplete format");
14574 return -1;
14575 }
14576 return 0;
14577
14578#undef FORMAT_READ
14579}
14580
14581/* Format one argument. Supported conversion specifiers:
14582
14583 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014584 - "i", "d", "u": int or float
14585 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014586 - "e", "E", "f", "F", "g", "G": float
14587 - "c": int or str (1 character)
14588
Victor Stinner8dbd4212012-12-04 09:30:24 +010014589 When possible, the output is written directly into the Unicode writer
14590 (ctx->writer). A string is created when padding is required.
14591
Victor Stinnera47082312012-10-04 02:19:54 +020014592 Return 0 if the argument has been formatted into *p_str,
14593 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014594 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014595static int
14596unicode_format_arg_format(struct unicode_formatter_t *ctx,
14597 struct unicode_format_arg_t *arg,
14598 PyObject **p_str)
14599{
14600 PyObject *v;
14601 _PyUnicodeWriter *writer = &ctx->writer;
14602
14603 if (ctx->fmtcnt == 0)
14604 ctx->writer.overallocate = 0;
14605
14606 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014607 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014608 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014609 return 1;
14610 }
14611
14612 v = unicode_format_getnextarg(ctx);
14613 if (v == NULL)
14614 return -1;
14615
Victor Stinnera47082312012-10-04 02:19:54 +020014616
14617 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014618 case 's':
14619 case 'r':
14620 case 'a':
14621 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14622 /* Fast path */
14623 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14624 return -1;
14625 return 1;
14626 }
14627
14628 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14629 *p_str = v;
14630 Py_INCREF(*p_str);
14631 }
14632 else {
14633 if (arg->ch == 's')
14634 *p_str = PyObject_Str(v);
14635 else if (arg->ch == 'r')
14636 *p_str = PyObject_Repr(v);
14637 else
14638 *p_str = PyObject_ASCII(v);
14639 }
14640 break;
14641
14642 case 'i':
14643 case 'd':
14644 case 'u':
14645 case 'o':
14646 case 'x':
14647 case 'X':
14648 {
14649 int ret = mainformatlong(v, arg, p_str, writer);
14650 if (ret != 0)
14651 return ret;
14652 arg->sign = 1;
14653 break;
14654 }
14655
14656 case 'e':
14657 case 'E':
14658 case 'f':
14659 case 'F':
14660 case 'g':
14661 case 'G':
14662 if (arg->width == -1 && arg->prec == -1
14663 && !(arg->flags & (F_SIGN | F_BLANK)))
14664 {
14665 /* Fast path */
14666 if (formatfloat(v, arg, NULL, writer) == -1)
14667 return -1;
14668 return 1;
14669 }
14670
14671 arg->sign = 1;
14672 if (formatfloat(v, arg, p_str, NULL) == -1)
14673 return -1;
14674 break;
14675
14676 case 'c':
14677 {
14678 Py_UCS4 ch = formatchar(v);
14679 if (ch == (Py_UCS4) -1)
14680 return -1;
14681 if (arg->width == -1 && arg->prec == -1) {
14682 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014683 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014684 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014685 return 1;
14686 }
14687 *p_str = PyUnicode_FromOrdinal(ch);
14688 break;
14689 }
14690
14691 default:
14692 PyErr_Format(PyExc_ValueError,
14693 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014694 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014695 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14696 (int)arg->ch,
14697 ctx->fmtpos - 1);
14698 return -1;
14699 }
14700 if (*p_str == NULL)
14701 return -1;
14702 assert (PyUnicode_Check(*p_str));
14703 return 0;
14704}
14705
14706static int
14707unicode_format_arg_output(struct unicode_formatter_t *ctx,
14708 struct unicode_format_arg_t *arg,
14709 PyObject *str)
14710{
14711 Py_ssize_t len;
14712 enum PyUnicode_Kind kind;
14713 void *pbuf;
14714 Py_ssize_t pindex;
14715 Py_UCS4 signchar;
14716 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014717 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014718 Py_ssize_t sublen;
14719 _PyUnicodeWriter *writer = &ctx->writer;
14720 Py_UCS4 fill;
14721
14722 fill = ' ';
14723 if (arg->sign && arg->flags & F_ZERO)
14724 fill = '0';
14725
14726 if (PyUnicode_READY(str) == -1)
14727 return -1;
14728
14729 len = PyUnicode_GET_LENGTH(str);
14730 if ((arg->width == -1 || arg->width <= len)
14731 && (arg->prec == -1 || arg->prec >= len)
14732 && !(arg->flags & (F_SIGN | F_BLANK)))
14733 {
14734 /* Fast path */
14735 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14736 return -1;
14737 return 0;
14738 }
14739
14740 /* Truncate the string for "s", "r" and "a" formats
14741 if the precision is set */
14742 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14743 if (arg->prec >= 0 && len > arg->prec)
14744 len = arg->prec;
14745 }
14746
14747 /* Adjust sign and width */
14748 kind = PyUnicode_KIND(str);
14749 pbuf = PyUnicode_DATA(str);
14750 pindex = 0;
14751 signchar = '\0';
14752 if (arg->sign) {
14753 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14754 if (ch == '-' || ch == '+') {
14755 signchar = ch;
14756 len--;
14757 pindex++;
14758 }
14759 else if (arg->flags & F_SIGN)
14760 signchar = '+';
14761 else if (arg->flags & F_BLANK)
14762 signchar = ' ';
14763 else
14764 arg->sign = 0;
14765 }
14766 if (arg->width < len)
14767 arg->width = len;
14768
14769 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014770 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014771 if (!(arg->flags & F_LJUST)) {
14772 if (arg->sign) {
14773 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014774 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014775 }
14776 else {
14777 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014778 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014779 }
14780 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014781 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14782 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014783 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014784 }
14785
Victor Stinnera47082312012-10-04 02:19:54 +020014786 buflen = arg->width;
14787 if (arg->sign && len == arg->width)
14788 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014789 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014790 return -1;
14791
14792 /* Write the sign if needed */
14793 if (arg->sign) {
14794 if (fill != ' ') {
14795 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14796 writer->pos += 1;
14797 }
14798 if (arg->width > len)
14799 arg->width--;
14800 }
14801
14802 /* Write the numeric prefix for "x", "X" and "o" formats
14803 if the alternate form is used.
14804 For example, write "0x" for the "%#x" format. */
14805 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14806 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14807 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14808 if (fill != ' ') {
14809 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14810 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14811 writer->pos += 2;
14812 pindex += 2;
14813 }
14814 arg->width -= 2;
14815 if (arg->width < 0)
14816 arg->width = 0;
14817 len -= 2;
14818 }
14819
14820 /* Pad left with the fill character if needed */
14821 if (arg->width > len && !(arg->flags & F_LJUST)) {
14822 sublen = arg->width - len;
14823 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14824 writer->pos += sublen;
14825 arg->width = len;
14826 }
14827
14828 /* If padding with spaces: write sign if needed and/or numeric prefix if
14829 the alternate form is used */
14830 if (fill == ' ') {
14831 if (arg->sign) {
14832 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14833 writer->pos += 1;
14834 }
14835 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14836 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14837 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14838 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14839 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14840 writer->pos += 2;
14841 pindex += 2;
14842 }
14843 }
14844
14845 /* Write characters */
14846 if (len) {
14847 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14848 str, pindex, len);
14849 writer->pos += len;
14850 }
14851
14852 /* Pad right with the fill character if needed */
14853 if (arg->width > len) {
14854 sublen = arg->width - len;
14855 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14856 writer->pos += sublen;
14857 }
14858 return 0;
14859}
14860
14861/* Helper of PyUnicode_Format(): format one arg.
14862 Return 0 on success, raise an exception and return -1 on error. */
14863static int
14864unicode_format_arg(struct unicode_formatter_t *ctx)
14865{
14866 struct unicode_format_arg_t arg;
14867 PyObject *str;
14868 int ret;
14869
Victor Stinner8dbd4212012-12-04 09:30:24 +010014870 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14871 arg.flags = 0;
14872 arg.width = -1;
14873 arg.prec = -1;
14874 arg.sign = 0;
14875 str = NULL;
14876
Victor Stinnera47082312012-10-04 02:19:54 +020014877 ret = unicode_format_arg_parse(ctx, &arg);
14878 if (ret == -1)
14879 return -1;
14880
14881 ret = unicode_format_arg_format(ctx, &arg, &str);
14882 if (ret == -1)
14883 return -1;
14884
14885 if (ret != 1) {
14886 ret = unicode_format_arg_output(ctx, &arg, str);
14887 Py_DECREF(str);
14888 if (ret == -1)
14889 return -1;
14890 }
14891
14892 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14893 PyErr_SetString(PyExc_TypeError,
14894 "not all arguments converted during string formatting");
14895 return -1;
14896 }
14897 return 0;
14898}
14899
Alexander Belopolsky40018472011-02-26 01:02:56 +000014900PyObject *
14901PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014902{
Victor Stinnera47082312012-10-04 02:19:54 +020014903 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014904
Guido van Rossumd57fd912000-03-10 22:53:23 +000014905 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014906 PyErr_BadInternalCall();
14907 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014908 }
Victor Stinnera47082312012-10-04 02:19:54 +020014909
14910 ctx.fmtstr = PyUnicode_FromObject(format);
14911 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014912 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014913 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14914 Py_DECREF(ctx.fmtstr);
14915 return NULL;
14916 }
14917 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14918 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14919 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14920 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014921
Victor Stinner8f674cc2013-04-17 23:02:17 +020014922 _PyUnicodeWriter_Init(&ctx.writer);
14923 ctx.writer.min_length = ctx.fmtcnt + 100;
14924 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014925
Guido van Rossumd57fd912000-03-10 22:53:23 +000014926 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014927 ctx.arglen = PyTuple_Size(args);
14928 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014929 }
14930 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014931 ctx.arglen = -1;
14932 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014933 }
Victor Stinnera47082312012-10-04 02:19:54 +020014934 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014935 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014936 ctx.dict = args;
14937 else
14938 ctx.dict = NULL;
14939 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014940
Victor Stinnera47082312012-10-04 02:19:54 +020014941 while (--ctx.fmtcnt >= 0) {
14942 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014943 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014944
14945 nonfmtpos = ctx.fmtpos++;
14946 while (ctx.fmtcnt >= 0 &&
14947 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14948 ctx.fmtpos++;
14949 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014950 }
Victor Stinnera47082312012-10-04 02:19:54 +020014951 if (ctx.fmtcnt < 0) {
14952 ctx.fmtpos--;
14953 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014954 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014955
Victor Stinnercfc4c132013-04-03 01:48:39 +020014956 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14957 nonfmtpos, ctx.fmtpos) < 0)
14958 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014959 }
14960 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014961 ctx.fmtpos++;
14962 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014963 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014964 }
14965 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014966
Victor Stinnera47082312012-10-04 02:19:54 +020014967 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014968 PyErr_SetString(PyExc_TypeError,
14969 "not all arguments converted during string formatting");
14970 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014971 }
14972
Victor Stinnera47082312012-10-04 02:19:54 +020014973 if (ctx.args_owned) {
14974 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014975 }
Victor Stinnera47082312012-10-04 02:19:54 +020014976 Py_DECREF(ctx.fmtstr);
14977 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014978
Benjamin Peterson29060642009-01-31 22:14:21 +000014979 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014980 Py_DECREF(ctx.fmtstr);
14981 _PyUnicodeWriter_Dealloc(&ctx.writer);
14982 if (ctx.args_owned) {
14983 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014984 }
14985 return NULL;
14986}
14987
Jeremy Hylton938ace62002-07-17 16:30:39 +000014988static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014989unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14990
Tim Peters6d6c1a32001-08-02 04:15:00 +000014991static PyObject *
14992unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14993{
Benjamin Peterson29060642009-01-31 22:14:21 +000014994 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014995 static char *kwlist[] = {"object", "encoding", "errors", 0};
14996 char *encoding = NULL;
14997 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014998
Benjamin Peterson14339b62009-01-31 16:36:08 +000014999 if (type != &PyUnicode_Type)
15000 return unicode_subtype_new(type, args, kwds);
15001 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000015002 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000015003 return NULL;
15004 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020015005 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015006 if (encoding == NULL && errors == NULL)
15007 return PyObject_Str(x);
15008 else
Benjamin Peterson29060642009-01-31 22:14:21 +000015009 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000015010}
15011
Guido van Rossume023fe02001-08-30 03:12:59 +000015012static PyObject *
15013unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15014{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015015 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015016 Py_ssize_t length, char_size;
15017 int share_wstr, share_utf8;
15018 unsigned int kind;
15019 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000015020
Benjamin Peterson14339b62009-01-31 16:36:08 +000015021 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015022
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015023 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015024 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015025 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015026 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050015027 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060015028 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015029 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060015030 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015031
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015032 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015033 if (self == NULL) {
15034 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015035 return NULL;
15036 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015037 kind = PyUnicode_KIND(unicode);
15038 length = PyUnicode_GET_LENGTH(unicode);
15039
15040 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015041#ifdef Py_DEBUG
15042 _PyUnicode_HASH(self) = -1;
15043#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015044 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015045#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015046 _PyUnicode_STATE(self).interned = 0;
15047 _PyUnicode_STATE(self).kind = kind;
15048 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015049 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015050 _PyUnicode_STATE(self).ready = 1;
15051 _PyUnicode_WSTR(self) = NULL;
15052 _PyUnicode_UTF8_LENGTH(self) = 0;
15053 _PyUnicode_UTF8(self) = NULL;
15054 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015055 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015056
15057 share_utf8 = 0;
15058 share_wstr = 0;
15059 if (kind == PyUnicode_1BYTE_KIND) {
15060 char_size = 1;
15061 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15062 share_utf8 = 1;
15063 }
15064 else if (kind == PyUnicode_2BYTE_KIND) {
15065 char_size = 2;
15066 if (sizeof(wchar_t) == 2)
15067 share_wstr = 1;
15068 }
15069 else {
15070 assert(kind == PyUnicode_4BYTE_KIND);
15071 char_size = 4;
15072 if (sizeof(wchar_t) == 4)
15073 share_wstr = 1;
15074 }
15075
15076 /* Ensure we won't overflow the length. */
15077 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15078 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015079 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015080 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015081 data = PyObject_MALLOC((length + 1) * char_size);
15082 if (data == NULL) {
15083 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015084 goto onError;
15085 }
15086
Victor Stinnerc3c74152011-10-02 20:39:55 +020015087 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015088 if (share_utf8) {
15089 _PyUnicode_UTF8_LENGTH(self) = length;
15090 _PyUnicode_UTF8(self) = data;
15091 }
15092 if (share_wstr) {
15093 _PyUnicode_WSTR_LENGTH(self) = length;
15094 _PyUnicode_WSTR(self) = (wchar_t *)data;
15095 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015096
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015097 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015098 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015099 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015100#ifdef Py_DEBUG
15101 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15102#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015103 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015104 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015105
15106onError:
15107 Py_DECREF(unicode);
15108 Py_DECREF(self);
15109 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015110}
15111
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015112PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015113"str(object='') -> str\n\
15114str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015115\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015116Create a new string object from the given object. If encoding or\n\
15117errors is specified, then the object must expose a data buffer\n\
15118that will be decoded using the given encoding and error handler.\n\
15119Otherwise, returns the result of object.__str__() (if defined)\n\
15120or repr(object).\n\
15121encoding defaults to sys.getdefaultencoding().\n\
15122errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015123
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015124static PyObject *unicode_iter(PyObject *seq);
15125
Guido van Rossumd57fd912000-03-10 22:53:23 +000015126PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015127 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015128 "str", /* tp_name */
15129 sizeof(PyUnicodeObject), /* tp_size */
15130 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015131 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015132 (destructor)unicode_dealloc, /* tp_dealloc */
15133 0, /* tp_print */
15134 0, /* tp_getattr */
15135 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015136 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015137 unicode_repr, /* tp_repr */
15138 &unicode_as_number, /* tp_as_number */
15139 &unicode_as_sequence, /* tp_as_sequence */
15140 &unicode_as_mapping, /* tp_as_mapping */
15141 (hashfunc) unicode_hash, /* tp_hash*/
15142 0, /* tp_call*/
15143 (reprfunc) unicode_str, /* tp_str */
15144 PyObject_GenericGetAttr, /* tp_getattro */
15145 0, /* tp_setattro */
15146 0, /* tp_as_buffer */
15147 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015148 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015149 unicode_doc, /* tp_doc */
15150 0, /* tp_traverse */
15151 0, /* tp_clear */
15152 PyUnicode_RichCompare, /* tp_richcompare */
15153 0, /* tp_weaklistoffset */
15154 unicode_iter, /* tp_iter */
15155 0, /* tp_iternext */
15156 unicode_methods, /* tp_methods */
15157 0, /* tp_members */
15158 0, /* tp_getset */
15159 &PyBaseObject_Type, /* tp_base */
15160 0, /* tp_dict */
15161 0, /* tp_descr_get */
15162 0, /* tp_descr_set */
15163 0, /* tp_dictoffset */
15164 0, /* tp_init */
15165 0, /* tp_alloc */
15166 unicode_new, /* tp_new */
15167 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015168};
15169
15170/* Initialize the Unicode implementation */
15171
Victor Stinner3a50e702011-10-18 21:21:00 +020015172int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015173{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015174 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015175 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015176 0x000A, /* LINE FEED */
15177 0x000D, /* CARRIAGE RETURN */
15178 0x001C, /* FILE SEPARATOR */
15179 0x001D, /* GROUP SEPARATOR */
15180 0x001E, /* RECORD SEPARATOR */
15181 0x0085, /* NEXT LINE */
15182 0x2028, /* LINE SEPARATOR */
15183 0x2029, /* PARAGRAPH SEPARATOR */
15184 };
15185
Fred Drakee4315f52000-05-09 19:53:39 +000015186 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015187 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015188 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015189 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015190 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015191
Guido van Rossumcacfc072002-05-24 19:01:59 +000015192 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015193 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015194
15195 /* initialize the linebreak bloom filter */
15196 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015197 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015198 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015199
Christian Heimes26532f72013-07-20 14:57:16 +020015200 if (PyType_Ready(&EncodingMapType) < 0)
15201 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015202
Benjamin Petersonc4311282012-10-30 23:21:10 -040015203 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15204 Py_FatalError("Can't initialize field name iterator type");
15205
15206 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15207 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015208
Victor Stinner3a50e702011-10-18 21:21:00 +020015209 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015210}
15211
15212/* Finalize the Unicode implementation */
15213
Christian Heimesa156e092008-02-16 07:38:31 +000015214int
15215PyUnicode_ClearFreeList(void)
15216{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015217 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015218}
15219
Guido van Rossumd57fd912000-03-10 22:53:23 +000015220void
Thomas Wouters78890102000-07-22 19:25:51 +000015221_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015222{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015223 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015224
Serhiy Storchaka05997252013-01-26 12:14:02 +020015225 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015226
Serhiy Storchaka05997252013-01-26 12:14:02 +020015227 for (i = 0; i < 256; i++)
15228 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015229 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015230 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015231}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015232
Walter Dörwald16807132007-05-25 13:52:07 +000015233void
15234PyUnicode_InternInPlace(PyObject **p)
15235{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015236 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015237 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015238#ifdef Py_DEBUG
15239 assert(s != NULL);
15240 assert(_PyUnicode_CHECK(s));
15241#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015242 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015243 return;
15244#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015245 /* If it's a subclass, we don't really know what putting
15246 it in the interned dict might do. */
15247 if (!PyUnicode_CheckExact(s))
15248 return;
15249 if (PyUnicode_CHECK_INTERNED(s))
15250 return;
15251 if (interned == NULL) {
15252 interned = PyDict_New();
15253 if (interned == NULL) {
15254 PyErr_Clear(); /* Don't leave an exception */
15255 return;
15256 }
15257 }
15258 /* It might be that the GetItem call fails even
15259 though the key is present in the dictionary,
15260 namely when this happens during a stack overflow. */
15261 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015262 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015263 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015264
Victor Stinnerf0335102013-04-14 19:13:03 +020015265 if (t) {
15266 Py_INCREF(t);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +020015267 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015268 return;
15269 }
Walter Dörwald16807132007-05-25 13:52:07 +000015270
Benjamin Peterson14339b62009-01-31 16:36:08 +000015271 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015272 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015273 PyErr_Clear();
15274 PyThreadState_GET()->recursion_critical = 0;
15275 return;
15276 }
15277 PyThreadState_GET()->recursion_critical = 0;
15278 /* The two references in interned are not counted by refcnt.
15279 The deallocator will take care of this */
15280 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015281 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015282}
15283
15284void
15285PyUnicode_InternImmortal(PyObject **p)
15286{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015287 PyUnicode_InternInPlace(p);
15288 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015289 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015290 Py_INCREF(*p);
15291 }
Walter Dörwald16807132007-05-25 13:52:07 +000015292}
15293
15294PyObject *
15295PyUnicode_InternFromString(const char *cp)
15296{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015297 PyObject *s = PyUnicode_FromString(cp);
15298 if (s == NULL)
15299 return NULL;
15300 PyUnicode_InternInPlace(&s);
15301 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015302}
15303
Alexander Belopolsky40018472011-02-26 01:02:56 +000015304void
15305_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015306{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015307 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015308 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015309 Py_ssize_t i, n;
15310 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015311
Benjamin Peterson14339b62009-01-31 16:36:08 +000015312 if (interned == NULL || !PyDict_Check(interned))
15313 return;
15314 keys = PyDict_Keys(interned);
15315 if (keys == NULL || !PyList_Check(keys)) {
15316 PyErr_Clear();
15317 return;
15318 }
Walter Dörwald16807132007-05-25 13:52:07 +000015319
Benjamin Peterson14339b62009-01-31 16:36:08 +000015320 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15321 detector, interned unicode strings are not forcibly deallocated;
15322 rather, we give them their stolen references back, and then clear
15323 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015324
Benjamin Peterson14339b62009-01-31 16:36:08 +000015325 n = PyList_GET_SIZE(keys);
15326 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015327 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015328 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015329 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015330 if (PyUnicode_READY(s) == -1) {
15331 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015332 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015333 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015334 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015335 case SSTATE_NOT_INTERNED:
15336 /* XXX Shouldn't happen */
15337 break;
15338 case SSTATE_INTERNED_IMMORTAL:
15339 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015340 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015341 break;
15342 case SSTATE_INTERNED_MORTAL:
15343 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015344 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015345 break;
15346 default:
15347 Py_FatalError("Inconsistent interned string state.");
15348 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015349 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015350 }
15351 fprintf(stderr, "total size of all interned strings: "
15352 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15353 "mortal/immortal\n", mortal_size, immortal_size);
15354 Py_DECREF(keys);
15355 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015356 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015357}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015358
15359
15360/********************* Unicode Iterator **************************/
15361
15362typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015363 PyObject_HEAD
15364 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015365 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015366} unicodeiterobject;
15367
15368static void
15369unicodeiter_dealloc(unicodeiterobject *it)
15370{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015371 _PyObject_GC_UNTRACK(it);
15372 Py_XDECREF(it->it_seq);
15373 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015374}
15375
15376static int
15377unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15378{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015379 Py_VISIT(it->it_seq);
15380 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015381}
15382
15383static PyObject *
15384unicodeiter_next(unicodeiterobject *it)
15385{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015386 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015387
Benjamin Peterson14339b62009-01-31 16:36:08 +000015388 assert(it != NULL);
15389 seq = it->it_seq;
15390 if (seq == NULL)
15391 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015392 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015393
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015394 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15395 int kind = PyUnicode_KIND(seq);
15396 void *data = PyUnicode_DATA(seq);
15397 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15398 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015399 if (item != NULL)
15400 ++it->it_index;
15401 return item;
15402 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015403
Benjamin Peterson14339b62009-01-31 16:36:08 +000015404 Py_DECREF(seq);
15405 it->it_seq = NULL;
15406 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015407}
15408
15409static PyObject *
15410unicodeiter_len(unicodeiterobject *it)
15411{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015412 Py_ssize_t len = 0;
15413 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015414 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015415 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015416}
15417
15418PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15419
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015420static PyObject *
15421unicodeiter_reduce(unicodeiterobject *it)
15422{
15423 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015424 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015425 it->it_seq, it->it_index);
15426 } else {
15427 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15428 if (u == NULL)
15429 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015430 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015431 }
15432}
15433
15434PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15435
15436static PyObject *
15437unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15438{
15439 Py_ssize_t index = PyLong_AsSsize_t(state);
15440 if (index == -1 && PyErr_Occurred())
15441 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015442 if (it->it_seq != NULL) {
15443 if (index < 0)
15444 index = 0;
15445 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15446 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15447 it->it_index = index;
15448 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015449 Py_RETURN_NONE;
15450}
15451
15452PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15453
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015454static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015455 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015456 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015457 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15458 reduce_doc},
15459 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15460 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015461 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015462};
15463
15464PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015465 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15466 "str_iterator", /* tp_name */
15467 sizeof(unicodeiterobject), /* tp_basicsize */
15468 0, /* tp_itemsize */
15469 /* methods */
15470 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15471 0, /* tp_print */
15472 0, /* tp_getattr */
15473 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015474 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015475 0, /* tp_repr */
15476 0, /* tp_as_number */
15477 0, /* tp_as_sequence */
15478 0, /* tp_as_mapping */
15479 0, /* tp_hash */
15480 0, /* tp_call */
15481 0, /* tp_str */
15482 PyObject_GenericGetAttr, /* tp_getattro */
15483 0, /* tp_setattro */
15484 0, /* tp_as_buffer */
15485 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15486 0, /* tp_doc */
15487 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15488 0, /* tp_clear */
15489 0, /* tp_richcompare */
15490 0, /* tp_weaklistoffset */
15491 PyObject_SelfIter, /* tp_iter */
15492 (iternextfunc)unicodeiter_next, /* tp_iternext */
15493 unicodeiter_methods, /* tp_methods */
15494 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015495};
15496
15497static PyObject *
15498unicode_iter(PyObject *seq)
15499{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015500 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015501
Benjamin Peterson14339b62009-01-31 16:36:08 +000015502 if (!PyUnicode_Check(seq)) {
15503 PyErr_BadInternalCall();
15504 return NULL;
15505 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015506 if (PyUnicode_READY(seq) == -1)
15507 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015508 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15509 if (it == NULL)
15510 return NULL;
15511 it->it_index = 0;
15512 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015513 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015514 _PyObject_GC_TRACK(it);
15515 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015516}
15517
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015518
15519size_t
15520Py_UNICODE_strlen(const Py_UNICODE *u)
15521{
15522 int res = 0;
15523 while(*u++)
15524 res++;
15525 return res;
15526}
15527
15528Py_UNICODE*
15529Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15530{
15531 Py_UNICODE *u = s1;
15532 while ((*u++ = *s2++));
15533 return s1;
15534}
15535
15536Py_UNICODE*
15537Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15538{
15539 Py_UNICODE *u = s1;
15540 while ((*u++ = *s2++))
15541 if (n-- == 0)
15542 break;
15543 return s1;
15544}
15545
15546Py_UNICODE*
15547Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15548{
15549 Py_UNICODE *u1 = s1;
15550 u1 += Py_UNICODE_strlen(u1);
15551 Py_UNICODE_strcpy(u1, s2);
15552 return s1;
15553}
15554
15555int
15556Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15557{
15558 while (*s1 && *s2 && *s1 == *s2)
15559 s1++, s2++;
15560 if (*s1 && *s2)
15561 return (*s1 < *s2) ? -1 : +1;
15562 if (*s1)
15563 return 1;
15564 if (*s2)
15565 return -1;
15566 return 0;
15567}
15568
15569int
15570Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15571{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015572 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015573 for (; n != 0; n--) {
15574 u1 = *s1;
15575 u2 = *s2;
15576 if (u1 != u2)
15577 return (u1 < u2) ? -1 : +1;
15578 if (u1 == '\0')
15579 return 0;
15580 s1++;
15581 s2++;
15582 }
15583 return 0;
15584}
15585
15586Py_UNICODE*
15587Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15588{
15589 const Py_UNICODE *p;
15590 for (p = s; *p; p++)
15591 if (*p == c)
15592 return (Py_UNICODE*)p;
15593 return NULL;
15594}
15595
15596Py_UNICODE*
15597Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15598{
15599 const Py_UNICODE *p;
15600 p = s + Py_UNICODE_strlen(s);
15601 while (p != s) {
15602 p--;
15603 if (*p == c)
15604 return (Py_UNICODE*)p;
15605 }
15606 return NULL;
15607}
Victor Stinner331ea922010-08-10 16:37:20 +000015608
Victor Stinner71133ff2010-09-01 23:43:53 +000015609Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015610PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015611{
Victor Stinner577db2c2011-10-11 22:12:48 +020015612 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015613 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015614
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015615 if (!PyUnicode_Check(unicode)) {
15616 PyErr_BadArgument();
15617 return NULL;
15618 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015619 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015620 if (u == NULL)
15621 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015622 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015623 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015624 PyErr_NoMemory();
15625 return NULL;
15626 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015627 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015628 size *= sizeof(Py_UNICODE);
15629 copy = PyMem_Malloc(size);
15630 if (copy == NULL) {
15631 PyErr_NoMemory();
15632 return NULL;
15633 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015634 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015635 return copy;
15636}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015637
Georg Brandl66c221e2010-10-14 07:04:07 +000015638/* A _string module, to export formatter_parser and formatter_field_name_split
15639 to the string.Formatter class implemented in Python. */
15640
15641static PyMethodDef _string_methods[] = {
15642 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15643 METH_O, PyDoc_STR("split the argument as a field name")},
15644 {"formatter_parser", (PyCFunction) formatter_parser,
15645 METH_O, PyDoc_STR("parse the argument as a format string")},
15646 {NULL, NULL}
15647};
15648
15649static struct PyModuleDef _string_module = {
15650 PyModuleDef_HEAD_INIT,
15651 "_string",
15652 PyDoc_STR("string helper module"),
15653 0,
15654 _string_methods,
15655 NULL,
15656 NULL,
15657 NULL,
15658 NULL
15659};
15660
15661PyMODINIT_FUNC
15662PyInit__string(void)
15663{
15664 return PyModule_Create(&_string_module);
15665}
15666
15667
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015668#ifdef __cplusplus
15669}
15670#endif