blob: fb79bd94f6f2e371dedc7fc8a294eda5a727cb73 [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;
914 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200915#ifdef Py_DEBUG
916 unicode_fill_invalid(unicode, old_length);
917#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200918 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
919 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200920 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200921 return unicode;
922}
923
Alexander Belopolsky40018472011-02-26 01:02:56 +0000924static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200925resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000926{
Victor Stinner95663112011-10-04 01:03:50 +0200927 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100928 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200929 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200930 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000931
Victor Stinnerfe226c02011-10-03 03:52:20 +0200932 if (PyUnicode_IS_READY(unicode)) {
933 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200934 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200935 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200936#ifdef Py_DEBUG
937 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
938#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200939
940 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200941 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200942 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
943 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200944
945 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
946 PyErr_NoMemory();
947 return -1;
948 }
949 new_size = (length + 1) * char_size;
950
Victor Stinner7a9105a2011-12-12 00:13:42 +0100951 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
952 {
953 PyObject_DEL(_PyUnicode_UTF8(unicode));
954 _PyUnicode_UTF8(unicode) = NULL;
955 _PyUnicode_UTF8_LENGTH(unicode) = 0;
956 }
957
Victor Stinnerfe226c02011-10-03 03:52:20 +0200958 data = (PyObject *)PyObject_REALLOC(data, new_size);
959 if (data == NULL) {
960 PyErr_NoMemory();
961 return -1;
962 }
963 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200964 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200965 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200966 _PyUnicode_WSTR_LENGTH(unicode) = length;
967 }
968 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200969 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200970 _PyUnicode_UTF8_LENGTH(unicode) = length;
971 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200972 _PyUnicode_LENGTH(unicode) = length;
973 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200974#ifdef Py_DEBUG
975 unicode_fill_invalid(unicode, old_length);
976#endif
Victor Stinner95663112011-10-04 01:03:50 +0200977 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200978 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200979 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200980 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200981 }
Victor Stinner95663112011-10-04 01:03:50 +0200982 assert(_PyUnicode_WSTR(unicode) != NULL);
983
984 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700985 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +0200986 PyErr_NoMemory();
987 return -1;
988 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100989 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200990 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100991 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200992 if (!wstr) {
993 PyErr_NoMemory();
994 return -1;
995 }
996 _PyUnicode_WSTR(unicode) = wstr;
997 _PyUnicode_WSTR(unicode)[length] = 0;
998 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200999 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001000 return 0;
1001}
1002
Victor Stinnerfe226c02011-10-03 03:52:20 +02001003static PyObject*
1004resize_copy(PyObject *unicode, Py_ssize_t length)
1005{
1006 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001007 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001008 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001009
Benjamin Petersonbac79492012-01-14 13:34:47 -05001010 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +01001011 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001012
1013 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1014 if (copy == NULL)
1015 return NULL;
1016
1017 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001018 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001019 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001020 }
1021 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001022 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001023
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001024 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001025 if (w == NULL)
1026 return NULL;
1027 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1028 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001029 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
1030 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001031 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001032 }
1033}
1034
Guido van Rossumd57fd912000-03-10 22:53:23 +00001035/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001036 Ux0000 terminated; some code (e.g. new_identifier)
1037 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001038
1039 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001040 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001041
1042*/
1043
Alexander Belopolsky40018472011-02-26 01:02:56 +00001044static PyUnicodeObject *
1045_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001046{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001047 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001049
Thomas Wouters477c8d52006-05-27 19:21:47 +00001050 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001051 if (length == 0 && unicode_empty != NULL) {
1052 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001053 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001054 }
1055
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001056 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001057 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001058 return (PyUnicodeObject *)PyErr_NoMemory();
1059 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001060 if (length < 0) {
1061 PyErr_SetString(PyExc_SystemError,
1062 "Negative size passed to _PyUnicode_New");
1063 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001064 }
1065
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001066 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1067 if (unicode == NULL)
1068 return NULL;
1069 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001070
1071 _PyUnicode_WSTR_LENGTH(unicode) = length;
1072 _PyUnicode_HASH(unicode) = -1;
1073 _PyUnicode_STATE(unicode).interned = 0;
1074 _PyUnicode_STATE(unicode).kind = 0;
1075 _PyUnicode_STATE(unicode).compact = 0;
1076 _PyUnicode_STATE(unicode).ready = 0;
1077 _PyUnicode_STATE(unicode).ascii = 0;
1078 _PyUnicode_DATA_ANY(unicode) = NULL;
1079 _PyUnicode_LENGTH(unicode) = 0;
1080 _PyUnicode_UTF8(unicode) = NULL;
1081 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1082
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1084 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001085 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001086 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001087 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001088 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001089
Jeremy Hyltond8082792003-09-16 19:41:39 +00001090 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001091 * the caller fails before initializing str -- unicode_resize()
1092 * reads str[0], and the Keep-Alive optimization can keep memory
1093 * allocated for str alive across a call to unicode_dealloc(unicode).
1094 * We don't want unicode_resize to read uninitialized memory in
1095 * that case.
1096 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001097 _PyUnicode_WSTR(unicode)[0] = 0;
1098 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001099
Victor Stinner7931d9a2011-11-04 00:22:48 +01001100 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001101 return unicode;
1102}
1103
Victor Stinnerf42dc442011-10-02 23:33:16 +02001104static const char*
1105unicode_kind_name(PyObject *unicode)
1106{
Victor Stinner42dfd712011-10-03 14:41:45 +02001107 /* don't check consistency: unicode_kind_name() is called from
1108 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001109 if (!PyUnicode_IS_COMPACT(unicode))
1110 {
1111 if (!PyUnicode_IS_READY(unicode))
1112 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001113 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001114 {
1115 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001116 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001117 return "legacy ascii";
1118 else
1119 return "legacy latin1";
1120 case PyUnicode_2BYTE_KIND:
1121 return "legacy UCS2";
1122 case PyUnicode_4BYTE_KIND:
1123 return "legacy UCS4";
1124 default:
1125 return "<legacy invalid kind>";
1126 }
1127 }
1128 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001129 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001130 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001131 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001132 return "ascii";
1133 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001134 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001135 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001136 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001137 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001138 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001139 default:
1140 return "<invalid compact kind>";
1141 }
1142}
1143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001144#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001145/* Functions wrapping macros for use in debugger */
1146char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001147 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001148}
1149
1150void *_PyUnicode_compact_data(void *unicode) {
1151 return _PyUnicode_COMPACT_DATA(unicode);
1152}
1153void *_PyUnicode_data(void *unicode){
1154 printf("obj %p\n", unicode);
1155 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1156 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1157 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1158 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1159 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1160 return PyUnicode_DATA(unicode);
1161}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001162
1163void
1164_PyUnicode_Dump(PyObject *op)
1165{
1166 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001167 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1168 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1169 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001170
Victor Stinnera849a4b2011-10-03 12:12:11 +02001171 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001172 {
1173 if (ascii->state.ascii)
1174 data = (ascii + 1);
1175 else
1176 data = (compact + 1);
1177 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001178 else
1179 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001180 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1181 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001182
Victor Stinnera849a4b2011-10-03 12:12:11 +02001183 if (ascii->wstr == data)
1184 printf("shared ");
1185 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001186
Victor Stinnera3b334d2011-10-03 13:53:37 +02001187 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001188 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001189 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1190 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001191 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1192 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001193 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001194 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001195}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001196#endif
1197
1198PyObject *
1199PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1200{
1201 PyObject *obj;
1202 PyCompactUnicodeObject *unicode;
1203 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001204 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001205 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001206 Py_ssize_t char_size;
1207 Py_ssize_t struct_size;
1208
1209 /* Optimization for empty strings */
1210 if (size == 0 && unicode_empty != NULL) {
1211 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001212 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001213 }
1214
Victor Stinner9e9d6892011-10-04 01:02:02 +02001215 is_ascii = 0;
1216 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001217 struct_size = sizeof(PyCompactUnicodeObject);
1218 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001219 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220 char_size = 1;
1221 is_ascii = 1;
1222 struct_size = sizeof(PyASCIIObject);
1223 }
1224 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001225 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001226 char_size = 1;
1227 }
1228 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001229 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001230 char_size = 2;
1231 if (sizeof(wchar_t) == 2)
1232 is_sharing = 1;
1233 }
1234 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001235 if (maxchar > MAX_UNICODE) {
1236 PyErr_SetString(PyExc_SystemError,
1237 "invalid maximum character passed to PyUnicode_New");
1238 return NULL;
1239 }
Victor Stinner8f825062012-04-27 13:55:39 +02001240 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001241 char_size = 4;
1242 if (sizeof(wchar_t) == 4)
1243 is_sharing = 1;
1244 }
1245
1246 /* Ensure we won't overflow the size. */
1247 if (size < 0) {
1248 PyErr_SetString(PyExc_SystemError,
1249 "Negative size passed to PyUnicode_New");
1250 return NULL;
1251 }
1252 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1253 return PyErr_NoMemory();
1254
1255 /* Duplicated allocation code from _PyObject_New() instead of a call to
1256 * PyObject_New() so we are able to allocate space for the object and
1257 * it's data buffer.
1258 */
1259 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1260 if (obj == NULL)
1261 return PyErr_NoMemory();
1262 obj = PyObject_INIT(obj, &PyUnicode_Type);
1263 if (obj == NULL)
1264 return NULL;
1265
1266 unicode = (PyCompactUnicodeObject *)obj;
1267 if (is_ascii)
1268 data = ((PyASCIIObject*)obj) + 1;
1269 else
1270 data = unicode + 1;
1271 _PyUnicode_LENGTH(unicode) = size;
1272 _PyUnicode_HASH(unicode) = -1;
1273 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001274 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001275 _PyUnicode_STATE(unicode).compact = 1;
1276 _PyUnicode_STATE(unicode).ready = 1;
1277 _PyUnicode_STATE(unicode).ascii = is_ascii;
1278 if (is_ascii) {
1279 ((char*)data)[size] = 0;
1280 _PyUnicode_WSTR(unicode) = NULL;
1281 }
Victor Stinner8f825062012-04-27 13:55:39 +02001282 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001283 ((char*)data)[size] = 0;
1284 _PyUnicode_WSTR(unicode) = NULL;
1285 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001286 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001287 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001288 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001289 else {
1290 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001291 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001292 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001293 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001294 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001295 ((Py_UCS4*)data)[size] = 0;
1296 if (is_sharing) {
1297 _PyUnicode_WSTR_LENGTH(unicode) = size;
1298 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1299 }
1300 else {
1301 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1302 _PyUnicode_WSTR(unicode) = NULL;
1303 }
1304 }
Victor Stinner8f825062012-04-27 13:55:39 +02001305#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001306 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001307#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001308 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001309 return obj;
1310}
1311
1312#if SIZEOF_WCHAR_T == 2
1313/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1314 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001315 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316
1317 This function assumes that unicode can hold one more code point than wstr
1318 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001319static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001321 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001322{
1323 const wchar_t *iter;
1324 Py_UCS4 *ucs4_out;
1325
Victor Stinner910337b2011-10-03 03:20:16 +02001326 assert(unicode != NULL);
1327 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001328 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1329 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1330
1331 for (iter = begin; iter < end; ) {
1332 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1333 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001334 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1335 && (iter+1) < end
1336 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337 {
Victor Stinner551ac952011-11-29 22:58:13 +01001338 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001339 iter += 2;
1340 }
1341 else {
1342 *ucs4_out++ = *iter;
1343 iter++;
1344 }
1345 }
1346 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1347 _PyUnicode_GET_LENGTH(unicode)));
1348
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001349}
1350#endif
1351
Victor Stinnercd9950f2011-10-02 00:34:53 +02001352static int
Victor Stinner488fa492011-12-12 00:01:39 +01001353unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001354{
Victor Stinner488fa492011-12-12 00:01:39 +01001355 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001356 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001357 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001358 return -1;
1359 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001360 return 0;
1361}
1362
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001363static int
1364_copy_characters(PyObject *to, Py_ssize_t to_start,
1365 PyObject *from, Py_ssize_t from_start,
1366 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001367{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001368 unsigned int from_kind, to_kind;
1369 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001370
Victor Stinneree4544c2012-05-09 22:24:08 +02001371 assert(0 <= how_many);
1372 assert(0 <= from_start);
1373 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001374 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001375 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001376 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377
Victor Stinnerd3f08822012-05-29 12:57:52 +02001378 assert(PyUnicode_Check(to));
1379 assert(PyUnicode_IS_READY(to));
1380 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1381
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001382 if (how_many == 0)
1383 return 0;
1384
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001385 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001386 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001387 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001388 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001389
Victor Stinnerf1852262012-06-16 16:38:26 +02001390#ifdef Py_DEBUG
1391 if (!check_maxchar
1392 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1393 {
1394 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1395 Py_UCS4 ch;
1396 Py_ssize_t i;
1397 for (i=0; i < how_many; i++) {
1398 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1399 assert(ch <= to_maxchar);
1400 }
1401 }
1402#endif
1403
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001404 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001405 if (check_maxchar
1406 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1407 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001408 /* Writing Latin-1 characters into an ASCII string requires to
1409 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001410 Py_UCS4 max_char;
1411 max_char = ucs1lib_find_max_char(from_data,
1412 (Py_UCS1*)from_data + how_many);
1413 if (max_char >= 128)
1414 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001415 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001416 Py_MEMCPY((char*)to_data + to_kind * to_start,
1417 (char*)from_data + from_kind * from_start,
1418 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001419 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001420 else if (from_kind == PyUnicode_1BYTE_KIND
1421 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001422 {
1423 _PyUnicode_CONVERT_BYTES(
1424 Py_UCS1, Py_UCS2,
1425 PyUnicode_1BYTE_DATA(from) + from_start,
1426 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1427 PyUnicode_2BYTE_DATA(to) + to_start
1428 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001429 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001430 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001431 && to_kind == PyUnicode_4BYTE_KIND)
1432 {
1433 _PyUnicode_CONVERT_BYTES(
1434 Py_UCS1, Py_UCS4,
1435 PyUnicode_1BYTE_DATA(from) + from_start,
1436 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1437 PyUnicode_4BYTE_DATA(to) + to_start
1438 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001439 }
1440 else if (from_kind == PyUnicode_2BYTE_KIND
1441 && to_kind == PyUnicode_4BYTE_KIND)
1442 {
1443 _PyUnicode_CONVERT_BYTES(
1444 Py_UCS2, Py_UCS4,
1445 PyUnicode_2BYTE_DATA(from) + from_start,
1446 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1447 PyUnicode_4BYTE_DATA(to) + to_start
1448 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001449 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001450 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001451 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1452
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001453 if (!check_maxchar) {
1454 if (from_kind == PyUnicode_2BYTE_KIND
1455 && to_kind == PyUnicode_1BYTE_KIND)
1456 {
1457 _PyUnicode_CONVERT_BYTES(
1458 Py_UCS2, Py_UCS1,
1459 PyUnicode_2BYTE_DATA(from) + from_start,
1460 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1461 PyUnicode_1BYTE_DATA(to) + to_start
1462 );
1463 }
1464 else if (from_kind == PyUnicode_4BYTE_KIND
1465 && to_kind == PyUnicode_1BYTE_KIND)
1466 {
1467 _PyUnicode_CONVERT_BYTES(
1468 Py_UCS4, Py_UCS1,
1469 PyUnicode_4BYTE_DATA(from) + from_start,
1470 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1471 PyUnicode_1BYTE_DATA(to) + to_start
1472 );
1473 }
1474 else if (from_kind == PyUnicode_4BYTE_KIND
1475 && to_kind == PyUnicode_2BYTE_KIND)
1476 {
1477 _PyUnicode_CONVERT_BYTES(
1478 Py_UCS4, Py_UCS2,
1479 PyUnicode_4BYTE_DATA(from) + from_start,
1480 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1481 PyUnicode_2BYTE_DATA(to) + to_start
1482 );
1483 }
1484 else {
1485 assert(0);
1486 return -1;
1487 }
1488 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001489 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001490 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001491 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001492 Py_ssize_t i;
1493
Victor Stinnera0702ab2011-09-29 14:14:38 +02001494 for (i=0; i < how_many; i++) {
1495 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001496 if (ch > to_maxchar)
1497 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001498 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1499 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001500 }
1501 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001502 return 0;
1503}
1504
Victor Stinnerd3f08822012-05-29 12:57:52 +02001505void
1506_PyUnicode_FastCopyCharacters(
1507 PyObject *to, Py_ssize_t to_start,
1508 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001509{
1510 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1511}
1512
1513Py_ssize_t
1514PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1515 PyObject *from, Py_ssize_t from_start,
1516 Py_ssize_t how_many)
1517{
1518 int err;
1519
1520 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1521 PyErr_BadInternalCall();
1522 return -1;
1523 }
1524
Benjamin Petersonbac79492012-01-14 13:34:47 -05001525 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001526 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001527 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001528 return -1;
1529
Victor Stinnerd3f08822012-05-29 12:57:52 +02001530 if (from_start < 0) {
1531 PyErr_SetString(PyExc_IndexError, "string index out of range");
1532 return -1;
1533 }
1534 if (to_start < 0) {
1535 PyErr_SetString(PyExc_IndexError, "string index out of range");
1536 return -1;
1537 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001538 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1539 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1540 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001541 "Cannot write %zi characters at %zi "
1542 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001543 how_many, to_start, PyUnicode_GET_LENGTH(to));
1544 return -1;
1545 }
1546
1547 if (how_many == 0)
1548 return 0;
1549
Victor Stinner488fa492011-12-12 00:01:39 +01001550 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001551 return -1;
1552
1553 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1554 if (err) {
1555 PyErr_Format(PyExc_SystemError,
1556 "Cannot copy %s characters "
1557 "into a string of %s characters",
1558 unicode_kind_name(from),
1559 unicode_kind_name(to));
1560 return -1;
1561 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001562 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001563}
1564
Victor Stinner17222162011-09-28 22:15:37 +02001565/* Find the maximum code point and count the number of surrogate pairs so a
1566 correct string length can be computed before converting a string to UCS4.
1567 This function counts single surrogates as a character and not as a pair.
1568
1569 Return 0 on success, or -1 on error. */
1570static int
1571find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1572 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001573{
1574 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001575 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001576
Victor Stinnerc53be962011-10-02 21:33:54 +02001577 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001578 *num_surrogates = 0;
1579 *maxchar = 0;
1580
1581 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001582#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001583 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1584 && (iter+1) < end
1585 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1586 {
1587 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1588 ++(*num_surrogates);
1589 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001590 }
1591 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001593 {
1594 ch = *iter;
1595 iter++;
1596 }
1597 if (ch > *maxchar) {
1598 *maxchar = ch;
1599 if (*maxchar > MAX_UNICODE) {
1600 PyErr_Format(PyExc_ValueError,
1601 "character U+%x is not in range [U+0000; U+10ffff]",
1602 ch);
1603 return -1;
1604 }
1605 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001606 }
1607 return 0;
1608}
1609
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001610int
1611_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001612{
1613 wchar_t *end;
1614 Py_UCS4 maxchar = 0;
1615 Py_ssize_t num_surrogates;
1616#if SIZEOF_WCHAR_T == 2
1617 Py_ssize_t length_wo_surrogates;
1618#endif
1619
Georg Brandl7597add2011-10-05 16:36:47 +02001620 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001621 strings were created using _PyObject_New() and where no canonical
1622 representation (the str field) has been set yet aka strings
1623 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001624 assert(_PyUnicode_CHECK(unicode));
1625 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001626 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001627 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001628 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001629 /* Actually, it should neither be interned nor be anything else: */
1630 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001632 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001633 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001634 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001635 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001636
1637 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001638 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1639 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001640 PyErr_NoMemory();
1641 return -1;
1642 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001643 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001644 _PyUnicode_WSTR(unicode), end,
1645 PyUnicode_1BYTE_DATA(unicode));
1646 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1647 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1648 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1649 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001650 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001651 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001652 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001653 }
1654 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001655 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001656 _PyUnicode_UTF8(unicode) = NULL;
1657 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001658 }
1659 PyObject_FREE(_PyUnicode_WSTR(unicode));
1660 _PyUnicode_WSTR(unicode) = NULL;
1661 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1662 }
1663 /* In this case we might have to convert down from 4-byte native
1664 wchar_t to 2-byte unicode. */
1665 else if (maxchar < 65536) {
1666 assert(num_surrogates == 0 &&
1667 "FindMaxCharAndNumSurrogatePairs() messed up");
1668
Victor Stinner506f5922011-09-28 22:34:18 +02001669#if SIZEOF_WCHAR_T == 2
1670 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001671 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001672 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1673 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1674 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001675 _PyUnicode_UTF8(unicode) = NULL;
1676 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001677#else
1678 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001679 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001680 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001681 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001682 PyErr_NoMemory();
1683 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001684 }
Victor Stinner506f5922011-09-28 22:34:18 +02001685 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1686 _PyUnicode_WSTR(unicode), end,
1687 PyUnicode_2BYTE_DATA(unicode));
1688 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1689 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1690 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001691 _PyUnicode_UTF8(unicode) = NULL;
1692 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001693 PyObject_FREE(_PyUnicode_WSTR(unicode));
1694 _PyUnicode_WSTR(unicode) = NULL;
1695 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1696#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001697 }
1698 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1699 else {
1700#if SIZEOF_WCHAR_T == 2
1701 /* in case the native representation is 2-bytes, we need to allocate a
1702 new normalized 4-byte version. */
1703 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001704 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1705 PyErr_NoMemory();
1706 return -1;
1707 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001708 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1709 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001710 PyErr_NoMemory();
1711 return -1;
1712 }
1713 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1714 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001715 _PyUnicode_UTF8(unicode) = NULL;
1716 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001717 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1718 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001719 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001720 PyObject_FREE(_PyUnicode_WSTR(unicode));
1721 _PyUnicode_WSTR(unicode) = NULL;
1722 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1723#else
1724 assert(num_surrogates == 0);
1725
Victor Stinnerc3c74152011-10-02 20:39:55 +02001726 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001727 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001728 _PyUnicode_UTF8(unicode) = NULL;
1729 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001730 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1731#endif
1732 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1733 }
1734 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001735 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001736 return 0;
1737}
1738
Alexander Belopolsky40018472011-02-26 01:02:56 +00001739static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001740unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001741{
Walter Dörwald16807132007-05-25 13:52:07 +00001742 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001743 case SSTATE_NOT_INTERNED:
1744 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001745
Benjamin Peterson29060642009-01-31 22:14:21 +00001746 case SSTATE_INTERNED_MORTAL:
1747 /* revive dead object temporarily for DelItem */
1748 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001749 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001750 Py_FatalError(
1751 "deletion of interned string failed");
1752 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001753
Benjamin Peterson29060642009-01-31 22:14:21 +00001754 case SSTATE_INTERNED_IMMORTAL:
1755 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001756
Benjamin Peterson29060642009-01-31 22:14:21 +00001757 default:
1758 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001759 }
1760
Victor Stinner03490912011-10-03 23:45:12 +02001761 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001762 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001763 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001764 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001765 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1766 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001768 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001769}
1770
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001771#ifdef Py_DEBUG
1772static int
1773unicode_is_singleton(PyObject *unicode)
1774{
1775 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1776 if (unicode == unicode_empty)
1777 return 1;
1778 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1779 {
1780 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1781 if (ch < 256 && unicode_latin1[ch] == unicode)
1782 return 1;
1783 }
1784 return 0;
1785}
1786#endif
1787
Alexander Belopolsky40018472011-02-26 01:02:56 +00001788static int
Victor Stinner488fa492011-12-12 00:01:39 +01001789unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001790{
Victor Stinner488fa492011-12-12 00:01:39 +01001791 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001792 if (Py_REFCNT(unicode) != 1)
1793 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001794 if (_PyUnicode_HASH(unicode) != -1)
1795 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001796 if (PyUnicode_CHECK_INTERNED(unicode))
1797 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001798 if (!PyUnicode_CheckExact(unicode))
1799 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001800#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001801 /* singleton refcount is greater than 1 */
1802 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001803#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001804 return 1;
1805}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001806
Victor Stinnerfe226c02011-10-03 03:52:20 +02001807static int
1808unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1809{
1810 PyObject *unicode;
1811 Py_ssize_t old_length;
1812
1813 assert(p_unicode != NULL);
1814 unicode = *p_unicode;
1815
1816 assert(unicode != NULL);
1817 assert(PyUnicode_Check(unicode));
1818 assert(0 <= length);
1819
Victor Stinner910337b2011-10-03 03:20:16 +02001820 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001821 old_length = PyUnicode_WSTR_LENGTH(unicode);
1822 else
1823 old_length = PyUnicode_GET_LENGTH(unicode);
1824 if (old_length == length)
1825 return 0;
1826
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001827 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001828 _Py_INCREF_UNICODE_EMPTY();
1829 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001830 return -1;
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +02001831 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001832 return 0;
1833 }
1834
Victor Stinner488fa492011-12-12 00:01:39 +01001835 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001836 PyObject *copy = resize_copy(unicode, length);
1837 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001838 return -1;
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +02001839 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001840 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001841 }
1842
Victor Stinnerfe226c02011-10-03 03:52:20 +02001843 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001844 PyObject *new_unicode = resize_compact(unicode, length);
1845 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001846 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001847 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001848 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001849 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001850 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001851}
1852
Alexander Belopolsky40018472011-02-26 01:02:56 +00001853int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001854PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001855{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001856 PyObject *unicode;
1857 if (p_unicode == NULL) {
1858 PyErr_BadInternalCall();
1859 return -1;
1860 }
1861 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001862 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001863 {
1864 PyErr_BadInternalCall();
1865 return -1;
1866 }
1867 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001868}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001869
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001870/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001871
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001872 WARNING: The function doesn't copy the terminating null character and
1873 doesn't check the maximum character (may write a latin1 character in an
1874 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001875static void
1876unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1877 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001878{
1879 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1880 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001881 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001882
1883 switch (kind) {
1884 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001885 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001886#ifdef Py_DEBUG
1887 if (PyUnicode_IS_ASCII(unicode)) {
1888 Py_UCS4 maxchar = ucs1lib_find_max_char(
1889 (const Py_UCS1*)str,
1890 (const Py_UCS1*)str + len);
1891 assert(maxchar < 128);
1892 }
1893#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001894 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001895 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001896 }
1897 case PyUnicode_2BYTE_KIND: {
1898 Py_UCS2 *start = (Py_UCS2 *)data + index;
1899 Py_UCS2 *ucs2 = start;
1900 assert(index <= PyUnicode_GET_LENGTH(unicode));
1901
Victor Stinner184252a2012-06-16 02:57:41 +02001902 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001903 *ucs2 = (Py_UCS2)*str;
1904
1905 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001906 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001907 }
1908 default: {
1909 Py_UCS4 *start = (Py_UCS4 *)data + index;
1910 Py_UCS4 *ucs4 = start;
1911 assert(kind == PyUnicode_4BYTE_KIND);
1912 assert(index <= PyUnicode_GET_LENGTH(unicode));
1913
Victor Stinner184252a2012-06-16 02:57:41 +02001914 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001915 *ucs4 = (Py_UCS4)*str;
1916
1917 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001918 }
1919 }
1920}
1921
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001922static PyObject*
1923get_latin1_char(unsigned char ch)
1924{
Victor Stinnera464fc12011-10-02 20:39:30 +02001925 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001926 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001927 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001928 if (!unicode)
1929 return NULL;
1930 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001931 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001932 unicode_latin1[ch] = unicode;
1933 }
1934 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001935 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001936}
1937
Victor Stinner985a82a2014-01-03 12:53:47 +01001938static PyObject*
1939unicode_char(Py_UCS4 ch)
1940{
1941 PyObject *unicode;
1942
1943 assert(ch <= MAX_UNICODE);
1944
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001945 if (ch < 256)
1946 return get_latin1_char(ch);
1947
Victor Stinner985a82a2014-01-03 12:53:47 +01001948 unicode = PyUnicode_New(1, ch);
1949 if (unicode == NULL)
1950 return NULL;
1951 switch (PyUnicode_KIND(unicode)) {
1952 case PyUnicode_1BYTE_KIND:
1953 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1954 break;
1955 case PyUnicode_2BYTE_KIND:
1956 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1957 break;
1958 default:
1959 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1960 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1961 }
1962 assert(_PyUnicode_CheckConsistency(unicode, 1));
1963 return unicode;
1964}
1965
Alexander Belopolsky40018472011-02-26 01:02:56 +00001966PyObject *
1967PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001968{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001969 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001970 Py_UCS4 maxchar = 0;
1971 Py_ssize_t num_surrogates;
1972
1973 if (u == NULL)
1974 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001975
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001976 /* If the Unicode data is known at construction time, we can apply
1977 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001978
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001979 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001980 if (size == 0)
1981 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001983 /* Single character Unicode objects in the Latin-1 range are
1984 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001985 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001986 return get_latin1_char((unsigned char)*u);
1987
1988 /* If not empty and not single character, copy the Unicode data
1989 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001990 if (find_maxchar_surrogates(u, u + size,
1991 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001992 return NULL;
1993
Victor Stinner8faf8212011-12-08 22:14:11 +01001994 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001995 if (!unicode)
1996 return NULL;
1997
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001998 switch (PyUnicode_KIND(unicode)) {
1999 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002000 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002001 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2002 break;
2003 case PyUnicode_2BYTE_KIND:
2004#if Py_UNICODE_SIZE == 2
2005 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
2006#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002007 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002008 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2009#endif
2010 break;
2011 case PyUnicode_4BYTE_KIND:
2012#if SIZEOF_WCHAR_T == 2
2013 /* This is the only case which has to process surrogates, thus
2014 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002015 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002016#else
2017 assert(num_surrogates == 0);
2018 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
2019#endif
2020 break;
2021 default:
2022 assert(0 && "Impossible state");
2023 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002024
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002025 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002026}
2027
Alexander Belopolsky40018472011-02-26 01:02:56 +00002028PyObject *
2029PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002030{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002031 if (size < 0) {
2032 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002033 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002034 return NULL;
2035 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002036 if (u != NULL)
2037 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2038 else
2039 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002040}
2041
Alexander Belopolsky40018472011-02-26 01:02:56 +00002042PyObject *
2043PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002044{
2045 size_t size = strlen(u);
2046 if (size > PY_SSIZE_T_MAX) {
2047 PyErr_SetString(PyExc_OverflowError, "input too long");
2048 return NULL;
2049 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002050 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002051}
2052
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002053PyObject *
2054_PyUnicode_FromId(_Py_Identifier *id)
2055{
2056 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002057 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2058 strlen(id->string),
2059 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002060 if (!id->object)
2061 return NULL;
2062 PyUnicode_InternInPlace(&id->object);
2063 assert(!id->next);
2064 id->next = static_strings;
2065 static_strings = id;
2066 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002067 return id->object;
2068}
2069
2070void
2071_PyUnicode_ClearStaticStrings()
2072{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002073 _Py_Identifier *tmp, *s = static_strings;
2074 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002075 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002076 tmp = s->next;
2077 s->next = NULL;
2078 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002079 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002080 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002081}
2082
Benjamin Peterson0df54292012-03-26 14:50:32 -04002083/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002084
Victor Stinnerd3f08822012-05-29 12:57:52 +02002085PyObject*
2086_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002087{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002088 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002089 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002090 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002091#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002092 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002093#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002094 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002095 }
Victor Stinner785938e2011-12-11 20:09:03 +01002096 unicode = PyUnicode_New(size, 127);
2097 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002098 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002099 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2100 assert(_PyUnicode_CheckConsistency(unicode, 1));
2101 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002102}
2103
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002104static Py_UCS4
2105kind_maxchar_limit(unsigned int kind)
2106{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002107 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002108 case PyUnicode_1BYTE_KIND:
2109 return 0x80;
2110 case PyUnicode_2BYTE_KIND:
2111 return 0x100;
2112 case PyUnicode_4BYTE_KIND:
2113 return 0x10000;
2114 default:
2115 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01002116 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002117 }
2118}
2119
Victor Stinnere6abb482012-05-02 01:15:40 +02002120Py_LOCAL_INLINE(Py_UCS4)
2121align_maxchar(Py_UCS4 maxchar)
2122{
2123 if (maxchar <= 127)
2124 return 127;
2125 else if (maxchar <= 255)
2126 return 255;
2127 else if (maxchar <= 65535)
2128 return 65535;
2129 else
2130 return MAX_UNICODE;
2131}
2132
Victor Stinner702c7342011-10-05 13:50:52 +02002133static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002134_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002135{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002136 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002137 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002138
Serhiy Storchaka678db842013-01-26 12:16:36 +02002139 if (size == 0)
2140 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002141 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002142 if (size == 1)
2143 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002144
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002145 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002146 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002147 if (!res)
2148 return NULL;
2149 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002150 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002151 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002152}
2153
Victor Stinnere57b1c02011-09-28 22:20:48 +02002154static PyObject*
2155_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002156{
2157 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002158 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002159
Serhiy Storchaka678db842013-01-26 12:16:36 +02002160 if (size == 0)
2161 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002162 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002163 if (size == 1)
2164 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002165
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002166 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002167 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002168 if (!res)
2169 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002170 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002171 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002172 else {
2173 _PyUnicode_CONVERT_BYTES(
2174 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2175 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002176 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177 return res;
2178}
2179
Victor Stinnere57b1c02011-09-28 22:20:48 +02002180static PyObject*
2181_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002182{
2183 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002184 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002185
Serhiy Storchaka678db842013-01-26 12:16:36 +02002186 if (size == 0)
2187 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002188 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002189 if (size == 1)
2190 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002191
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002192 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002193 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002194 if (!res)
2195 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002196 if (max_char < 256)
2197 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2198 PyUnicode_1BYTE_DATA(res));
2199 else if (max_char < 0x10000)
2200 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2201 PyUnicode_2BYTE_DATA(res));
2202 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002203 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002204 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002205 return res;
2206}
2207
2208PyObject*
2209PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2210{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002211 if (size < 0) {
2212 PyErr_SetString(PyExc_ValueError, "size must be positive");
2213 return NULL;
2214 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002215 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002217 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002219 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002220 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002221 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002222 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002223 PyErr_SetString(PyExc_SystemError, "invalid kind");
2224 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002225 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002226}
2227
Victor Stinnerece58de2012-04-23 23:36:38 +02002228Py_UCS4
2229_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2230{
2231 enum PyUnicode_Kind kind;
2232 void *startptr, *endptr;
2233
2234 assert(PyUnicode_IS_READY(unicode));
2235 assert(0 <= start);
2236 assert(end <= PyUnicode_GET_LENGTH(unicode));
2237 assert(start <= end);
2238
2239 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2240 return PyUnicode_MAX_CHAR_VALUE(unicode);
2241
2242 if (start == end)
2243 return 127;
2244
Victor Stinner94d558b2012-04-27 22:26:58 +02002245 if (PyUnicode_IS_ASCII(unicode))
2246 return 127;
2247
Victor Stinnerece58de2012-04-23 23:36:38 +02002248 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002249 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002250 endptr = (char *)startptr + end * kind;
2251 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002252 switch(kind) {
2253 case PyUnicode_1BYTE_KIND:
2254 return ucs1lib_find_max_char(startptr, endptr);
2255 case PyUnicode_2BYTE_KIND:
2256 return ucs2lib_find_max_char(startptr, endptr);
2257 case PyUnicode_4BYTE_KIND:
2258 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002259 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002260 assert(0);
2261 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002262 }
2263}
2264
Victor Stinner25a4b292011-10-06 12:31:55 +02002265/* Ensure that a string uses the most efficient storage, if it is not the
2266 case: create a new string with of the right kind. Write NULL into *p_unicode
2267 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002268static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002269unicode_adjust_maxchar(PyObject **p_unicode)
2270{
2271 PyObject *unicode, *copy;
2272 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002273 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002274 unsigned int kind;
2275
2276 assert(p_unicode != NULL);
2277 unicode = *p_unicode;
2278 assert(PyUnicode_IS_READY(unicode));
2279 if (PyUnicode_IS_ASCII(unicode))
2280 return;
2281
2282 len = PyUnicode_GET_LENGTH(unicode);
2283 kind = PyUnicode_KIND(unicode);
2284 if (kind == PyUnicode_1BYTE_KIND) {
2285 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002286 max_char = ucs1lib_find_max_char(u, u + len);
2287 if (max_char >= 128)
2288 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002289 }
2290 else if (kind == PyUnicode_2BYTE_KIND) {
2291 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002292 max_char = ucs2lib_find_max_char(u, u + len);
2293 if (max_char >= 256)
2294 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002295 }
2296 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002297 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002298 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002299 max_char = ucs4lib_find_max_char(u, u + len);
2300 if (max_char >= 0x10000)
2301 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002302 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002303 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002304 if (copy != NULL)
2305 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002306 Py_DECREF(unicode);
2307 *p_unicode = copy;
2308}
2309
Victor Stinner034f6cf2011-09-30 02:26:44 +02002310PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002311_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002312{
Victor Stinner87af4f22011-11-21 23:03:47 +01002313 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002314 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002315
Victor Stinner034f6cf2011-09-30 02:26:44 +02002316 if (!PyUnicode_Check(unicode)) {
2317 PyErr_BadInternalCall();
2318 return NULL;
2319 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002320 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002321 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002322
Victor Stinner87af4f22011-11-21 23:03:47 +01002323 length = PyUnicode_GET_LENGTH(unicode);
2324 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002325 if (!copy)
2326 return NULL;
2327 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2328
Victor Stinner87af4f22011-11-21 23:03:47 +01002329 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2330 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002331 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002332 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002333}
2334
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002335
Victor Stinnerbc603d12011-10-02 01:00:40 +02002336/* Widen Unicode objects to larger buffers. Don't write terminating null
2337 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002338
2339void*
2340_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2341{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002342 Py_ssize_t len;
2343 void *result;
2344 unsigned int skind;
2345
Benjamin Petersonbac79492012-01-14 13:34:47 -05002346 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002347 return NULL;
2348
2349 len = PyUnicode_GET_LENGTH(s);
2350 skind = PyUnicode_KIND(s);
2351 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002352 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002353 return NULL;
2354 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002355 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002356 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002357 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002358 if (!result)
2359 return PyErr_NoMemory();
2360 assert(skind == PyUnicode_1BYTE_KIND);
2361 _PyUnicode_CONVERT_BYTES(
2362 Py_UCS1, Py_UCS2,
2363 PyUnicode_1BYTE_DATA(s),
2364 PyUnicode_1BYTE_DATA(s) + len,
2365 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002366 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002367 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002368 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002369 if (!result)
2370 return PyErr_NoMemory();
2371 if (skind == PyUnicode_2BYTE_KIND) {
2372 _PyUnicode_CONVERT_BYTES(
2373 Py_UCS2, Py_UCS4,
2374 PyUnicode_2BYTE_DATA(s),
2375 PyUnicode_2BYTE_DATA(s) + len,
2376 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002377 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002378 else {
2379 assert(skind == PyUnicode_1BYTE_KIND);
2380 _PyUnicode_CONVERT_BYTES(
2381 Py_UCS1, Py_UCS4,
2382 PyUnicode_1BYTE_DATA(s),
2383 PyUnicode_1BYTE_DATA(s) + len,
2384 result);
2385 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002386 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002387 default:
2388 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002389 }
Victor Stinner01698042011-10-04 00:04:26 +02002390 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002391 return NULL;
2392}
2393
2394static Py_UCS4*
2395as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2396 int copy_null)
2397{
2398 int kind;
2399 void *data;
2400 Py_ssize_t len, targetlen;
2401 if (PyUnicode_READY(string) == -1)
2402 return NULL;
2403 kind = PyUnicode_KIND(string);
2404 data = PyUnicode_DATA(string);
2405 len = PyUnicode_GET_LENGTH(string);
2406 targetlen = len;
2407 if (copy_null)
2408 targetlen++;
2409 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002410 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002411 if (!target) {
2412 PyErr_NoMemory();
2413 return NULL;
2414 }
2415 }
2416 else {
2417 if (targetsize < targetlen) {
2418 PyErr_Format(PyExc_SystemError,
2419 "string is longer than the buffer");
2420 if (copy_null && 0 < targetsize)
2421 target[0] = 0;
2422 return NULL;
2423 }
2424 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002425 if (kind == PyUnicode_1BYTE_KIND) {
2426 Py_UCS1 *start = (Py_UCS1 *) data;
2427 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002428 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002429 else if (kind == PyUnicode_2BYTE_KIND) {
2430 Py_UCS2 *start = (Py_UCS2 *) data;
2431 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2432 }
2433 else {
2434 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002435 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002436 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002437 if (copy_null)
2438 target[len] = 0;
2439 return target;
2440}
2441
2442Py_UCS4*
2443PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2444 int copy_null)
2445{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002446 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002447 PyErr_BadInternalCall();
2448 return NULL;
2449 }
2450 return as_ucs4(string, target, targetsize, copy_null);
2451}
2452
2453Py_UCS4*
2454PyUnicode_AsUCS4Copy(PyObject *string)
2455{
2456 return as_ucs4(string, NULL, 0, 1);
2457}
2458
2459#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002460
Alexander Belopolsky40018472011-02-26 01:02:56 +00002461PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002462PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002463{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002464 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002465 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002466 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002467 PyErr_BadInternalCall();
2468 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002469 }
2470
Martin v. Löwis790465f2008-04-05 20:41:37 +00002471 if (size == -1) {
2472 size = wcslen(w);
2473 }
2474
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002475 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002476}
2477
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002478#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002479
Victor Stinner15a11362012-10-06 23:48:20 +02002480/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002481 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2482 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2483#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002484
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002485static int
2486unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2487 Py_ssize_t width, Py_ssize_t precision)
2488{
2489 Py_ssize_t length, fill, arglen;
2490 Py_UCS4 maxchar;
2491
2492 if (PyUnicode_READY(str) == -1)
2493 return -1;
2494
2495 length = PyUnicode_GET_LENGTH(str);
2496 if ((precision == -1 || precision >= length)
2497 && width <= length)
2498 return _PyUnicodeWriter_WriteStr(writer, str);
2499
2500 if (precision != -1)
2501 length = Py_MIN(precision, length);
2502
2503 arglen = Py_MAX(length, width);
2504 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2505 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2506 else
2507 maxchar = writer->maxchar;
2508
2509 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2510 return -1;
2511
2512 if (width > length) {
2513 fill = width - length;
2514 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2515 return -1;
2516 writer->pos += fill;
2517 }
2518
2519 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2520 str, 0, length);
2521 writer->pos += length;
2522 return 0;
2523}
2524
2525static int
2526unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2527 Py_ssize_t width, Py_ssize_t precision)
2528{
2529 /* UTF-8 */
2530 Py_ssize_t length;
2531 PyObject *unicode;
2532 int res;
2533
2534 length = strlen(str);
2535 if (precision != -1)
2536 length = Py_MIN(length, precision);
2537 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2538 if (unicode == NULL)
2539 return -1;
2540
2541 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2542 Py_DECREF(unicode);
2543 return res;
2544}
2545
Victor Stinner96865452011-03-01 23:44:09 +00002546static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002547unicode_fromformat_arg(_PyUnicodeWriter *writer,
2548 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002549{
Victor Stinnere215d962012-10-06 23:03:36 +02002550 const char *p;
2551 Py_ssize_t len;
2552 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002553 Py_ssize_t width;
2554 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002555 int longflag;
2556 int longlongflag;
2557 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002558 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002559
2560 p = f;
2561 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002562 zeropad = 0;
2563 if (*f == '0') {
2564 zeropad = 1;
2565 f++;
2566 }
Victor Stinner96865452011-03-01 23:44:09 +00002567
2568 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002569 width = -1;
2570 if (Py_ISDIGIT((unsigned)*f)) {
2571 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002572 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002573 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002574 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002575 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002576 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002577 return NULL;
2578 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002579 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002580 f++;
2581 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002582 }
2583 precision = -1;
2584 if (*f == '.') {
2585 f++;
2586 if (Py_ISDIGIT((unsigned)*f)) {
2587 precision = (*f - '0');
2588 f++;
2589 while (Py_ISDIGIT((unsigned)*f)) {
2590 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2591 PyErr_SetString(PyExc_ValueError,
2592 "precision too big");
2593 return NULL;
2594 }
2595 precision = (precision * 10) + (*f - '0');
2596 f++;
2597 }
2598 }
Victor Stinner96865452011-03-01 23:44:09 +00002599 if (*f == '%') {
2600 /* "%.3%s" => f points to "3" */
2601 f--;
2602 }
2603 }
2604 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002605 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002606 f--;
2607 }
Victor Stinner96865452011-03-01 23:44:09 +00002608
2609 /* Handle %ld, %lu, %lld and %llu. */
2610 longflag = 0;
2611 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002612 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002613 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002614 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002615 longflag = 1;
2616 ++f;
2617 }
2618#ifdef HAVE_LONG_LONG
2619 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002620 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002621 longlongflag = 1;
2622 f += 2;
2623 }
2624#endif
2625 }
2626 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002627 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002628 size_tflag = 1;
2629 ++f;
2630 }
Victor Stinnere215d962012-10-06 23:03:36 +02002631
2632 if (f[1] == '\0')
2633 writer->overallocate = 0;
2634
2635 switch (*f) {
2636 case 'c':
2637 {
2638 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002639 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002640 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002641 "character argument not in range(0x110000)");
2642 return NULL;
2643 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002644 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002645 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002646 break;
2647 }
2648
2649 case 'i':
2650 case 'd':
2651 case 'u':
2652 case 'x':
2653 {
2654 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002655 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002656 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002657
2658 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002659 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002660 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002661 va_arg(*vargs, unsigned long));
2662#ifdef HAVE_LONG_LONG
2663 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002664 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002665 va_arg(*vargs, unsigned PY_LONG_LONG));
2666#endif
2667 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002668 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002669 va_arg(*vargs, size_t));
2670 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002671 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002672 va_arg(*vargs, unsigned int));
2673 }
2674 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002675 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002676 }
2677 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002678 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002679 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002680 va_arg(*vargs, long));
2681#ifdef HAVE_LONG_LONG
2682 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002683 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002684 va_arg(*vargs, PY_LONG_LONG));
2685#endif
2686 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002687 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002688 va_arg(*vargs, Py_ssize_t));
2689 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002690 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002691 va_arg(*vargs, int));
2692 }
2693 assert(len >= 0);
2694
Victor Stinnere215d962012-10-06 23:03:36 +02002695 if (precision < len)
2696 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002697
2698 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002699 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2700 return NULL;
2701
Victor Stinnere215d962012-10-06 23:03:36 +02002702 if (width > precision) {
2703 Py_UCS4 fillchar;
2704 fill = width - precision;
2705 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002706 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2707 return NULL;
2708 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002709 }
Victor Stinner15a11362012-10-06 23:48:20 +02002710 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002711 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002712 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2713 return NULL;
2714 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002715 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002716
Victor Stinner4a587072013-11-19 12:54:53 +01002717 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2718 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002719 break;
2720 }
2721
2722 case 'p':
2723 {
2724 char number[MAX_LONG_LONG_CHARS];
2725
2726 len = sprintf(number, "%p", va_arg(*vargs, void*));
2727 assert(len >= 0);
2728
2729 /* %p is ill-defined: ensure leading 0x. */
2730 if (number[1] == 'X')
2731 number[1] = 'x';
2732 else if (number[1] != 'x') {
2733 memmove(number + 2, number,
2734 strlen(number) + 1);
2735 number[0] = '0';
2736 number[1] = 'x';
2737 len += 2;
2738 }
2739
Victor Stinner4a587072013-11-19 12:54:53 +01002740 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002741 return NULL;
2742 break;
2743 }
2744
2745 case 's':
2746 {
2747 /* UTF-8 */
2748 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002749 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002750 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002751 break;
2752 }
2753
2754 case 'U':
2755 {
2756 PyObject *obj = va_arg(*vargs, PyObject *);
2757 assert(obj && _PyUnicode_CHECK(obj));
2758
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002759 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002760 return NULL;
2761 break;
2762 }
2763
2764 case 'V':
2765 {
2766 PyObject *obj = va_arg(*vargs, PyObject *);
2767 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002768 if (obj) {
2769 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002770 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002771 return NULL;
2772 }
2773 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002774 assert(str != NULL);
2775 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002776 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002777 }
2778 break;
2779 }
2780
2781 case 'S':
2782 {
2783 PyObject *obj = va_arg(*vargs, PyObject *);
2784 PyObject *str;
2785 assert(obj);
2786 str = PyObject_Str(obj);
2787 if (!str)
2788 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002789 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002790 Py_DECREF(str);
2791 return NULL;
2792 }
2793 Py_DECREF(str);
2794 break;
2795 }
2796
2797 case 'R':
2798 {
2799 PyObject *obj = va_arg(*vargs, PyObject *);
2800 PyObject *repr;
2801 assert(obj);
2802 repr = PyObject_Repr(obj);
2803 if (!repr)
2804 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002805 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002806 Py_DECREF(repr);
2807 return NULL;
2808 }
2809 Py_DECREF(repr);
2810 break;
2811 }
2812
2813 case 'A':
2814 {
2815 PyObject *obj = va_arg(*vargs, PyObject *);
2816 PyObject *ascii;
2817 assert(obj);
2818 ascii = PyObject_ASCII(obj);
2819 if (!ascii)
2820 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002821 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002822 Py_DECREF(ascii);
2823 return NULL;
2824 }
2825 Py_DECREF(ascii);
2826 break;
2827 }
2828
2829 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002830 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002831 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002832 break;
2833
2834 default:
2835 /* if we stumble upon an unknown formatting code, copy the rest
2836 of the format string to the output string. (we cannot just
2837 skip the code, since there's no way to know what's in the
2838 argument list) */
2839 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002840 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002841 return NULL;
2842 f = p+len;
2843 return f;
2844 }
2845
2846 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002847 return f;
2848}
2849
Walter Dörwaldd2034312007-05-18 16:29:38 +00002850PyObject *
2851PyUnicode_FromFormatV(const char *format, va_list vargs)
2852{
Victor Stinnere215d962012-10-06 23:03:36 +02002853 va_list vargs2;
2854 const char *f;
2855 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002856
Victor Stinner8f674cc2013-04-17 23:02:17 +02002857 _PyUnicodeWriter_Init(&writer);
2858 writer.min_length = strlen(format) + 100;
2859 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002860
2861 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2862 Copy it to be able to pass a reference to a subfunction. */
2863 Py_VA_COPY(vargs2, vargs);
2864
2865 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002866 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002867 f = unicode_fromformat_arg(&writer, f, &vargs2);
2868 if (f == NULL)
2869 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002870 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002871 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002872 const char *p;
2873 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002874
Victor Stinnere215d962012-10-06 23:03:36 +02002875 p = f;
2876 do
2877 {
2878 if ((unsigned char)*p > 127) {
2879 PyErr_Format(PyExc_ValueError,
2880 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2881 "string, got a non-ASCII byte: 0x%02x",
2882 (unsigned char)*p);
2883 return NULL;
2884 }
2885 p++;
2886 }
2887 while (*p != '\0' && *p != '%');
2888 len = p - f;
2889
2890 if (*p == '\0')
2891 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002892
2893 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002894 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002895
2896 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002897 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002898 }
Victor Stinnere215d962012-10-06 23:03:36 +02002899 return _PyUnicodeWriter_Finish(&writer);
2900
2901 fail:
2902 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002903 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002904}
2905
Walter Dörwaldd2034312007-05-18 16:29:38 +00002906PyObject *
2907PyUnicode_FromFormat(const char *format, ...)
2908{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002909 PyObject* ret;
2910 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002911
2912#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002913 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002914#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002915 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002916#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002917 ret = PyUnicode_FromFormatV(format, vargs);
2918 va_end(vargs);
2919 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002920}
2921
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002922#ifdef HAVE_WCHAR_H
2923
Victor Stinner5593d8a2010-10-02 11:11:27 +00002924/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2925 convert a Unicode object to a wide character string.
2926
Victor Stinnerd88d9832011-09-06 02:00:05 +02002927 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002928 character) required to convert the unicode object. Ignore size argument.
2929
Victor Stinnerd88d9832011-09-06 02:00:05 +02002930 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002931 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002932 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002933static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002934unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002935 wchar_t *w,
2936 Py_ssize_t size)
2937{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002938 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002939 const wchar_t *wstr;
2940
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002941 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002942 if (wstr == NULL)
2943 return -1;
2944
Victor Stinner5593d8a2010-10-02 11:11:27 +00002945 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002946 if (size > res)
2947 size = res + 1;
2948 else
2949 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002950 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002951 return res;
2952 }
2953 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002954 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002955}
2956
2957Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002958PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002959 wchar_t *w,
2960 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002961{
2962 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002963 PyErr_BadInternalCall();
2964 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002965 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002966 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002967}
2968
Victor Stinner137c34c2010-09-29 10:25:54 +00002969wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002970PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002971 Py_ssize_t *size)
2972{
2973 wchar_t* buffer;
2974 Py_ssize_t buflen;
2975
2976 if (unicode == NULL) {
2977 PyErr_BadInternalCall();
2978 return NULL;
2979 }
2980
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002981 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002982 if (buflen == -1)
2983 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002984 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00002985 if (buffer == NULL) {
2986 PyErr_NoMemory();
2987 return NULL;
2988 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002989 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002990 if (buflen == -1) {
2991 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002992 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002993 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002994 if (size != NULL)
2995 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002996 return buffer;
2997}
2998
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002999#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003000
Alexander Belopolsky40018472011-02-26 01:02:56 +00003001PyObject *
3002PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003003{
Victor Stinner8faf8212011-12-08 22:14:11 +01003004 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003005 PyErr_SetString(PyExc_ValueError,
3006 "chr() arg not in range(0x110000)");
3007 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003008 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003009
Victor Stinner985a82a2014-01-03 12:53:47 +01003010 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003011}
3012
Alexander Belopolsky40018472011-02-26 01:02:56 +00003013PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003014PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003015{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003016 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003017 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003018 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003019 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003020 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003021 Py_INCREF(obj);
3022 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003023 }
3024 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003025 /* For a Unicode subtype that's not a Unicode object,
3026 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003027 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003028 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003029 PyErr_Format(PyExc_TypeError,
3030 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003031 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003032 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003033}
3034
Alexander Belopolsky40018472011-02-26 01:02:56 +00003035PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003036PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003037 const char *encoding,
3038 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003039{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003040 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003041 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003042
Guido van Rossumd57fd912000-03-10 22:53:23 +00003043 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003044 PyErr_BadInternalCall();
3045 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003046 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003047
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003048 /* Decoding bytes objects is the most common case and should be fast */
3049 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003050 if (PyBytes_GET_SIZE(obj) == 0)
3051 _Py_RETURN_UNICODE_EMPTY();
3052 v = PyUnicode_Decode(
3053 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3054 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003055 return v;
3056 }
3057
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003058 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003059 PyErr_SetString(PyExc_TypeError,
3060 "decoding str is not supported");
3061 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003062 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003063
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003064 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3065 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3066 PyErr_Format(PyExc_TypeError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02003067 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003068 Py_TYPE(obj)->tp_name);
3069 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003070 }
Tim Petersced69f82003-09-16 20:30:58 +00003071
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003072 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003073 PyBuffer_Release(&buffer);
3074 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003075 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003076
Serhiy Storchaka05997252013-01-26 12:14:02 +02003077 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003078 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003079 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003080}
3081
Victor Stinner600d3be2010-06-10 12:00:55 +00003082/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00003083 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
3084 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003085int
3086_Py_normalize_encoding(const char *encoding,
3087 char *lower,
3088 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003089{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003090 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003091 char *l;
3092 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003093
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003094 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01003095 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01003096 if (lower_len < 6)
3097 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003098 strcpy(lower, "utf-8");
3099 return 1;
3100 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003101 e = encoding;
3102 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003103 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003104 while (*e) {
3105 if (l == l_end)
3106 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003107 if (Py_ISUPPER(*e)) {
3108 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003109 }
3110 else if (*e == '_') {
3111 *l++ = '-';
3112 e++;
3113 }
3114 else {
3115 *l++ = *e++;
3116 }
3117 }
3118 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003119 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003120}
3121
Alexander Belopolsky40018472011-02-26 01:02:56 +00003122PyObject *
3123PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003124 Py_ssize_t size,
3125 const char *encoding,
3126 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003127{
3128 PyObject *buffer = NULL, *unicode;
3129 Py_buffer info;
3130 char lower[11]; /* Enough for any encoding shortcut */
3131
Fred Drakee4315f52000-05-09 19:53:39 +00003132 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003133 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003134 if ((strcmp(lower, "utf-8") == 0) ||
3135 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003136 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003137 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003138 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003139 (strcmp(lower, "iso-8859-1") == 0) ||
3140 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003141 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003142#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003143 else if (strcmp(lower, "mbcs") == 0)
3144 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003145#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003146 else if (strcmp(lower, "ascii") == 0)
3147 return PyUnicode_DecodeASCII(s, size, errors);
3148 else if (strcmp(lower, "utf-16") == 0)
3149 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3150 else if (strcmp(lower, "utf-32") == 0)
3151 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3152 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003153
3154 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003155 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003156 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003157 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003158 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003159 if (buffer == NULL)
3160 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003161 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003162 if (unicode == NULL)
3163 goto onError;
3164 if (!PyUnicode_Check(unicode)) {
3165 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003166 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3167 "use codecs.decode() to decode to arbitrary types",
3168 encoding,
3169 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003170 Py_DECREF(unicode);
3171 goto onError;
3172 }
3173 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003174 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003175
Benjamin Peterson29060642009-01-31 22:14:21 +00003176 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003177 Py_XDECREF(buffer);
3178 return NULL;
3179}
3180
Alexander Belopolsky40018472011-02-26 01:02:56 +00003181PyObject *
3182PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003183 const char *encoding,
3184 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003185{
3186 PyObject *v;
3187
3188 if (!PyUnicode_Check(unicode)) {
3189 PyErr_BadArgument();
3190 goto onError;
3191 }
3192
3193 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003194 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003195
3196 /* Decode via the codec registry */
3197 v = PyCodec_Decode(unicode, encoding, errors);
3198 if (v == NULL)
3199 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003200 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003201
Benjamin Peterson29060642009-01-31 22:14:21 +00003202 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003203 return NULL;
3204}
3205
Alexander Belopolsky40018472011-02-26 01:02:56 +00003206PyObject *
3207PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003208 const char *encoding,
3209 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003210{
3211 PyObject *v;
3212
3213 if (!PyUnicode_Check(unicode)) {
3214 PyErr_BadArgument();
3215 goto onError;
3216 }
3217
3218 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003219 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003220
3221 /* Decode via the codec registry */
3222 v = PyCodec_Decode(unicode, encoding, errors);
3223 if (v == NULL)
3224 goto onError;
3225 if (!PyUnicode_Check(v)) {
3226 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003227 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3228 "use codecs.decode() to decode to arbitrary types",
3229 encoding,
3230 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003231 Py_DECREF(v);
3232 goto onError;
3233 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003234 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003235
Benjamin Peterson29060642009-01-31 22:14:21 +00003236 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003237 return NULL;
3238}
3239
Alexander Belopolsky40018472011-02-26 01:02:56 +00003240PyObject *
3241PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003242 Py_ssize_t size,
3243 const char *encoding,
3244 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003245{
3246 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003247
Guido van Rossumd57fd912000-03-10 22:53:23 +00003248 unicode = PyUnicode_FromUnicode(s, size);
3249 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003250 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003251 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3252 Py_DECREF(unicode);
3253 return v;
3254}
3255
Alexander Belopolsky40018472011-02-26 01:02:56 +00003256PyObject *
3257PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003258 const char *encoding,
3259 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003260{
3261 PyObject *v;
3262
3263 if (!PyUnicode_Check(unicode)) {
3264 PyErr_BadArgument();
3265 goto onError;
3266 }
3267
3268 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003269 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003270
3271 /* Encode via the codec registry */
3272 v = PyCodec_Encode(unicode, encoding, errors);
3273 if (v == NULL)
3274 goto onError;
3275 return v;
3276
Benjamin Peterson29060642009-01-31 22:14:21 +00003277 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003278 return NULL;
3279}
3280
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003281static size_t
3282wcstombs_errorpos(const wchar_t *wstr)
3283{
3284 size_t len;
3285#if SIZEOF_WCHAR_T == 2
3286 wchar_t buf[3];
3287#else
3288 wchar_t buf[2];
3289#endif
3290 char outbuf[MB_LEN_MAX];
3291 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003292
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003293#if SIZEOF_WCHAR_T == 2
3294 buf[2] = 0;
3295#else
3296 buf[1] = 0;
3297#endif
3298 start = wstr;
3299 while (*wstr != L'\0')
3300 {
3301 previous = wstr;
3302#if SIZEOF_WCHAR_T == 2
3303 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3304 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3305 {
3306 buf[0] = wstr[0];
3307 buf[1] = wstr[1];
3308 wstr += 2;
3309 }
3310 else {
3311 buf[0] = *wstr;
3312 buf[1] = 0;
3313 wstr++;
3314 }
3315#else
3316 buf[0] = *wstr;
3317 wstr++;
3318#endif
3319 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003320 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003321 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003322 }
3323
3324 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003325 return 0;
3326}
3327
Victor Stinner1b579672011-12-17 05:47:23 +01003328static int
3329locale_error_handler(const char *errors, int *surrogateescape)
3330{
Victor Stinner50149202015-09-22 00:26:54 +02003331 _Py_error_handler error_handler = get_error_handler(errors);
3332 switch (error_handler)
3333 {
3334 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003335 *surrogateescape = 0;
3336 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003337 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003338 *surrogateescape = 1;
3339 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003340 default:
3341 PyErr_Format(PyExc_ValueError,
3342 "only 'strict' and 'surrogateescape' error handlers "
3343 "are supported, not '%s'",
3344 errors);
3345 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003346 }
Victor Stinner1b579672011-12-17 05:47:23 +01003347}
3348
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003349PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003350PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003351{
3352 Py_ssize_t wlen, wlen2;
3353 wchar_t *wstr;
3354 PyObject *bytes = NULL;
3355 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003356 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003357 PyObject *exc;
3358 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003359 int surrogateescape;
3360
3361 if (locale_error_handler(errors, &surrogateescape) < 0)
3362 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003363
3364 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3365 if (wstr == NULL)
3366 return NULL;
3367
3368 wlen2 = wcslen(wstr);
3369 if (wlen2 != wlen) {
3370 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003371 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003372 return NULL;
3373 }
3374
3375 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003376 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003377 char *str;
3378
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003379 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003380 if (str == NULL) {
3381 if (error_pos == (size_t)-1) {
3382 PyErr_NoMemory();
3383 PyMem_Free(wstr);
3384 return NULL;
3385 }
3386 else {
3387 goto encode_error;
3388 }
3389 }
3390 PyMem_Free(wstr);
3391
3392 bytes = PyBytes_FromString(str);
3393 PyMem_Free(str);
3394 }
3395 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003396 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003397 size_t len, len2;
3398
3399 len = wcstombs(NULL, wstr, 0);
3400 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003401 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003402 goto encode_error;
3403 }
3404
3405 bytes = PyBytes_FromStringAndSize(NULL, len);
3406 if (bytes == NULL) {
3407 PyMem_Free(wstr);
3408 return NULL;
3409 }
3410
3411 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3412 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003413 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003414 goto encode_error;
3415 }
3416 PyMem_Free(wstr);
3417 }
3418 return bytes;
3419
3420encode_error:
3421 errmsg = strerror(errno);
3422 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003423
3424 if (error_pos == (size_t)-1)
3425 error_pos = wcstombs_errorpos(wstr);
3426
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003427 PyMem_Free(wstr);
3428 Py_XDECREF(bytes);
3429
Victor Stinner2f197072011-12-17 07:08:30 +01003430 if (errmsg != NULL) {
3431 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003432 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003433 if (wstr != NULL) {
3434 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003435 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003436 } else
3437 errmsg = NULL;
3438 }
3439 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003440 reason = PyUnicode_FromString(
3441 "wcstombs() encountered an unencodable "
3442 "wide character");
3443 if (reason == NULL)
3444 return NULL;
3445
3446 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3447 "locale", unicode,
3448 (Py_ssize_t)error_pos,
3449 (Py_ssize_t)(error_pos+1),
3450 reason);
3451 Py_DECREF(reason);
3452 if (exc != NULL) {
3453 PyCodec_StrictErrors(exc);
3454 Py_XDECREF(exc);
3455 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003456 return NULL;
3457}
3458
Victor Stinnerad158722010-10-27 00:25:46 +00003459PyObject *
3460PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003461{
Victor Stinner99b95382011-07-04 14:23:54 +02003462#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003463 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003464#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003465 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003466#else
Victor Stinner793b5312011-04-27 00:24:21 +02003467 PyInterpreterState *interp = PyThreadState_GET()->interp;
3468 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3469 cannot use it to encode and decode filenames before it is loaded. Load
3470 the Python codec requires to encode at least its own filename. Use the C
3471 version of the locale codec until the codec registry is initialized and
3472 the Python codec is loaded.
3473
3474 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3475 cannot only rely on it: check also interp->fscodec_initialized for
3476 subinterpreters. */
3477 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003478 return PyUnicode_AsEncodedString(unicode,
3479 Py_FileSystemDefaultEncoding,
3480 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003481 }
3482 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003483 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003484 }
Victor Stinnerad158722010-10-27 00:25:46 +00003485#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003486}
3487
Alexander Belopolsky40018472011-02-26 01:02:56 +00003488PyObject *
3489PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003490 const char *encoding,
3491 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003492{
3493 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003494 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003495
Guido van Rossumd57fd912000-03-10 22:53:23 +00003496 if (!PyUnicode_Check(unicode)) {
3497 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003498 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003499 }
Fred Drakee4315f52000-05-09 19:53:39 +00003500
Fred Drakee4315f52000-05-09 19:53:39 +00003501 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003502 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003503 if ((strcmp(lower, "utf-8") == 0) ||
3504 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003505 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003506 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003507 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003508 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003509 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003510 }
Victor Stinner37296e82010-06-10 13:36:23 +00003511 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003512 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003513 (strcmp(lower, "iso-8859-1") == 0) ||
3514 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003515 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003516#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003517 else if (strcmp(lower, "mbcs") == 0)
3518 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003519#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003520 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003521 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003522 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003523
3524 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003525 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003526 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003527 return NULL;
3528
3529 /* The normal path */
3530 if (PyBytes_Check(v))
3531 return v;
3532
3533 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003534 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003535 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003536 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003537
3538 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003539 "encoder %s returned bytearray instead of bytes; "
3540 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003541 encoding);
3542 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003543 Py_DECREF(v);
3544 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003545 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003546
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003547 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3548 Py_DECREF(v);
3549 return b;
3550 }
3551
3552 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003553 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3554 "use codecs.encode() to encode to arbitrary types",
3555 encoding,
3556 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003557 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003558 return NULL;
3559}
3560
Alexander Belopolsky40018472011-02-26 01:02:56 +00003561PyObject *
3562PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003563 const char *encoding,
3564 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003565{
3566 PyObject *v;
3567
3568 if (!PyUnicode_Check(unicode)) {
3569 PyErr_BadArgument();
3570 goto onError;
3571 }
3572
3573 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003574 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003575
3576 /* Encode via the codec registry */
3577 v = PyCodec_Encode(unicode, encoding, errors);
3578 if (v == NULL)
3579 goto onError;
3580 if (!PyUnicode_Check(v)) {
3581 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003582 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3583 "use codecs.encode() to encode to arbitrary types",
3584 encoding,
3585 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003586 Py_DECREF(v);
3587 goto onError;
3588 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003589 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003590
Benjamin Peterson29060642009-01-31 22:14:21 +00003591 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003592 return NULL;
3593}
3594
Victor Stinner2f197072011-12-17 07:08:30 +01003595static size_t
3596mbstowcs_errorpos(const char *str, size_t len)
3597{
3598#ifdef HAVE_MBRTOWC
3599 const char *start = str;
3600 mbstate_t mbs;
3601 size_t converted;
3602 wchar_t ch;
3603
3604 memset(&mbs, 0, sizeof mbs);
3605 while (len)
3606 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003607 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003608 if (converted == 0)
3609 /* Reached end of string */
3610 break;
3611 if (converted == (size_t)-1 || converted == (size_t)-2) {
3612 /* Conversion error or incomplete character */
3613 return str - start;
3614 }
3615 else {
3616 str += converted;
3617 len -= converted;
3618 }
3619 }
3620 /* failed to find the undecodable byte sequence */
3621 return 0;
3622#endif
3623 return 0;
3624}
3625
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003626PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003627PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003628 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003629{
3630 wchar_t smallbuf[256];
3631 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3632 wchar_t *wstr;
3633 size_t wlen, wlen2;
3634 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003635 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003636 size_t error_pos;
3637 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003638 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3639 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003640
3641 if (locale_error_handler(errors, &surrogateescape) < 0)
3642 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003643
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003644 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3645 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003646 return NULL;
3647 }
3648
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003649 if (surrogateescape) {
3650 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003651 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003652 if (wstr == NULL) {
3653 if (wlen == (size_t)-1)
3654 PyErr_NoMemory();
3655 else
3656 PyErr_SetFromErrno(PyExc_OSError);
3657 return NULL;
3658 }
3659
3660 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003661 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003662 }
3663 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003664 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003665#ifndef HAVE_BROKEN_MBSTOWCS
3666 wlen = mbstowcs(NULL, str, 0);
3667#else
3668 wlen = len;
3669#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003670 if (wlen == (size_t)-1)
3671 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003672 if (wlen+1 <= smallbuf_len) {
3673 wstr = smallbuf;
3674 }
3675 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003676 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003677 if (!wstr)
3678 return PyErr_NoMemory();
3679 }
3680
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003681 wlen2 = mbstowcs(wstr, str, wlen+1);
3682 if (wlen2 == (size_t)-1) {
3683 if (wstr != smallbuf)
3684 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003685 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003686 }
3687#ifdef HAVE_BROKEN_MBSTOWCS
3688 assert(wlen2 == wlen);
3689#endif
3690 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3691 if (wstr != smallbuf)
3692 PyMem_Free(wstr);
3693 }
3694 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003695
3696decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003697 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003698 errmsg = strerror(errno);
3699 assert(errmsg != NULL);
3700
3701 error_pos = mbstowcs_errorpos(str, len);
3702 if (errmsg != NULL) {
3703 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003704 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003705 if (wstr != NULL) {
3706 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003707 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003708 }
Victor Stinner2f197072011-12-17 07:08:30 +01003709 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003710 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003711 reason = PyUnicode_FromString(
3712 "mbstowcs() encountered an invalid multibyte sequence");
3713 if (reason == NULL)
3714 return NULL;
3715
3716 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3717 "locale", str, len,
3718 (Py_ssize_t)error_pos,
3719 (Py_ssize_t)(error_pos+1),
3720 reason);
3721 Py_DECREF(reason);
3722 if (exc != NULL) {
3723 PyCodec_StrictErrors(exc);
3724 Py_XDECREF(exc);
3725 }
3726 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003727}
3728
3729PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003730PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003731{
3732 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003733 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003734}
3735
3736
3737PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003738PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003739 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003740 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3741}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003742
Christian Heimes5894ba72007-11-04 11:43:14 +00003743PyObject*
3744PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3745{
Victor Stinner99b95382011-07-04 14:23:54 +02003746#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003747 return PyUnicode_DecodeMBCS(s, size, NULL);
3748#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003749 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003750#else
Victor Stinner793b5312011-04-27 00:24:21 +02003751 PyInterpreterState *interp = PyThreadState_GET()->interp;
3752 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3753 cannot use it to encode and decode filenames before it is loaded. Load
3754 the Python codec requires to encode at least its own filename. Use the C
3755 version of the locale codec until the codec registry is initialized and
3756 the Python codec is loaded.
3757
3758 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3759 cannot only rely on it: check also interp->fscodec_initialized for
3760 subinterpreters. */
3761 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003762 return PyUnicode_Decode(s, size,
3763 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003764 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003765 }
3766 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003767 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003768 }
Victor Stinnerad158722010-10-27 00:25:46 +00003769#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003770}
3771
Martin v. Löwis011e8422009-05-05 04:43:17 +00003772
3773int
3774PyUnicode_FSConverter(PyObject* arg, void* addr)
3775{
3776 PyObject *output = NULL;
3777 Py_ssize_t size;
3778 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003779 if (arg == NULL) {
3780 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003781 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003782 return 1;
3783 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003784 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003785 output = arg;
3786 Py_INCREF(output);
3787 }
3788 else {
3789 arg = PyUnicode_FromObject(arg);
3790 if (!arg)
3791 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003792 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003793 Py_DECREF(arg);
3794 if (!output)
3795 return 0;
3796 if (!PyBytes_Check(output)) {
3797 Py_DECREF(output);
3798 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3799 return 0;
3800 }
3801 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003802 size = PyBytes_GET_SIZE(output);
3803 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003804 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003805 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003806 Py_DECREF(output);
3807 return 0;
3808 }
3809 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003810 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003811}
3812
3813
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003814int
3815PyUnicode_FSDecoder(PyObject* arg, void* addr)
3816{
3817 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003818 if (arg == NULL) {
3819 Py_DECREF(*(PyObject**)addr);
3820 return 1;
3821 }
3822 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003823 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003824 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003825 output = arg;
3826 Py_INCREF(output);
3827 }
3828 else {
3829 arg = PyBytes_FromObject(arg);
3830 if (!arg)
3831 return 0;
3832 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3833 PyBytes_GET_SIZE(arg));
3834 Py_DECREF(arg);
3835 if (!output)
3836 return 0;
3837 if (!PyUnicode_Check(output)) {
3838 Py_DECREF(output);
3839 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3840 return 0;
3841 }
3842 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003843 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003844 Py_DECREF(output);
3845 return 0;
3846 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003847 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003848 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003849 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003850 Py_DECREF(output);
3851 return 0;
3852 }
3853 *(PyObject**)addr = output;
3854 return Py_CLEANUP_SUPPORTED;
3855}
3856
3857
Martin v. Löwis5b222132007-06-10 09:51:05 +00003858char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003859PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003860{
Christian Heimesf3863112007-11-22 07:46:41 +00003861 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003862
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003863 if (!PyUnicode_Check(unicode)) {
3864 PyErr_BadArgument();
3865 return NULL;
3866 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003867 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003868 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003869
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003870 if (PyUnicode_UTF8(unicode) == NULL) {
3871 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003872 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3873 if (bytes == NULL)
3874 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003875 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3876 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003877 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003878 Py_DECREF(bytes);
3879 return NULL;
3880 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003881 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3882 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3883 PyBytes_AS_STRING(bytes),
3884 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003885 Py_DECREF(bytes);
3886 }
3887
3888 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003889 *psize = PyUnicode_UTF8_LENGTH(unicode);
3890 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003891}
3892
3893char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003894PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003895{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003896 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3897}
3898
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003899Py_UNICODE *
3900PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3901{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003902 const unsigned char *one_byte;
3903#if SIZEOF_WCHAR_T == 4
3904 const Py_UCS2 *two_bytes;
3905#else
3906 const Py_UCS4 *four_bytes;
3907 const Py_UCS4 *ucs4_end;
3908 Py_ssize_t num_surrogates;
3909#endif
3910 wchar_t *w;
3911 wchar_t *wchar_end;
3912
3913 if (!PyUnicode_Check(unicode)) {
3914 PyErr_BadArgument();
3915 return NULL;
3916 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003917 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003918 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003919 assert(_PyUnicode_KIND(unicode) != 0);
3920 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003921
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003922 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003923#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003924 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3925 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926 num_surrogates = 0;
3927
3928 for (; four_bytes < ucs4_end; ++four_bytes) {
3929 if (*four_bytes > 0xFFFF)
3930 ++num_surrogates;
3931 }
3932
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003933 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3934 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3935 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003936 PyErr_NoMemory();
3937 return NULL;
3938 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003939 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003940
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003941 w = _PyUnicode_WSTR(unicode);
3942 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3943 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003944 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3945 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003946 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003947 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003948 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3949 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003950 }
3951 else
3952 *w = *four_bytes;
3953
3954 if (w > wchar_end) {
3955 assert(0 && "Miscalculated string end");
3956 }
3957 }
3958 *w = 0;
3959#else
3960 /* sizeof(wchar_t) == 4 */
3961 Py_FatalError("Impossible unicode object state, wstr and str "
3962 "should share memory already.");
3963 return NULL;
3964#endif
3965 }
3966 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003967 if ((size_t)_PyUnicode_LENGTH(unicode) >
3968 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3969 PyErr_NoMemory();
3970 return NULL;
3971 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003972 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3973 (_PyUnicode_LENGTH(unicode) + 1));
3974 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003975 PyErr_NoMemory();
3976 return NULL;
3977 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003978 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3979 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3980 w = _PyUnicode_WSTR(unicode);
3981 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003982
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003983 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3984 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003985 for (; w < wchar_end; ++one_byte, ++w)
3986 *w = *one_byte;
3987 /* null-terminate the wstr */
3988 *w = 0;
3989 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003990 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003991#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003992 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003993 for (; w < wchar_end; ++two_bytes, ++w)
3994 *w = *two_bytes;
3995 /* null-terminate the wstr */
3996 *w = 0;
3997#else
3998 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003999 PyObject_FREE(_PyUnicode_WSTR(unicode));
4000 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004001 Py_FatalError("Impossible unicode object state, wstr "
4002 "and str should share memory already.");
4003 return NULL;
4004#endif
4005 }
4006 else {
4007 assert(0 && "This should never happen.");
4008 }
4009 }
4010 }
4011 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004012 *size = PyUnicode_WSTR_LENGTH(unicode);
4013 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004014}
4015
Alexander Belopolsky40018472011-02-26 01:02:56 +00004016Py_UNICODE *
4017PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004018{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004019 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004020}
4021
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004022
Alexander Belopolsky40018472011-02-26 01:02:56 +00004023Py_ssize_t
4024PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004025{
4026 if (!PyUnicode_Check(unicode)) {
4027 PyErr_BadArgument();
4028 goto onError;
4029 }
4030 return PyUnicode_GET_SIZE(unicode);
4031
Benjamin Peterson29060642009-01-31 22:14:21 +00004032 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004033 return -1;
4034}
4035
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004036Py_ssize_t
4037PyUnicode_GetLength(PyObject *unicode)
4038{
Victor Stinner07621332012-06-16 04:53:46 +02004039 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004040 PyErr_BadArgument();
4041 return -1;
4042 }
Victor Stinner07621332012-06-16 04:53:46 +02004043 if (PyUnicode_READY(unicode) == -1)
4044 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004045 return PyUnicode_GET_LENGTH(unicode);
4046}
4047
4048Py_UCS4
4049PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4050{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004051 void *data;
4052 int kind;
4053
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004054 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4055 PyErr_BadArgument();
4056 return (Py_UCS4)-1;
4057 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004058 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004059 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004060 return (Py_UCS4)-1;
4061 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004062 data = PyUnicode_DATA(unicode);
4063 kind = PyUnicode_KIND(unicode);
4064 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004065}
4066
4067int
4068PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4069{
4070 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004071 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004072 return -1;
4073 }
Victor Stinner488fa492011-12-12 00:01:39 +01004074 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004075 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004076 PyErr_SetString(PyExc_IndexError, "string index out of range");
4077 return -1;
4078 }
Victor Stinner488fa492011-12-12 00:01:39 +01004079 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004080 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004081 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4082 PyErr_SetString(PyExc_ValueError, "character out of range");
4083 return -1;
4084 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004085 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4086 index, ch);
4087 return 0;
4088}
4089
Alexander Belopolsky40018472011-02-26 01:02:56 +00004090const char *
4091PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004092{
Victor Stinner42cb4622010-09-01 19:39:01 +00004093 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004094}
4095
Victor Stinner554f3f02010-06-16 23:33:54 +00004096/* create or adjust a UnicodeDecodeError */
4097static void
4098make_decode_exception(PyObject **exceptionObject,
4099 const char *encoding,
4100 const char *input, Py_ssize_t length,
4101 Py_ssize_t startpos, Py_ssize_t endpos,
4102 const char *reason)
4103{
4104 if (*exceptionObject == NULL) {
4105 *exceptionObject = PyUnicodeDecodeError_Create(
4106 encoding, input, length, startpos, endpos, reason);
4107 }
4108 else {
4109 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4110 goto onError;
4111 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4112 goto onError;
4113 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4114 goto onError;
4115 }
4116 return;
4117
4118onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004119 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004120}
4121
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004122#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004123/* error handling callback helper:
4124 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004125 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004126 and adjust various state variables.
4127 return 0 on success, -1 on error
4128*/
4129
Alexander Belopolsky40018472011-02-26 01:02:56 +00004130static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004131unicode_decode_call_errorhandler_wchar(
4132 const char *errors, PyObject **errorHandler,
4133 const char *encoding, const char *reason,
4134 const char **input, const char **inend, Py_ssize_t *startinpos,
4135 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4136 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004137{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004138 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004139
4140 PyObject *restuple = NULL;
4141 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004142 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004143 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004144 Py_ssize_t requiredsize;
4145 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004146 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004147 wchar_t *repwstr;
4148 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004149
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004150 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4151 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004152
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004153 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004154 *errorHandler = PyCodec_LookupError(errors);
4155 if (*errorHandler == NULL)
4156 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004157 }
4158
Victor Stinner554f3f02010-06-16 23:33:54 +00004159 make_decode_exception(exceptionObject,
4160 encoding,
4161 *input, *inend - *input,
4162 *startinpos, *endinpos,
4163 reason);
4164 if (*exceptionObject == NULL)
4165 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004166
4167 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4168 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004169 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004170 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004171 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004172 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004173 }
4174 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004175 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004176
4177 /* Copy back the bytes variables, which might have been modified by the
4178 callback */
4179 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4180 if (!inputobj)
4181 goto onError;
4182 if (!PyBytes_Check(inputobj)) {
4183 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4184 }
4185 *input = PyBytes_AS_STRING(inputobj);
4186 insize = PyBytes_GET_SIZE(inputobj);
4187 *inend = *input + insize;
4188 /* we can DECREF safely, as the exception has another reference,
4189 so the object won't go away. */
4190 Py_DECREF(inputobj);
4191
4192 if (newpos<0)
4193 newpos = insize+newpos;
4194 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004195 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004196 goto onError;
4197 }
4198
4199 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4200 if (repwstr == NULL)
4201 goto onError;
4202 /* need more space? (at least enough for what we
4203 have+the replacement+the rest of the string (starting
4204 at the new input position), so we won't have to check space
4205 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004206 requiredsize = *outpos;
4207 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4208 goto overflow;
4209 requiredsize += repwlen;
4210 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4211 goto overflow;
4212 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004213 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004214 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004215 requiredsize = 2*outsize;
4216 if (unicode_resize(output, requiredsize) < 0)
4217 goto onError;
4218 }
4219 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4220 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004221 *endinpos = newpos;
4222 *inptr = *input + newpos;
4223
4224 /* we made it! */
4225 Py_XDECREF(restuple);
4226 return 0;
4227
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004228 overflow:
4229 PyErr_SetString(PyExc_OverflowError,
4230 "decoded result is too long for a Python string");
4231
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004232 onError:
4233 Py_XDECREF(restuple);
4234 return -1;
4235}
4236#endif /* HAVE_MBCS */
4237
4238static int
4239unicode_decode_call_errorhandler_writer(
4240 const char *errors, PyObject **errorHandler,
4241 const char *encoding, const char *reason,
4242 const char **input, const char **inend, Py_ssize_t *startinpos,
4243 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4244 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4245{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004246 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004247
4248 PyObject *restuple = NULL;
4249 PyObject *repunicode = NULL;
4250 Py_ssize_t insize;
4251 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004252 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004253 PyObject *inputobj = NULL;
4254
4255 if (*errorHandler == NULL) {
4256 *errorHandler = PyCodec_LookupError(errors);
4257 if (*errorHandler == NULL)
4258 goto onError;
4259 }
4260
4261 make_decode_exception(exceptionObject,
4262 encoding,
4263 *input, *inend - *input,
4264 *startinpos, *endinpos,
4265 reason);
4266 if (*exceptionObject == NULL)
4267 goto onError;
4268
4269 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4270 if (restuple == NULL)
4271 goto onError;
4272 if (!PyTuple_Check(restuple)) {
4273 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4274 goto onError;
4275 }
4276 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004277 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004278
4279 /* Copy back the bytes variables, which might have been modified by the
4280 callback */
4281 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4282 if (!inputobj)
4283 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004284 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004285 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004286 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004287 *input = PyBytes_AS_STRING(inputobj);
4288 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004289 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004290 /* we can DECREF safely, as the exception has another reference,
4291 so the object won't go away. */
4292 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004293
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004294 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004295 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004296 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004297 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004298 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004299 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004300
Victor Stinner8f674cc2013-04-17 23:02:17 +02004301 if (PyUnicode_READY(repunicode) < 0)
4302 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004303 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004304 if (replen > 1) {
4305 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004306 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004307 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4308 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4309 goto onError;
4310 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004311 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004312 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004313
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004314 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004315 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004316
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004317 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004318 Py_XDECREF(restuple);
4319 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004320
Benjamin Peterson29060642009-01-31 22:14:21 +00004321 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004322 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004323 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004324}
4325
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004326/* --- UTF-7 Codec -------------------------------------------------------- */
4327
Antoine Pitrou244651a2009-05-04 18:56:13 +00004328/* See RFC2152 for details. We encode conservatively and decode liberally. */
4329
4330/* Three simple macros defining base-64. */
4331
4332/* Is c a base-64 character? */
4333
4334#define IS_BASE64(c) \
4335 (((c) >= 'A' && (c) <= 'Z') || \
4336 ((c) >= 'a' && (c) <= 'z') || \
4337 ((c) >= '0' && (c) <= '9') || \
4338 (c) == '+' || (c) == '/')
4339
4340/* given that c is a base-64 character, what is its base-64 value? */
4341
4342#define FROM_BASE64(c) \
4343 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4344 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4345 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4346 (c) == '+' ? 62 : 63)
4347
4348/* What is the base-64 character of the bottom 6 bits of n? */
4349
4350#define TO_BASE64(n) \
4351 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4352
4353/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4354 * decoded as itself. We are permissive on decoding; the only ASCII
4355 * byte not decoding to itself is the + which begins a base64
4356 * string. */
4357
4358#define DECODE_DIRECT(c) \
4359 ((c) <= 127 && (c) != '+')
4360
4361/* The UTF-7 encoder treats ASCII characters differently according to
4362 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4363 * the above). See RFC2152. This array identifies these different
4364 * sets:
4365 * 0 : "Set D"
4366 * alphanumeric and '(),-./:?
4367 * 1 : "Set O"
4368 * !"#$%&*;<=>@[]^_`{|}
4369 * 2 : "whitespace"
4370 * ht nl cr sp
4371 * 3 : special (must be base64 encoded)
4372 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4373 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004374
Tim Petersced69f82003-09-16 20:30:58 +00004375static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376char utf7_category[128] = {
4377/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4378 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4379/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4380 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4381/* sp ! " # $ % & ' ( ) * + , - . / */
4382 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4383/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4384 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4385/* @ A B C D E F G H I J K L M N O */
4386 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4387/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4388 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4389/* ` a b c d e f g h i j k l m n o */
4390 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4391/* p q r s t u v w x y z { | } ~ del */
4392 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004393};
4394
Antoine Pitrou244651a2009-05-04 18:56:13 +00004395/* ENCODE_DIRECT: this character should be encoded as itself. The
4396 * answer depends on whether we are encoding set O as itself, and also
4397 * on whether we are encoding whitespace as itself. RFC2152 makes it
4398 * clear that the answers to these questions vary between
4399 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004400
Antoine Pitrou244651a2009-05-04 18:56:13 +00004401#define ENCODE_DIRECT(c, directO, directWS) \
4402 ((c) < 128 && (c) > 0 && \
4403 ((utf7_category[(c)] == 0) || \
4404 (directWS && (utf7_category[(c)] == 2)) || \
4405 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004406
Alexander Belopolsky40018472011-02-26 01:02:56 +00004407PyObject *
4408PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004409 Py_ssize_t size,
4410 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004411{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004412 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4413}
4414
Antoine Pitrou244651a2009-05-04 18:56:13 +00004415/* The decoder. The only state we preserve is our read position,
4416 * i.e. how many characters we have consumed. So if we end in the
4417 * middle of a shift sequence we have to back off the read position
4418 * and the output to the beginning of the sequence, otherwise we lose
4419 * all the shift state (seen bits, number of bits seen, high
4420 * surrogate). */
4421
Alexander Belopolsky40018472011-02-26 01:02:56 +00004422PyObject *
4423PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004424 Py_ssize_t size,
4425 const char *errors,
4426 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004427{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004428 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004429 Py_ssize_t startinpos;
4430 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004431 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004432 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004433 const char *errmsg = "";
4434 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004435 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004436 unsigned int base64bits = 0;
4437 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004438 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004439 PyObject *errorHandler = NULL;
4440 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004441
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004442 if (size == 0) {
4443 if (consumed)
4444 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004445 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004446 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004447
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004448 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004449 _PyUnicodeWriter_Init(&writer);
4450 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004451
4452 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004453 e = s + size;
4454
4455 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004456 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004457 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004458 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004459
Antoine Pitrou244651a2009-05-04 18:56:13 +00004460 if (inShift) { /* in a base-64 section */
4461 if (IS_BASE64(ch)) { /* consume a base-64 character */
4462 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4463 base64bits += 6;
4464 s++;
4465 if (base64bits >= 16) {
4466 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004467 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004468 base64bits -= 16;
4469 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004470 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004471 if (surrogate) {
4472 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004473 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4474 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004475 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004476 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004477 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004478 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004479 }
4480 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004481 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004482 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004483 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004484 }
4485 }
Victor Stinner551ac952011-11-29 22:58:13 +01004486 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487 /* first surrogate */
4488 surrogate = outCh;
4489 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004490 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004491 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004492 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004493 }
4494 }
4495 }
4496 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004497 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004498 if (base64bits > 0) { /* left-over bits */
4499 if (base64bits >= 6) {
4500 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004501 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004502 errmsg = "partial character in shift sequence";
4503 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004504 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004505 else {
4506 /* Some bits remain; they should be zero */
4507 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004508 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004509 errmsg = "non-zero padding bits in shift sequence";
4510 goto utf7Error;
4511 }
4512 }
4513 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004514 if (surrogate && DECODE_DIRECT(ch)) {
4515 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4516 goto onError;
4517 }
4518 surrogate = 0;
4519 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004520 /* '-' is absorbed; other terminating
4521 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004522 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004523 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004524 }
4525 }
4526 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004527 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004528 s++; /* consume '+' */
4529 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004530 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004531 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004532 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004533 }
4534 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004535 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004536 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004537 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004538 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004539 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004540 }
4541 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004542 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004543 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004544 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004545 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004546 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004547 else {
4548 startinpos = s-starts;
4549 s++;
4550 errmsg = "unexpected special character";
4551 goto utf7Error;
4552 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004553 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004554utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004555 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004556 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004557 errors, &errorHandler,
4558 "utf7", errmsg,
4559 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004560 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004561 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004562 }
4563
Antoine Pitrou244651a2009-05-04 18:56:13 +00004564 /* end of string */
4565
4566 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4567 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004568 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004569 if (surrogate ||
4570 (base64bits >= 6) ||
4571 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004572 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004573 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 errors, &errorHandler,
4575 "utf7", "unterminated shift sequence",
4576 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004577 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004578 goto onError;
4579 if (s < e)
4580 goto restart;
4581 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004582 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004583
4584 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004585 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004586 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004587 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004588 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004589 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004590 writer.kind, writer.data, shiftOutStart);
4591 Py_XDECREF(errorHandler);
4592 Py_XDECREF(exc);
4593 _PyUnicodeWriter_Dealloc(&writer);
4594 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004595 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004596 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004597 }
4598 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004599 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004600 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004601 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004602
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004603 Py_XDECREF(errorHandler);
4604 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004605 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004606
Benjamin Peterson29060642009-01-31 22:14:21 +00004607 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004608 Py_XDECREF(errorHandler);
4609 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004610 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004611 return NULL;
4612}
4613
4614
Alexander Belopolsky40018472011-02-26 01:02:56 +00004615PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004616_PyUnicode_EncodeUTF7(PyObject *str,
4617 int base64SetO,
4618 int base64WhiteSpace,
4619 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004620{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004621 int kind;
4622 void *data;
4623 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004624 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004625 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004626 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004627 unsigned int base64bits = 0;
4628 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004629 char * out;
4630 char * start;
4631
Benjamin Petersonbac79492012-01-14 13:34:47 -05004632 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004633 return NULL;
4634 kind = PyUnicode_KIND(str);
4635 data = PyUnicode_DATA(str);
4636 len = PyUnicode_GET_LENGTH(str);
4637
4638 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004639 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004640
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004641 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004642 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004643 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004644 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004645 if (v == NULL)
4646 return NULL;
4647
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004648 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004649 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004650 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004651
Antoine Pitrou244651a2009-05-04 18:56:13 +00004652 if (inShift) {
4653 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4654 /* shifting out */
4655 if (base64bits) { /* output remaining bits */
4656 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4657 base64buffer = 0;
4658 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004659 }
4660 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004661 /* Characters not in the BASE64 set implicitly unshift the sequence
4662 so no '-' is required, except if the character is itself a '-' */
4663 if (IS_BASE64(ch) || ch == '-') {
4664 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004665 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004666 *out++ = (char) ch;
4667 }
4668 else {
4669 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004670 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004671 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004672 else { /* not in a shift sequence */
4673 if (ch == '+') {
4674 *out++ = '+';
4675 *out++ = '-';
4676 }
4677 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4678 *out++ = (char) ch;
4679 }
4680 else {
4681 *out++ = '+';
4682 inShift = 1;
4683 goto encode_char;
4684 }
4685 }
4686 continue;
4687encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004688 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004689 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004690
Antoine Pitrou244651a2009-05-04 18:56:13 +00004691 /* code first surrogate */
4692 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004693 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004694 while (base64bits >= 6) {
4695 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4696 base64bits -= 6;
4697 }
4698 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004699 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004700 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004701 base64bits += 16;
4702 base64buffer = (base64buffer << 16) | ch;
4703 while (base64bits >= 6) {
4704 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4705 base64bits -= 6;
4706 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004707 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004708 if (base64bits)
4709 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4710 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004711 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004712 if (_PyBytes_Resize(&v, out - start) < 0)
4713 return NULL;
4714 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004715}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004716PyObject *
4717PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4718 Py_ssize_t size,
4719 int base64SetO,
4720 int base64WhiteSpace,
4721 const char *errors)
4722{
4723 PyObject *result;
4724 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4725 if (tmp == NULL)
4726 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004727 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004728 base64WhiteSpace, errors);
4729 Py_DECREF(tmp);
4730 return result;
4731}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004732
Antoine Pitrou244651a2009-05-04 18:56:13 +00004733#undef IS_BASE64
4734#undef FROM_BASE64
4735#undef TO_BASE64
4736#undef DECODE_DIRECT
4737#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004738
Guido van Rossumd57fd912000-03-10 22:53:23 +00004739/* --- UTF-8 Codec -------------------------------------------------------- */
4740
Alexander Belopolsky40018472011-02-26 01:02:56 +00004741PyObject *
4742PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004743 Py_ssize_t size,
4744 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004745{
Walter Dörwald69652032004-09-07 20:24:22 +00004746 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4747}
4748
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004749#include "stringlib/asciilib.h"
4750#include "stringlib/codecs.h"
4751#include "stringlib/undef.h"
4752
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004753#include "stringlib/ucs1lib.h"
4754#include "stringlib/codecs.h"
4755#include "stringlib/undef.h"
4756
4757#include "stringlib/ucs2lib.h"
4758#include "stringlib/codecs.h"
4759#include "stringlib/undef.h"
4760
4761#include "stringlib/ucs4lib.h"
4762#include "stringlib/codecs.h"
4763#include "stringlib/undef.h"
4764
Antoine Pitrouab868312009-01-10 15:40:25 +00004765/* Mask to quickly check whether a C 'long' contains a
4766 non-ASCII, UTF8-encoded char. */
4767#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004768# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004769#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004770# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004771#else
4772# error C 'long' size should be either 4 or 8!
4773#endif
4774
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004775static Py_ssize_t
4776ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004777{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004778 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004779 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004780
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004781 /*
4782 * Issue #17237: m68k is a bit different from most architectures in
4783 * that objects do not use "natural alignment" - for example, int and
4784 * long are only aligned at 2-byte boundaries. Therefore the assert()
4785 * won't work; also, tests have shown that skipping the "optimised
4786 * version" will even speed up m68k.
4787 */
4788#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004789#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004790 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4791 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004792 /* Fast path, see in STRINGLIB(utf8_decode) for
4793 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004794 /* Help allocation */
4795 const char *_p = p;
4796 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004797 while (_p < aligned_end) {
4798 unsigned long value = *(const unsigned long *) _p;
4799 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004800 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004801 *((unsigned long *)q) = value;
4802 _p += SIZEOF_LONG;
4803 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004804 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004805 p = _p;
4806 while (p < end) {
4807 if ((unsigned char)*p & 0x80)
4808 break;
4809 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004810 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004811 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004812 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004813#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004814#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004815 while (p < end) {
4816 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4817 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004818 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004819 /* Help allocation */
4820 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004821 while (_p < aligned_end) {
4822 unsigned long value = *(unsigned long *) _p;
4823 if (value & ASCII_CHAR_MASK)
4824 break;
4825 _p += SIZEOF_LONG;
4826 }
4827 p = _p;
4828 if (_p == end)
4829 break;
4830 }
4831 if ((unsigned char)*p & 0x80)
4832 break;
4833 ++p;
4834 }
4835 memcpy(dest, start, p - start);
4836 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004837}
Antoine Pitrouab868312009-01-10 15:40:25 +00004838
Victor Stinner785938e2011-12-11 20:09:03 +01004839PyObject *
4840PyUnicode_DecodeUTF8Stateful(const char *s,
4841 Py_ssize_t size,
4842 const char *errors,
4843 Py_ssize_t *consumed)
4844{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004845 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004846 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004847 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004848
4849 Py_ssize_t startinpos;
4850 Py_ssize_t endinpos;
4851 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004852 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004853 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004854 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004855
4856 if (size == 0) {
4857 if (consumed)
4858 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004859 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004860 }
4861
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004862 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4863 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004864 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004865 *consumed = 1;
4866 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004867 }
4868
Victor Stinner8f674cc2013-04-17 23:02:17 +02004869 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004870 writer.min_length = size;
4871 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004872 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004873
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004874 writer.pos = ascii_decode(s, end, writer.data);
4875 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004876 while (s < end) {
4877 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004878 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004879
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004880 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004881 if (PyUnicode_IS_ASCII(writer.buffer))
4882 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004883 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004884 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004885 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004886 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004887 } else {
4888 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004889 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004890 }
4891
4892 switch (ch) {
4893 case 0:
4894 if (s == end || consumed)
4895 goto End;
4896 errmsg = "unexpected end of data";
4897 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004898 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004899 break;
4900 case 1:
4901 errmsg = "invalid start byte";
4902 startinpos = s - starts;
4903 endinpos = startinpos + 1;
4904 break;
4905 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004906 case 3:
4907 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004908 errmsg = "invalid continuation byte";
4909 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004910 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004911 break;
4912 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004913 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004914 goto onError;
4915 continue;
4916 }
4917
Victor Stinner1d65d912015-10-05 13:43:50 +02004918 if (error_handler == _Py_ERROR_UNKNOWN)
4919 error_handler = get_error_handler(errors);
4920
4921 switch (error_handler) {
4922 case _Py_ERROR_IGNORE:
4923 s += (endinpos - startinpos);
4924 break;
4925
4926 case _Py_ERROR_REPLACE:
4927 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4928 goto onError;
4929 s += (endinpos - startinpos);
4930 break;
4931
4932 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004933 {
4934 Py_ssize_t i;
4935
Victor Stinner1d65d912015-10-05 13:43:50 +02004936 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4937 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004938 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004939 ch = (Py_UCS4)(unsigned char)(starts[i]);
4940 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4941 ch + 0xdc00);
4942 writer.pos++;
4943 }
4944 s += (endinpos - startinpos);
4945 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004946 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004947
4948 default:
4949 if (unicode_decode_call_errorhandler_writer(
4950 errors, &error_handler_obj,
4951 "utf-8", errmsg,
4952 &starts, &end, &startinpos, &endinpos, &exc, &s,
4953 &writer))
4954 goto onError;
4955 }
Victor Stinner785938e2011-12-11 20:09:03 +01004956 }
4957
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004958End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004959 if (consumed)
4960 *consumed = s - starts;
4961
Victor Stinner1d65d912015-10-05 13:43:50 +02004962 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004963 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004964 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004965
4966onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004967 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004968 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004969 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004970 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004971}
4972
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004973#ifdef __APPLE__
4974
4975/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004976 used to decode the command line arguments on Mac OS X.
4977
4978 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004979 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004980
4981wchar_t*
4982_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4983{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004984 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004985 wchar_t *unicode;
4986 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004987
4988 /* Note: size will always be longer than the resulting Unicode
4989 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01004990 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004991 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004992 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004993 if (!unicode)
4994 return NULL;
4995
4996 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004997 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004998 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004999 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005000 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005001#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005002 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005003#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005004 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005005#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005006 if (ch > 0xFF) {
5007#if SIZEOF_WCHAR_T == 4
5008 assert(0);
5009#else
5010 assert(Py_UNICODE_IS_SURROGATE(ch));
5011 /* compute and append the two surrogates: */
5012 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5013 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5014#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005015 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005016 else {
5017 if (!ch && s == e)
5018 break;
5019 /* surrogateescape */
5020 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5021 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005022 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005023 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005024 return unicode;
5025}
5026
5027#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005028
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005029/* Primary internal function which creates utf8 encoded bytes objects.
5030
5031 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005032 and allocate exactly as much space needed at the end. Else allocate the
5033 maximum possible needed (4 result bytes per Unicode character), and return
5034 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005035*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005036PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005037_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005038{
Victor Stinner6099a032011-12-18 14:22:26 +01005039 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005040 void *data;
5041 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005043 if (!PyUnicode_Check(unicode)) {
5044 PyErr_BadArgument();
5045 return NULL;
5046 }
5047
5048 if (PyUnicode_READY(unicode) == -1)
5049 return NULL;
5050
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005051 if (PyUnicode_UTF8(unicode))
5052 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5053 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005054
5055 kind = PyUnicode_KIND(unicode);
5056 data = PyUnicode_DATA(unicode);
5057 size = PyUnicode_GET_LENGTH(unicode);
5058
Benjamin Petersonead6b532011-12-20 17:23:42 -06005059 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005060 default:
5061 assert(0);
5062 case PyUnicode_1BYTE_KIND:
5063 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5064 assert(!PyUnicode_IS_ASCII(unicode));
5065 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5066 case PyUnicode_2BYTE_KIND:
5067 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5068 case PyUnicode_4BYTE_KIND:
5069 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005070 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005071}
5072
Alexander Belopolsky40018472011-02-26 01:02:56 +00005073PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005074PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5075 Py_ssize_t size,
5076 const char *errors)
5077{
5078 PyObject *v, *unicode;
5079
5080 unicode = PyUnicode_FromUnicode(s, size);
5081 if (unicode == NULL)
5082 return NULL;
5083 v = _PyUnicode_AsUTF8String(unicode, errors);
5084 Py_DECREF(unicode);
5085 return v;
5086}
5087
5088PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005089PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005090{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005091 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005092}
5093
Walter Dörwald41980ca2007-08-16 21:55:45 +00005094/* --- UTF-32 Codec ------------------------------------------------------- */
5095
5096PyObject *
5097PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005098 Py_ssize_t size,
5099 const char *errors,
5100 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005101{
5102 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5103}
5104
5105PyObject *
5106PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005107 Py_ssize_t size,
5108 const char *errors,
5109 int *byteorder,
5110 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005111{
5112 const char *starts = s;
5113 Py_ssize_t startinpos;
5114 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005115 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005116 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005117 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005118 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005119 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005120 PyObject *errorHandler = NULL;
5121 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005122
Walter Dörwald41980ca2007-08-16 21:55:45 +00005123 q = (unsigned char *)s;
5124 e = q + size;
5125
5126 if (byteorder)
5127 bo = *byteorder;
5128
5129 /* Check for BOM marks (U+FEFF) in the input and adjust current
5130 byte order setting accordingly. In native mode, the leading BOM
5131 mark is skipped, in all other modes, it is copied to the output
5132 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005133 if (bo == 0 && size >= 4) {
5134 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5135 if (bom == 0x0000FEFF) {
5136 bo = -1;
5137 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005138 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005139 else if (bom == 0xFFFE0000) {
5140 bo = 1;
5141 q += 4;
5142 }
5143 if (byteorder)
5144 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005145 }
5146
Victor Stinnere64322e2012-10-30 23:12:47 +01005147 if (q == e) {
5148 if (consumed)
5149 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005150 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005151 }
5152
Victor Stinnere64322e2012-10-30 23:12:47 +01005153#ifdef WORDS_BIGENDIAN
5154 le = bo < 0;
5155#else
5156 le = bo <= 0;
5157#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005158 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005159
Victor Stinner8f674cc2013-04-17 23:02:17 +02005160 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005161 writer.min_length = (e - q + 3) / 4;
5162 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005163 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005164
Victor Stinnere64322e2012-10-30 23:12:47 +01005165 while (1) {
5166 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005167 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005168
Victor Stinnere64322e2012-10-30 23:12:47 +01005169 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005170 enum PyUnicode_Kind kind = writer.kind;
5171 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005172 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005173 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005174 if (le) {
5175 do {
5176 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5177 if (ch > maxch)
5178 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005179 if (kind != PyUnicode_1BYTE_KIND &&
5180 Py_UNICODE_IS_SURROGATE(ch))
5181 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005182 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005183 q += 4;
5184 } while (q <= last);
5185 }
5186 else {
5187 do {
5188 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5189 if (ch > maxch)
5190 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005191 if (kind != PyUnicode_1BYTE_KIND &&
5192 Py_UNICODE_IS_SURROGATE(ch))
5193 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005194 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005195 q += 4;
5196 } while (q <= last);
5197 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005198 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005199 }
5200
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005201 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005202 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005203 startinpos = ((const char *)q) - starts;
5204 endinpos = startinpos + 4;
5205 }
5206 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005207 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005208 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005209 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005210 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005211 startinpos = ((const char *)q) - starts;
5212 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005213 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005214 else {
5215 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005216 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005217 goto onError;
5218 q += 4;
5219 continue;
5220 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005221 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005222 startinpos = ((const char *)q) - starts;
5223 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005224 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005225
5226 /* The remaining input chars are ignored if the callback
5227 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005228 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005229 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005230 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005231 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005232 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005233 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005234 }
5235
Walter Dörwald41980ca2007-08-16 21:55:45 +00005236 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005237 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005238
Walter Dörwald41980ca2007-08-16 21:55:45 +00005239 Py_XDECREF(errorHandler);
5240 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005241 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005242
Benjamin Peterson29060642009-01-31 22:14:21 +00005243 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005244 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005245 Py_XDECREF(errorHandler);
5246 Py_XDECREF(exc);
5247 return NULL;
5248}
5249
5250PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005251_PyUnicode_EncodeUTF32(PyObject *str,
5252 const char *errors,
5253 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005254{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005255 enum PyUnicode_Kind kind;
5256 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005257 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005258 PyObject *v;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005259 PY_UINT32_T *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005260#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005261 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005262#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005263 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005264#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005265 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005266 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005267 PyObject *errorHandler = NULL;
5268 PyObject *exc = NULL;
5269 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005270
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005271 if (!PyUnicode_Check(str)) {
5272 PyErr_BadArgument();
5273 return NULL;
5274 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005275 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005276 return NULL;
5277 kind = PyUnicode_KIND(str);
5278 data = PyUnicode_DATA(str);
5279 len = PyUnicode_GET_LENGTH(str);
5280
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005281 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005282 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005283 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005284 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005285 if (v == NULL)
5286 return NULL;
5287
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005288 /* output buffer is 4-bytes aligned */
5289 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
5290 out = (PY_UINT32_T *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005291 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005292 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005293 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005294 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005295
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005296 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005297 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005298 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005299 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005300 else
5301 encoding = "utf-32";
5302
5303 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005304 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5305 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005306 }
5307
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005308 pos = 0;
5309 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005310 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005311
5312 if (kind == PyUnicode_2BYTE_KIND) {
5313 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5314 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005315 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005316 else {
5317 assert(kind == PyUnicode_4BYTE_KIND);
5318 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5319 &out, native_ordering);
5320 }
5321 if (pos == len)
5322 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005323
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005324 rep = unicode_encode_call_errorhandler(
5325 errors, &errorHandler,
5326 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005327 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005328 if (!rep)
5329 goto error;
5330
5331 if (PyBytes_Check(rep)) {
5332 repsize = PyBytes_GET_SIZE(rep);
5333 if (repsize & 3) {
5334 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005335 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005336 "surrogates not allowed");
5337 goto error;
5338 }
5339 moreunits = repsize / 4;
5340 }
5341 else {
5342 assert(PyUnicode_Check(rep));
5343 if (PyUnicode_READY(rep) < 0)
5344 goto error;
5345 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5346 if (!PyUnicode_IS_ASCII(rep)) {
5347 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005348 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005349 "surrogates not allowed");
5350 goto error;
5351 }
5352 }
5353
5354 /* four bytes are reserved for each surrogate */
5355 if (moreunits > 1) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005356 Py_ssize_t outpos = out - (PY_UINT32_T*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005357 Py_ssize_t morebytes = 4 * (moreunits - 1);
5358 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5359 /* integer overflow */
5360 PyErr_NoMemory();
5361 goto error;
5362 }
5363 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5364 goto error;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005365 out = (PY_UINT32_T*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005366 }
5367
5368 if (PyBytes_Check(rep)) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005369 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5370 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005371 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005372 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005373 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5374 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005375 }
5376
5377 Py_CLEAR(rep);
5378 }
5379
5380 /* Cut back to size actually needed. This is necessary for, for example,
5381 encoding of a string containing isolated surrogates and the 'ignore'
5382 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005383 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005384 if (nsize != PyBytes_GET_SIZE(v))
5385 _PyBytes_Resize(&v, nsize);
5386 Py_XDECREF(errorHandler);
5387 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005388 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005389 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005390 error:
5391 Py_XDECREF(rep);
5392 Py_XDECREF(errorHandler);
5393 Py_XDECREF(exc);
5394 Py_XDECREF(v);
5395 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005396}
5397
Alexander Belopolsky40018472011-02-26 01:02:56 +00005398PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005399PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5400 Py_ssize_t size,
5401 const char *errors,
5402 int byteorder)
5403{
5404 PyObject *result;
5405 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5406 if (tmp == NULL)
5407 return NULL;
5408 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5409 Py_DECREF(tmp);
5410 return result;
5411}
5412
5413PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005414PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005415{
Victor Stinnerb960b342011-11-20 19:12:52 +01005416 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005417}
5418
Guido van Rossumd57fd912000-03-10 22:53:23 +00005419/* --- UTF-16 Codec ------------------------------------------------------- */
5420
Tim Peters772747b2001-08-09 22:21:55 +00005421PyObject *
5422PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005423 Py_ssize_t size,
5424 const char *errors,
5425 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005426{
Walter Dörwald69652032004-09-07 20:24:22 +00005427 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5428}
5429
5430PyObject *
5431PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005432 Py_ssize_t size,
5433 const char *errors,
5434 int *byteorder,
5435 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005436{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005437 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005438 Py_ssize_t startinpos;
5439 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005440 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005441 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005442 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005443 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005444 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005445 PyObject *errorHandler = NULL;
5446 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005447 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005448
Tim Peters772747b2001-08-09 22:21:55 +00005449 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005450 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005451
5452 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005453 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005454
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005455 /* Check for BOM marks (U+FEFF) in the input and adjust current
5456 byte order setting accordingly. In native mode, the leading BOM
5457 mark is skipped, in all other modes, it is copied to the output
5458 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005459 if (bo == 0 && size >= 2) {
5460 const Py_UCS4 bom = (q[1] << 8) | q[0];
5461 if (bom == 0xFEFF) {
5462 q += 2;
5463 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005464 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005465 else if (bom == 0xFFFE) {
5466 q += 2;
5467 bo = 1;
5468 }
5469 if (byteorder)
5470 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005471 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005472
Antoine Pitrou63065d72012-05-15 23:48:04 +02005473 if (q == e) {
5474 if (consumed)
5475 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005476 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005477 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005478
Christian Heimes743e0cd2012-10-17 23:52:17 +02005479#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005480 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005481 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005482#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005483 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005484 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005485#endif
Tim Peters772747b2001-08-09 22:21:55 +00005486
Antoine Pitrou63065d72012-05-15 23:48:04 +02005487 /* Note: size will always be longer than the resulting Unicode
5488 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005489 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005490 writer.min_length = (e - q + 1) / 2;
5491 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005492 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005493
Antoine Pitrou63065d72012-05-15 23:48:04 +02005494 while (1) {
5495 Py_UCS4 ch = 0;
5496 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005497 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005498 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005499 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005500 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005501 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005502 native_ordering);
5503 else
5504 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005505 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005506 native_ordering);
5507 } else if (kind == PyUnicode_2BYTE_KIND) {
5508 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005509 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005510 native_ordering);
5511 } else {
5512 assert(kind == PyUnicode_4BYTE_KIND);
5513 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005514 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005515 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005516 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005517 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005518
Antoine Pitrou63065d72012-05-15 23:48:04 +02005519 switch (ch)
5520 {
5521 case 0:
5522 /* remaining byte at the end? (size should be even) */
5523 if (q == e || consumed)
5524 goto End;
5525 errmsg = "truncated data";
5526 startinpos = ((const char *)q) - starts;
5527 endinpos = ((const char *)e) - starts;
5528 break;
5529 /* The remaining input chars are ignored if the callback
5530 chooses to skip the input */
5531 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005532 q -= 2;
5533 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005534 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005535 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005536 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005537 endinpos = ((const char *)e) - starts;
5538 break;
5539 case 2:
5540 errmsg = "illegal encoding";
5541 startinpos = ((const char *)q) - 2 - starts;
5542 endinpos = startinpos + 2;
5543 break;
5544 case 3:
5545 errmsg = "illegal UTF-16 surrogate";
5546 startinpos = ((const char *)q) - 4 - starts;
5547 endinpos = startinpos + 2;
5548 break;
5549 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005550 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005551 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005552 continue;
5553 }
5554
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005555 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005556 errors,
5557 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005558 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005559 &starts,
5560 (const char **)&e,
5561 &startinpos,
5562 &endinpos,
5563 &exc,
5564 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005565 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005566 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005567 }
5568
Antoine Pitrou63065d72012-05-15 23:48:04 +02005569End:
Walter Dörwald69652032004-09-07 20:24:22 +00005570 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005571 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005572
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005573 Py_XDECREF(errorHandler);
5574 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005575 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005576
Benjamin Peterson29060642009-01-31 22:14:21 +00005577 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005578 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005579 Py_XDECREF(errorHandler);
5580 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005581 return NULL;
5582}
5583
Tim Peters772747b2001-08-09 22:21:55 +00005584PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005585_PyUnicode_EncodeUTF16(PyObject *str,
5586 const char *errors,
5587 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005588{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005589 enum PyUnicode_Kind kind;
5590 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005591 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005592 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005593 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005594 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005595#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005596 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005597#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005598 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005599#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005600 const char *encoding;
5601 Py_ssize_t nsize, pos;
5602 PyObject *errorHandler = NULL;
5603 PyObject *exc = NULL;
5604 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005605
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005606 if (!PyUnicode_Check(str)) {
5607 PyErr_BadArgument();
5608 return NULL;
5609 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005610 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005611 return NULL;
5612 kind = PyUnicode_KIND(str);
5613 data = PyUnicode_DATA(str);
5614 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005615
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005616 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005617 if (kind == PyUnicode_4BYTE_KIND) {
5618 const Py_UCS4 *in = (const Py_UCS4 *)data;
5619 const Py_UCS4 *end = in + len;
5620 while (in < end)
5621 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005622 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005623 }
5624 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005625 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005626 nsize = len + pairs + (byteorder == 0);
5627 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005628 if (v == NULL)
5629 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005631 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005632 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005633 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005634 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005635 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005636 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005637 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005638
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005639 if (kind == PyUnicode_1BYTE_KIND) {
5640 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5641 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005642 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005643
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005644 if (byteorder < 0)
5645 encoding = "utf-16-le";
5646 else if (byteorder > 0)
5647 encoding = "utf-16-be";
5648 else
5649 encoding = "utf-16";
5650
5651 pos = 0;
5652 while (pos < len) {
5653 Py_ssize_t repsize, moreunits;
5654
5655 if (kind == PyUnicode_2BYTE_KIND) {
5656 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5657 &out, native_ordering);
5658 }
5659 else {
5660 assert(kind == PyUnicode_4BYTE_KIND);
5661 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5662 &out, native_ordering);
5663 }
5664 if (pos == len)
5665 break;
5666
5667 rep = unicode_encode_call_errorhandler(
5668 errors, &errorHandler,
5669 encoding, "surrogates not allowed",
5670 str, &exc, pos, pos + 1, &pos);
5671 if (!rep)
5672 goto error;
5673
5674 if (PyBytes_Check(rep)) {
5675 repsize = PyBytes_GET_SIZE(rep);
5676 if (repsize & 1) {
5677 raise_encode_exception(&exc, encoding,
5678 str, pos - 1, pos,
5679 "surrogates not allowed");
5680 goto error;
5681 }
5682 moreunits = repsize / 2;
5683 }
5684 else {
5685 assert(PyUnicode_Check(rep));
5686 if (PyUnicode_READY(rep) < 0)
5687 goto error;
5688 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5689 if (!PyUnicode_IS_ASCII(rep)) {
5690 raise_encode_exception(&exc, encoding,
5691 str, pos - 1, pos,
5692 "surrogates not allowed");
5693 goto error;
5694 }
5695 }
5696
5697 /* two bytes are reserved for each surrogate */
5698 if (moreunits > 1) {
5699 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5700 Py_ssize_t morebytes = 2 * (moreunits - 1);
5701 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5702 /* integer overflow */
5703 PyErr_NoMemory();
5704 goto error;
5705 }
5706 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5707 goto error;
5708 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5709 }
5710
5711 if (PyBytes_Check(rep)) {
5712 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5713 out += moreunits;
5714 } else /* rep is unicode */ {
5715 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5716 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5717 &out, native_ordering);
5718 }
5719
5720 Py_CLEAR(rep);
5721 }
5722
5723 /* Cut back to size actually needed. This is necessary for, for example,
5724 encoding of a string containing isolated surrogates and the 'ignore' handler
5725 is used. */
5726 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5727 if (nsize != PyBytes_GET_SIZE(v))
5728 _PyBytes_Resize(&v, nsize);
5729 Py_XDECREF(errorHandler);
5730 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005731 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005732 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005733 error:
5734 Py_XDECREF(rep);
5735 Py_XDECREF(errorHandler);
5736 Py_XDECREF(exc);
5737 Py_XDECREF(v);
5738 return NULL;
5739#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740}
5741
Alexander Belopolsky40018472011-02-26 01:02:56 +00005742PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005743PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5744 Py_ssize_t size,
5745 const char *errors,
5746 int byteorder)
5747{
5748 PyObject *result;
5749 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5750 if (tmp == NULL)
5751 return NULL;
5752 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5753 Py_DECREF(tmp);
5754 return result;
5755}
5756
5757PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005758PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005759{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005760 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005761}
5762
5763/* --- Unicode Escape Codec ----------------------------------------------- */
5764
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005765/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5766 if all the escapes in the string make it still a valid ASCII string.
5767 Returns -1 if any escapes were found which cause the string to
5768 pop out of ASCII range. Otherwise returns the length of the
5769 required buffer to hold the string.
5770 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005771static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005772length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5773{
5774 const unsigned char *p = (const unsigned char *)s;
5775 const unsigned char *end = p + size;
5776 Py_ssize_t length = 0;
5777
5778 if (size < 0)
5779 return -1;
5780
5781 for (; p < end; ++p) {
5782 if (*p > 127) {
5783 /* Non-ASCII */
5784 return -1;
5785 }
5786 else if (*p != '\\') {
5787 /* Normal character */
5788 ++length;
5789 }
5790 else {
5791 /* Backslash-escape, check next char */
5792 ++p;
5793 /* Escape sequence reaches till end of string or
5794 non-ASCII follow-up. */
5795 if (p >= end || *p > 127)
5796 return -1;
5797 switch (*p) {
5798 case '\n':
5799 /* backslash + \n result in zero characters */
5800 break;
5801 case '\\': case '\'': case '\"':
5802 case 'b': case 'f': case 't':
5803 case 'n': case 'r': case 'v': case 'a':
5804 ++length;
5805 break;
5806 case '0': case '1': case '2': case '3':
5807 case '4': case '5': case '6': case '7':
5808 case 'x': case 'u': case 'U': case 'N':
5809 /* these do not guarantee ASCII characters */
5810 return -1;
5811 default:
5812 /* count the backslash + the other character */
5813 length += 2;
5814 }
5815 }
5816 }
5817 return length;
5818}
5819
Fredrik Lundh06d12682001-01-24 07:59:11 +00005820static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005821
Alexander Belopolsky40018472011-02-26 01:02:56 +00005822PyObject *
5823PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005824 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005825 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005826{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005827 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005828 Py_ssize_t startinpos;
5829 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005830 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005831 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005832 char* message;
5833 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005834 PyObject *errorHandler = NULL;
5835 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005836 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005837
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005838 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005839 if (len == 0)
5840 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005841
5842 /* After length_of_escaped_ascii_string() there are two alternatives,
5843 either the string is pure ASCII with named escapes like \n, etc.
5844 and we determined it's exact size (common case)
5845 or it contains \x, \u, ... escape sequences. then we create a
5846 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005847 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005848 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005849 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005850 }
5851 else {
5852 /* Escaped strings will always be longer than the resulting
5853 Unicode string, so we start with size here and then reduce the
5854 length after conversion to the true value.
5855 (but if the error callback returns a long replacement string
5856 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005857 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005858 }
5859
Guido van Rossumd57fd912000-03-10 22:53:23 +00005860 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005861 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005862 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005863
Guido van Rossumd57fd912000-03-10 22:53:23 +00005864 while (s < end) {
5865 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005866 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005867 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005868
5869 /* Non-escape characters are interpreted as Unicode ordinals */
5870 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005871 x = (unsigned char)*s;
5872 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005873 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005874 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005875 continue;
5876 }
5877
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005878 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005879 /* \ - Escapes */
5880 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005881 c = *s++;
5882 if (s > end)
5883 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005884
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005885 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005886
Benjamin Peterson29060642009-01-31 22:14:21 +00005887 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005888#define WRITECHAR(ch) \
5889 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005890 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005891 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005892 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005893
Guido van Rossumd57fd912000-03-10 22:53:23 +00005894 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005895 case '\\': WRITECHAR('\\'); break;
5896 case '\'': WRITECHAR('\''); break;
5897 case '\"': WRITECHAR('\"'); break;
5898 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005899 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005900 case 'f': WRITECHAR('\014'); break;
5901 case 't': WRITECHAR('\t'); break;
5902 case 'n': WRITECHAR('\n'); break;
5903 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005904 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005905 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005906 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005907 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005908
Benjamin Peterson29060642009-01-31 22:14:21 +00005909 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910 case '0': case '1': case '2': case '3':
5911 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005912 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005913 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005914 x = (x<<3) + *s++ - '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 Rossumd57fd912000-03-10 22:53:23 +00005917 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005918 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919 break;
5920
Benjamin Peterson29060642009-01-31 22:14:21 +00005921 /* hex escapes */
5922 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005923 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005924 digits = 2;
5925 message = "truncated \\xXX escape";
5926 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005927
Benjamin Peterson29060642009-01-31 22:14:21 +00005928 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005930 digits = 4;
5931 message = "truncated \\uXXXX escape";
5932 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933
Benjamin Peterson29060642009-01-31 22:14:21 +00005934 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005935 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005936 digits = 8;
5937 message = "truncated \\UXXXXXXXX escape";
5938 hexescape:
5939 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005940 if (end - s < digits) {
5941 /* count only hex digits */
5942 for (; s < end; ++s) {
5943 c = (unsigned char)*s;
5944 if (!Py_ISXDIGIT(c))
5945 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005946 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005947 goto error;
5948 }
5949 for (; digits--; ++s) {
5950 c = (unsigned char)*s;
5951 if (!Py_ISXDIGIT(c))
5952 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005953 chr = (chr<<4) & ~0xF;
5954 if (c >= '0' && c <= '9')
5955 chr += c - '0';
5956 else if (c >= 'a' && c <= 'f')
5957 chr += 10 + c - 'a';
5958 else
5959 chr += 10 + c - 'A';
5960 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005961 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005962 /* _decoding_error will have already written into the
5963 target buffer. */
5964 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005965 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005966 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005967 message = "illegal Unicode character";
5968 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005969 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005970 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005971 break;
5972
Benjamin Peterson29060642009-01-31 22:14:21 +00005973 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005974 case 'N':
5975 message = "malformed \\N character escape";
5976 if (ucnhash_CAPI == NULL) {
5977 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005978 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5979 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005980 if (ucnhash_CAPI == NULL)
5981 goto ucnhashError;
5982 }
5983 if (*s == '{') {
5984 const char *start = s+1;
5985 /* look for the closing brace */
5986 while (*s != '}' && s < end)
5987 s++;
5988 if (s > start && s < end && *s == '}') {
5989 /* found a name. look it up in the unicode database */
5990 message = "unknown Unicode character name";
5991 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005992 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005993 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005994 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005995 goto store;
5996 }
5997 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005998 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005999
6000 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00006001 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006002 message = "\\ at end of string";
6003 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02006004 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00006005 }
6006 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006007 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02006008 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00006009 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006010 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006011 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006012 continue;
6013
6014 error:
6015 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006016 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006017 errors, &errorHandler,
6018 "unicodeescape", message,
6019 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006020 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02006021 goto onError;
6022 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006023 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006024#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006025
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006026 Py_XDECREF(errorHandler);
6027 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006028 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006029
Benjamin Peterson29060642009-01-31 22:14:21 +00006030 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00006031 PyErr_SetString(
6032 PyExc_UnicodeError,
6033 "\\N escapes not supported (can't load unicodedata module)"
6034 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006035 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006036 Py_XDECREF(errorHandler);
6037 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00006038 return NULL;
6039
Benjamin Peterson29060642009-01-31 22:14:21 +00006040 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006041 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006042 Py_XDECREF(errorHandler);
6043 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044 return NULL;
6045}
6046
6047/* Return a Unicode-Escape string version of the Unicode object.
6048
6049 If quotes is true, the string is enclosed in u"" or u'' quotes as
6050 appropriate.
6051
6052*/
6053
Alexander Belopolsky40018472011-02-26 01:02:56 +00006054PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006055PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006056{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006057 Py_ssize_t i, len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006058 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006059 int kind;
6060 void *data;
Victor Stinner358af132015-10-12 22:36:57 +02006061 _PyBytesWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006062
Ezio Melottie7f90372012-10-05 03:33:31 +03006063 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006064 escape.
6065
Ezio Melottie7f90372012-10-05 03:33:31 +03006066 For UCS1 strings it's '\xxx', 4 bytes per source character.
6067 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6068 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006069 */
6070
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006071 if (!PyUnicode_Check(unicode)) {
6072 PyErr_BadArgument();
6073 return NULL;
6074 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006075 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006076 return NULL;
Victor Stinner358af132015-10-12 22:36:57 +02006077
6078 _PyBytesWriter_Init(&writer);
6079
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006080 len = PyUnicode_GET_LENGTH(unicode);
6081 kind = PyUnicode_KIND(unicode);
6082 data = PyUnicode_DATA(unicode);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006083
Victor Stinner358af132015-10-12 22:36:57 +02006084 p = _PyBytesWriter_Alloc(&writer, len);
6085 if (p == NULL)
6086 goto error;
6087 writer.overallocate = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006088
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006089 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006090 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006091
Walter Dörwald79e913e2007-05-12 11:08:06 +00006092 /* Escape backslashes */
6093 if (ch == '\\') {
Victor Stinner358af132015-10-12 22:36:57 +02006094 /* -1: substract 1 preallocated byte */
6095 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6096 if (p == NULL)
6097 goto error;
6098
Guido van Rossumd57fd912000-03-10 22:53:23 +00006099 *p++ = '\\';
6100 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006101 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006102 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006103
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006104 /* Map 21-bit characters to '\U00xxxxxx' */
6105 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006106 assert(ch <= MAX_UNICODE);
Victor Stinner358af132015-10-12 22:36:57 +02006107
6108 p = _PyBytesWriter_Prepare(&writer, p, 10-1);
6109 if (p == NULL)
6110 goto error;
6111
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006112 *p++ = '\\';
6113 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006114 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6115 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6116 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6117 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6118 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6119 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6120 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6121 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006122 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006123 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006124
Guido van Rossumd57fd912000-03-10 22:53:23 +00006125 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006126 if (ch >= 256) {
Victor Stinner358af132015-10-12 22:36:57 +02006127 p = _PyBytesWriter_Prepare(&writer, p, 6-1);
6128 if (p == NULL)
6129 goto error;
6130
Guido van Rossumd57fd912000-03-10 22:53:23 +00006131 *p++ = '\\';
6132 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006133 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6134 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6135 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6136 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006137 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006138
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006139 /* Map special whitespace to '\t', \n', '\r' */
6140 else if (ch == '\t') {
Victor Stinner358af132015-10-12 22:36:57 +02006141 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6142 if (p == NULL)
6143 goto error;
6144
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006145 *p++ = '\\';
6146 *p++ = 't';
6147 }
6148 else if (ch == '\n') {
Victor Stinner358af132015-10-12 22:36:57 +02006149 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6150 if (p == NULL)
6151 goto error;
6152
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006153 *p++ = '\\';
6154 *p++ = 'n';
6155 }
6156 else if (ch == '\r') {
Victor Stinner358af132015-10-12 22:36:57 +02006157 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6158 if (p == NULL)
6159 goto error;
6160
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006161 *p++ = '\\';
6162 *p++ = 'r';
6163 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006164
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006165 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006166 else if (ch < ' ' || ch >= 0x7F) {
Victor Stinner358af132015-10-12 22:36:57 +02006167 /* -1: substract 1 preallocated byte */
6168 p = _PyBytesWriter_Prepare(&writer, p, 4-1);
6169 if (p == NULL)
6170 goto error;
6171
Guido van Rossumd57fd912000-03-10 22:53:23 +00006172 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006173 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006174 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6175 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006176 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006177
Guido van Rossumd57fd912000-03-10 22:53:23 +00006178 /* Copy everything else as-is */
6179 else
6180 *p++ = (char) ch;
6181 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006182
Victor Stinner358af132015-10-12 22:36:57 +02006183 return _PyBytesWriter_Finish(&writer, p);
6184
6185error:
6186 _PyBytesWriter_Dealloc(&writer);
6187 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188}
6189
Alexander Belopolsky40018472011-02-26 01:02:56 +00006190PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006191PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6192 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006194 PyObject *result;
6195 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6196 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006197 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006198 result = PyUnicode_AsUnicodeEscapeString(tmp);
6199 Py_DECREF(tmp);
6200 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006201}
6202
6203/* --- Raw Unicode Escape Codec ------------------------------------------- */
6204
Alexander Belopolsky40018472011-02-26 01:02:56 +00006205PyObject *
6206PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006207 Py_ssize_t size,
6208 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006210 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006211 Py_ssize_t startinpos;
6212 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006213 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006214 const char *end;
6215 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006216 PyObject *errorHandler = NULL;
6217 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006218
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006219 if (size == 0)
6220 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006221
Guido van Rossumd57fd912000-03-10 22:53:23 +00006222 /* Escaped strings will always be longer than the resulting
6223 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006224 length after conversion to the true value. (But decoding error
6225 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006226 _PyUnicodeWriter_Init(&writer);
6227 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006228
Guido van Rossumd57fd912000-03-10 22:53:23 +00006229 end = s + size;
6230 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006231 unsigned char c;
6232 Py_UCS4 x;
6233 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006234 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006235
Benjamin Peterson29060642009-01-31 22:14:21 +00006236 /* Non-escape characters are interpreted as Unicode ordinals */
6237 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006238 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006239 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006240 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006241 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006242 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006243 startinpos = s-starts;
6244
6245 /* \u-escapes are only interpreted iff the number of leading
6246 backslashes if odd */
6247 bs = s;
6248 for (;s < end;) {
6249 if (*s != '\\')
6250 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006251 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006252 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006253 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006254 }
6255 if (((s - bs) & 1) == 0 ||
6256 s >= end ||
6257 (*s != 'u' && *s != 'U')) {
6258 continue;
6259 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006260 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006261 count = *s=='u' ? 4 : 8;
6262 s++;
6263
6264 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006265 for (x = 0, i = 0; i < count; ++i, ++s) {
6266 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006267 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006268 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006269 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006270 errors, &errorHandler,
6271 "rawunicodeescape", "truncated \\uXXXX",
6272 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006273 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006274 goto onError;
6275 goto nextByte;
6276 }
6277 x = (x<<4) & ~0xF;
6278 if (c >= '0' && c <= '9')
6279 x += c - '0';
6280 else if (c >= 'a' && c <= 'f')
6281 x += 10 + c - 'a';
6282 else
6283 x += 10 + c - 'A';
6284 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006285 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006286 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006287 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006288 }
6289 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006290 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006291 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006292 errors, &errorHandler,
6293 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006294 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006295 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006296 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006297 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006298 nextByte:
6299 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006300 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006301 Py_XDECREF(errorHandler);
6302 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006303 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006304
Benjamin Peterson29060642009-01-31 22:14:21 +00006305 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006306 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006307 Py_XDECREF(errorHandler);
6308 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006309 return NULL;
6310}
6311
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006312
Alexander Belopolsky40018472011-02-26 01:02:56 +00006313PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006314PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006315{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006316 char *p;
Victor Stinner358af132015-10-12 22:36:57 +02006317 Py_ssize_t pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006318 int kind;
6319 void *data;
6320 Py_ssize_t len;
Victor Stinner358af132015-10-12 22:36:57 +02006321 _PyBytesWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006322
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006323 if (!PyUnicode_Check(unicode)) {
6324 PyErr_BadArgument();
6325 return NULL;
6326 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006327 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006328 return NULL;
Victor Stinner358af132015-10-12 22:36:57 +02006329
6330 _PyBytesWriter_Init(&writer);
6331
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006332 kind = PyUnicode_KIND(unicode);
6333 data = PyUnicode_DATA(unicode);
6334 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner0e368262011-11-10 20:12:49 +01006335
Victor Stinner358af132015-10-12 22:36:57 +02006336 p = _PyBytesWriter_Alloc(&writer, len);
6337 if (p == NULL)
6338 goto error;
6339 writer.overallocate = 1;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006340
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006341 for (pos = 0; pos < len; pos++) {
6342 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006343 /* Map 32-bit characters to '\Uxxxxxxxx' */
6344 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006345 assert(ch <= MAX_UNICODE);
Victor Stinner358af132015-10-12 22:36:57 +02006346
6347 /* -1: substract 1 preallocated byte */
6348 p = _PyBytesWriter_Prepare(&writer, p, 10-1);
6349 if (p == NULL)
6350 goto error;
6351
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006352 *p++ = '\\';
6353 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006354 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6355 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6356 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6357 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6358 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6359 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6360 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6361 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006362 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006363 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006364 else if (ch >= 256) {
Victor Stinner358af132015-10-12 22:36:57 +02006365 /* -1: substract 1 preallocated byte */
6366 p = _PyBytesWriter_Prepare(&writer, p, 6-1);
6367 if (p == NULL)
6368 goto error;
6369
Guido van Rossumd57fd912000-03-10 22:53:23 +00006370 *p++ = '\\';
6371 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006372 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6373 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6374 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6375 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006376 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006377 /* Copy everything else as-is */
6378 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006379 *p++ = (char) ch;
6380 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006381
Victor Stinner358af132015-10-12 22:36:57 +02006382 return _PyBytesWriter_Finish(&writer, p);
6383
6384error:
6385 _PyBytesWriter_Dealloc(&writer);
6386 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006387}
6388
Alexander Belopolsky40018472011-02-26 01:02:56 +00006389PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006390PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6391 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006392{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006393 PyObject *result;
6394 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6395 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006396 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006397 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6398 Py_DECREF(tmp);
6399 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006400}
6401
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006402/* --- Unicode Internal Codec ------------------------------------------- */
6403
Alexander Belopolsky40018472011-02-26 01:02:56 +00006404PyObject *
6405_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006406 Py_ssize_t size,
6407 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006408{
6409 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006410 Py_ssize_t startinpos;
6411 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006412 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006413 const char *end;
6414 const char *reason;
6415 PyObject *errorHandler = NULL;
6416 PyObject *exc = NULL;
6417
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006418 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006419 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006420 1))
6421 return NULL;
6422
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006423 if (size == 0)
6424 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006425
Victor Stinner8f674cc2013-04-17 23:02:17 +02006426 _PyUnicodeWriter_Init(&writer);
6427 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6428 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006430 }
6431 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006432
Victor Stinner8f674cc2013-04-17 23:02:17 +02006433 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006434 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006435 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006436 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006437 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006438 endinpos = end-starts;
6439 reason = "truncated input";
6440 goto error;
6441 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006442 /* We copy the raw representation one byte at a time because the
6443 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006444 ((char *) &uch)[0] = s[0];
6445 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006446#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006447 ((char *) &uch)[2] = s[2];
6448 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006449#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006450 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006451#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006452 /* We have to sanity check the raw data, otherwise doom looms for
6453 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006454 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006455 endinpos = s - starts + Py_UNICODE_SIZE;
6456 reason = "illegal code point (> 0x10FFFF)";
6457 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006458 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006459#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006460 s += Py_UNICODE_SIZE;
6461#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006462 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006463 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006464 Py_UNICODE uch2;
6465 ((char *) &uch2)[0] = s[0];
6466 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006467 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006468 {
Victor Stinner551ac952011-11-29 22:58:13 +01006469 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006470 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006471 }
6472 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006473#endif
6474
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006475 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006476 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006477 continue;
6478
6479 error:
6480 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006481 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006482 errors, &errorHandler,
6483 "unicode_internal", reason,
6484 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006485 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006486 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006487 }
6488
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006489 Py_XDECREF(errorHandler);
6490 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006491 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006492
Benjamin Peterson29060642009-01-31 22:14:21 +00006493 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006494 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006495 Py_XDECREF(errorHandler);
6496 Py_XDECREF(exc);
6497 return NULL;
6498}
6499
Guido van Rossumd57fd912000-03-10 22:53:23 +00006500/* --- Latin-1 Codec ------------------------------------------------------ */
6501
Alexander Belopolsky40018472011-02-26 01:02:56 +00006502PyObject *
6503PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006504 Py_ssize_t size,
6505 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006506{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006507 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006508 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006509}
6510
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006511/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006512static void
6513make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006514 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006515 PyObject *unicode,
6516 Py_ssize_t startpos, Py_ssize_t endpos,
6517 const char *reason)
6518{
6519 if (*exceptionObject == NULL) {
6520 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006521 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006522 encoding, unicode, startpos, endpos, reason);
6523 }
6524 else {
6525 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6526 goto onError;
6527 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6528 goto onError;
6529 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6530 goto onError;
6531 return;
6532 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006533 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006534 }
6535}
6536
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006537/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006538static void
6539raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006540 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006541 PyObject *unicode,
6542 Py_ssize_t startpos, Py_ssize_t endpos,
6543 const char *reason)
6544{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006545 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006546 encoding, unicode, startpos, endpos, reason);
6547 if (*exceptionObject != NULL)
6548 PyCodec_StrictErrors(*exceptionObject);
6549}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006550
6551/* error handling callback helper:
6552 build arguments, call the callback and check the arguments,
6553 put the result into newpos and return the replacement string, which
6554 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006555static PyObject *
6556unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006557 PyObject **errorHandler,
6558 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006559 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006560 Py_ssize_t startpos, Py_ssize_t endpos,
6561 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006562{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006563 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006564 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006565 PyObject *restuple;
6566 PyObject *resunicode;
6567
6568 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006569 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006570 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006571 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006572 }
6573
Benjamin Petersonbac79492012-01-14 13:34:47 -05006574 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006575 return NULL;
6576 len = PyUnicode_GET_LENGTH(unicode);
6577
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006578 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006579 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006580 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006581 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006582
6583 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006584 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006585 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006586 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006587 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006588 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 Py_DECREF(restuple);
6590 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006591 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006592 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 &resunicode, newpos)) {
6594 Py_DECREF(restuple);
6595 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006596 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006597 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6598 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6599 Py_DECREF(restuple);
6600 return NULL;
6601 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006602 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006603 *newpos = len + *newpos;
6604 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006605 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006606 Py_DECREF(restuple);
6607 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006608 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006609 Py_INCREF(resunicode);
6610 Py_DECREF(restuple);
6611 return resunicode;
6612}
6613
Alexander Belopolsky40018472011-02-26 01:02:56 +00006614static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006615unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006616 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006617 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006618{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006619 /* input state */
6620 Py_ssize_t pos=0, size;
6621 int kind;
6622 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006623 /* pointer into the output */
6624 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006625 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6626 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006627 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006628 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006629 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006630 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006631 /* output object */
6632 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006633
Benjamin Petersonbac79492012-01-14 13:34:47 -05006634 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006635 return NULL;
6636 size = PyUnicode_GET_LENGTH(unicode);
6637 kind = PyUnicode_KIND(unicode);
6638 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006639 /* allocate enough for a simple encoding without
6640 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006641 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006642 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006643
6644 _PyBytesWriter_Init(&writer);
6645 str = _PyBytesWriter_Alloc(&writer, size);
6646 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006647 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006648
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006649 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006650 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006651
Benjamin Peterson29060642009-01-31 22:14:21 +00006652 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006653 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006654 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006655 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006656 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006657 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006658 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006659 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006660 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006661 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006662 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006663 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006664
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006665 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006666 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006667
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006668 /* Only overallocate the buffer if it's not the last write */
6669 writer.overallocate = (collend < size);
6670
Benjamin Peterson29060642009-01-31 22:14:21 +00006671 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006672 if (error_handler == _Py_ERROR_UNKNOWN)
6673 error_handler = get_error_handler(errors);
6674
6675 switch (error_handler) {
6676 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006677 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006678 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006679
6680 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006681 memset(str, '?', collend - collstart);
6682 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006683 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006684 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006685 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006686 break;
Victor Stinner50149202015-09-22 00:26:54 +02006687
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006688 case _Py_ERROR_BACKSLASHREPLACE:
Victor Stinnerad771582015-10-09 12:38:53 +02006689 /* substract preallocated bytes */
6690 writer.min_size -= (collend - collstart);
6691 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006692 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006693 if (str == NULL)
6694 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006695 pos = collend;
6696 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006697
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006698 case _Py_ERROR_XMLCHARREFREPLACE:
Victor Stinnerad771582015-10-09 12:38:53 +02006699 /* substract preallocated bytes */
6700 writer.min_size -= (collend - collstart);
6701 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006702 unicode, collstart, collend);
6703 if (str == NULL)
6704 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006705 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006706 break;
Victor Stinner50149202015-09-22 00:26:54 +02006707
Victor Stinnerc3713e92015-09-29 12:32:13 +02006708 case _Py_ERROR_SURROGATEESCAPE:
6709 for (i = collstart; i < collend; ++i) {
6710 ch = PyUnicode_READ(kind, data, i);
6711 if (ch < 0xdc80 || 0xdcff < ch) {
6712 /* Not a UTF-8b surrogate */
6713 break;
6714 }
6715 *str++ = (char)(ch - 0xdc00);
6716 ++pos;
6717 }
6718 if (i >= collend)
6719 break;
6720 collstart = pos;
6721 assert(collstart != collend);
6722 /* fallback to general error handling */
6723
Benjamin Peterson29060642009-01-31 22:14:21 +00006724 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006725 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6726 encoding, reason, unicode, &exc,
6727 collstart, collend, &newpos);
6728 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006730
Victor Stinnerad771582015-10-09 12:38:53 +02006731 /* substract preallocated bytes */
6732 writer.min_size -= 1;
6733
Victor Stinner6bd525b2015-10-09 13:10:05 +02006734 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006735 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006736 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006737 PyBytes_AS_STRING(rep),
6738 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006739 if (str == NULL)
6740 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006741 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006742 else {
6743 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006744
Victor Stinner6bd525b2015-10-09 13:10:05 +02006745 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006746 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006747
6748 if (PyUnicode_IS_ASCII(rep)) {
6749 /* Fast path: all characters are smaller than limit */
6750 assert(limit >= 128);
6751 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6752 str = _PyBytesWriter_WriteBytes(&writer, str,
6753 PyUnicode_DATA(rep),
6754 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006755 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006756 else {
6757 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6758
6759 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6760 if (str == NULL)
6761 goto onError;
6762
6763 /* check if there is anything unencodable in the
6764 replacement and copy it to the output */
6765 for (i = 0; repsize-->0; ++i, ++str) {
6766 ch = PyUnicode_READ_CHAR(rep, i);
6767 if (ch >= limit) {
6768 raise_encode_exception(&exc, encoding, unicode,
6769 pos, pos+1, reason);
6770 goto onError;
6771 }
6772 *str = (char)ch;
6773 }
6774 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006775 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006776 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006777 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006778 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006779
6780 /* If overallocation was disabled, ensure that it was the last
6781 write. Otherwise, we missed an optimization */
6782 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006783 }
6784 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006785
Victor Stinner50149202015-09-22 00:26:54 +02006786 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006787 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006788 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006789
6790 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006791 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006792 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006793 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006794 Py_XDECREF(exc);
6795 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006796}
6797
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006798/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006799PyObject *
6800PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006801 Py_ssize_t size,
6802 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006803{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006804 PyObject *result;
6805 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6806 if (unicode == NULL)
6807 return NULL;
6808 result = unicode_encode_ucs1(unicode, errors, 256);
6809 Py_DECREF(unicode);
6810 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006811}
6812
Alexander Belopolsky40018472011-02-26 01:02:56 +00006813PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006814_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006815{
6816 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006817 PyErr_BadArgument();
6818 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006819 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006820 if (PyUnicode_READY(unicode) == -1)
6821 return NULL;
6822 /* Fast path: if it is a one-byte string, construct
6823 bytes object directly. */
6824 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6825 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6826 PyUnicode_GET_LENGTH(unicode));
6827 /* Non-Latin-1 characters present. Defer to above function to
6828 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006829 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006830}
6831
6832PyObject*
6833PyUnicode_AsLatin1String(PyObject *unicode)
6834{
6835 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006836}
6837
6838/* --- 7-bit ASCII Codec -------------------------------------------------- */
6839
Alexander Belopolsky40018472011-02-26 01:02:56 +00006840PyObject *
6841PyUnicode_DecodeASCII(const char *s,
6842 Py_ssize_t size,
6843 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006844{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006845 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006846 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006847 int kind;
6848 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006849 Py_ssize_t startinpos;
6850 Py_ssize_t endinpos;
6851 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006852 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006853 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006854 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006855 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006856
Guido van Rossumd57fd912000-03-10 22:53:23 +00006857 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006858 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006859
Guido van Rossumd57fd912000-03-10 22:53:23 +00006860 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006861 if (size == 1 && (unsigned char)s[0] < 128)
6862 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006863
Victor Stinner8f674cc2013-04-17 23:02:17 +02006864 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006865 writer.min_length = size;
6866 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006867 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006868
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006869 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006870 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006871 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006872 writer.pos = outpos;
6873 if (writer.pos == size)
6874 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006875
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006876 s += writer.pos;
6877 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006878 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006879 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006880 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006881 PyUnicode_WRITE(kind, data, writer.pos, c);
6882 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006883 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006884 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006885 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006886
6887 /* byte outsize range 0x00..0x7f: call the error handler */
6888
6889 if (error_handler == _Py_ERROR_UNKNOWN)
6890 error_handler = get_error_handler(errors);
6891
6892 switch (error_handler)
6893 {
6894 case _Py_ERROR_REPLACE:
6895 case _Py_ERROR_SURROGATEESCAPE:
6896 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006897 but we may switch to UCS2 at the first write */
6898 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6899 goto onError;
6900 kind = writer.kind;
6901 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006902
6903 if (error_handler == _Py_ERROR_REPLACE)
6904 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6905 else
6906 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6907 writer.pos++;
6908 ++s;
6909 break;
6910
6911 case _Py_ERROR_IGNORE:
6912 ++s;
6913 break;
6914
6915 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006916 startinpos = s-starts;
6917 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006918 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006919 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006920 "ascii", "ordinal not in range(128)",
6921 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006922 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006923 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006924 kind = writer.kind;
6925 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006926 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006927 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006928 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006929 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006930 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006931
Benjamin Peterson29060642009-01-31 22:14:21 +00006932 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006933 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006934 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006935 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006936 return NULL;
6937}
6938
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006939/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006940PyObject *
6941PyUnicode_EncodeASCII(const Py_UNICODE *p,
6942 Py_ssize_t size,
6943 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006944{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006945 PyObject *result;
6946 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6947 if (unicode == NULL)
6948 return NULL;
6949 result = unicode_encode_ucs1(unicode, errors, 128);
6950 Py_DECREF(unicode);
6951 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006952}
6953
Alexander Belopolsky40018472011-02-26 01:02:56 +00006954PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006955_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006956{
6957 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006958 PyErr_BadArgument();
6959 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006960 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006961 if (PyUnicode_READY(unicode) == -1)
6962 return NULL;
6963 /* Fast path: if it is an ASCII-only string, construct bytes object
6964 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006965 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006966 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6967 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006968 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006969}
6970
6971PyObject *
6972PyUnicode_AsASCIIString(PyObject *unicode)
6973{
6974 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006975}
6976
Victor Stinner99b95382011-07-04 14:23:54 +02006977#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006978
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006979/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006980
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006981#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006982#define NEED_RETRY
6983#endif
6984
Victor Stinner3a50e702011-10-18 21:21:00 +02006985#ifndef WC_ERR_INVALID_CHARS
6986# define WC_ERR_INVALID_CHARS 0x0080
6987#endif
6988
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02006989static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02006990code_page_name(UINT code_page, PyObject **obj)
6991{
6992 *obj = NULL;
6993 if (code_page == CP_ACP)
6994 return "mbcs";
6995 if (code_page == CP_UTF7)
6996 return "CP_UTF7";
6997 if (code_page == CP_UTF8)
6998 return "CP_UTF8";
6999
7000 *obj = PyBytes_FromFormat("cp%u", code_page);
7001 if (*obj == NULL)
7002 return NULL;
7003 return PyBytes_AS_STRING(*obj);
7004}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007005
Victor Stinner3a50e702011-10-18 21:21:00 +02007006static DWORD
7007decode_code_page_flags(UINT code_page)
7008{
7009 if (code_page == CP_UTF7) {
7010 /* The CP_UTF7 decoder only supports flags=0 */
7011 return 0;
7012 }
7013 else
7014 return MB_ERR_INVALID_CHARS;
7015}
7016
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007017/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007018 * Decode a byte string from a Windows code page into unicode object in strict
7019 * mode.
7020 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007021 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7022 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007023 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007024static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007025decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007026 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007027 const char *in,
7028 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007029{
Victor Stinner3a50e702011-10-18 21:21:00 +02007030 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007031 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007032 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007033
7034 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007035 assert(insize > 0);
7036 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7037 if (outsize <= 0)
7038 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007039
7040 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007041 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007042 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007043 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007044 if (*v == NULL)
7045 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007046 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007047 }
7048 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007049 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007050 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007051 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007052 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007053 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007054 }
7055
7056 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007057 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7058 if (outsize <= 0)
7059 goto error;
7060 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007061
Victor Stinner3a50e702011-10-18 21:21:00 +02007062error:
7063 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7064 return -2;
7065 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007066 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007067}
7068
Victor Stinner3a50e702011-10-18 21:21:00 +02007069/*
7070 * Decode a byte string from a code page into unicode object with an error
7071 * handler.
7072 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007073 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007074 * UnicodeDecodeError exception and returns -1 on error.
7075 */
7076static int
7077decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007078 PyObject **v,
7079 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007080 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007081{
7082 const char *startin = in;
7083 const char *endin = in + size;
7084 const DWORD flags = decode_code_page_flags(code_page);
7085 /* Ideally, we should get reason from FormatMessage. This is the Windows
7086 2000 English version of the message. */
7087 const char *reason = "No mapping for the Unicode character exists "
7088 "in the target code page.";
7089 /* each step cannot decode more than 1 character, but a character can be
7090 represented as a surrogate pair */
7091 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007092 int insize;
7093 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007094 PyObject *errorHandler = NULL;
7095 PyObject *exc = NULL;
7096 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007097 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007098 DWORD err;
7099 int ret = -1;
7100
7101 assert(size > 0);
7102
7103 encoding = code_page_name(code_page, &encoding_obj);
7104 if (encoding == NULL)
7105 return -1;
7106
Victor Stinner7d00cc12014-03-17 23:08:06 +01007107 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007108 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7109 UnicodeDecodeError. */
7110 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7111 if (exc != NULL) {
7112 PyCodec_StrictErrors(exc);
7113 Py_CLEAR(exc);
7114 }
7115 goto error;
7116 }
7117
7118 if (*v == NULL) {
7119 /* Create unicode object */
7120 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7121 PyErr_NoMemory();
7122 goto error;
7123 }
Victor Stinnerab595942011-12-17 04:59:06 +01007124 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007125 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007126 if (*v == NULL)
7127 goto error;
7128 startout = PyUnicode_AS_UNICODE(*v);
7129 }
7130 else {
7131 /* Extend unicode object */
7132 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7133 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7134 PyErr_NoMemory();
7135 goto error;
7136 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007137 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007138 goto error;
7139 startout = PyUnicode_AS_UNICODE(*v) + n;
7140 }
7141
7142 /* Decode the byte string character per character */
7143 out = startout;
7144 while (in < endin)
7145 {
7146 /* Decode a character */
7147 insize = 1;
7148 do
7149 {
7150 outsize = MultiByteToWideChar(code_page, flags,
7151 in, insize,
7152 buffer, Py_ARRAY_LENGTH(buffer));
7153 if (outsize > 0)
7154 break;
7155 err = GetLastError();
7156 if (err != ERROR_NO_UNICODE_TRANSLATION
7157 && err != ERROR_INSUFFICIENT_BUFFER)
7158 {
7159 PyErr_SetFromWindowsErr(0);
7160 goto error;
7161 }
7162 insize++;
7163 }
7164 /* 4=maximum length of a UTF-8 sequence */
7165 while (insize <= 4 && (in + insize) <= endin);
7166
7167 if (outsize <= 0) {
7168 Py_ssize_t startinpos, endinpos, outpos;
7169
Victor Stinner7d00cc12014-03-17 23:08:06 +01007170 /* last character in partial decode? */
7171 if (in + insize >= endin && !final)
7172 break;
7173
Victor Stinner3a50e702011-10-18 21:21:00 +02007174 startinpos = in - startin;
7175 endinpos = startinpos + 1;
7176 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007177 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007178 errors, &errorHandler,
7179 encoding, reason,
7180 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007181 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007182 {
7183 goto error;
7184 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007185 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007186 }
7187 else {
7188 in += insize;
7189 memcpy(out, buffer, outsize * sizeof(wchar_t));
7190 out += outsize;
7191 }
7192 }
7193
7194 /* write a NUL character at the end */
7195 *out = 0;
7196
7197 /* Extend unicode object */
7198 outsize = out - startout;
7199 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007200 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007202 /* (in - startin) <= size and size is an int */
7203 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007204
7205error:
7206 Py_XDECREF(encoding_obj);
7207 Py_XDECREF(errorHandler);
7208 Py_XDECREF(exc);
7209 return ret;
7210}
7211
Victor Stinner3a50e702011-10-18 21:21:00 +02007212static PyObject *
7213decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007214 const char *s, Py_ssize_t size,
7215 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007216{
Victor Stinner76a31a62011-11-04 00:05:13 +01007217 PyObject *v = NULL;
7218 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007219
Victor Stinner3a50e702011-10-18 21:21:00 +02007220 if (code_page < 0) {
7221 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7222 return NULL;
7223 }
7224
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007225 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007226 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007227
Victor Stinner76a31a62011-11-04 00:05:13 +01007228 do
7229 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007230#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007231 if (size > INT_MAX) {
7232 chunk_size = INT_MAX;
7233 final = 0;
7234 done = 0;
7235 }
7236 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007237#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007238 {
7239 chunk_size = (int)size;
7240 final = (consumed == NULL);
7241 done = 1;
7242 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007243
Victor Stinner76a31a62011-11-04 00:05:13 +01007244 if (chunk_size == 0 && done) {
7245 if (v != NULL)
7246 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007247 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007248 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007249
Victor Stinner76a31a62011-11-04 00:05:13 +01007250 converted = decode_code_page_strict(code_page, &v,
7251 s, chunk_size);
7252 if (converted == -2)
7253 converted = decode_code_page_errors(code_page, &v,
7254 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007255 errors, final);
7256 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007257
7258 if (converted < 0) {
7259 Py_XDECREF(v);
7260 return NULL;
7261 }
7262
7263 if (consumed)
7264 *consumed += converted;
7265
7266 s += converted;
7267 size -= converted;
7268 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007269
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007270 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007271}
7272
Alexander Belopolsky40018472011-02-26 01:02:56 +00007273PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007274PyUnicode_DecodeCodePageStateful(int code_page,
7275 const char *s,
7276 Py_ssize_t size,
7277 const char *errors,
7278 Py_ssize_t *consumed)
7279{
7280 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7281}
7282
7283PyObject *
7284PyUnicode_DecodeMBCSStateful(const char *s,
7285 Py_ssize_t size,
7286 const char *errors,
7287 Py_ssize_t *consumed)
7288{
7289 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7290}
7291
7292PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007293PyUnicode_DecodeMBCS(const char *s,
7294 Py_ssize_t size,
7295 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007296{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007297 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7298}
7299
Victor Stinner3a50e702011-10-18 21:21:00 +02007300static DWORD
7301encode_code_page_flags(UINT code_page, const char *errors)
7302{
7303 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007304 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007305 }
7306 else if (code_page == CP_UTF7) {
7307 /* CP_UTF7 only supports flags=0 */
7308 return 0;
7309 }
7310 else {
7311 if (errors != NULL && strcmp(errors, "replace") == 0)
7312 return 0;
7313 else
7314 return WC_NO_BEST_FIT_CHARS;
7315 }
7316}
7317
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007318/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007319 * Encode a Unicode string to a Windows code page into a byte string in strict
7320 * mode.
7321 *
7322 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007323 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007324 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007325static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007326encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007327 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007328 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007329{
Victor Stinner554f3f02010-06-16 23:33:54 +00007330 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007331 BOOL *pusedDefaultChar = &usedDefaultChar;
7332 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007333 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007334 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007335 const DWORD flags = encode_code_page_flags(code_page, NULL);
7336 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007337 /* Create a substring so that we can get the UTF-16 representation
7338 of just the slice under consideration. */
7339 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007340
Martin v. Löwis3d325192011-11-04 18:23:06 +01007341 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007342
Victor Stinner3a50e702011-10-18 21:21:00 +02007343 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007344 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007345 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007346 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007347
Victor Stinner2fc507f2011-11-04 20:06:39 +01007348 substring = PyUnicode_Substring(unicode, offset, offset+len);
7349 if (substring == NULL)
7350 return -1;
7351 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7352 if (p == NULL) {
7353 Py_DECREF(substring);
7354 return -1;
7355 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007356 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007357
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007358 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007359 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007360 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007361 NULL, 0,
7362 NULL, pusedDefaultChar);
7363 if (outsize <= 0)
7364 goto error;
7365 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007366 if (pusedDefaultChar && *pusedDefaultChar) {
7367 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007368 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007369 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007370
Victor Stinner3a50e702011-10-18 21:21:00 +02007371 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007372 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007373 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007374 if (*outbytes == NULL) {
7375 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007376 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007377 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007378 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007379 }
7380 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007381 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007382 const Py_ssize_t n = PyBytes_Size(*outbytes);
7383 if (outsize > PY_SSIZE_T_MAX - n) {
7384 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007385 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007386 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007387 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007388 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7389 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007390 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007391 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007393 }
7394
7395 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007396 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007397 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007398 out, outsize,
7399 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007400 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007401 if (outsize <= 0)
7402 goto error;
7403 if (pusedDefaultChar && *pusedDefaultChar)
7404 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007405 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007406
Victor Stinner3a50e702011-10-18 21:21:00 +02007407error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007408 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007409 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7410 return -2;
7411 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007412 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007413}
7414
Victor Stinner3a50e702011-10-18 21:21:00 +02007415/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007416 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007417 * error handler.
7418 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007419 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 * -1 on other error.
7421 */
7422static int
7423encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007424 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007425 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007426{
Victor Stinner3a50e702011-10-18 21:21:00 +02007427 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007428 Py_ssize_t pos = unicode_offset;
7429 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007430 /* Ideally, we should get reason from FormatMessage. This is the Windows
7431 2000 English version of the message. */
7432 const char *reason = "invalid character";
7433 /* 4=maximum length of a UTF-8 sequence */
7434 char buffer[4];
7435 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7436 Py_ssize_t outsize;
7437 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007438 PyObject *errorHandler = NULL;
7439 PyObject *exc = NULL;
7440 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007441 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007442 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007443 PyObject *rep;
7444 int ret = -1;
7445
7446 assert(insize > 0);
7447
7448 encoding = code_page_name(code_page, &encoding_obj);
7449 if (encoding == NULL)
7450 return -1;
7451
7452 if (errors == NULL || strcmp(errors, "strict") == 0) {
7453 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7454 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007455 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007456 if (exc != NULL) {
7457 PyCodec_StrictErrors(exc);
7458 Py_DECREF(exc);
7459 }
7460 Py_XDECREF(encoding_obj);
7461 return -1;
7462 }
7463
7464 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7465 pusedDefaultChar = &usedDefaultChar;
7466 else
7467 pusedDefaultChar = NULL;
7468
7469 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7470 PyErr_NoMemory();
7471 goto error;
7472 }
7473 outsize = insize * Py_ARRAY_LENGTH(buffer);
7474
7475 if (*outbytes == NULL) {
7476 /* Create string object */
7477 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7478 if (*outbytes == NULL)
7479 goto error;
7480 out = PyBytes_AS_STRING(*outbytes);
7481 }
7482 else {
7483 /* Extend string object */
7484 Py_ssize_t n = PyBytes_Size(*outbytes);
7485 if (n > PY_SSIZE_T_MAX - outsize) {
7486 PyErr_NoMemory();
7487 goto error;
7488 }
7489 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7490 goto error;
7491 out = PyBytes_AS_STRING(*outbytes) + n;
7492 }
7493
7494 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007495 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007496 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007497 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7498 wchar_t chars[2];
7499 int charsize;
7500 if (ch < 0x10000) {
7501 chars[0] = (wchar_t)ch;
7502 charsize = 1;
7503 }
7504 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007505 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7506 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007507 charsize = 2;
7508 }
7509
Victor Stinner3a50e702011-10-18 21:21:00 +02007510 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007511 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007512 buffer, Py_ARRAY_LENGTH(buffer),
7513 NULL, pusedDefaultChar);
7514 if (outsize > 0) {
7515 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7516 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007517 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007518 memcpy(out, buffer, outsize);
7519 out += outsize;
7520 continue;
7521 }
7522 }
7523 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7524 PyErr_SetFromWindowsErr(0);
7525 goto error;
7526 }
7527
Victor Stinner3a50e702011-10-18 21:21:00 +02007528 rep = unicode_encode_call_errorhandler(
7529 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007530 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007531 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007532 if (rep == NULL)
7533 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007534 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007535
7536 if (PyBytes_Check(rep)) {
7537 outsize = PyBytes_GET_SIZE(rep);
7538 if (outsize != 1) {
7539 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7540 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7541 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7542 Py_DECREF(rep);
7543 goto error;
7544 }
7545 out = PyBytes_AS_STRING(*outbytes) + offset;
7546 }
7547 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7548 out += outsize;
7549 }
7550 else {
7551 Py_ssize_t i;
7552 enum PyUnicode_Kind kind;
7553 void *data;
7554
Benjamin Petersonbac79492012-01-14 13:34:47 -05007555 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007556 Py_DECREF(rep);
7557 goto error;
7558 }
7559
7560 outsize = PyUnicode_GET_LENGTH(rep);
7561 if (outsize != 1) {
7562 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7563 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7564 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7565 Py_DECREF(rep);
7566 goto error;
7567 }
7568 out = PyBytes_AS_STRING(*outbytes) + offset;
7569 }
7570 kind = PyUnicode_KIND(rep);
7571 data = PyUnicode_DATA(rep);
7572 for (i=0; i < outsize; i++) {
7573 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7574 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007575 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007576 encoding, unicode,
7577 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007578 "unable to encode error handler result to ASCII");
7579 Py_DECREF(rep);
7580 goto error;
7581 }
7582 *out = (unsigned char)ch;
7583 out++;
7584 }
7585 }
7586 Py_DECREF(rep);
7587 }
7588 /* write a NUL byte */
7589 *out = 0;
7590 outsize = out - PyBytes_AS_STRING(*outbytes);
7591 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7592 if (_PyBytes_Resize(outbytes, outsize) < 0)
7593 goto error;
7594 ret = 0;
7595
7596error:
7597 Py_XDECREF(encoding_obj);
7598 Py_XDECREF(errorHandler);
7599 Py_XDECREF(exc);
7600 return ret;
7601}
7602
Victor Stinner3a50e702011-10-18 21:21:00 +02007603static PyObject *
7604encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007605 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007606 const char *errors)
7607{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007608 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007609 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007610 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007611 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007612
Victor Stinner29dacf22015-01-26 16:41:32 +01007613 if (!PyUnicode_Check(unicode)) {
7614 PyErr_BadArgument();
7615 return NULL;
7616 }
7617
Benjamin Petersonbac79492012-01-14 13:34:47 -05007618 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007619 return NULL;
7620 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007621
Victor Stinner3a50e702011-10-18 21:21:00 +02007622 if (code_page < 0) {
7623 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7624 return NULL;
7625 }
7626
Martin v. Löwis3d325192011-11-04 18:23:06 +01007627 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007628 return PyBytes_FromStringAndSize(NULL, 0);
7629
Victor Stinner7581cef2011-11-03 22:32:33 +01007630 offset = 0;
7631 do
7632 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007633#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007634 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007635 chunks. */
7636 if (len > INT_MAX/2) {
7637 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007638 done = 0;
7639 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007640 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007641#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007642 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007643 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007644 done = 1;
7645 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007646
Victor Stinner76a31a62011-11-04 00:05:13 +01007647 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007648 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007649 errors);
7650 if (ret == -2)
7651 ret = encode_code_page_errors(code_page, &outbytes,
7652 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007653 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007654 if (ret < 0) {
7655 Py_XDECREF(outbytes);
7656 return NULL;
7657 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007658
Victor Stinner7581cef2011-11-03 22:32:33 +01007659 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007660 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007661 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007662
Victor Stinner3a50e702011-10-18 21:21:00 +02007663 return outbytes;
7664}
7665
7666PyObject *
7667PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7668 Py_ssize_t size,
7669 const char *errors)
7670{
Victor Stinner7581cef2011-11-03 22:32:33 +01007671 PyObject *unicode, *res;
7672 unicode = PyUnicode_FromUnicode(p, size);
7673 if (unicode == NULL)
7674 return NULL;
7675 res = encode_code_page(CP_ACP, unicode, errors);
7676 Py_DECREF(unicode);
7677 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007678}
7679
7680PyObject *
7681PyUnicode_EncodeCodePage(int code_page,
7682 PyObject *unicode,
7683 const char *errors)
7684{
Victor Stinner7581cef2011-11-03 22:32:33 +01007685 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007686}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007687
Alexander Belopolsky40018472011-02-26 01:02:56 +00007688PyObject *
7689PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007690{
Victor Stinner7581cef2011-11-03 22:32:33 +01007691 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007692}
7693
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007694#undef NEED_RETRY
7695
Victor Stinner99b95382011-07-04 14:23:54 +02007696#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007697
Guido van Rossumd57fd912000-03-10 22:53:23 +00007698/* --- Character Mapping Codec -------------------------------------------- */
7699
Victor Stinnerfb161b12013-04-18 01:44:27 +02007700static int
7701charmap_decode_string(const char *s,
7702 Py_ssize_t size,
7703 PyObject *mapping,
7704 const char *errors,
7705 _PyUnicodeWriter *writer)
7706{
7707 const char *starts = s;
7708 const char *e;
7709 Py_ssize_t startinpos, endinpos;
7710 PyObject *errorHandler = NULL, *exc = NULL;
7711 Py_ssize_t maplen;
7712 enum PyUnicode_Kind mapkind;
7713 void *mapdata;
7714 Py_UCS4 x;
7715 unsigned char ch;
7716
7717 if (PyUnicode_READY(mapping) == -1)
7718 return -1;
7719
7720 maplen = PyUnicode_GET_LENGTH(mapping);
7721 mapdata = PyUnicode_DATA(mapping);
7722 mapkind = PyUnicode_KIND(mapping);
7723
7724 e = s + size;
7725
7726 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7727 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7728 * is disabled in encoding aliases, latin1 is preferred because
7729 * its implementation is faster. */
7730 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7731 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7732 Py_UCS4 maxchar = writer->maxchar;
7733
7734 assert (writer->kind == PyUnicode_1BYTE_KIND);
7735 while (s < e) {
7736 ch = *s;
7737 x = mapdata_ucs1[ch];
7738 if (x > maxchar) {
7739 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7740 goto onError;
7741 maxchar = writer->maxchar;
7742 outdata = (Py_UCS1 *)writer->data;
7743 }
7744 outdata[writer->pos] = x;
7745 writer->pos++;
7746 ++s;
7747 }
7748 return 0;
7749 }
7750
7751 while (s < e) {
7752 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7753 enum PyUnicode_Kind outkind = writer->kind;
7754 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7755 if (outkind == PyUnicode_1BYTE_KIND) {
7756 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7757 Py_UCS4 maxchar = writer->maxchar;
7758 while (s < e) {
7759 ch = *s;
7760 x = mapdata_ucs2[ch];
7761 if (x > maxchar)
7762 goto Error;
7763 outdata[writer->pos] = x;
7764 writer->pos++;
7765 ++s;
7766 }
7767 break;
7768 }
7769 else if (outkind == PyUnicode_2BYTE_KIND) {
7770 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7771 while (s < e) {
7772 ch = *s;
7773 x = mapdata_ucs2[ch];
7774 if (x == 0xFFFE)
7775 goto Error;
7776 outdata[writer->pos] = x;
7777 writer->pos++;
7778 ++s;
7779 }
7780 break;
7781 }
7782 }
7783 ch = *s;
7784
7785 if (ch < maplen)
7786 x = PyUnicode_READ(mapkind, mapdata, ch);
7787 else
7788 x = 0xfffe; /* invalid value */
7789Error:
7790 if (x == 0xfffe)
7791 {
7792 /* undefined mapping */
7793 startinpos = s-starts;
7794 endinpos = startinpos+1;
7795 if (unicode_decode_call_errorhandler_writer(
7796 errors, &errorHandler,
7797 "charmap", "character maps to <undefined>",
7798 &starts, &e, &startinpos, &endinpos, &exc, &s,
7799 writer)) {
7800 goto onError;
7801 }
7802 continue;
7803 }
7804
7805 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7806 goto onError;
7807 ++s;
7808 }
7809 Py_XDECREF(errorHandler);
7810 Py_XDECREF(exc);
7811 return 0;
7812
7813onError:
7814 Py_XDECREF(errorHandler);
7815 Py_XDECREF(exc);
7816 return -1;
7817}
7818
7819static int
7820charmap_decode_mapping(const char *s,
7821 Py_ssize_t size,
7822 PyObject *mapping,
7823 const char *errors,
7824 _PyUnicodeWriter *writer)
7825{
7826 const char *starts = s;
7827 const char *e;
7828 Py_ssize_t startinpos, endinpos;
7829 PyObject *errorHandler = NULL, *exc = NULL;
7830 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007831 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007832
7833 e = s + size;
7834
7835 while (s < e) {
7836 ch = *s;
7837
7838 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7839 key = PyLong_FromLong((long)ch);
7840 if (key == NULL)
7841 goto onError;
7842
7843 item = PyObject_GetItem(mapping, key);
7844 Py_DECREF(key);
7845 if (item == NULL) {
7846 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7847 /* No mapping found means: mapping is undefined. */
7848 PyErr_Clear();
7849 goto Undefined;
7850 } else
7851 goto onError;
7852 }
7853
7854 /* Apply mapping */
7855 if (item == Py_None)
7856 goto Undefined;
7857 if (PyLong_Check(item)) {
7858 long value = PyLong_AS_LONG(item);
7859 if (value == 0xFFFE)
7860 goto Undefined;
7861 if (value < 0 || value > MAX_UNICODE) {
7862 PyErr_Format(PyExc_TypeError,
7863 "character mapping must be in range(0x%lx)",
7864 (unsigned long)MAX_UNICODE + 1);
7865 goto onError;
7866 }
7867
7868 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7869 goto onError;
7870 }
7871 else if (PyUnicode_Check(item)) {
7872 if (PyUnicode_READY(item) == -1)
7873 goto onError;
7874 if (PyUnicode_GET_LENGTH(item) == 1) {
7875 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7876 if (value == 0xFFFE)
7877 goto Undefined;
7878 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7879 goto onError;
7880 }
7881 else {
7882 writer->overallocate = 1;
7883 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7884 goto onError;
7885 }
7886 }
7887 else {
7888 /* wrong return value */
7889 PyErr_SetString(PyExc_TypeError,
7890 "character mapping must return integer, None or str");
7891 goto onError;
7892 }
7893 Py_CLEAR(item);
7894 ++s;
7895 continue;
7896
7897Undefined:
7898 /* undefined mapping */
7899 Py_CLEAR(item);
7900 startinpos = s-starts;
7901 endinpos = startinpos+1;
7902 if (unicode_decode_call_errorhandler_writer(
7903 errors, &errorHandler,
7904 "charmap", "character maps to <undefined>",
7905 &starts, &e, &startinpos, &endinpos, &exc, &s,
7906 writer)) {
7907 goto onError;
7908 }
7909 }
7910 Py_XDECREF(errorHandler);
7911 Py_XDECREF(exc);
7912 return 0;
7913
7914onError:
7915 Py_XDECREF(item);
7916 Py_XDECREF(errorHandler);
7917 Py_XDECREF(exc);
7918 return -1;
7919}
7920
Alexander Belopolsky40018472011-02-26 01:02:56 +00007921PyObject *
7922PyUnicode_DecodeCharmap(const char *s,
7923 Py_ssize_t size,
7924 PyObject *mapping,
7925 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007926{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007927 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007928
Guido van Rossumd57fd912000-03-10 22:53:23 +00007929 /* Default to Latin-1 */
7930 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007931 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007932
Guido van Rossumd57fd912000-03-10 22:53:23 +00007933 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007934 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007935 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007936 writer.min_length = size;
7937 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007938 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007939
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007940 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007941 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7942 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007943 }
7944 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007945 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7946 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007947 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007948 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007949
Benjamin Peterson29060642009-01-31 22:14:21 +00007950 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007951 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007952 return NULL;
7953}
7954
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007955/* Charmap encoding: the lookup table */
7956
Alexander Belopolsky40018472011-02-26 01:02:56 +00007957struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007958 PyObject_HEAD
7959 unsigned char level1[32];
7960 int count2, count3;
7961 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007962};
7963
7964static PyObject*
7965encoding_map_size(PyObject *obj, PyObject* args)
7966{
7967 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007968 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007969 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007970}
7971
7972static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007973 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007974 PyDoc_STR("Return the size (in bytes) of this object") },
7975 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007976};
7977
7978static void
7979encoding_map_dealloc(PyObject* o)
7980{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007981 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007982}
7983
7984static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007985 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007986 "EncodingMap", /*tp_name*/
7987 sizeof(struct encoding_map), /*tp_basicsize*/
7988 0, /*tp_itemsize*/
7989 /* methods */
7990 encoding_map_dealloc, /*tp_dealloc*/
7991 0, /*tp_print*/
7992 0, /*tp_getattr*/
7993 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007994 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007995 0, /*tp_repr*/
7996 0, /*tp_as_number*/
7997 0, /*tp_as_sequence*/
7998 0, /*tp_as_mapping*/
7999 0, /*tp_hash*/
8000 0, /*tp_call*/
8001 0, /*tp_str*/
8002 0, /*tp_getattro*/
8003 0, /*tp_setattro*/
8004 0, /*tp_as_buffer*/
8005 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8006 0, /*tp_doc*/
8007 0, /*tp_traverse*/
8008 0, /*tp_clear*/
8009 0, /*tp_richcompare*/
8010 0, /*tp_weaklistoffset*/
8011 0, /*tp_iter*/
8012 0, /*tp_iternext*/
8013 encoding_map_methods, /*tp_methods*/
8014 0, /*tp_members*/
8015 0, /*tp_getset*/
8016 0, /*tp_base*/
8017 0, /*tp_dict*/
8018 0, /*tp_descr_get*/
8019 0, /*tp_descr_set*/
8020 0, /*tp_dictoffset*/
8021 0, /*tp_init*/
8022 0, /*tp_alloc*/
8023 0, /*tp_new*/
8024 0, /*tp_free*/
8025 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008026};
8027
8028PyObject*
8029PyUnicode_BuildEncodingMap(PyObject* string)
8030{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008031 PyObject *result;
8032 struct encoding_map *mresult;
8033 int i;
8034 int need_dict = 0;
8035 unsigned char level1[32];
8036 unsigned char level2[512];
8037 unsigned char *mlevel1, *mlevel2, *mlevel3;
8038 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008039 int kind;
8040 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008041 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008042 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008043
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008044 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008045 PyErr_BadArgument();
8046 return NULL;
8047 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008048 kind = PyUnicode_KIND(string);
8049 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008050 length = PyUnicode_GET_LENGTH(string);
8051 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008052 memset(level1, 0xFF, sizeof level1);
8053 memset(level2, 0xFF, sizeof level2);
8054
8055 /* If there isn't a one-to-one mapping of NULL to \0,
8056 or if there are non-BMP characters, we need to use
8057 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008058 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008059 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008060 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008061 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008062 ch = PyUnicode_READ(kind, data, i);
8063 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008064 need_dict = 1;
8065 break;
8066 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008067 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008068 /* unmapped character */
8069 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008070 l1 = ch >> 11;
8071 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008072 if (level1[l1] == 0xFF)
8073 level1[l1] = count2++;
8074 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008075 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008076 }
8077
8078 if (count2 >= 0xFF || count3 >= 0xFF)
8079 need_dict = 1;
8080
8081 if (need_dict) {
8082 PyObject *result = PyDict_New();
8083 PyObject *key, *value;
8084 if (!result)
8085 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008086 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008087 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008088 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008089 if (!key || !value)
8090 goto failed1;
8091 if (PyDict_SetItem(result, key, value) == -1)
8092 goto failed1;
8093 Py_DECREF(key);
8094 Py_DECREF(value);
8095 }
8096 return result;
8097 failed1:
8098 Py_XDECREF(key);
8099 Py_XDECREF(value);
8100 Py_DECREF(result);
8101 return NULL;
8102 }
8103
8104 /* Create a three-level trie */
8105 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8106 16*count2 + 128*count3 - 1);
8107 if (!result)
8108 return PyErr_NoMemory();
8109 PyObject_Init(result, &EncodingMapType);
8110 mresult = (struct encoding_map*)result;
8111 mresult->count2 = count2;
8112 mresult->count3 = count3;
8113 mlevel1 = mresult->level1;
8114 mlevel2 = mresult->level23;
8115 mlevel3 = mresult->level23 + 16*count2;
8116 memcpy(mlevel1, level1, 32);
8117 memset(mlevel2, 0xFF, 16*count2);
8118 memset(mlevel3, 0, 128*count3);
8119 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008120 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008121 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008122 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8123 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008124 /* unmapped character */
8125 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008126 o1 = ch>>11;
8127 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008128 i2 = 16*mlevel1[o1] + o2;
8129 if (mlevel2[i2] == 0xFF)
8130 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008131 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008132 i3 = 128*mlevel2[i2] + o3;
8133 mlevel3[i3] = i;
8134 }
8135 return result;
8136}
8137
8138static int
Victor Stinner22168992011-11-20 17:09:18 +01008139encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008140{
8141 struct encoding_map *map = (struct encoding_map*)mapping;
8142 int l1 = c>>11;
8143 int l2 = (c>>7) & 0xF;
8144 int l3 = c & 0x7F;
8145 int i;
8146
Victor Stinner22168992011-11-20 17:09:18 +01008147 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008149 if (c == 0)
8150 return 0;
8151 /* level 1*/
8152 i = map->level1[l1];
8153 if (i == 0xFF) {
8154 return -1;
8155 }
8156 /* level 2*/
8157 i = map->level23[16*i+l2];
8158 if (i == 0xFF) {
8159 return -1;
8160 }
8161 /* level 3 */
8162 i = map->level23[16*map->count2 + 128*i + l3];
8163 if (i == 0) {
8164 return -1;
8165 }
8166 return i;
8167}
8168
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008169/* Lookup the character ch in the mapping. If the character
8170 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008171 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008172static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008173charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008174{
Christian Heimes217cfd12007-12-02 14:31:20 +00008175 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008176 PyObject *x;
8177
8178 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008179 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008180 x = PyObject_GetItem(mapping, w);
8181 Py_DECREF(w);
8182 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008183 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8184 /* No mapping found means: mapping is undefined. */
8185 PyErr_Clear();
8186 x = Py_None;
8187 Py_INCREF(x);
8188 return x;
8189 } else
8190 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008191 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008192 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008193 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008194 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008195 long value = PyLong_AS_LONG(x);
8196 if (value < 0 || value > 255) {
8197 PyErr_SetString(PyExc_TypeError,
8198 "character mapping must be in range(256)");
8199 Py_DECREF(x);
8200 return NULL;
8201 }
8202 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008203 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008204 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008205 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008206 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008207 /* wrong return value */
8208 PyErr_Format(PyExc_TypeError,
8209 "character mapping must return integer, bytes or None, not %.400s",
8210 x->ob_type->tp_name);
8211 Py_DECREF(x);
8212 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008213 }
8214}
8215
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008216static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008217charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008218{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008219 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8220 /* exponentially overallocate to minimize reallocations */
8221 if (requiredsize < 2*outsize)
8222 requiredsize = 2*outsize;
8223 if (_PyBytes_Resize(outobj, requiredsize))
8224 return -1;
8225 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008226}
8227
Benjamin Peterson14339b62009-01-31 16:36:08 +00008228typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008229 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008230} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008232 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008233 space is available. Return a new reference to the object that
8234 was put in the output buffer, or Py_None, if the mapping was undefined
8235 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008236 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008237static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008238charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008239 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008240{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008241 PyObject *rep;
8242 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008243 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008244
Christian Heimes90aa7642007-12-19 02:45:37 +00008245 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008246 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008247 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008248 if (res == -1)
8249 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008250 if (outsize<requiredsize)
8251 if (charmapencode_resize(outobj, outpos, requiredsize))
8252 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008253 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008254 outstart[(*outpos)++] = (char)res;
8255 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008256 }
8257
8258 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008259 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008260 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008261 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008262 Py_DECREF(rep);
8263 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008264 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 if (PyLong_Check(rep)) {
8266 Py_ssize_t requiredsize = *outpos+1;
8267 if (outsize<requiredsize)
8268 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8269 Py_DECREF(rep);
8270 return enc_EXCEPTION;
8271 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008272 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008273 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008274 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008275 else {
8276 const char *repchars = PyBytes_AS_STRING(rep);
8277 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8278 Py_ssize_t requiredsize = *outpos+repsize;
8279 if (outsize<requiredsize)
8280 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8281 Py_DECREF(rep);
8282 return enc_EXCEPTION;
8283 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008284 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008285 memcpy(outstart + *outpos, repchars, repsize);
8286 *outpos += repsize;
8287 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008288 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008289 Py_DECREF(rep);
8290 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008291}
8292
8293/* handle an error in PyUnicode_EncodeCharmap
8294 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008295static int
8296charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008297 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008298 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008299 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008300 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008301{
8302 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008303 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008304 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008305 enum PyUnicode_Kind kind;
8306 void *data;
8307 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008308 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008309 Py_ssize_t collstartpos = *inpos;
8310 Py_ssize_t collendpos = *inpos+1;
8311 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008312 char *encoding = "charmap";
8313 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008314 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008315 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008316 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008317
Benjamin Petersonbac79492012-01-14 13:34:47 -05008318 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008319 return -1;
8320 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008321 /* find all unencodable characters */
8322 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008323 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008324 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008325 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008326 val = encoding_map_lookup(ch, mapping);
8327 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008328 break;
8329 ++collendpos;
8330 continue;
8331 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008332
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008333 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8334 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 if (rep==NULL)
8336 return -1;
8337 else if (rep!=Py_None) {
8338 Py_DECREF(rep);
8339 break;
8340 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008341 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008342 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008343 }
8344 /* cache callback name lookup
8345 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008346 if (*error_handler == _Py_ERROR_UNKNOWN)
8347 *error_handler = get_error_handler(errors);
8348
8349 switch (*error_handler) {
8350 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008351 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008352 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008353
8354 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008355 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 x = charmapencode_output('?', mapping, res, respos);
8357 if (x==enc_EXCEPTION) {
8358 return -1;
8359 }
8360 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008361 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 return -1;
8363 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008364 }
8365 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008366 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008367 *inpos = collendpos;
8368 break;
Victor Stinner50149202015-09-22 00:26:54 +02008369
8370 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008371 /* generate replacement (temporarily (mis)uses p) */
8372 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008373 char buffer[2+29+1+1];
8374 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008375 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 for (cp = buffer; *cp; ++cp) {
8377 x = charmapencode_output(*cp, mapping, res, respos);
8378 if (x==enc_EXCEPTION)
8379 return -1;
8380 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008381 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008382 return -1;
8383 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008384 }
8385 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008386 *inpos = collendpos;
8387 break;
Victor Stinner50149202015-09-22 00:26:54 +02008388
Benjamin Peterson14339b62009-01-31 16:36:08 +00008389 default:
Victor Stinner50149202015-09-22 00:26:54 +02008390 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008391 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008392 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008393 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008394 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008395 if (PyBytes_Check(repunicode)) {
8396 /* Directly copy bytes result to output. */
8397 Py_ssize_t outsize = PyBytes_Size(*res);
8398 Py_ssize_t requiredsize;
8399 repsize = PyBytes_Size(repunicode);
8400 requiredsize = *respos + repsize;
8401 if (requiredsize > outsize)
8402 /* Make room for all additional bytes. */
8403 if (charmapencode_resize(res, respos, requiredsize)) {
8404 Py_DECREF(repunicode);
8405 return -1;
8406 }
8407 memcpy(PyBytes_AsString(*res) + *respos,
8408 PyBytes_AsString(repunicode), repsize);
8409 *respos += repsize;
8410 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008411 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008412 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008413 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008414 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008415 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008416 Py_DECREF(repunicode);
8417 return -1;
8418 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008419 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008420 data = PyUnicode_DATA(repunicode);
8421 kind = PyUnicode_KIND(repunicode);
8422 for (index = 0; index < repsize; index++) {
8423 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8424 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008425 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008426 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008427 return -1;
8428 }
8429 else if (x==enc_FAILED) {
8430 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008431 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008432 return -1;
8433 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008434 }
8435 *inpos = newpos;
8436 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008437 }
8438 return 0;
8439}
8440
Alexander Belopolsky40018472011-02-26 01:02:56 +00008441PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008442_PyUnicode_EncodeCharmap(PyObject *unicode,
8443 PyObject *mapping,
8444 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008445{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446 /* output object */
8447 PyObject *res = NULL;
8448 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008449 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008450 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008451 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008452 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008453 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008454 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008455 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008456 void *data;
8457 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008458
Benjamin Petersonbac79492012-01-14 13:34:47 -05008459 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008460 return NULL;
8461 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008462 data = PyUnicode_DATA(unicode);
8463 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008464
Guido van Rossumd57fd912000-03-10 22:53:23 +00008465 /* Default to Latin-1 */
8466 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008467 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008468
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008469 /* allocate enough for a simple encoding without
8470 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008471 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008472 if (res == NULL)
8473 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008474 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008475 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008476
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008477 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008478 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008479 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008480 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 if (x==enc_EXCEPTION) /* error */
8482 goto onError;
8483 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008484 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008485 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008486 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 &res, &respos)) {
8488 goto onError;
8489 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008490 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 else
8492 /* done with this character => adjust input position */
8493 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008494 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008495
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008496 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008497 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008498 if (_PyBytes_Resize(&res, respos) < 0)
8499 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008500
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008501 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008502 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008503 return res;
8504
Benjamin Peterson29060642009-01-31 22:14:21 +00008505 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008506 Py_XDECREF(res);
8507 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008508 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008509 return NULL;
8510}
8511
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008512/* Deprecated */
8513PyObject *
8514PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8515 Py_ssize_t size,
8516 PyObject *mapping,
8517 const char *errors)
8518{
8519 PyObject *result;
8520 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8521 if (unicode == NULL)
8522 return NULL;
8523 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8524 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008525 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008526}
8527
Alexander Belopolsky40018472011-02-26 01:02:56 +00008528PyObject *
8529PyUnicode_AsCharmapString(PyObject *unicode,
8530 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008531{
8532 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008533 PyErr_BadArgument();
8534 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008535 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008536 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008537}
8538
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008539/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008540static void
8541make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008542 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008543 Py_ssize_t startpos, Py_ssize_t endpos,
8544 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008545{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008546 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008547 *exceptionObject = _PyUnicodeTranslateError_Create(
8548 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008549 }
8550 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008551 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8552 goto onError;
8553 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8554 goto onError;
8555 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8556 goto onError;
8557 return;
8558 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008559 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008560 }
8561}
8562
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008563/* error handling callback helper:
8564 build arguments, call the callback and check the arguments,
8565 put the result into newpos and return the replacement string, which
8566 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008567static PyObject *
8568unicode_translate_call_errorhandler(const char *errors,
8569 PyObject **errorHandler,
8570 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008572 Py_ssize_t startpos, Py_ssize_t endpos,
8573 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008574{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02008575 static const char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008576
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008577 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008578 PyObject *restuple;
8579 PyObject *resunicode;
8580
8581 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008582 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008583 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008584 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008585 }
8586
8587 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008588 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008589 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591
8592 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008593 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008594 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008595 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008596 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008597 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 Py_DECREF(restuple);
8599 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008600 }
8601 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008602 &resunicode, &i_newpos)) {
8603 Py_DECREF(restuple);
8604 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008605 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008606 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008608 else
8609 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008610 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008611 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008612 Py_DECREF(restuple);
8613 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008614 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008615 Py_INCREF(resunicode);
8616 Py_DECREF(restuple);
8617 return resunicode;
8618}
8619
8620/* Lookup the character ch in the mapping and put the result in result,
8621 which must be decrefed by the caller.
8622 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008623static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008624charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008625{
Christian Heimes217cfd12007-12-02 14:31:20 +00008626 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008627 PyObject *x;
8628
8629 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008630 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008631 x = PyObject_GetItem(mapping, w);
8632 Py_DECREF(w);
8633 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008634 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8635 /* No mapping found means: use 1:1 mapping. */
8636 PyErr_Clear();
8637 *result = NULL;
8638 return 0;
8639 } else
8640 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008641 }
8642 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008643 *result = x;
8644 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008645 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008646 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008647 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008648 if (value < 0 || value > MAX_UNICODE) {
8649 PyErr_Format(PyExc_ValueError,
8650 "character mapping must be in range(0x%x)",
8651 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008652 Py_DECREF(x);
8653 return -1;
8654 }
8655 *result = x;
8656 return 0;
8657 }
8658 else if (PyUnicode_Check(x)) {
8659 *result = x;
8660 return 0;
8661 }
8662 else {
8663 /* wrong return value */
8664 PyErr_SetString(PyExc_TypeError,
8665 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008666 Py_DECREF(x);
8667 return -1;
8668 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008669}
Victor Stinner1194ea02014-04-04 19:37:40 +02008670
8671/* lookup the character, write the result into the writer.
8672 Return 1 if the result was written into the writer, return 0 if the mapping
8673 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008674static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008675charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8676 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008677{
Victor Stinner1194ea02014-04-04 19:37:40 +02008678 PyObject *item;
8679
8680 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008681 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008682
8683 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008684 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008685 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008686 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008687 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008688 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008689 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008690
8691 if (item == Py_None) {
8692 Py_DECREF(item);
8693 return 0;
8694 }
8695
8696 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008697 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8698 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8699 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008700 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8701 Py_DECREF(item);
8702 return -1;
8703 }
8704 Py_DECREF(item);
8705 return 1;
8706 }
8707
8708 if (!PyUnicode_Check(item)) {
8709 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008711 }
8712
8713 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8714 Py_DECREF(item);
8715 return -1;
8716 }
8717
8718 Py_DECREF(item);
8719 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008720}
8721
Victor Stinner89a76ab2014-04-05 11:44:04 +02008722static int
8723unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8724 Py_UCS1 *translate)
8725{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008726 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008727 int ret = 0;
8728
Victor Stinner89a76ab2014-04-05 11:44:04 +02008729 if (charmaptranslate_lookup(ch, mapping, &item)) {
8730 return -1;
8731 }
8732
8733 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008734 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008735 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008736 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008737 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008738 /* not found => default to 1:1 mapping */
8739 translate[ch] = ch;
8740 return 1;
8741 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008742 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008743 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008744 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8745 used it */
8746 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008747 /* invalid character or character outside ASCII:
8748 skip the fast translate */
8749 goto exit;
8750 }
8751 translate[ch] = (Py_UCS1)replace;
8752 }
8753 else if (PyUnicode_Check(item)) {
8754 Py_UCS4 replace;
8755
8756 if (PyUnicode_READY(item) == -1) {
8757 Py_DECREF(item);
8758 return -1;
8759 }
8760 if (PyUnicode_GET_LENGTH(item) != 1)
8761 goto exit;
8762
8763 replace = PyUnicode_READ_CHAR(item, 0);
8764 if (replace > 127)
8765 goto exit;
8766 translate[ch] = (Py_UCS1)replace;
8767 }
8768 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008769 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008770 goto exit;
8771 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008772 ret = 1;
8773
Benjamin Peterson1365de72014-04-07 20:15:41 -04008774 exit:
8775 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008776 return ret;
8777}
8778
8779/* Fast path for ascii => ascii translation. Return 1 if the whole string
8780 was translated into writer, return 0 if the input string was partially
8781 translated into writer, raise an exception and return -1 on error. */
8782static int
8783unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner872b2912014-04-05 14:27:07 +02008784 _PyUnicodeWriter *writer, int ignore)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008785{
Victor Stinner872b2912014-04-05 14:27:07 +02008786 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008787 Py_ssize_t len;
8788 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008789 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008790
8791 if (PyUnicode_READY(input) == -1)
8792 return -1;
8793 if (!PyUnicode_IS_ASCII(input))
8794 return 0;
8795 len = PyUnicode_GET_LENGTH(input);
8796
Victor Stinner872b2912014-04-05 14:27:07 +02008797 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008798
8799 in = PyUnicode_1BYTE_DATA(input);
8800 end = in + len;
8801
8802 assert(PyUnicode_IS_ASCII(writer->buffer));
8803 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8804 out = PyUnicode_1BYTE_DATA(writer->buffer);
8805
Victor Stinner872b2912014-04-05 14:27:07 +02008806 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008807 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008808 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008809 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008810 int translate = unicode_fast_translate_lookup(mapping, ch,
8811 ascii_table);
8812 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008813 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008814 if (translate == 0)
8815 goto exit;
8816 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008817 }
Victor Stinner872b2912014-04-05 14:27:07 +02008818 if (ch2 == 0xfe) {
8819 if (ignore)
8820 continue;
8821 goto exit;
8822 }
8823 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008824 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008825 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008826 }
Victor Stinner872b2912014-04-05 14:27:07 +02008827 res = 1;
8828
8829exit:
8830 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
8831 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
8876 res = unicode_fast_translate(input, mapping, &writer, ignore);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008877 if (res < 0) {
8878 _PyUnicodeWriter_Dealloc(&writer);
8879 return NULL;
8880 }
8881 if (res == 1)
8882 return _PyUnicodeWriter_Finish(&writer);
8883
Victor Stinner89a76ab2014-04-05 11:44:04 +02008884 i = writer.pos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008885 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008886 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008887 int translate;
8888 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8889 Py_ssize_t newpos;
8890 /* startpos for collecting untranslatable chars */
8891 Py_ssize_t collstart;
8892 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008893 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008894
Victor Stinner1194ea02014-04-04 19:37:40 +02008895 ch = PyUnicode_READ(kind, data, i);
8896 translate = charmaptranslate_output(ch, mapping, &writer);
8897 if (translate < 0)
8898 goto onError;
8899
8900 if (translate != 0) {
8901 /* it worked => adjust input pointer */
8902 ++i;
8903 continue;
8904 }
8905
8906 /* untranslatable character */
8907 collstart = i;
8908 collend = i+1;
8909
8910 /* find all untranslatable characters */
8911 while (collend < size) {
8912 PyObject *x;
8913 ch = PyUnicode_READ(kind, data, collend);
8914 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008915 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008916 Py_XDECREF(x);
8917 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008918 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008919 ++collend;
8920 }
8921
8922 if (ignore) {
8923 i = collend;
8924 }
8925 else {
8926 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8927 reason, input, &exc,
8928 collstart, collend, &newpos);
8929 if (repunicode == NULL)
8930 goto onError;
8931 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008932 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008933 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008934 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008935 Py_DECREF(repunicode);
8936 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008937 }
8938 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008939 Py_XDECREF(exc);
8940 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008941 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008942
Benjamin Peterson29060642009-01-31 22:14:21 +00008943 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008944 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008945 Py_XDECREF(exc);
8946 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008947 return NULL;
8948}
8949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008950/* Deprecated. Use PyUnicode_Translate instead. */
8951PyObject *
8952PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8953 Py_ssize_t size,
8954 PyObject *mapping,
8955 const char *errors)
8956{
Christian Heimes5f520f42012-09-11 14:03:25 +02008957 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008958 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8959 if (!unicode)
8960 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008961 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8962 Py_DECREF(unicode);
8963 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008964}
8965
Alexander Belopolsky40018472011-02-26 01:02:56 +00008966PyObject *
8967PyUnicode_Translate(PyObject *str,
8968 PyObject *mapping,
8969 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008970{
8971 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008972
Guido van Rossumd57fd912000-03-10 22:53:23 +00008973 str = PyUnicode_FromObject(str);
8974 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008975 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008976 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008977 Py_DECREF(str);
8978 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008979}
Tim Petersced69f82003-09-16 20:30:58 +00008980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008981static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008982fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008983{
8984 /* No need to call PyUnicode_READY(self) because this function is only
8985 called as a callback from fixup() which does it already. */
8986 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8987 const int kind = PyUnicode_KIND(self);
8988 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008989 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008990 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008991 Py_ssize_t i;
8992
8993 for (i = 0; i < len; ++i) {
8994 ch = PyUnicode_READ(kind, data, i);
8995 fixed = 0;
8996 if (ch > 127) {
8997 if (Py_UNICODE_ISSPACE(ch))
8998 fixed = ' ';
8999 else {
9000 const int decimal = Py_UNICODE_TODECIMAL(ch);
9001 if (decimal >= 0)
9002 fixed = '0' + decimal;
9003 }
9004 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009005 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009006 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009007 PyUnicode_WRITE(kind, data, i, fixed);
9008 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009009 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009010 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009011 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009012 }
9013
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009014 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009015}
9016
9017PyObject *
9018_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9019{
9020 if (!PyUnicode_Check(unicode)) {
9021 PyErr_BadInternalCall();
9022 return NULL;
9023 }
9024 if (PyUnicode_READY(unicode) == -1)
9025 return NULL;
9026 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9027 /* If the string is already ASCII, just return the same string */
9028 Py_INCREF(unicode);
9029 return unicode;
9030 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009031 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009032}
9033
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009034PyObject *
9035PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9036 Py_ssize_t length)
9037{
Victor Stinnerf0124502011-11-21 23:12:56 +01009038 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009039 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009040 Py_UCS4 maxchar;
9041 enum PyUnicode_Kind kind;
9042 void *data;
9043
Victor Stinner99d7ad02012-02-22 13:37:39 +01009044 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009045 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009046 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009047 if (ch > 127) {
9048 int decimal = Py_UNICODE_TODECIMAL(ch);
9049 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009050 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009051 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009052 }
9053 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009054
9055 /* Copy to a new string */
9056 decimal = PyUnicode_New(length, maxchar);
9057 if (decimal == NULL)
9058 return decimal;
9059 kind = PyUnicode_KIND(decimal);
9060 data = PyUnicode_DATA(decimal);
9061 /* Iterate over code points */
9062 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009063 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009064 if (ch > 127) {
9065 int decimal = Py_UNICODE_TODECIMAL(ch);
9066 if (decimal >= 0)
9067 ch = '0' + decimal;
9068 }
9069 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009070 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009071 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009072}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009073/* --- Decimal Encoder ---------------------------------------------------- */
9074
Alexander Belopolsky40018472011-02-26 01:02:56 +00009075int
9076PyUnicode_EncodeDecimal(Py_UNICODE *s,
9077 Py_ssize_t length,
9078 char *output,
9079 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009080{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009081 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009082 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009083 enum PyUnicode_Kind kind;
9084 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009085
9086 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009087 PyErr_BadArgument();
9088 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009089 }
9090
Victor Stinner42bf7752011-11-21 22:52:58 +01009091 unicode = PyUnicode_FromUnicode(s, length);
9092 if (unicode == NULL)
9093 return -1;
9094
Benjamin Petersonbac79492012-01-14 13:34:47 -05009095 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009096 Py_DECREF(unicode);
9097 return -1;
9098 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009099 kind = PyUnicode_KIND(unicode);
9100 data = PyUnicode_DATA(unicode);
9101
Victor Stinnerb84d7232011-11-22 01:50:07 +01009102 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009103 PyObject *exc;
9104 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009105 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009106 Py_ssize_t startpos;
9107
9108 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009109
Benjamin Peterson29060642009-01-31 22:14:21 +00009110 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009111 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009112 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009113 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009114 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009115 decimal = Py_UNICODE_TODECIMAL(ch);
9116 if (decimal >= 0) {
9117 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009118 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009119 continue;
9120 }
9121 if (0 < ch && ch < 256) {
9122 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009123 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009124 continue;
9125 }
Victor Stinner6345be92011-11-25 20:09:01 +01009126
Victor Stinner42bf7752011-11-21 22:52:58 +01009127 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009128 exc = NULL;
9129 raise_encode_exception(&exc, "decimal", unicode,
9130 startpos, startpos+1,
9131 "invalid decimal Unicode string");
9132 Py_XDECREF(exc);
9133 Py_DECREF(unicode);
9134 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009135 }
9136 /* 0-terminate the output string */
9137 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009138 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009139 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009140}
9141
Guido van Rossumd57fd912000-03-10 22:53:23 +00009142/* --- Helpers ------------------------------------------------------------ */
9143
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009144/* helper macro to fixup start/end slice values */
9145#define ADJUST_INDICES(start, end, len) \
9146 if (end > len) \
9147 end = len; \
9148 else if (end < 0) { \
9149 end += len; \
9150 if (end < 0) \
9151 end = 0; \
9152 } \
9153 if (start < 0) { \
9154 start += len; \
9155 if (start < 0) \
9156 start = 0; \
9157 }
9158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009159static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009160any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009161 Py_ssize_t start,
9162 Py_ssize_t end)
9163{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009164 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009165 void *buf1, *buf2;
9166 Py_ssize_t len1, len2, result;
9167
9168 kind1 = PyUnicode_KIND(s1);
9169 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009170 if (kind1 < kind2)
9171 return -1;
9172
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009173 len1 = PyUnicode_GET_LENGTH(s1);
9174 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009175 ADJUST_INDICES(start, end, len1);
9176 if (end - start < len2)
9177 return -1;
9178
9179 buf1 = PyUnicode_DATA(s1);
9180 buf2 = PyUnicode_DATA(s2);
9181 if (len2 == 1) {
9182 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9183 result = findchar((const char *)buf1 + kind1*start,
9184 kind1, end - start, ch, direction);
9185 if (result == -1)
9186 return -1;
9187 else
9188 return start + result;
9189 }
9190
9191 if (kind2 != kind1) {
9192 buf2 = _PyUnicode_AsKind(s2, kind1);
9193 if (!buf2)
9194 return -2;
9195 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009196
Victor Stinner794d5672011-10-10 03:21:36 +02009197 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009198 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009199 case PyUnicode_1BYTE_KIND:
9200 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9201 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9202 else
9203 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9204 break;
9205 case PyUnicode_2BYTE_KIND:
9206 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9207 break;
9208 case PyUnicode_4BYTE_KIND:
9209 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9210 break;
9211 default:
9212 assert(0); result = -2;
9213 }
9214 }
9215 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009216 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009217 case PyUnicode_1BYTE_KIND:
9218 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9219 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9220 else
9221 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9222 break;
9223 case PyUnicode_2BYTE_KIND:
9224 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9225 break;
9226 case PyUnicode_4BYTE_KIND:
9227 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9228 break;
9229 default:
9230 assert(0); result = -2;
9231 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009232 }
9233
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009234 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009235 PyMem_Free(buf2);
9236
9237 return result;
9238}
9239
9240Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009241_PyUnicode_InsertThousandsGrouping(
9242 PyObject *unicode, Py_ssize_t index,
9243 Py_ssize_t n_buffer,
9244 void *digits, Py_ssize_t n_digits,
9245 Py_ssize_t min_width,
9246 const char *grouping, PyObject *thousands_sep,
9247 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009248{
Victor Stinner41a863c2012-02-24 00:37:51 +01009249 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009250 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009251 Py_ssize_t thousands_sep_len;
9252 Py_ssize_t len;
9253
9254 if (unicode != NULL) {
9255 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009256 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009257 }
9258 else {
9259 kind = PyUnicode_1BYTE_KIND;
9260 data = NULL;
9261 }
9262 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9263 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9264 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9265 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009266 if (thousands_sep_kind < kind) {
9267 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9268 if (!thousands_sep_data)
9269 return -1;
9270 }
9271 else {
9272 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9273 if (!data)
9274 return -1;
9275 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009276 }
9277
Benjamin Petersonead6b532011-12-20 17:23:42 -06009278 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009279 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009280 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009281 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009282 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009283 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009284 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009285 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009286 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009287 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009288 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009289 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009290 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009291 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009292 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009293 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009294 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009295 (Py_UCS2 *) 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_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009298 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009299 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009300 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009301 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009302 break;
9303 default:
9304 assert(0);
9305 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009306 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009307 if (unicode != NULL && thousands_sep_kind != kind) {
9308 if (thousands_sep_kind < kind)
9309 PyMem_Free(thousands_sep_data);
9310 else
9311 PyMem_Free(data);
9312 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009313 if (unicode == NULL) {
9314 *maxchar = 127;
9315 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009316 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009317 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009318 }
9319 }
9320 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009321}
9322
9323
Alexander Belopolsky40018472011-02-26 01:02:56 +00009324Py_ssize_t
9325PyUnicode_Count(PyObject *str,
9326 PyObject *substr,
9327 Py_ssize_t start,
9328 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009329{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009330 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009331 PyObject* str_obj;
9332 PyObject* sub_obj;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009333 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009334 void *buf1 = NULL, *buf2 = NULL;
9335 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009336
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009337 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009338 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009339 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009340 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009341 if (!sub_obj) {
9342 Py_DECREF(str_obj);
9343 return -1;
9344 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009345 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009346 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009347 Py_DECREF(str_obj);
9348 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009349 }
Tim Petersced69f82003-09-16 20:30:58 +00009350
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009351 kind1 = PyUnicode_KIND(str_obj);
9352 kind2 = PyUnicode_KIND(sub_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009353 if (kind1 < kind2) {
9354 Py_DECREF(sub_obj);
9355 Py_DECREF(str_obj);
9356 return 0;
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009357 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009358
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009359 len1 = PyUnicode_GET_LENGTH(str_obj);
9360 len2 = PyUnicode_GET_LENGTH(sub_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009361 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009362 if (end - start < len2) {
9363 Py_DECREF(sub_obj);
9364 Py_DECREF(str_obj);
9365 return 0;
9366 }
9367
9368 buf1 = PyUnicode_DATA(str_obj);
9369 buf2 = PyUnicode_DATA(sub_obj);
9370 if (kind2 != kind1) {
9371 buf2 = _PyUnicode_AsKind(sub_obj, kind1);
9372 if (!buf2)
9373 goto onError;
9374 }
9375
9376 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009378 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9379 result = asciilib_count(
9380 ((Py_UCS1*)buf1) + start, end - start,
9381 buf2, len2, PY_SSIZE_T_MAX
9382 );
9383 else
9384 result = ucs1lib_count(
9385 ((Py_UCS1*)buf1) + start, end - start,
9386 buf2, len2, PY_SSIZE_T_MAX
9387 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009388 break;
9389 case PyUnicode_2BYTE_KIND:
9390 result = ucs2lib_count(
9391 ((Py_UCS2*)buf1) + start, end - start,
9392 buf2, len2, PY_SSIZE_T_MAX
9393 );
9394 break;
9395 case PyUnicode_4BYTE_KIND:
9396 result = ucs4lib_count(
9397 ((Py_UCS4*)buf1) + start, end - start,
9398 buf2, len2, PY_SSIZE_T_MAX
9399 );
9400 break;
9401 default:
9402 assert(0); result = 0;
9403 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009404
9405 Py_DECREF(sub_obj);
9406 Py_DECREF(str_obj);
9407
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009408 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009409 PyMem_Free(buf2);
9410
Guido van Rossumd57fd912000-03-10 22:53:23 +00009411 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009412 onError:
9413 Py_DECREF(sub_obj);
9414 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009415 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 PyMem_Free(buf2);
9417 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009418}
9419
Alexander Belopolsky40018472011-02-26 01:02:56 +00009420Py_ssize_t
9421PyUnicode_Find(PyObject *str,
9422 PyObject *sub,
9423 Py_ssize_t start,
9424 Py_ssize_t end,
9425 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009426{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009427 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009428
Guido van Rossumd57fd912000-03-10 22:53:23 +00009429 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009430 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009431 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009432 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009433 if (!sub) {
9434 Py_DECREF(str);
9435 return -2;
9436 }
9437 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9438 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009439 Py_DECREF(str);
9440 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009441 }
Tim Petersced69f82003-09-16 20:30:58 +00009442
Victor Stinner794d5672011-10-10 03:21:36 +02009443 result = any_find_slice(direction,
9444 str, sub, start, end
9445 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009446
Guido van Rossumd57fd912000-03-10 22:53:23 +00009447 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009448 Py_DECREF(sub);
9449
Guido van Rossumd57fd912000-03-10 22:53:23 +00009450 return result;
9451}
9452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009453Py_ssize_t
9454PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9455 Py_ssize_t start, Py_ssize_t end,
9456 int direction)
9457{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009458 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009459 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 if (PyUnicode_READY(str) == -1)
9461 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009462 if (start < 0 || end < 0) {
9463 PyErr_SetString(PyExc_IndexError, "string index out of range");
9464 return -2;
9465 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466 if (end > PyUnicode_GET_LENGTH(str))
9467 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009468 if (start >= end)
9469 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009470 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009471 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9472 kind, end-start, ch, direction);
9473 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009474 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009475 else
9476 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009477}
9478
Alexander Belopolsky40018472011-02-26 01:02:56 +00009479static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009480tailmatch(PyObject *self,
9481 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009482 Py_ssize_t start,
9483 Py_ssize_t end,
9484 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009485{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009486 int kind_self;
9487 int kind_sub;
9488 void *data_self;
9489 void *data_sub;
9490 Py_ssize_t offset;
9491 Py_ssize_t i;
9492 Py_ssize_t end_sub;
9493
9494 if (PyUnicode_READY(self) == -1 ||
9495 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009496 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009497
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009498 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9499 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009500 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009501 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009502
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009503 if (PyUnicode_GET_LENGTH(substring) == 0)
9504 return 1;
9505
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009506 kind_self = PyUnicode_KIND(self);
9507 data_self = PyUnicode_DATA(self);
9508 kind_sub = PyUnicode_KIND(substring);
9509 data_sub = PyUnicode_DATA(substring);
9510 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9511
9512 if (direction > 0)
9513 offset = end;
9514 else
9515 offset = start;
9516
9517 if (PyUnicode_READ(kind_self, data_self, offset) ==
9518 PyUnicode_READ(kind_sub, data_sub, 0) &&
9519 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9520 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9521 /* If both are of the same kind, memcmp is sufficient */
9522 if (kind_self == kind_sub) {
9523 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009524 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009525 data_sub,
9526 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009527 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009528 }
9529 /* otherwise we have to compare each character by first accesing it */
9530 else {
9531 /* We do not need to compare 0 and len(substring)-1 because
9532 the if statement above ensured already that they are equal
9533 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009534 for (i = 1; i < end_sub; ++i) {
9535 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9536 PyUnicode_READ(kind_sub, data_sub, i))
9537 return 0;
9538 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009539 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009540 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009541 }
9542
9543 return 0;
9544}
9545
Alexander Belopolsky40018472011-02-26 01:02:56 +00009546Py_ssize_t
9547PyUnicode_Tailmatch(PyObject *str,
9548 PyObject *substr,
9549 Py_ssize_t start,
9550 Py_ssize_t end,
9551 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009552{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009553 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009554
Guido van Rossumd57fd912000-03-10 22:53:23 +00009555 str = PyUnicode_FromObject(str);
9556 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009557 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009558 substr = PyUnicode_FromObject(substr);
9559 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009560 Py_DECREF(str);
9561 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009562 }
Tim Petersced69f82003-09-16 20:30:58 +00009563
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009564 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009565 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009566 Py_DECREF(str);
9567 Py_DECREF(substr);
9568 return result;
9569}
9570
Guido van Rossumd57fd912000-03-10 22:53:23 +00009571/* Apply fixfct filter to the Unicode object self and return a
9572 reference to the modified object */
9573
Alexander Belopolsky40018472011-02-26 01:02:56 +00009574static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009575fixup(PyObject *self,
9576 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009577{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009578 PyObject *u;
9579 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009580 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009581
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009582 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009583 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009584 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009585 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009586
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009587 /* fix functions return the new maximum character in a string,
9588 if the kind of the resulting unicode object does not change,
9589 everything is fine. Otherwise we need to change the string kind
9590 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009591 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009592
9593 if (maxchar_new == 0) {
9594 /* no changes */;
9595 if (PyUnicode_CheckExact(self)) {
9596 Py_DECREF(u);
9597 Py_INCREF(self);
9598 return self;
9599 }
9600 else
9601 return u;
9602 }
9603
Victor Stinnere6abb482012-05-02 01:15:40 +02009604 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009605
Victor Stinnereaab6042011-12-11 22:22:39 +01009606 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009607 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009608
9609 /* In case the maximum character changed, we need to
9610 convert the string to the new category. */
9611 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9612 if (v == NULL) {
9613 Py_DECREF(u);
9614 return NULL;
9615 }
9616 if (maxchar_new > maxchar_old) {
9617 /* If the maxchar increased so that the kind changed, not all
9618 characters are representable anymore and we need to fix the
9619 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009620 _PyUnicode_FastCopyCharacters(v, 0,
9621 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009622 maxchar_old = fixfct(v);
9623 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009624 }
9625 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009626 _PyUnicode_FastCopyCharacters(v, 0,
9627 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009628 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009629 Py_DECREF(u);
9630 assert(_PyUnicode_CheckConsistency(v, 1));
9631 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009632}
9633
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009634static PyObject *
9635ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009636{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009637 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9638 char *resdata, *data = PyUnicode_DATA(self);
9639 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009640
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009641 res = PyUnicode_New(len, 127);
9642 if (res == NULL)
9643 return NULL;
9644 resdata = PyUnicode_DATA(res);
9645 if (lower)
9646 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009647 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009648 _Py_bytes_upper(resdata, data, len);
9649 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009650}
9651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009652static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009653handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009654{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009655 Py_ssize_t j;
9656 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009657 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009658 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009659
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009660 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9661
9662 where ! is a negation and \p{xxx} is a character with property xxx.
9663 */
9664 for (j = i - 1; j >= 0; j--) {
9665 c = PyUnicode_READ(kind, data, j);
9666 if (!_PyUnicode_IsCaseIgnorable(c))
9667 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009668 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009669 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9670 if (final_sigma) {
9671 for (j = i + 1; j < length; j++) {
9672 c = PyUnicode_READ(kind, data, j);
9673 if (!_PyUnicode_IsCaseIgnorable(c))
9674 break;
9675 }
9676 final_sigma = j == length || !_PyUnicode_IsCased(c);
9677 }
9678 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009679}
9680
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009681static int
9682lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9683 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009684{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009685 /* Obscure special case. */
9686 if (c == 0x3A3) {
9687 mapped[0] = handle_capital_sigma(kind, data, length, i);
9688 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009689 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009690 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009691}
9692
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009693static Py_ssize_t
9694do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009695{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009696 Py_ssize_t i, k = 0;
9697 int n_res, j;
9698 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009699
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009700 c = PyUnicode_READ(kind, data, 0);
9701 n_res = _PyUnicode_ToUpperFull(c, mapped);
9702 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009703 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009704 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009705 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009706 for (i = 1; i < length; i++) {
9707 c = PyUnicode_READ(kind, data, i);
9708 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9709 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009710 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009711 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009712 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009713 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009714 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009715}
9716
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009717static Py_ssize_t
9718do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9719 Py_ssize_t i, k = 0;
9720
9721 for (i = 0; i < length; i++) {
9722 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9723 int n_res, j;
9724 if (Py_UNICODE_ISUPPER(c)) {
9725 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9726 }
9727 else if (Py_UNICODE_ISLOWER(c)) {
9728 n_res = _PyUnicode_ToUpperFull(c, mapped);
9729 }
9730 else {
9731 n_res = 1;
9732 mapped[0] = c;
9733 }
9734 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009735 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009736 res[k++] = mapped[j];
9737 }
9738 }
9739 return k;
9740}
9741
9742static Py_ssize_t
9743do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9744 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009745{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009746 Py_ssize_t i, k = 0;
9747
9748 for (i = 0; i < length; i++) {
9749 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9750 int n_res, j;
9751 if (lower)
9752 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9753 else
9754 n_res = _PyUnicode_ToUpperFull(c, mapped);
9755 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009756 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009757 res[k++] = mapped[j];
9758 }
9759 }
9760 return k;
9761}
9762
9763static Py_ssize_t
9764do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9765{
9766 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9767}
9768
9769static Py_ssize_t
9770do_lower(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, 1);
9773}
9774
Benjamin Petersone51757f2012-01-12 21:10:29 -05009775static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009776do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9777{
9778 Py_ssize_t i, k = 0;
9779
9780 for (i = 0; i < length; i++) {
9781 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9782 Py_UCS4 mapped[3];
9783 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9784 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009785 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009786 res[k++] = mapped[j];
9787 }
9788 }
9789 return k;
9790}
9791
9792static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009793do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9794{
9795 Py_ssize_t i, k = 0;
9796 int previous_is_cased;
9797
9798 previous_is_cased = 0;
9799 for (i = 0; i < length; i++) {
9800 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9801 Py_UCS4 mapped[3];
9802 int n_res, j;
9803
9804 if (previous_is_cased)
9805 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9806 else
9807 n_res = _PyUnicode_ToTitleFull(c, mapped);
9808
9809 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009810 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009811 res[k++] = mapped[j];
9812 }
9813
9814 previous_is_cased = _PyUnicode_IsCased(c);
9815 }
9816 return k;
9817}
9818
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009819static PyObject *
9820case_operation(PyObject *self,
9821 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9822{
9823 PyObject *res = NULL;
9824 Py_ssize_t length, newlength = 0;
9825 int kind, outkind;
9826 void *data, *outdata;
9827 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9828
Benjamin Petersoneea48462012-01-16 14:28:50 -05009829 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009830
9831 kind = PyUnicode_KIND(self);
9832 data = PyUnicode_DATA(self);
9833 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009834 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009835 PyErr_SetString(PyExc_OverflowError, "string is too long");
9836 return NULL;
9837 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009838 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009839 if (tmp == NULL)
9840 return PyErr_NoMemory();
9841 newlength = perform(kind, data, length, tmp, &maxchar);
9842 res = PyUnicode_New(newlength, maxchar);
9843 if (res == NULL)
9844 goto leave;
9845 tmpend = tmp + newlength;
9846 outdata = PyUnicode_DATA(res);
9847 outkind = PyUnicode_KIND(res);
9848 switch (outkind) {
9849 case PyUnicode_1BYTE_KIND:
9850 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9851 break;
9852 case PyUnicode_2BYTE_KIND:
9853 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9854 break;
9855 case PyUnicode_4BYTE_KIND:
9856 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9857 break;
9858 default:
9859 assert(0);
9860 break;
9861 }
9862 leave:
9863 PyMem_FREE(tmp);
9864 return res;
9865}
9866
Tim Peters8ce9f162004-08-27 01:49:32 +00009867PyObject *
9868PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009869{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009870 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009871 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009872 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009873 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009874 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9875 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009876 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009877 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009878 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009879 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009880 int use_memcpy;
9881 unsigned char *res_data = NULL, *sep_data = NULL;
9882 PyObject *last_obj;
9883 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009884
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009885 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009886 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009887 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009888 }
9889
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009890 /* NOTE: the following code can't call back into Python code,
9891 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009892 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009893
Tim Peters05eba1f2004-08-27 21:32:02 +00009894 seqlen = PySequence_Fast_GET_SIZE(fseq);
9895 /* If empty sequence, return u"". */
9896 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009897 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009898 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009899 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009900
Tim Peters05eba1f2004-08-27 21:32:02 +00009901 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009902 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009903 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009904 if (seqlen == 1) {
9905 if (PyUnicode_CheckExact(items[0])) {
9906 res = items[0];
9907 Py_INCREF(res);
9908 Py_DECREF(fseq);
9909 return res;
9910 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009911 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009912 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009913 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009914 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009915 /* Set up sep and seplen */
9916 if (separator == NULL) {
9917 /* fall back to a blank space separator */
9918 sep = PyUnicode_FromOrdinal(' ');
9919 if (!sep)
9920 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009921 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009922 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009923 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009924 else {
9925 if (!PyUnicode_Check(separator)) {
9926 PyErr_Format(PyExc_TypeError,
9927 "separator: expected str instance,"
9928 " %.80s found",
9929 Py_TYPE(separator)->tp_name);
9930 goto onError;
9931 }
9932 if (PyUnicode_READY(separator))
9933 goto onError;
9934 sep = separator;
9935 seplen = PyUnicode_GET_LENGTH(separator);
9936 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9937 /* inc refcount to keep this code path symmetric with the
9938 above case of a blank separator */
9939 Py_INCREF(sep);
9940 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009941 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009942 }
9943
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009944 /* There are at least two things to join, or else we have a subclass
9945 * of str in the sequence.
9946 * Do a pre-pass to figure out the total amount of space we'll
9947 * need (sz), and see whether all argument are strings.
9948 */
9949 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009950#ifdef Py_DEBUG
9951 use_memcpy = 0;
9952#else
9953 use_memcpy = 1;
9954#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009955 for (i = 0; i < seqlen; i++) {
9956 const Py_ssize_t old_sz = sz;
9957 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009958 if (!PyUnicode_Check(item)) {
9959 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009960 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009961 " %.80s found",
9962 i, Py_TYPE(item)->tp_name);
9963 goto onError;
9964 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009965 if (PyUnicode_READY(item) == -1)
9966 goto onError;
9967 sz += PyUnicode_GET_LENGTH(item);
9968 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009969 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009970 if (i != 0)
9971 sz += seplen;
9972 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9973 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009974 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009975 goto onError;
9976 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009977 if (use_memcpy && last_obj != NULL) {
9978 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9979 use_memcpy = 0;
9980 }
9981 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009982 }
Tim Petersced69f82003-09-16 20:30:58 +00009983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009985 if (res == NULL)
9986 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009987
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009988 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009989#ifdef Py_DEBUG
9990 use_memcpy = 0;
9991#else
9992 if (use_memcpy) {
9993 res_data = PyUnicode_1BYTE_DATA(res);
9994 kind = PyUnicode_KIND(res);
9995 if (seplen != 0)
9996 sep_data = PyUnicode_1BYTE_DATA(sep);
9997 }
9998#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009999 if (use_memcpy) {
10000 for (i = 0; i < seqlen; ++i) {
10001 Py_ssize_t itemlen;
10002 item = items[i];
10003
10004 /* Copy item, and maybe the separator. */
10005 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +020010006 Py_MEMCPY(res_data,
10007 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010008 kind * seplen);
10009 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010010 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010011
10012 itemlen = PyUnicode_GET_LENGTH(item);
10013 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +020010014 Py_MEMCPY(res_data,
10015 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010016 kind * itemlen);
10017 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010018 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010019 }
10020 assert(res_data == PyUnicode_1BYTE_DATA(res)
10021 + kind * PyUnicode_GET_LENGTH(res));
10022 }
10023 else {
10024 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10025 Py_ssize_t itemlen;
10026 item = items[i];
10027
10028 /* Copy item, and maybe the separator. */
10029 if (i && seplen != 0) {
10030 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10031 res_offset += seplen;
10032 }
10033
10034 itemlen = PyUnicode_GET_LENGTH(item);
10035 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010036 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010037 res_offset += itemlen;
10038 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010039 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010040 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010041 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010042
Tim Peters05eba1f2004-08-27 21:32:02 +000010043 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010044 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010045 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010046 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010047
Benjamin Peterson29060642009-01-31 22:14:21 +000010048 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +000010049 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010050 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010051 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010052 return NULL;
10053}
10054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010055#define FILL(kind, data, value, start, length) \
10056 do { \
10057 Py_ssize_t i_ = 0; \
10058 assert(kind != PyUnicode_WCHAR_KIND); \
10059 switch ((kind)) { \
10060 case PyUnicode_1BYTE_KIND: { \
10061 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010062 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063 break; \
10064 } \
10065 case PyUnicode_2BYTE_KIND: { \
10066 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10067 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10068 break; \
10069 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010070 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10072 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10073 break; \
10074 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010075 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 } \
10077 } while (0)
10078
Victor Stinnerd3f08822012-05-29 12:57:52 +020010079void
10080_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10081 Py_UCS4 fill_char)
10082{
10083 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10084 const void *data = PyUnicode_DATA(unicode);
10085 assert(PyUnicode_IS_READY(unicode));
10086 assert(unicode_modifiable(unicode));
10087 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10088 assert(start >= 0);
10089 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10090 FILL(kind, data, fill_char, start, length);
10091}
10092
Victor Stinner3fe55312012-01-04 00:33:50 +010010093Py_ssize_t
10094PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10095 Py_UCS4 fill_char)
10096{
10097 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010098
10099 if (!PyUnicode_Check(unicode)) {
10100 PyErr_BadInternalCall();
10101 return -1;
10102 }
10103 if (PyUnicode_READY(unicode) == -1)
10104 return -1;
10105 if (unicode_check_modifiable(unicode))
10106 return -1;
10107
Victor Stinnerd3f08822012-05-29 12:57:52 +020010108 if (start < 0) {
10109 PyErr_SetString(PyExc_IndexError, "string index out of range");
10110 return -1;
10111 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010112 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10113 PyErr_SetString(PyExc_ValueError,
10114 "fill character is bigger than "
10115 "the string maximum character");
10116 return -1;
10117 }
10118
10119 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10120 length = Py_MIN(maxlen, length);
10121 if (length <= 0)
10122 return 0;
10123
Victor Stinnerd3f08822012-05-29 12:57:52 +020010124 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010125 return length;
10126}
10127
Victor Stinner9310abb2011-10-05 00:59:23 +020010128static PyObject *
10129pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010130 Py_ssize_t left,
10131 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010132 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010133{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 PyObject *u;
10135 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010136 int kind;
10137 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010138
10139 if (left < 0)
10140 left = 0;
10141 if (right < 0)
10142 right = 0;
10143
Victor Stinnerc4b49542011-12-11 22:44:26 +010010144 if (left == 0 && right == 0)
10145 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10148 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010149 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10150 return NULL;
10151 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010153 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010155 if (!u)
10156 return NULL;
10157
10158 kind = PyUnicode_KIND(u);
10159 data = PyUnicode_DATA(u);
10160 if (left)
10161 FILL(kind, data, fill, 0, left);
10162 if (right)
10163 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010164 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010165 assert(_PyUnicode_CheckConsistency(u, 1));
10166 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010167}
10168
Alexander Belopolsky40018472011-02-26 01:02:56 +000010169PyObject *
10170PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010171{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010172 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010173
10174 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010175 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010176 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060010177 if (PyUnicode_READY(string) == -1) {
10178 Py_DECREF(string);
10179 return NULL;
10180 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010181
Benjamin Petersonead6b532011-12-20 17:23:42 -060010182 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010184 if (PyUnicode_IS_ASCII(string))
10185 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010186 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010187 PyUnicode_GET_LENGTH(string), keepends);
10188 else
10189 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010190 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010191 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 break;
10193 case PyUnicode_2BYTE_KIND:
10194 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010195 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010196 PyUnicode_GET_LENGTH(string), keepends);
10197 break;
10198 case PyUnicode_4BYTE_KIND:
10199 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010200 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 PyUnicode_GET_LENGTH(string), keepends);
10202 break;
10203 default:
10204 assert(0);
10205 list = 0;
10206 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010207 Py_DECREF(string);
10208 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010209}
10210
Alexander Belopolsky40018472011-02-26 01:02:56 +000010211static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010212split(PyObject *self,
10213 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010214 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010215{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010216 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 void *buf1, *buf2;
10218 Py_ssize_t len1, len2;
10219 PyObject* out;
10220
Guido van Rossumd57fd912000-03-10 22:53:23 +000010221 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010222 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010223
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 if (PyUnicode_READY(self) == -1)
10225 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010226
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010228 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010230 if (PyUnicode_IS_ASCII(self))
10231 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010232 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010233 PyUnicode_GET_LENGTH(self), maxcount
10234 );
10235 else
10236 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010237 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010238 PyUnicode_GET_LENGTH(self), maxcount
10239 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 case PyUnicode_2BYTE_KIND:
10241 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010242 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 PyUnicode_GET_LENGTH(self), maxcount
10244 );
10245 case PyUnicode_4BYTE_KIND:
10246 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010247 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010248 PyUnicode_GET_LENGTH(self), maxcount
10249 );
10250 default:
10251 assert(0);
10252 return NULL;
10253 }
10254
10255 if (PyUnicode_READY(substring) == -1)
10256 return NULL;
10257
10258 kind1 = PyUnicode_KIND(self);
10259 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 len1 = PyUnicode_GET_LENGTH(self);
10261 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010262 if (kind1 < kind2 || len1 < len2) {
10263 out = PyList_New(1);
10264 if (out == NULL)
10265 return NULL;
10266 Py_INCREF(self);
10267 PyList_SET_ITEM(out, 0, self);
10268 return out;
10269 }
10270 buf1 = PyUnicode_DATA(self);
10271 buf2 = PyUnicode_DATA(substring);
10272 if (kind2 != kind1) {
10273 buf2 = _PyUnicode_AsKind(substring, kind1);
10274 if (!buf2)
10275 return NULL;
10276 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010278 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010280 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10281 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010282 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010283 else
10284 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010285 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286 break;
10287 case PyUnicode_2BYTE_KIND:
10288 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010289 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 break;
10291 case PyUnicode_4BYTE_KIND:
10292 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010293 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010294 break;
10295 default:
10296 out = NULL;
10297 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010298 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 PyMem_Free(buf2);
10300 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010301}
10302
Alexander Belopolsky40018472011-02-26 01:02:56 +000010303static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010304rsplit(PyObject *self,
10305 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010306 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010307{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010308 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 void *buf1, *buf2;
10310 Py_ssize_t len1, len2;
10311 PyObject* out;
10312
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010313 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010314 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010315
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 if (PyUnicode_READY(self) == -1)
10317 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010318
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010320 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010321 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010322 if (PyUnicode_IS_ASCII(self))
10323 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010324 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010325 PyUnicode_GET_LENGTH(self), maxcount
10326 );
10327 else
10328 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010329 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010330 PyUnicode_GET_LENGTH(self), maxcount
10331 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010332 case PyUnicode_2BYTE_KIND:
10333 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010334 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010335 PyUnicode_GET_LENGTH(self), maxcount
10336 );
10337 case PyUnicode_4BYTE_KIND:
10338 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010339 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010340 PyUnicode_GET_LENGTH(self), maxcount
10341 );
10342 default:
10343 assert(0);
10344 return NULL;
10345 }
10346
10347 if (PyUnicode_READY(substring) == -1)
10348 return NULL;
10349
10350 kind1 = PyUnicode_KIND(self);
10351 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010352 len1 = PyUnicode_GET_LENGTH(self);
10353 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010354 if (kind1 < kind2 || len1 < len2) {
10355 out = PyList_New(1);
10356 if (out == NULL)
10357 return NULL;
10358 Py_INCREF(self);
10359 PyList_SET_ITEM(out, 0, self);
10360 return out;
10361 }
10362 buf1 = PyUnicode_DATA(self);
10363 buf2 = PyUnicode_DATA(substring);
10364 if (kind2 != kind1) {
10365 buf2 = _PyUnicode_AsKind(substring, kind1);
10366 if (!buf2)
10367 return NULL;
10368 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010370 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010371 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010372 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10373 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010374 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010375 else
10376 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010377 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 break;
10379 case PyUnicode_2BYTE_KIND:
10380 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010381 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010382 break;
10383 case PyUnicode_4BYTE_KIND:
10384 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010385 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010386 break;
10387 default:
10388 out = NULL;
10389 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010390 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 PyMem_Free(buf2);
10392 return out;
10393}
10394
10395static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010396anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10397 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010399 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010401 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10402 return asciilib_find(buf1, len1, buf2, len2, offset);
10403 else
10404 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 case PyUnicode_2BYTE_KIND:
10406 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10407 case PyUnicode_4BYTE_KIND:
10408 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10409 }
10410 assert(0);
10411 return -1;
10412}
10413
10414static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010415anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10416 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010417{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010418 switch (kind) {
10419 case PyUnicode_1BYTE_KIND:
10420 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10421 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10422 else
10423 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10424 case PyUnicode_2BYTE_KIND:
10425 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10426 case PyUnicode_4BYTE_KIND:
10427 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10428 }
10429 assert(0);
10430 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010431}
10432
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010433static void
10434replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10435 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10436{
10437 int kind = PyUnicode_KIND(u);
10438 void *data = PyUnicode_DATA(u);
10439 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10440 if (kind == PyUnicode_1BYTE_KIND) {
10441 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10442 (Py_UCS1 *)data + len,
10443 u1, u2, maxcount);
10444 }
10445 else if (kind == PyUnicode_2BYTE_KIND) {
10446 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10447 (Py_UCS2 *)data + len,
10448 u1, u2, maxcount);
10449 }
10450 else {
10451 assert(kind == PyUnicode_4BYTE_KIND);
10452 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10453 (Py_UCS4 *)data + len,
10454 u1, u2, maxcount);
10455 }
10456}
10457
Alexander Belopolsky40018472011-02-26 01:02:56 +000010458static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459replace(PyObject *self, PyObject *str1,
10460 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010461{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010462 PyObject *u;
10463 char *sbuf = PyUnicode_DATA(self);
10464 char *buf1 = PyUnicode_DATA(str1);
10465 char *buf2 = PyUnicode_DATA(str2);
10466 int srelease = 0, release1 = 0, release2 = 0;
10467 int skind = PyUnicode_KIND(self);
10468 int kind1 = PyUnicode_KIND(str1);
10469 int kind2 = PyUnicode_KIND(str2);
10470 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10471 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10472 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010473 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010474 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010475
10476 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010477 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010478 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010479 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010480
Victor Stinner59de0ee2011-10-07 10:01:28 +020010481 if (str1 == str2)
10482 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010483
Victor Stinner49a0a212011-10-12 23:46:10 +020010484 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010485 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10486 if (maxchar < maxchar_str1)
10487 /* substring too wide to be present */
10488 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010489 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10490 /* Replacing str1 with str2 may cause a maxchar reduction in the
10491 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010492 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010493 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010494
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010496 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010498 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010500 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010501 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010502 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010503
Victor Stinner69ed0f42013-04-09 21:48:24 +020010504 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010505 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010506 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010507 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010508 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010510 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010512
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010513 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10514 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010515 }
10516 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 int rkind = skind;
10518 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010519 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010520
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 if (kind1 < rkind) {
10522 /* widen substring */
10523 buf1 = _PyUnicode_AsKind(str1, rkind);
10524 if (!buf1) goto error;
10525 release1 = 1;
10526 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010527 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010528 if (i < 0)
10529 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 if (rkind > kind2) {
10531 /* widen replacement */
10532 buf2 = _PyUnicode_AsKind(str2, rkind);
10533 if (!buf2) goto error;
10534 release2 = 1;
10535 }
10536 else if (rkind < kind2) {
10537 /* widen self and buf1 */
10538 rkind = kind2;
10539 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010540 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 sbuf = _PyUnicode_AsKind(self, rkind);
10542 if (!sbuf) goto error;
10543 srelease = 1;
10544 buf1 = _PyUnicode_AsKind(str1, rkind);
10545 if (!buf1) goto error;
10546 release1 = 1;
10547 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010548 u = PyUnicode_New(slen, maxchar);
10549 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010551 assert(PyUnicode_KIND(u) == rkind);
10552 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010553
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010554 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010555 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010556 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010557 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010558 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010560
10561 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010562 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010563 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010564 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010565 if (i == -1)
10566 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010567 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010568 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010569 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010570 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010571 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010572 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010573 }
10574 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010575 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010576 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 int rkind = skind;
10578 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010579
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010581 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 buf1 = _PyUnicode_AsKind(str1, rkind);
10583 if (!buf1) goto error;
10584 release1 = 1;
10585 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010586 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010587 if (n == 0)
10588 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010590 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010591 buf2 = _PyUnicode_AsKind(str2, rkind);
10592 if (!buf2) goto error;
10593 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010594 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010596 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 rkind = kind2;
10598 sbuf = _PyUnicode_AsKind(self, rkind);
10599 if (!sbuf) goto error;
10600 srelease = 1;
10601 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010602 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 buf1 = _PyUnicode_AsKind(str1, rkind);
10604 if (!buf1) goto error;
10605 release1 = 1;
10606 }
10607 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10608 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010609 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 PyErr_SetString(PyExc_OverflowError,
10611 "replace string is too long");
10612 goto error;
10613 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010614 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010615 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010616 _Py_INCREF_UNICODE_EMPTY();
10617 if (!unicode_empty)
10618 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010619 u = unicode_empty;
10620 goto done;
10621 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010622 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010623 PyErr_SetString(PyExc_OverflowError,
10624 "replace string is too long");
10625 goto error;
10626 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010627 u = PyUnicode_New(new_size, maxchar);
10628 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010630 assert(PyUnicode_KIND(u) == rkind);
10631 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010632 ires = i = 0;
10633 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010634 while (n-- > 0) {
10635 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010636 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010637 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010638 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010639 if (j == -1)
10640 break;
10641 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010642 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010643 memcpy(res + rkind * ires,
10644 sbuf + rkind * i,
10645 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010647 }
10648 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010649 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010650 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010652 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010653 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010654 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010656 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010657 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010658 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010659 memcpy(res + rkind * ires,
10660 sbuf + rkind * i,
10661 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010662 }
10663 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010664 /* interleave */
10665 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010666 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010667 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010668 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010669 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010670 if (--n <= 0)
10671 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010672 memcpy(res + rkind * ires,
10673 sbuf + rkind * i,
10674 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010675 ires++;
10676 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010677 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010678 memcpy(res + rkind * ires,
10679 sbuf + rkind * i,
10680 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010681 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010682 }
10683
10684 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010685 unicode_adjust_maxchar(&u);
10686 if (u == NULL)
10687 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010688 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010689
10690 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010691 if (srelease)
10692 PyMem_FREE(sbuf);
10693 if (release1)
10694 PyMem_FREE(buf1);
10695 if (release2)
10696 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010697 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010698 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010699
Benjamin Peterson29060642009-01-31 22:14:21 +000010700 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010701 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010702 if (srelease)
10703 PyMem_FREE(sbuf);
10704 if (release1)
10705 PyMem_FREE(buf1);
10706 if (release2)
10707 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010708 return unicode_result_unchanged(self);
10709
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010710 error:
10711 if (srelease && sbuf)
10712 PyMem_FREE(sbuf);
10713 if (release1 && buf1)
10714 PyMem_FREE(buf1);
10715 if (release2 && buf2)
10716 PyMem_FREE(buf2);
10717 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010718}
10719
10720/* --- Unicode Object Methods --------------------------------------------- */
10721
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010722PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010723 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010724\n\
10725Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010726characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010727
10728static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010729unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010730{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010731 if (PyUnicode_READY(self) == -1)
10732 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010733 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010734}
10735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010736PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010737 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010738\n\
10739Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010740have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010741
10742static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010743unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010744{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010745 if (PyUnicode_READY(self) == -1)
10746 return NULL;
10747 if (PyUnicode_GET_LENGTH(self) == 0)
10748 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010749 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750}
10751
Benjamin Petersond5890c82012-01-14 13:23:30 -050010752PyDoc_STRVAR(casefold__doc__,
10753 "S.casefold() -> str\n\
10754\n\
10755Return a version of S suitable for caseless comparisons.");
10756
10757static PyObject *
10758unicode_casefold(PyObject *self)
10759{
10760 if (PyUnicode_READY(self) == -1)
10761 return NULL;
10762 if (PyUnicode_IS_ASCII(self))
10763 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010764 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010765}
10766
10767
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010768/* Argument converter. Coerces to a single unicode character */
10769
10770static int
10771convert_uc(PyObject *obj, void *addr)
10772{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010773 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010774 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010775
Benjamin Peterson14339b62009-01-31 16:36:08 +000010776 uniobj = PyUnicode_FromObject(obj);
10777 if (uniobj == NULL) {
10778 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010779 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010780 return 0;
10781 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010782 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010783 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010784 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010785 Py_DECREF(uniobj);
10786 return 0;
10787 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010788 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010789 Py_DECREF(uniobj);
10790 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010791}
10792
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010793PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010794 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010795\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010796Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010797done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798
10799static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010800unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010801{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010802 Py_ssize_t marg, left;
10803 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010804 Py_UCS4 fillchar = ' ';
10805
Victor Stinnere9a29352011-10-01 02:14:59 +020010806 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010807 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010808
Benjamin Petersonbac79492012-01-14 13:34:47 -050010809 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010810 return NULL;
10811
Victor Stinnerc4b49542011-12-11 22:44:26 +010010812 if (PyUnicode_GET_LENGTH(self) >= width)
10813 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010814
Victor Stinnerc4b49542011-12-11 22:44:26 +010010815 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010816 left = marg / 2 + (marg & width & 1);
10817
Victor Stinner9310abb2011-10-05 00:59:23 +020010818 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010819}
10820
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010821/* This function assumes that str1 and str2 are readied by the caller. */
10822
Marc-André Lemburge5034372000-08-08 08:04:29 +000010823static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010824unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010825{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010826#define COMPARE(TYPE1, TYPE2) \
10827 do { \
10828 TYPE1* p1 = (TYPE1 *)data1; \
10829 TYPE2* p2 = (TYPE2 *)data2; \
10830 TYPE1* end = p1 + len; \
10831 Py_UCS4 c1, c2; \
10832 for (; p1 != end; p1++, p2++) { \
10833 c1 = *p1; \
10834 c2 = *p2; \
10835 if (c1 != c2) \
10836 return (c1 < c2) ? -1 : 1; \
10837 } \
10838 } \
10839 while (0)
10840
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010841 int kind1, kind2;
10842 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010843 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010844
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010845 kind1 = PyUnicode_KIND(str1);
10846 kind2 = PyUnicode_KIND(str2);
10847 data1 = PyUnicode_DATA(str1);
10848 data2 = PyUnicode_DATA(str2);
10849 len1 = PyUnicode_GET_LENGTH(str1);
10850 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010851 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010852
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010853 switch(kind1) {
10854 case PyUnicode_1BYTE_KIND:
10855 {
10856 switch(kind2) {
10857 case PyUnicode_1BYTE_KIND:
10858 {
10859 int cmp = memcmp(data1, data2, len);
10860 /* normalize result of memcmp() into the range [-1; 1] */
10861 if (cmp < 0)
10862 return -1;
10863 if (cmp > 0)
10864 return 1;
10865 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010866 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010867 case PyUnicode_2BYTE_KIND:
10868 COMPARE(Py_UCS1, Py_UCS2);
10869 break;
10870 case PyUnicode_4BYTE_KIND:
10871 COMPARE(Py_UCS1, Py_UCS4);
10872 break;
10873 default:
10874 assert(0);
10875 }
10876 break;
10877 }
10878 case PyUnicode_2BYTE_KIND:
10879 {
10880 switch(kind2) {
10881 case PyUnicode_1BYTE_KIND:
10882 COMPARE(Py_UCS2, Py_UCS1);
10883 break;
10884 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010885 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010886 COMPARE(Py_UCS2, Py_UCS2);
10887 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010888 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010889 case PyUnicode_4BYTE_KIND:
10890 COMPARE(Py_UCS2, Py_UCS4);
10891 break;
10892 default:
10893 assert(0);
10894 }
10895 break;
10896 }
10897 case PyUnicode_4BYTE_KIND:
10898 {
10899 switch(kind2) {
10900 case PyUnicode_1BYTE_KIND:
10901 COMPARE(Py_UCS4, Py_UCS1);
10902 break;
10903 case PyUnicode_2BYTE_KIND:
10904 COMPARE(Py_UCS4, Py_UCS2);
10905 break;
10906 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010907 {
10908#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10909 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10910 /* normalize result of wmemcmp() into the range [-1; 1] */
10911 if (cmp < 0)
10912 return -1;
10913 if (cmp > 0)
10914 return 1;
10915#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010916 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010917#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010918 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010919 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010920 default:
10921 assert(0);
10922 }
10923 break;
10924 }
10925 default:
10926 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010927 }
10928
Victor Stinner770e19e2012-10-04 22:59:45 +020010929 if (len1 == len2)
10930 return 0;
10931 if (len1 < len2)
10932 return -1;
10933 else
10934 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010935
10936#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010937}
10938
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010939Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010940unicode_compare_eq(PyObject *str1, PyObject *str2)
10941{
10942 int kind;
10943 void *data1, *data2;
10944 Py_ssize_t len;
10945 int cmp;
10946
Victor Stinnere5567ad2012-10-23 02:48:49 +020010947 len = PyUnicode_GET_LENGTH(str1);
10948 if (PyUnicode_GET_LENGTH(str2) != len)
10949 return 0;
10950 kind = PyUnicode_KIND(str1);
10951 if (PyUnicode_KIND(str2) != kind)
10952 return 0;
10953 data1 = PyUnicode_DATA(str1);
10954 data2 = PyUnicode_DATA(str2);
10955
10956 cmp = memcmp(data1, data2, len * kind);
10957 return (cmp == 0);
10958}
10959
10960
Alexander Belopolsky40018472011-02-26 01:02:56 +000010961int
10962PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010963{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010964 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10965 if (PyUnicode_READY(left) == -1 ||
10966 PyUnicode_READY(right) == -1)
10967 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010968
10969 /* a string is equal to itself */
10970 if (left == right)
10971 return 0;
10972
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010973 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010974 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010975 PyErr_Format(PyExc_TypeError,
10976 "Can't compare %.100s and %.100s",
10977 left->ob_type->tp_name,
10978 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010979 return -1;
10980}
10981
Martin v. Löwis5b222132007-06-10 09:51:05 +000010982int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010983_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10984{
10985 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10986 if (right_str == NULL)
10987 return -1;
10988 return PyUnicode_Compare(left, right_str);
10989}
10990
10991int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010992PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10993{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010994 Py_ssize_t i;
10995 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 Py_UCS4 chr;
10997
Victor Stinner910337b2011-10-03 03:20:16 +020010998 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010999 if (PyUnicode_READY(uni) == -1)
11000 return -1;
11001 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011002 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011003 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011004 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011005 size_t len, len2 = strlen(str);
11006 int cmp;
11007
11008 len = Py_MIN(len1, len2);
11009 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011010 if (cmp != 0) {
11011 if (cmp < 0)
11012 return -1;
11013 else
11014 return 1;
11015 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011016 if (len1 > len2)
11017 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011018 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011019 return -1; /* str is longer */
11020 return 0;
11021 }
11022 else {
11023 void *data = PyUnicode_DATA(uni);
11024 /* Compare Unicode string and source character set string */
11025 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011026 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011027 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11028 /* This check keeps Python strings that end in '\0' from comparing equal
11029 to C strings identical up to that point. */
11030 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11031 return 1; /* uni is longer */
11032 if (str[i])
11033 return -1; /* str is longer */
11034 return 0;
11035 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011036}
11037
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011038
Benjamin Peterson29060642009-01-31 22:14:21 +000011039#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011040 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011041
Alexander Belopolsky40018472011-02-26 01:02:56 +000011042PyObject *
11043PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011044{
11045 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011046 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011047
Victor Stinnere5567ad2012-10-23 02:48:49 +020011048 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11049 Py_RETURN_NOTIMPLEMENTED;
11050
11051 if (PyUnicode_READY(left) == -1 ||
11052 PyUnicode_READY(right) == -1)
11053 return NULL;
11054
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011055 if (left == right) {
11056 switch (op) {
11057 case Py_EQ:
11058 case Py_LE:
11059 case Py_GE:
11060 /* a string is equal to itself */
11061 v = Py_True;
11062 break;
11063 case Py_NE:
11064 case Py_LT:
11065 case Py_GT:
11066 v = Py_False;
11067 break;
11068 default:
11069 PyErr_BadArgument();
11070 return NULL;
11071 }
11072 }
11073 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011074 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011075 result ^= (op == Py_NE);
11076 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011077 }
11078 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011079 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011080
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011081 /* Convert the return value to a Boolean */
11082 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011083 case Py_LE:
11084 v = TEST_COND(result <= 0);
11085 break;
11086 case Py_GE:
11087 v = TEST_COND(result >= 0);
11088 break;
11089 case Py_LT:
11090 v = TEST_COND(result == -1);
11091 break;
11092 case Py_GT:
11093 v = TEST_COND(result == 1);
11094 break;
11095 default:
11096 PyErr_BadArgument();
11097 return NULL;
11098 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011099 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011100 Py_INCREF(v);
11101 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011102}
11103
Alexander Belopolsky40018472011-02-26 01:02:56 +000011104int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011105_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11106{
11107 return unicode_eq(aa, bb);
11108}
11109
11110int
Alexander Belopolsky40018472011-02-26 01:02:56 +000011111PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011112{
Thomas Wouters477c8d52006-05-27 19:21:47 +000011113 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020011114 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011115 void *buf1, *buf2;
11116 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011117 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011118
11119 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000011120 sub = PyUnicode_FromObject(element);
11121 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011122 PyErr_Format(PyExc_TypeError,
11123 "'in <string>' requires string as left operand, not %s",
11124 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011125 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011126 }
11127
Thomas Wouters477c8d52006-05-27 19:21:47 +000011128 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011129 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011130 Py_DECREF(sub);
11131 return -1;
11132 }
11133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134 kind1 = PyUnicode_KIND(str);
11135 kind2 = PyUnicode_KIND(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011136 if (kind1 < kind2) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011137 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050011138 Py_DECREF(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011139 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011140 }
11141 len1 = PyUnicode_GET_LENGTH(str);
11142 len2 = PyUnicode_GET_LENGTH(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011143 if (len1 < len2) {
11144 Py_DECREF(sub);
11145 Py_DECREF(str);
11146 return 0;
11147 }
11148 buf1 = PyUnicode_DATA(str);
11149 buf2 = PyUnicode_DATA(sub);
11150 if (len2 == 1) {
11151 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11152 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
11153 Py_DECREF(sub);
11154 Py_DECREF(str);
11155 return result;
11156 }
11157 if (kind2 != kind1) {
11158 buf2 = _PyUnicode_AsKind(sub, kind1);
11159 if (!buf2) {
11160 Py_DECREF(sub);
11161 Py_DECREF(str);
11162 return -1;
11163 }
11164 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011165
Victor Stinner77282cb2013-04-14 19:22:47 +020011166 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167 case PyUnicode_1BYTE_KIND:
11168 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11169 break;
11170 case PyUnicode_2BYTE_KIND:
11171 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11172 break;
11173 case PyUnicode_4BYTE_KIND:
11174 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11175 break;
11176 default:
11177 result = -1;
11178 assert(0);
11179 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011180
11181 Py_DECREF(str);
11182 Py_DECREF(sub);
11183
Victor Stinner77282cb2013-04-14 19:22:47 +020011184 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011185 PyMem_Free(buf2);
11186
Guido van Rossum403d68b2000-03-13 15:55:09 +000011187 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011188}
11189
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190/* Concat to string or Unicode object giving a new Unicode object. */
11191
Alexander Belopolsky40018472011-02-26 01:02:56 +000011192PyObject *
11193PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011195 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020011196 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010011197 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198
11199 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011200 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011202 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011203 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011205 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206
11207 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020011208 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011209 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011210 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011211 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011212 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011213 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011214 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215 }
11216
Victor Stinner488fa492011-12-12 00:01:39 +010011217 u_len = PyUnicode_GET_LENGTH(u);
11218 v_len = PyUnicode_GET_LENGTH(v);
11219 if (u_len > PY_SSIZE_T_MAX - v_len) {
11220 PyErr_SetString(PyExc_OverflowError,
11221 "strings are too large to concat");
11222 goto onError;
11223 }
11224 new_len = u_len + v_len;
11225
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011226 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011227 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011228 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011229
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011231 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011233 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011234 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11235 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236 Py_DECREF(u);
11237 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011238 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011239 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011240
Benjamin Peterson29060642009-01-31 22:14:21 +000011241 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011242 Py_XDECREF(u);
11243 Py_XDECREF(v);
11244 return NULL;
11245}
11246
Walter Dörwald1ab83302007-05-18 17:15:44 +000011247void
Victor Stinner23e56682011-10-03 03:54:37 +020011248PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011249{
Victor Stinner23e56682011-10-03 03:54:37 +020011250 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011251 Py_UCS4 maxchar, maxchar2;
11252 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011253
11254 if (p_left == NULL) {
11255 if (!PyErr_Occurred())
11256 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011257 return;
11258 }
Victor Stinner23e56682011-10-03 03:54:37 +020011259 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011260 if (right == NULL || left == NULL
11261 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011262 if (!PyErr_Occurred())
11263 PyErr_BadInternalCall();
11264 goto error;
11265 }
11266
Benjamin Petersonbac79492012-01-14 13:34:47 -050011267 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011268 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011269 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011270 goto error;
11271
Victor Stinner488fa492011-12-12 00:01:39 +010011272 /* Shortcuts */
11273 if (left == unicode_empty) {
11274 Py_DECREF(left);
11275 Py_INCREF(right);
11276 *p_left = right;
11277 return;
11278 }
11279 if (right == unicode_empty)
11280 return;
11281
11282 left_len = PyUnicode_GET_LENGTH(left);
11283 right_len = PyUnicode_GET_LENGTH(right);
11284 if (left_len > PY_SSIZE_T_MAX - right_len) {
11285 PyErr_SetString(PyExc_OverflowError,
11286 "strings are too large to concat");
11287 goto error;
11288 }
11289 new_len = left_len + right_len;
11290
11291 if (unicode_modifiable(left)
11292 && PyUnicode_CheckExact(right)
11293 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011294 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11295 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011296 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011297 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011298 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11299 {
11300 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011301 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011302 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011303
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011304 /* copy 'right' into the newly allocated area of 'left' */
11305 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011306 }
Victor Stinner488fa492011-12-12 00:01:39 +010011307 else {
11308 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11309 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011310 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011311
Victor Stinner488fa492011-12-12 00:01:39 +010011312 /* Concat the two Unicode strings */
11313 res = PyUnicode_New(new_len, maxchar);
11314 if (res == NULL)
11315 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011316 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11317 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011318 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011319 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011320 }
11321 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011322 return;
11323
11324error:
Victor Stinner488fa492011-12-12 00:01:39 +010011325 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011326}
11327
11328void
11329PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11330{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011331 PyUnicode_Append(pleft, right);
11332 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011333}
11334
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011335PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011336 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011337\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011338Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011339string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011340interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011341
11342static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011343unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011345 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011346 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011347 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011348 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011349 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011350 void *buf1, *buf2;
11351 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011352
Jesus Ceaac451502011-04-20 17:09:23 +020011353 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11354 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011355 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011356
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011357 kind1 = PyUnicode_KIND(self);
11358 kind2 = PyUnicode_KIND(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011359 if (kind1 < kind2) {
Christian Heimesd47802e2013-06-29 21:33:36 +020011360 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011361 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011362 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011363 len1 = PyUnicode_GET_LENGTH(self);
11364 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011365 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011366 if (end - start < len2) {
11367 Py_DECREF(substring);
11368 return PyLong_FromLong(0);
11369 }
11370 buf1 = PyUnicode_DATA(self);
11371 buf2 = PyUnicode_DATA(substring);
11372 if (kind2 != kind1) {
11373 buf2 = _PyUnicode_AsKind(substring, kind1);
11374 if (!buf2) {
11375 Py_DECREF(substring);
11376 return NULL;
11377 }
11378 }
11379 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011380 case PyUnicode_1BYTE_KIND:
11381 iresult = ucs1lib_count(
11382 ((Py_UCS1*)buf1) + start, end - start,
11383 buf2, len2, PY_SSIZE_T_MAX
11384 );
11385 break;
11386 case PyUnicode_2BYTE_KIND:
11387 iresult = ucs2lib_count(
11388 ((Py_UCS2*)buf1) + start, end - start,
11389 buf2, len2, PY_SSIZE_T_MAX
11390 );
11391 break;
11392 case PyUnicode_4BYTE_KIND:
11393 iresult = ucs4lib_count(
11394 ((Py_UCS4*)buf1) + start, end - start,
11395 buf2, len2, PY_SSIZE_T_MAX
11396 );
11397 break;
11398 default:
11399 assert(0); iresult = 0;
11400 }
11401
11402 result = PyLong_FromSsize_t(iresult);
11403
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011404 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011405 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011406
11407 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011408
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409 return result;
11410}
11411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011412PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011413 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011415Encode S using the codec registered for encoding. Default encoding\n\
11416is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011417handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011418a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11419'xmlcharrefreplace' as well as any other name registered with\n\
11420codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421
11422static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011423unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011425 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426 char *encoding = NULL;
11427 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011428
Benjamin Peterson308d6372009-09-18 21:42:35 +000011429 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11430 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011432 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011433}
11434
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011435PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011436 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437\n\
11438Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011439If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011440
11441static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011442unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011444 Py_ssize_t i, j, line_pos, src_len, incr;
11445 Py_UCS4 ch;
11446 PyObject *u;
11447 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011448 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011450 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011451 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452
Ezio Melotti745d54d2013-11-16 19:10:57 +020011453 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11454 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011455 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456
Antoine Pitrou22425222011-10-04 19:10:51 +020011457 if (PyUnicode_READY(self) == -1)
11458 return NULL;
11459
Thomas Wouters7e474022000-07-16 12:04:32 +000011460 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011461 src_len = PyUnicode_GET_LENGTH(self);
11462 i = j = line_pos = 0;
11463 kind = PyUnicode_KIND(self);
11464 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011465 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011466 for (; i < src_len; i++) {
11467 ch = PyUnicode_READ(kind, src_data, i);
11468 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011469 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011470 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011471 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011472 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011473 goto overflow;
11474 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011475 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011476 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011477 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011479 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011480 goto overflow;
11481 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011483 if (ch == '\n' || ch == '\r')
11484 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011486 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011487 if (!found)
11488 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011489
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011491 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492 if (!u)
11493 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011494 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011495
Antoine Pitroue71d5742011-10-04 15:55:09 +020011496 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497
Antoine Pitroue71d5742011-10-04 15:55:09 +020011498 for (; i < src_len; i++) {
11499 ch = PyUnicode_READ(kind, src_data, i);
11500 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011501 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011502 incr = tabsize - (line_pos % tabsize);
11503 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011504 FILL(kind, dest_data, ' ', j, incr);
11505 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011506 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011507 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011508 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011509 line_pos++;
11510 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011511 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011512 if (ch == '\n' || ch == '\r')
11513 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011515 }
11516 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011517 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011518
Antoine Pitroue71d5742011-10-04 15:55:09 +020011519 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011520 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11521 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522}
11523
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011524PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011525 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526\n\
11527Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011528such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529arguments start and end are interpreted as in slice notation.\n\
11530\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011531Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532
11533static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011534unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011536 /* initialize variables to prevent gcc warning */
11537 PyObject *substring = NULL;
11538 Py_ssize_t start = 0;
11539 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011540 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541
Jesus Ceaac451502011-04-20 17:09:23 +020011542 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11543 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011544 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011545
Christian Heimesd47802e2013-06-29 21:33:36 +020011546 if (PyUnicode_READY(self) == -1) {
11547 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011548 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011549 }
11550 if (PyUnicode_READY(substring) == -1) {
11551 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011552 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011553 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011554
Victor Stinner7931d9a2011-11-04 00:22:48 +010011555 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011556
11557 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011559 if (result == -2)
11560 return NULL;
11561
Christian Heimes217cfd12007-12-02 14:31:20 +000011562 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563}
11564
11565static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011566unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011568 void *data;
11569 enum PyUnicode_Kind kind;
11570 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011571
11572 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11573 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011574 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011575 }
11576 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11577 PyErr_SetString(PyExc_IndexError, "string index out of range");
11578 return NULL;
11579 }
11580 kind = PyUnicode_KIND(self);
11581 data = PyUnicode_DATA(self);
11582 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011583 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584}
11585
Guido van Rossumc2504932007-09-18 19:42:40 +000011586/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011587 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011588static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011589unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590{
Guido van Rossumc2504932007-09-18 19:42:40 +000011591 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011592 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011593
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011594#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011595 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011596#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011597 if (_PyUnicode_HASH(self) != -1)
11598 return _PyUnicode_HASH(self);
11599 if (PyUnicode_READY(self) == -1)
11600 return -1;
11601 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011602 /*
11603 We make the hash of the empty string be 0, rather than using
11604 (prefix ^ suffix), since this slightly obfuscates the hash secret
11605 */
11606 if (len == 0) {
11607 _PyUnicode_HASH(self) = 0;
11608 return 0;
11609 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011610 x = _Py_HashBytes(PyUnicode_DATA(self),
11611 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011613 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614}
11615
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011616PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011617 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011619Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011620
11621static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011622unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011623{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011624 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011625 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011626 PyObject *substring = NULL;
11627 Py_ssize_t start = 0;
11628 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011629
Jesus Ceaac451502011-04-20 17:09:23 +020011630 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11631 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011632 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011633
Christian Heimesd47a0452013-06-29 21:21:37 +020011634 if (PyUnicode_READY(self) == -1) {
11635 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011636 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011637 }
11638 if (PyUnicode_READY(substring) == -1) {
11639 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011640 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011641 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011642
Victor Stinner7931d9a2011-11-04 00:22:48 +010011643 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011644
11645 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011646
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011647 if (result == -2)
11648 return NULL;
11649
Guido van Rossumd57fd912000-03-10 22:53:23 +000011650 if (result < 0) {
11651 PyErr_SetString(PyExc_ValueError, "substring not found");
11652 return NULL;
11653 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011654
Christian Heimes217cfd12007-12-02 14:31:20 +000011655 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011656}
11657
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011658PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011659 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011660\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011661Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011662at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011663
11664static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011665unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011666{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667 Py_ssize_t i, length;
11668 int kind;
11669 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011670 int cased;
11671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011672 if (PyUnicode_READY(self) == -1)
11673 return NULL;
11674 length = PyUnicode_GET_LENGTH(self);
11675 kind = PyUnicode_KIND(self);
11676 data = PyUnicode_DATA(self);
11677
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011679 if (length == 1)
11680 return PyBool_FromLong(
11681 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011682
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011683 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011685 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011686
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688 for (i = 0; i < length; i++) {
11689 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011690
Benjamin Peterson29060642009-01-31 22:14:21 +000011691 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11692 return PyBool_FromLong(0);
11693 else if (!cased && Py_UNICODE_ISLOWER(ch))
11694 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011696 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697}
11698
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011699PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011700 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011702Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011703at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704
11705static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011706unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011708 Py_ssize_t i, length;
11709 int kind;
11710 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711 int cased;
11712
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011713 if (PyUnicode_READY(self) == -1)
11714 return NULL;
11715 length = PyUnicode_GET_LENGTH(self);
11716 kind = PyUnicode_KIND(self);
11717 data = PyUnicode_DATA(self);
11718
Guido van Rossumd57fd912000-03-10 22:53:23 +000011719 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011720 if (length == 1)
11721 return PyBool_FromLong(
11722 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011724 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011725 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011726 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011727
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 for (i = 0; i < length; i++) {
11730 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011731
Benjamin Peterson29060642009-01-31 22:14:21 +000011732 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11733 return PyBool_FromLong(0);
11734 else if (!cased && Py_UNICODE_ISUPPER(ch))
11735 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011737 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738}
11739
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011740PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011741 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011743Return True if S is a titlecased string and there is at least one\n\
11744character in S, i.e. upper- and titlecase characters may only\n\
11745follow uncased characters and lowercase characters only cased ones.\n\
11746Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011747
11748static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011749unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011751 Py_ssize_t i, length;
11752 int kind;
11753 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754 int cased, previous_is_cased;
11755
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011756 if (PyUnicode_READY(self) == -1)
11757 return NULL;
11758 length = PyUnicode_GET_LENGTH(self);
11759 kind = PyUnicode_KIND(self);
11760 data = PyUnicode_DATA(self);
11761
Guido van Rossumd57fd912000-03-10 22:53:23 +000011762 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011763 if (length == 1) {
11764 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11765 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11766 (Py_UNICODE_ISUPPER(ch) != 0));
11767 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011769 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011770 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011771 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011772
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773 cased = 0;
11774 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011775 for (i = 0; i < length; i++) {
11776 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011777
Benjamin Peterson29060642009-01-31 22:14:21 +000011778 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11779 if (previous_is_cased)
11780 return PyBool_FromLong(0);
11781 previous_is_cased = 1;
11782 cased = 1;
11783 }
11784 else if (Py_UNICODE_ISLOWER(ch)) {
11785 if (!previous_is_cased)
11786 return PyBool_FromLong(0);
11787 previous_is_cased = 1;
11788 cased = 1;
11789 }
11790 else
11791 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011792 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011793 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794}
11795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011796PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011797 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011799Return True if all characters in S are whitespace\n\
11800and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011801
11802static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011803unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011805 Py_ssize_t i, length;
11806 int kind;
11807 void *data;
11808
11809 if (PyUnicode_READY(self) == -1)
11810 return NULL;
11811 length = PyUnicode_GET_LENGTH(self);
11812 kind = PyUnicode_KIND(self);
11813 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011814
Guido van Rossumd57fd912000-03-10 22:53:23 +000011815 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816 if (length == 1)
11817 return PyBool_FromLong(
11818 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011820 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011822 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011823
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011824 for (i = 0; i < length; i++) {
11825 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011826 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011827 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011828 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011829 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011830}
11831
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011832PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011833 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011834\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011835Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011836and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011837
11838static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011839unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011840{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011841 Py_ssize_t i, length;
11842 int kind;
11843 void *data;
11844
11845 if (PyUnicode_READY(self) == -1)
11846 return NULL;
11847 length = PyUnicode_GET_LENGTH(self);
11848 kind = PyUnicode_KIND(self);
11849 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011850
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011851 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011852 if (length == 1)
11853 return PyBool_FromLong(
11854 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011855
11856 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011858 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011859
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011860 for (i = 0; i < length; i++) {
11861 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011862 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011863 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011864 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011865}
11866
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011867PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011868 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011869\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011870Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011871and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011872
11873static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011874unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011875{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011876 int kind;
11877 void *data;
11878 Py_ssize_t len, i;
11879
11880 if (PyUnicode_READY(self) == -1)
11881 return NULL;
11882
11883 kind = PyUnicode_KIND(self);
11884 data = PyUnicode_DATA(self);
11885 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011886
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011887 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011888 if (len == 1) {
11889 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11890 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11891 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011892
11893 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011894 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011895 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011896
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011897 for (i = 0; i < len; i++) {
11898 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011899 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011900 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011901 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011902 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011903}
11904
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011905PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011906 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011907\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011908Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011909False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910
11911static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011912unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011913{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011914 Py_ssize_t i, length;
11915 int kind;
11916 void *data;
11917
11918 if (PyUnicode_READY(self) == -1)
11919 return NULL;
11920 length = PyUnicode_GET_LENGTH(self);
11921 kind = PyUnicode_KIND(self);
11922 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 if (length == 1)
11926 return PyBool_FromLong(
11927 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011928
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011929 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011930 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011931 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011932
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011933 for (i = 0; i < length; i++) {
11934 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011935 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011936 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011937 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011938}
11939
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011940PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011941 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011943Return True if all characters in S are digits\n\
11944and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945
11946static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011947unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011949 Py_ssize_t i, length;
11950 int kind;
11951 void *data;
11952
11953 if (PyUnicode_READY(self) == -1)
11954 return NULL;
11955 length = PyUnicode_GET_LENGTH(self);
11956 kind = PyUnicode_KIND(self);
11957 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011958
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011960 if (length == 1) {
11961 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11962 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11963 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011964
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011965 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011966 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011967 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011969 for (i = 0; i < length; i++) {
11970 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011971 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011972 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011973 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011974}
11975
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011976PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011977 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011978\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011979Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011980False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011981
11982static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011983unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011984{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011985 Py_ssize_t i, length;
11986 int kind;
11987 void *data;
11988
11989 if (PyUnicode_READY(self) == -1)
11990 return NULL;
11991 length = PyUnicode_GET_LENGTH(self);
11992 kind = PyUnicode_KIND(self);
11993 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011994
Guido van Rossumd57fd912000-03-10 22:53:23 +000011995 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 if (length == 1)
11997 return PyBool_FromLong(
11998 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011999
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012000 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012001 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012002 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012003
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012004 for (i = 0; i < length; i++) {
12005 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012006 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012007 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012008 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012009}
12010
Martin v. Löwis47383402007-08-15 07:32:56 +000012011int
12012PyUnicode_IsIdentifier(PyObject *self)
12013{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014 int kind;
12015 void *data;
12016 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012017 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012018
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019 if (PyUnicode_READY(self) == -1) {
12020 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012021 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012022 }
12023
12024 /* Special case for empty strings */
12025 if (PyUnicode_GET_LENGTH(self) == 0)
12026 return 0;
12027 kind = PyUnicode_KIND(self);
12028 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012029
12030 /* PEP 3131 says that the first character must be in
12031 XID_Start and subsequent characters in XID_Continue,
12032 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012033 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012034 letters, digits, underscore). However, given the current
12035 definition of XID_Start and XID_Continue, it is sufficient
12036 to check just for these, except that _ must be allowed
12037 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012038 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012039 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012040 return 0;
12041
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012042 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012043 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012044 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012045 return 1;
12046}
12047
12048PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012049 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000012050\n\
12051Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012052to the language definition.\n\
12053\n\
12054Use keyword.iskeyword() to test for reserved identifiers\n\
12055such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012056
12057static PyObject*
12058unicode_isidentifier(PyObject *self)
12059{
12060 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12061}
12062
Georg Brandl559e5d72008-06-11 18:37:52 +000012063PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012064 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012065\n\
12066Return True if all characters in S are considered\n\
12067printable in repr() or S is empty, False otherwise.");
12068
12069static PyObject*
12070unicode_isprintable(PyObject *self)
12071{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012072 Py_ssize_t i, length;
12073 int kind;
12074 void *data;
12075
12076 if (PyUnicode_READY(self) == -1)
12077 return NULL;
12078 length = PyUnicode_GET_LENGTH(self);
12079 kind = PyUnicode_KIND(self);
12080 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012081
12082 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012083 if (length == 1)
12084 return PyBool_FromLong(
12085 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012086
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012087 for (i = 0; i < length; i++) {
12088 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012089 Py_RETURN_FALSE;
12090 }
12091 }
12092 Py_RETURN_TRUE;
12093}
12094
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012095PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012096 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012097\n\
12098Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012099iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012100
12101static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012102unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012103{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012104 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105}
12106
Martin v. Löwis18e16552006-02-15 17:27:45 +000012107static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012108unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012110 if (PyUnicode_READY(self) == -1)
12111 return -1;
12112 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012113}
12114
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012115PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012116 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012117\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012118Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012119done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012120
12121static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012122unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012123{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012124 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012125 Py_UCS4 fillchar = ' ';
12126
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012127 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012128 return NULL;
12129
Benjamin Petersonbac79492012-01-14 13:34:47 -050012130 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012131 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012132
Victor Stinnerc4b49542011-12-11 22:44:26 +010012133 if (PyUnicode_GET_LENGTH(self) >= width)
12134 return unicode_result_unchanged(self);
12135
12136 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012137}
12138
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012139PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012140 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012142Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143
12144static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012145unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012146{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012147 if (PyUnicode_READY(self) == -1)
12148 return NULL;
12149 if (PyUnicode_IS_ASCII(self))
12150 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012151 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012152}
12153
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012154#define LEFTSTRIP 0
12155#define RIGHTSTRIP 1
12156#define BOTHSTRIP 2
12157
12158/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012159static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012160
12161#define STRIPNAME(i) (stripformat[i]+3)
12162
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012163/* externally visible for str.strip(unicode) */
12164PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012165_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012166{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012167 void *data;
12168 int kind;
12169 Py_ssize_t i, j, len;
12170 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012171 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012172
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012173 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12174 return NULL;
12175
12176 kind = PyUnicode_KIND(self);
12177 data = PyUnicode_DATA(self);
12178 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012179 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012180 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12181 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012182 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012183
Benjamin Peterson14339b62009-01-31 16:36:08 +000012184 i = 0;
12185 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012186 while (i < len) {
12187 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12188 if (!BLOOM(sepmask, ch))
12189 break;
12190 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12191 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012192 i++;
12193 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012194 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012195
Benjamin Peterson14339b62009-01-31 16:36:08 +000012196 j = len;
12197 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012198 j--;
12199 while (j >= i) {
12200 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12201 if (!BLOOM(sepmask, ch))
12202 break;
12203 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12204 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012205 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012206 }
12207
Benjamin Peterson29060642009-01-31 22:14:21 +000012208 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012209 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012210
Victor Stinner7931d9a2011-11-04 00:22:48 +010012211 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012212}
12213
12214PyObject*
12215PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12216{
12217 unsigned char *data;
12218 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012219 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012220
Victor Stinnerde636f32011-10-01 03:55:54 +020012221 if (PyUnicode_READY(self) == -1)
12222 return NULL;
12223
Victor Stinner684d5fd2012-05-03 02:32:34 +020012224 length = PyUnicode_GET_LENGTH(self);
12225 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012226
Victor Stinner684d5fd2012-05-03 02:32:34 +020012227 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012228 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012229
Victor Stinnerde636f32011-10-01 03:55:54 +020012230 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012231 PyErr_SetString(PyExc_IndexError, "string index out of range");
12232 return NULL;
12233 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012234 if (start >= length || end < start)
12235 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012236
Victor Stinner684d5fd2012-05-03 02:32:34 +020012237 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012238 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012239 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012240 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012241 }
12242 else {
12243 kind = PyUnicode_KIND(self);
12244 data = PyUnicode_1BYTE_DATA(self);
12245 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012246 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012247 length);
12248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012249}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012250
12251static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012252do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012253{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012254 Py_ssize_t len, i, j;
12255
12256 if (PyUnicode_READY(self) == -1)
12257 return NULL;
12258
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012259 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012260
Victor Stinnercc7af722013-04-09 22:39:24 +020012261 if (PyUnicode_IS_ASCII(self)) {
12262 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12263
12264 i = 0;
12265 if (striptype != RIGHTSTRIP) {
12266 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012267 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012268 if (!_Py_ascii_whitespace[ch])
12269 break;
12270 i++;
12271 }
12272 }
12273
12274 j = len;
12275 if (striptype != LEFTSTRIP) {
12276 j--;
12277 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012278 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012279 if (!_Py_ascii_whitespace[ch])
12280 break;
12281 j--;
12282 }
12283 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012284 }
12285 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012286 else {
12287 int kind = PyUnicode_KIND(self);
12288 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012289
Victor Stinnercc7af722013-04-09 22:39:24 +020012290 i = 0;
12291 if (striptype != RIGHTSTRIP) {
12292 while (i < len) {
12293 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12294 if (!Py_UNICODE_ISSPACE(ch))
12295 break;
12296 i++;
12297 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012298 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012299
12300 j = len;
12301 if (striptype != LEFTSTRIP) {
12302 j--;
12303 while (j >= i) {
12304 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12305 if (!Py_UNICODE_ISSPACE(ch))
12306 break;
12307 j--;
12308 }
12309 j++;
12310 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012311 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012312
Victor Stinner7931d9a2011-11-04 00:22:48 +010012313 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012314}
12315
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012316
12317static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012318do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012319{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012320 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012321
Serhiy Storchakac6792272013-10-19 21:03:34 +030012322 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012323 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012324
Benjamin Peterson14339b62009-01-31 16:36:08 +000012325 if (sep != NULL && sep != Py_None) {
12326 if (PyUnicode_Check(sep))
12327 return _PyUnicode_XStrip(self, striptype, sep);
12328 else {
12329 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012330 "%s arg must be None or str",
12331 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012332 return NULL;
12333 }
12334 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012335
Benjamin Peterson14339b62009-01-31 16:36:08 +000012336 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012337}
12338
12339
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012340PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012341 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012342\n\
12343Return a copy of the string S with leading and trailing\n\
12344whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012345If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012346
12347static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012348unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012349{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012350 if (PyTuple_GET_SIZE(args) == 0)
12351 return do_strip(self, BOTHSTRIP); /* Common case */
12352 else
12353 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012354}
12355
12356
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012357PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012358 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012359\n\
12360Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012361If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012362
12363static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012364unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012365{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012366 if (PyTuple_GET_SIZE(args) == 0)
12367 return do_strip(self, LEFTSTRIP); /* Common case */
12368 else
12369 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012370}
12371
12372
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012373PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012374 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012375\n\
12376Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012377If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012378
12379static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012380unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012381{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012382 if (PyTuple_GET_SIZE(args) == 0)
12383 return do_strip(self, RIGHTSTRIP); /* Common case */
12384 else
12385 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012386}
12387
12388
Guido van Rossumd57fd912000-03-10 22:53:23 +000012389static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012390unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012392 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012393 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012394
Serhiy Storchaka05997252013-01-26 12:14:02 +020012395 if (len < 1)
12396 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012397
Victor Stinnerc4b49542011-12-11 22:44:26 +010012398 /* no repeat, return original string */
12399 if (len == 1)
12400 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012401
Benjamin Petersonbac79492012-01-14 13:34:47 -050012402 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012403 return NULL;
12404
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012405 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012406 PyErr_SetString(PyExc_OverflowError,
12407 "repeated string is too long");
12408 return NULL;
12409 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012410 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012411
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012412 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012413 if (!u)
12414 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012415 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012416
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012417 if (PyUnicode_GET_LENGTH(str) == 1) {
12418 const int kind = PyUnicode_KIND(str);
12419 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012420 if (kind == PyUnicode_1BYTE_KIND) {
12421 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012422 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012423 }
12424 else if (kind == PyUnicode_2BYTE_KIND) {
12425 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012426 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012427 ucs2[n] = fill_char;
12428 } else {
12429 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12430 assert(kind == PyUnicode_4BYTE_KIND);
12431 for (n = 0; n < len; ++n)
12432 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012433 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012434 }
12435 else {
12436 /* number of characters copied this far */
12437 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012438 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012439 char *to = (char *) PyUnicode_DATA(u);
12440 Py_MEMCPY(to, PyUnicode_DATA(str),
12441 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012442 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012443 n = (done <= nchars-done) ? done : nchars-done;
12444 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012445 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012446 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012447 }
12448
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012449 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012450 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012451}
12452
Alexander Belopolsky40018472011-02-26 01:02:56 +000012453PyObject *
12454PyUnicode_Replace(PyObject *obj,
12455 PyObject *subobj,
12456 PyObject *replobj,
12457 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012458{
12459 PyObject *self;
12460 PyObject *str1;
12461 PyObject *str2;
12462 PyObject *result;
12463
12464 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012465 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012466 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012467 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012468 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012469 Py_DECREF(self);
12470 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012471 }
12472 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012473 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012474 Py_DECREF(self);
12475 Py_DECREF(str1);
12476 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012477 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012478 if (PyUnicode_READY(self) == -1 ||
12479 PyUnicode_READY(str1) == -1 ||
12480 PyUnicode_READY(str2) == -1)
12481 result = NULL;
12482 else
12483 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012484 Py_DECREF(self);
12485 Py_DECREF(str1);
12486 Py_DECREF(str2);
12487 return result;
12488}
12489
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012490PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012491 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492\n\
12493Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012494old replaced by new. If the optional argument count is\n\
12495given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012496
12497static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012498unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012499{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012500 PyObject *str1;
12501 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012502 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503 PyObject *result;
12504
Martin v. Löwis18e16552006-02-15 17:27:45 +000012505 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012506 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012507 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012508 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012509 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012510 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012511 return NULL;
12512 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012513 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012514 Py_DECREF(str1);
12515 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012516 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012517 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12518 result = NULL;
12519 else
12520 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012521
12522 Py_DECREF(str1);
12523 Py_DECREF(str2);
12524 return result;
12525}
12526
Alexander Belopolsky40018472011-02-26 01:02:56 +000012527static PyObject *
12528unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012530 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012531 Py_ssize_t isize;
12532 Py_ssize_t osize, squote, dquote, i, o;
12533 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012534 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012535 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012536
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012537 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012538 return NULL;
12539
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012540 isize = PyUnicode_GET_LENGTH(unicode);
12541 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012543 /* Compute length of output, quote characters, and
12544 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012545 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012546 max = 127;
12547 squote = dquote = 0;
12548 ikind = PyUnicode_KIND(unicode);
12549 for (i = 0; i < isize; i++) {
12550 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012551 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012552 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012553 case '\'': squote++; break;
12554 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012555 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012556 incr = 2;
12557 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012558 default:
12559 /* Fast-path ASCII */
12560 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012561 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012562 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012563 ;
12564 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012566 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012567 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012568 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012569 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012570 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012571 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012572 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012573 if (osize > PY_SSIZE_T_MAX - incr) {
12574 PyErr_SetString(PyExc_OverflowError,
12575 "string is too long to generate repr");
12576 return NULL;
12577 }
12578 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012579 }
12580
12581 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012582 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012583 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012584 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012585 if (dquote)
12586 /* Both squote and dquote present. Use squote,
12587 and escape them */
12588 osize += squote;
12589 else
12590 quote = '"';
12591 }
Victor Stinner55c08782013-04-14 18:45:39 +020012592 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012593
12594 repr = PyUnicode_New(osize, max);
12595 if (repr == NULL)
12596 return NULL;
12597 okind = PyUnicode_KIND(repr);
12598 odata = PyUnicode_DATA(repr);
12599
12600 PyUnicode_WRITE(okind, odata, 0, quote);
12601 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012602 if (unchanged) {
12603 _PyUnicode_FastCopyCharacters(repr, 1,
12604 unicode, 0,
12605 isize);
12606 }
12607 else {
12608 for (i = 0, o = 1; i < isize; i++) {
12609 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012610
Victor Stinner55c08782013-04-14 18:45:39 +020012611 /* Escape quotes and backslashes */
12612 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012613 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012614 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012615 continue;
12616 }
12617
12618 /* Map special whitespace to '\t', \n', '\r' */
12619 if (ch == '\t') {
12620 PyUnicode_WRITE(okind, odata, o++, '\\');
12621 PyUnicode_WRITE(okind, odata, o++, 't');
12622 }
12623 else if (ch == '\n') {
12624 PyUnicode_WRITE(okind, odata, o++, '\\');
12625 PyUnicode_WRITE(okind, odata, o++, 'n');
12626 }
12627 else if (ch == '\r') {
12628 PyUnicode_WRITE(okind, odata, o++, '\\');
12629 PyUnicode_WRITE(okind, odata, o++, 'r');
12630 }
12631
12632 /* Map non-printable US ASCII to '\xhh' */
12633 else if (ch < ' ' || ch == 0x7F) {
12634 PyUnicode_WRITE(okind, odata, o++, '\\');
12635 PyUnicode_WRITE(okind, odata, o++, 'x');
12636 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12637 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12638 }
12639
12640 /* Copy ASCII characters as-is */
12641 else if (ch < 0x7F) {
12642 PyUnicode_WRITE(okind, odata, o++, ch);
12643 }
12644
12645 /* Non-ASCII characters */
12646 else {
12647 /* Map Unicode whitespace and control characters
12648 (categories Z* and C* except ASCII space)
12649 */
12650 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12651 PyUnicode_WRITE(okind, odata, o++, '\\');
12652 /* Map 8-bit characters to '\xhh' */
12653 if (ch <= 0xff) {
12654 PyUnicode_WRITE(okind, odata, o++, 'x');
12655 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12656 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12657 }
12658 /* Map 16-bit characters to '\uxxxx' */
12659 else if (ch <= 0xffff) {
12660 PyUnicode_WRITE(okind, odata, o++, 'u');
12661 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12662 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12663 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12664 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12665 }
12666 /* Map 21-bit characters to '\U00xxxxxx' */
12667 else {
12668 PyUnicode_WRITE(okind, odata, o++, 'U');
12669 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12670 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12671 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12672 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12673 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12674 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12675 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12676 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12677 }
12678 }
12679 /* Copy characters as-is */
12680 else {
12681 PyUnicode_WRITE(okind, odata, o++, ch);
12682 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012683 }
12684 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012685 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012686 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012687 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012688 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012689}
12690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012691PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012692 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012693\n\
12694Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012695such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696arguments start and end are interpreted as in slice notation.\n\
12697\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012698Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699
12700static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012701unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012703 /* initialize variables to prevent gcc warning */
12704 PyObject *substring = NULL;
12705 Py_ssize_t start = 0;
12706 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012707 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708
Jesus Ceaac451502011-04-20 17:09:23 +020012709 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12710 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012711 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012712
Christian Heimesea71a522013-06-29 21:17:34 +020012713 if (PyUnicode_READY(self) == -1) {
12714 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012715 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012716 }
12717 if (PyUnicode_READY(substring) == -1) {
12718 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012719 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012720 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012721
Victor Stinner7931d9a2011-11-04 00:22:48 +010012722 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012723
12724 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012726 if (result == -2)
12727 return NULL;
12728
Christian Heimes217cfd12007-12-02 14:31:20 +000012729 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012730}
12731
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012732PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012733 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012734\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012735Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012736
12737static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012739{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012740 /* initialize variables to prevent gcc warning */
12741 PyObject *substring = NULL;
12742 Py_ssize_t start = 0;
12743 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012744 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745
Jesus Ceaac451502011-04-20 17:09:23 +020012746 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12747 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012748 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749
Christian Heimesea71a522013-06-29 21:17:34 +020012750 if (PyUnicode_READY(self) == -1) {
12751 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012752 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012753 }
12754 if (PyUnicode_READY(substring) == -1) {
12755 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012756 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012757 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012758
Victor Stinner7931d9a2011-11-04 00:22:48 +010012759 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012760
12761 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012762
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012763 if (result == -2)
12764 return NULL;
12765
Guido van Rossumd57fd912000-03-10 22:53:23 +000012766 if (result < 0) {
12767 PyErr_SetString(PyExc_ValueError, "substring not found");
12768 return NULL;
12769 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012770
Christian Heimes217cfd12007-12-02 14:31:20 +000012771 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012772}
12773
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012774PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012775 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012776\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012777Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012778done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012779
12780static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012781unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012782{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012783 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012784 Py_UCS4 fillchar = ' ';
12785
Victor Stinnere9a29352011-10-01 02:14:59 +020012786 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012787 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012788
Benjamin Petersonbac79492012-01-14 13:34:47 -050012789 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012790 return NULL;
12791
Victor Stinnerc4b49542011-12-11 22:44:26 +010012792 if (PyUnicode_GET_LENGTH(self) >= width)
12793 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012794
Victor Stinnerc4b49542011-12-11 22:44:26 +010012795 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796}
12797
Alexander Belopolsky40018472011-02-26 01:02:56 +000012798PyObject *
12799PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012800{
12801 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012802
Guido van Rossumd57fd912000-03-10 22:53:23 +000012803 s = PyUnicode_FromObject(s);
12804 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012805 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012806 if (sep != NULL) {
12807 sep = PyUnicode_FromObject(sep);
12808 if (sep == NULL) {
12809 Py_DECREF(s);
12810 return NULL;
12811 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012812 }
12813
Victor Stinner9310abb2011-10-05 00:59:23 +020012814 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012815
12816 Py_DECREF(s);
12817 Py_XDECREF(sep);
12818 return result;
12819}
12820
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012821PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012822 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012823\n\
12824Return a list of the words in S, using sep as the\n\
12825delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012826splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012827whitespace string is a separator and empty strings are\n\
12828removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012829
12830static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012831unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012832{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012833 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012834 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012835 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012836
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012837 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12838 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012839 return NULL;
12840
12841 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012842 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012843 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012844 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012845 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012846 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012847}
12848
Thomas Wouters477c8d52006-05-27 19:21:47 +000012849PyObject *
12850PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12851{
12852 PyObject* str_obj;
12853 PyObject* sep_obj;
12854 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012855 int kind1, kind2;
12856 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012857 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012858
12859 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012860 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012861 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012862 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012863 if (!sep_obj) {
12864 Py_DECREF(str_obj);
12865 return NULL;
12866 }
12867 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12868 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012869 Py_DECREF(str_obj);
12870 return NULL;
12871 }
12872
Victor Stinner14f8f022011-10-05 20:58:25 +020012873 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012874 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012875 len1 = PyUnicode_GET_LENGTH(str_obj);
12876 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012877 if (kind1 < kind2 || len1 < len2) {
12878 _Py_INCREF_UNICODE_EMPTY();
12879 if (!unicode_empty)
12880 out = NULL;
12881 else {
12882 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12883 Py_DECREF(unicode_empty);
12884 }
12885 Py_DECREF(sep_obj);
12886 Py_DECREF(str_obj);
12887 return out;
12888 }
12889 buf1 = PyUnicode_DATA(str_obj);
12890 buf2 = PyUnicode_DATA(sep_obj);
12891 if (kind2 != kind1) {
12892 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12893 if (!buf2)
12894 goto onError;
12895 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012896
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012897 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012898 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012899 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12900 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12901 else
12902 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012903 break;
12904 case PyUnicode_2BYTE_KIND:
12905 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12906 break;
12907 case PyUnicode_4BYTE_KIND:
12908 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12909 break;
12910 default:
12911 assert(0);
12912 out = 0;
12913 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012914
12915 Py_DECREF(sep_obj);
12916 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012917 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012918 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012919
12920 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012921 onError:
12922 Py_DECREF(sep_obj);
12923 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012924 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012925 PyMem_Free(buf2);
12926 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012927}
12928
12929
12930PyObject *
12931PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12932{
12933 PyObject* str_obj;
12934 PyObject* sep_obj;
12935 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012936 int kind1, kind2;
12937 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012938 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012939
12940 str_obj = PyUnicode_FromObject(str_in);
12941 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012942 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012943 sep_obj = PyUnicode_FromObject(sep_in);
12944 if (!sep_obj) {
12945 Py_DECREF(str_obj);
12946 return NULL;
12947 }
12948
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012949 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012950 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012951 len1 = PyUnicode_GET_LENGTH(str_obj);
12952 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012953 if (kind1 < kind2 || len1 < len2) {
12954 _Py_INCREF_UNICODE_EMPTY();
12955 if (!unicode_empty)
12956 out = NULL;
12957 else {
12958 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12959 Py_DECREF(unicode_empty);
12960 }
12961 Py_DECREF(sep_obj);
12962 Py_DECREF(str_obj);
12963 return out;
12964 }
12965 buf1 = PyUnicode_DATA(str_obj);
12966 buf2 = PyUnicode_DATA(sep_obj);
12967 if (kind2 != kind1) {
12968 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12969 if (!buf2)
12970 goto onError;
12971 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012972
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012973 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012974 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012975 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12976 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12977 else
12978 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012979 break;
12980 case PyUnicode_2BYTE_KIND:
12981 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12982 break;
12983 case PyUnicode_4BYTE_KIND:
12984 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12985 break;
12986 default:
12987 assert(0);
12988 out = 0;
12989 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012990
12991 Py_DECREF(sep_obj);
12992 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012993 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012994 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012995
12996 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012997 onError:
12998 Py_DECREF(sep_obj);
12999 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013000 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013001 PyMem_Free(buf2);
13002 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013003}
13004
13005PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013006 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013007\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000013008Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013009the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000013010found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013011
13012static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013013unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013014{
Victor Stinner9310abb2011-10-05 00:59:23 +020013015 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013016}
13017
13018PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000013019 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013020\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000013021Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013022the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000013023separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013024
13025static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013026unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013027{
Victor Stinner9310abb2011-10-05 00:59:23 +020013028 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013029}
13030
Alexander Belopolsky40018472011-02-26 01:02:56 +000013031PyObject *
13032PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013033{
13034 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013035
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013036 s = PyUnicode_FromObject(s);
13037 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013038 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013039 if (sep != NULL) {
13040 sep = PyUnicode_FromObject(sep);
13041 if (sep == NULL) {
13042 Py_DECREF(s);
13043 return NULL;
13044 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013045 }
13046
Victor Stinner9310abb2011-10-05 00:59:23 +020013047 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013048
13049 Py_DECREF(s);
13050 Py_XDECREF(sep);
13051 return result;
13052}
13053
13054PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013055 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013056\n\
13057Return a list of the words in S, using sep as the\n\
13058delimiter string, starting at the end of the string and\n\
13059working to the front. If maxsplit is given, at most maxsplit\n\
13060splits are done. If sep is not specified, any whitespace string\n\
13061is a separator.");
13062
13063static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013064unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013065{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013066 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013067 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013068 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013069
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013070 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
13071 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013072 return NULL;
13073
13074 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000013075 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013076 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020013077 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013078 else
Victor Stinner9310abb2011-10-05 00:59:23 +020013079 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013080}
13081
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013082PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013083 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013084\n\
13085Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000013086Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013087is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088
13089static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013090unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013091{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013092 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000013093 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013094
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013095 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
13096 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097 return NULL;
13098
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013099 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013100}
13101
13102static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013103PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013105 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013106}
13107
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013108PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013109 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110\n\
13111Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013112and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013113
13114static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013115unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013117 if (PyUnicode_READY(self) == -1)
13118 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013119 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013120}
13121
Larry Hastings61272b72014-01-07 12:41:53 -080013122/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013123
Larry Hastings31826802013-10-19 00:09:25 -070013124@staticmethod
13125str.maketrans as unicode_maketrans
13126
13127 x: object
13128
13129 y: unicode=NULL
13130
13131 z: unicode=NULL
13132
13133 /
13134
13135Return a translation table usable for str.translate().
13136
13137If there is only one argument, it must be a dictionary mapping Unicode
13138ordinals (integers) or characters to Unicode ordinals, strings or None.
13139Character keys will be then converted to ordinals.
13140If there are two arguments, they must be strings of equal length, and
13141in the resulting dictionary, each character in x will be mapped to the
13142character at the same position in y. If there is a third argument, it
13143must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013144[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013145
Larry Hastings31826802013-10-19 00:09:25 -070013146static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013147unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013148/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013149{
Georg Brandlceee0772007-11-27 23:48:05 +000013150 PyObject *new = NULL, *key, *value;
13151 Py_ssize_t i = 0;
13152 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013153
Georg Brandlceee0772007-11-27 23:48:05 +000013154 new = PyDict_New();
13155 if (!new)
13156 return NULL;
13157 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013158 int x_kind, y_kind, z_kind;
13159 void *x_data, *y_data, *z_data;
13160
Georg Brandlceee0772007-11-27 23:48:05 +000013161 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013162 if (!PyUnicode_Check(x)) {
13163 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13164 "be a string if there is a second argument");
13165 goto err;
13166 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013167 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013168 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13169 "arguments must have equal length");
13170 goto err;
13171 }
13172 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013173 x_kind = PyUnicode_KIND(x);
13174 y_kind = PyUnicode_KIND(y);
13175 x_data = PyUnicode_DATA(x);
13176 y_data = PyUnicode_DATA(y);
13177 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13178 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013179 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013180 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013181 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013182 if (!value) {
13183 Py_DECREF(key);
13184 goto err;
13185 }
Georg Brandlceee0772007-11-27 23:48:05 +000013186 res = PyDict_SetItem(new, key, value);
13187 Py_DECREF(key);
13188 Py_DECREF(value);
13189 if (res < 0)
13190 goto err;
13191 }
13192 /* create entries for deleting chars in z */
13193 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013194 z_kind = PyUnicode_KIND(z);
13195 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013196 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013197 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013198 if (!key)
13199 goto err;
13200 res = PyDict_SetItem(new, key, Py_None);
13201 Py_DECREF(key);
13202 if (res < 0)
13203 goto err;
13204 }
13205 }
13206 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013207 int kind;
13208 void *data;
13209
Georg Brandlceee0772007-11-27 23:48:05 +000013210 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013211 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013212 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13213 "to maketrans it must be a dict");
13214 goto err;
13215 }
13216 /* copy entries into the new dict, converting string keys to int keys */
13217 while (PyDict_Next(x, &i, &key, &value)) {
13218 if (PyUnicode_Check(key)) {
13219 /* convert string keys to integer keys */
13220 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013221 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013222 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13223 "table must be of length 1");
13224 goto err;
13225 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013226 kind = PyUnicode_KIND(key);
13227 data = PyUnicode_DATA(key);
13228 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013229 if (!newkey)
13230 goto err;
13231 res = PyDict_SetItem(new, newkey, value);
13232 Py_DECREF(newkey);
13233 if (res < 0)
13234 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013235 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013236 /* just keep integer keys */
13237 if (PyDict_SetItem(new, key, value) < 0)
13238 goto err;
13239 } else {
13240 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13241 "be strings or integers");
13242 goto err;
13243 }
13244 }
13245 }
13246 return new;
13247 err:
13248 Py_DECREF(new);
13249 return NULL;
13250}
13251
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013252PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013253 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013254\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013255Return a copy of the string S in which each character has been mapped\n\
13256through the given translation table. The table must implement\n\
13257lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13258mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13259this operation raises LookupError, the character is left untouched.\n\
13260Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013261
13262static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013263unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013264{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013265 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013266}
13267
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013268PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013269 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013270\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013271Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013272
13273static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013274unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013275{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013276 if (PyUnicode_READY(self) == -1)
13277 return NULL;
13278 if (PyUnicode_IS_ASCII(self))
13279 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013280 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013281}
13282
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013283PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013284 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013285\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013286Pad a numeric string S with zeros on the left, to fill a field\n\
13287of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013288
13289static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013290unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013291{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013292 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013293 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013294 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013295 int kind;
13296 void *data;
13297 Py_UCS4 chr;
13298
Martin v. Löwis18e16552006-02-15 17:27:45 +000013299 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013300 return NULL;
13301
Benjamin Petersonbac79492012-01-14 13:34:47 -050013302 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013303 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013304
Victor Stinnerc4b49542011-12-11 22:44:26 +010013305 if (PyUnicode_GET_LENGTH(self) >= width)
13306 return unicode_result_unchanged(self);
13307
13308 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013309
13310 u = pad(self, fill, 0, '0');
13311
Walter Dörwald068325e2002-04-15 13:36:47 +000013312 if (u == NULL)
13313 return NULL;
13314
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013315 kind = PyUnicode_KIND(u);
13316 data = PyUnicode_DATA(u);
13317 chr = PyUnicode_READ(kind, data, fill);
13318
13319 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013320 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013321 PyUnicode_WRITE(kind, data, 0, chr);
13322 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013323 }
13324
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013325 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013326 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013327}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013328
13329#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013330static PyObject *
13331unicode__decimal2ascii(PyObject *self)
13332{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013333 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013334}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013335#endif
13336
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013337PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013338 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013339\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013340Return True if S starts with the specified prefix, False otherwise.\n\
13341With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013342With optional end, stop comparing S at that position.\n\
13343prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013344
13345static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013346unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013347 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013348{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013349 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013350 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013351 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013352 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013353 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013354
Jesus Ceaac451502011-04-20 17:09:23 +020013355 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013356 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013357 if (PyTuple_Check(subobj)) {
13358 Py_ssize_t i;
13359 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013360 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013361 if (substring == NULL)
13362 return NULL;
13363 result = tailmatch(self, substring, start, end, -1);
13364 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013365 if (result == -1)
13366 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013367 if (result) {
13368 Py_RETURN_TRUE;
13369 }
13370 }
13371 /* nothing matched */
13372 Py_RETURN_FALSE;
13373 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013374 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013375 if (substring == NULL) {
13376 if (PyErr_ExceptionMatches(PyExc_TypeError))
13377 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13378 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013379 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013380 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013381 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013382 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013383 if (result == -1)
13384 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013385 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013386}
13387
13388
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013389PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013390 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013391\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013392Return True if S ends with the specified suffix, False otherwise.\n\
13393With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013394With optional end, stop comparing S at that position.\n\
13395suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013396
13397static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013398unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013399 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013400{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013401 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013402 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013403 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013404 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013405 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013406
Jesus Ceaac451502011-04-20 17:09:23 +020013407 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013408 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013409 if (PyTuple_Check(subobj)) {
13410 Py_ssize_t i;
13411 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013412 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013413 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013414 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013415 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013416 result = tailmatch(self, substring, start, end, +1);
13417 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013418 if (result == -1)
13419 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013420 if (result) {
13421 Py_RETURN_TRUE;
13422 }
13423 }
13424 Py_RETURN_FALSE;
13425 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013426 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013427 if (substring == NULL) {
13428 if (PyErr_ExceptionMatches(PyExc_TypeError))
13429 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13430 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013431 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013432 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013433 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013434 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013435 if (result == -1)
13436 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013437 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013438}
13439
Victor Stinner202fdca2012-05-07 12:47:02 +020013440Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013441_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013442{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013443 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13444 writer->data = PyUnicode_DATA(writer->buffer);
13445
13446 if (!writer->readonly) {
13447 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013448 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013449 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013450 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013451 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13452 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13453 writer->kind = PyUnicode_WCHAR_KIND;
13454 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13455
Victor Stinner8f674cc2013-04-17 23:02:17 +020013456 /* Copy-on-write mode: set buffer size to 0 so
13457 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13458 * next write. */
13459 writer->size = 0;
13460 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013461}
13462
Victor Stinnerd3f08822012-05-29 12:57:52 +020013463void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013464_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013465{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013466 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013467
13468 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013469 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013470
13471 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13472 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13473 writer->kind = PyUnicode_WCHAR_KIND;
13474 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013475}
13476
Victor Stinnerd3f08822012-05-29 12:57:52 +020013477int
13478_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13479 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013480{
13481 Py_ssize_t newlen;
13482 PyObject *newbuffer;
13483
Victor Stinnerca9381e2015-09-22 00:58:32 +020013484 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013485 assert((maxchar > writer->maxchar && length >= 0)
13486 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013487
Victor Stinner202fdca2012-05-07 12:47:02 +020013488 if (length > PY_SSIZE_T_MAX - writer->pos) {
13489 PyErr_NoMemory();
13490 return -1;
13491 }
13492 newlen = writer->pos + length;
13493
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013494 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013495
Victor Stinnerd3f08822012-05-29 12:57:52 +020013496 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013497 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013498 if (writer->overallocate
13499 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13500 /* overallocate to limit the number of realloc() */
13501 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013502 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013503 if (newlen < writer->min_length)
13504 newlen = writer->min_length;
13505
Victor Stinnerd3f08822012-05-29 12:57:52 +020013506 writer->buffer = PyUnicode_New(newlen, maxchar);
13507 if (writer->buffer == NULL)
13508 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013509 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013510 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013511 if (writer->overallocate
13512 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13513 /* overallocate to limit the number of realloc() */
13514 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013515 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013516 if (newlen < writer->min_length)
13517 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013518
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013519 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013520 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013521 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013522 newbuffer = PyUnicode_New(newlen, maxchar);
13523 if (newbuffer == NULL)
13524 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013525 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13526 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013527 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013528 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013529 }
13530 else {
13531 newbuffer = resize_compact(writer->buffer, newlen);
13532 if (newbuffer == NULL)
13533 return -1;
13534 }
13535 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013536 }
13537 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013538 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013539 newbuffer = PyUnicode_New(writer->size, maxchar);
13540 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013541 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013542 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13543 writer->buffer, 0, writer->pos);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +020013544 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013545 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013546 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013547 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013548
13549#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013550}
13551
Victor Stinnerca9381e2015-09-22 00:58:32 +020013552int
13553_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13554 enum PyUnicode_Kind kind)
13555{
13556 Py_UCS4 maxchar;
13557
13558 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13559 assert(writer->kind < kind);
13560
13561 switch (kind)
13562 {
13563 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13564 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13565 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13566 default:
13567 assert(0 && "invalid kind");
13568 return -1;
13569 }
13570
13571 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13572}
13573
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013574Py_LOCAL_INLINE(int)
13575_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013576{
13577 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13578 return -1;
13579 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13580 writer->pos++;
13581 return 0;
13582}
13583
13584int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013585_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13586{
13587 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13588}
13589
13590int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013591_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13592{
13593 Py_UCS4 maxchar;
13594 Py_ssize_t len;
13595
13596 if (PyUnicode_READY(str) == -1)
13597 return -1;
13598 len = PyUnicode_GET_LENGTH(str);
13599 if (len == 0)
13600 return 0;
13601 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13602 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013603 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013604 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013605 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013606 Py_INCREF(str);
13607 writer->buffer = str;
13608 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013609 writer->pos += len;
13610 return 0;
13611 }
13612 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13613 return -1;
13614 }
13615 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13616 str, 0, len);
13617 writer->pos += len;
13618 return 0;
13619}
13620
Victor Stinnere215d962012-10-06 23:03:36 +020013621int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013622_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13623 Py_ssize_t start, Py_ssize_t end)
13624{
13625 Py_UCS4 maxchar;
13626 Py_ssize_t len;
13627
13628 if (PyUnicode_READY(str) == -1)
13629 return -1;
13630
13631 assert(0 <= start);
13632 assert(end <= PyUnicode_GET_LENGTH(str));
13633 assert(start <= end);
13634
13635 if (end == 0)
13636 return 0;
13637
13638 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13639 return _PyUnicodeWriter_WriteStr(writer, str);
13640
13641 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13642 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13643 else
13644 maxchar = writer->maxchar;
13645 len = end - start;
13646
13647 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13648 return -1;
13649
13650 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13651 str, start, len);
13652 writer->pos += len;
13653 return 0;
13654}
13655
13656int
Victor Stinner4a587072013-11-19 12:54:53 +010013657_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13658 const char *ascii, Py_ssize_t len)
13659{
13660 if (len == -1)
13661 len = strlen(ascii);
13662
13663 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13664
13665 if (writer->buffer == NULL && !writer->overallocate) {
13666 PyObject *str;
13667
13668 str = _PyUnicode_FromASCII(ascii, len);
13669 if (str == NULL)
13670 return -1;
13671
13672 writer->readonly = 1;
13673 writer->buffer = str;
13674 _PyUnicodeWriter_Update(writer);
13675 writer->pos += len;
13676 return 0;
13677 }
13678
13679 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13680 return -1;
13681
13682 switch (writer->kind)
13683 {
13684 case PyUnicode_1BYTE_KIND:
13685 {
13686 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13687 Py_UCS1 *data = writer->data;
13688
13689 Py_MEMCPY(data + writer->pos, str, len);
13690 break;
13691 }
13692 case PyUnicode_2BYTE_KIND:
13693 {
13694 _PyUnicode_CONVERT_BYTES(
13695 Py_UCS1, Py_UCS2,
13696 ascii, ascii + len,
13697 (Py_UCS2 *)writer->data + writer->pos);
13698 break;
13699 }
13700 case PyUnicode_4BYTE_KIND:
13701 {
13702 _PyUnicode_CONVERT_BYTES(
13703 Py_UCS1, Py_UCS4,
13704 ascii, ascii + len,
13705 (Py_UCS4 *)writer->data + writer->pos);
13706 break;
13707 }
13708 default:
13709 assert(0);
13710 }
13711
13712 writer->pos += len;
13713 return 0;
13714}
13715
13716int
13717_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13718 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013719{
13720 Py_UCS4 maxchar;
13721
13722 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13723 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13724 return -1;
13725 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13726 writer->pos += len;
13727 return 0;
13728}
13729
Victor Stinnerd3f08822012-05-29 12:57:52 +020013730PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013731_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013732{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013733 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013734 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013735 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013736 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013737 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013738 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013739 str = writer->buffer;
13740 writer->buffer = NULL;
13741 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13742 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013743 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013744 if (writer->pos == 0) {
13745 Py_CLEAR(writer->buffer);
13746
13747 /* Get the empty Unicode string singleton ('') */
13748 _Py_INCREF_UNICODE_EMPTY();
13749 str = unicode_empty;
Victor Stinner202fdca2012-05-07 12:47:02 +020013750 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013751 else {
13752 str = writer->buffer;
13753 writer->buffer = NULL;
13754
13755 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13756 PyObject *str2;
13757 str2 = resize_compact(str, writer->pos);
13758 if (str2 == NULL)
13759 return NULL;
13760 str = str2;
13761 }
13762 }
13763
Victor Stinner15a0bd32013-07-08 22:29:55 +020013764 assert(_PyUnicode_CheckConsistency(str, 1));
13765 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013766}
13767
Victor Stinnerd3f08822012-05-29 12:57:52 +020013768void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013769_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013770{
13771 Py_CLEAR(writer->buffer);
13772}
13773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013774#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013775
13776PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013777 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013778\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013779Return a formatted version of S, using substitutions from args and kwargs.\n\
13780The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013781
Eric Smith27bbca62010-11-04 17:06:58 +000013782PyDoc_STRVAR(format_map__doc__,
13783 "S.format_map(mapping) -> str\n\
13784\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013785Return a formatted version of S, using substitutions from mapping.\n\
13786The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013787
Eric Smith4a7d76d2008-05-30 18:10:19 +000013788static PyObject *
13789unicode__format__(PyObject* self, PyObject* args)
13790{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013791 PyObject *format_spec;
13792 _PyUnicodeWriter writer;
13793 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013794
13795 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13796 return NULL;
13797
Victor Stinnerd3f08822012-05-29 12:57:52 +020013798 if (PyUnicode_READY(self) == -1)
13799 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013800 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013801 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13802 self, format_spec, 0,
13803 PyUnicode_GET_LENGTH(format_spec));
13804 if (ret == -1) {
13805 _PyUnicodeWriter_Dealloc(&writer);
13806 return NULL;
13807 }
13808 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013809}
13810
Eric Smith8c663262007-08-25 02:26:07 +000013811PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013812 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013813\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013814Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013815
13816static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013817unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013818{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013819 Py_ssize_t size;
13820
13821 /* If it's a compact object, account for base structure +
13822 character data. */
13823 if (PyUnicode_IS_COMPACT_ASCII(v))
13824 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13825 else if (PyUnicode_IS_COMPACT(v))
13826 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013827 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013828 else {
13829 /* If it is a two-block object, account for base object, and
13830 for character block if present. */
13831 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013832 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013833 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013834 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013835 }
13836 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013837 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013838 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013839 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013840 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013841 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013842
13843 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013844}
13845
13846PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013847 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013848
13849static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013850unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013851{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013852 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013853 if (!copy)
13854 return NULL;
13855 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013856}
13857
Guido van Rossumd57fd912000-03-10 22:53:23 +000013858static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013859 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013860 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013861 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13862 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013863 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13864 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013865 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013866 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13867 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13868 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013869 {"expandtabs", (PyCFunction) unicode_expandtabs,
13870 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013871 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013872 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013873 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13874 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13875 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013876 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013877 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13878 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13879 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013880 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013881 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013882 {"splitlines", (PyCFunction) unicode_splitlines,
13883 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013884 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013885 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13886 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13887 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13888 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13889 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13890 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13891 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13892 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13893 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13894 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13895 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13896 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13897 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13898 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013899 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013900 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013901 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013902 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013903 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013904 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013905 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013906 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013907#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013908 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013909 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013910#endif
13911
Benjamin Peterson14339b62009-01-31 16:36:08 +000013912 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013913 {NULL, NULL}
13914};
13915
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013916static PyObject *
13917unicode_mod(PyObject *v, PyObject *w)
13918{
Brian Curtindfc80e32011-08-10 20:28:54 -050013919 if (!PyUnicode_Check(v))
13920 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013921 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013922}
13923
13924static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013925 0, /*nb_add*/
13926 0, /*nb_subtract*/
13927 0, /*nb_multiply*/
13928 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013929};
13930
Guido van Rossumd57fd912000-03-10 22:53:23 +000013931static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013932 (lenfunc) unicode_length, /* sq_length */
13933 PyUnicode_Concat, /* sq_concat */
13934 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13935 (ssizeargfunc) unicode_getitem, /* sq_item */
13936 0, /* sq_slice */
13937 0, /* sq_ass_item */
13938 0, /* sq_ass_slice */
13939 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013940};
13941
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013942static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013943unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013944{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013945 if (PyUnicode_READY(self) == -1)
13946 return NULL;
13947
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013948 if (PyIndex_Check(item)) {
13949 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013950 if (i == -1 && PyErr_Occurred())
13951 return NULL;
13952 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013953 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013954 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013955 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013956 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013957 PyObject *result;
13958 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013959 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013960 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013961
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013962 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013963 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013964 return NULL;
13965 }
13966
13967 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013968 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013969 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013970 slicelength == PyUnicode_GET_LENGTH(self)) {
13971 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013972 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013973 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013974 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013975 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013976 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013977 src_kind = PyUnicode_KIND(self);
13978 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013979 if (!PyUnicode_IS_ASCII(self)) {
13980 kind_limit = kind_maxchar_limit(src_kind);
13981 max_char = 0;
13982 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13983 ch = PyUnicode_READ(src_kind, src_data, cur);
13984 if (ch > max_char) {
13985 max_char = ch;
13986 if (max_char >= kind_limit)
13987 break;
13988 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013989 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013990 }
Victor Stinner55c99112011-10-13 01:17:06 +020013991 else
13992 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013993 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013994 if (result == NULL)
13995 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013996 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013997 dest_data = PyUnicode_DATA(result);
13998
13999 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014000 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14001 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014002 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014003 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014004 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014005 } else {
14006 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
14007 return NULL;
14008 }
14009}
14010
14011static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014012 (lenfunc)unicode_length, /* mp_length */
14013 (binaryfunc)unicode_subscript, /* mp_subscript */
14014 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014015};
14016
Guido van Rossumd57fd912000-03-10 22:53:23 +000014017
Guido van Rossumd57fd912000-03-10 22:53:23 +000014018/* Helpers for PyUnicode_Format() */
14019
Victor Stinnera47082312012-10-04 02:19:54 +020014020struct unicode_formatter_t {
14021 PyObject *args;
14022 int args_owned;
14023 Py_ssize_t arglen, argidx;
14024 PyObject *dict;
14025
14026 enum PyUnicode_Kind fmtkind;
14027 Py_ssize_t fmtcnt, fmtpos;
14028 void *fmtdata;
14029 PyObject *fmtstr;
14030
14031 _PyUnicodeWriter writer;
14032};
14033
14034struct unicode_format_arg_t {
14035 Py_UCS4 ch;
14036 int flags;
14037 Py_ssize_t width;
14038 int prec;
14039 int sign;
14040};
14041
Guido van Rossumd57fd912000-03-10 22:53:23 +000014042static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014043unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014044{
Victor Stinnera47082312012-10-04 02:19:54 +020014045 Py_ssize_t argidx = ctx->argidx;
14046
14047 if (argidx < ctx->arglen) {
14048 ctx->argidx++;
14049 if (ctx->arglen < 0)
14050 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014051 else
Victor Stinnera47082312012-10-04 02:19:54 +020014052 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014053 }
14054 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014055 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014056 return NULL;
14057}
14058
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014059/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014060
Victor Stinnera47082312012-10-04 02:19:54 +020014061/* Format a float into the writer if the writer is not NULL, or into *p_output
14062 otherwise.
14063
14064 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014065static int
Victor Stinnera47082312012-10-04 02:19:54 +020014066formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14067 PyObject **p_output,
14068 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014069{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014070 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014071 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014072 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014073 int prec;
14074 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014075
Guido van Rossumd57fd912000-03-10 22:53:23 +000014076 x = PyFloat_AsDouble(v);
14077 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014078 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014079
Victor Stinnera47082312012-10-04 02:19:54 +020014080 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014081 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014082 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014083
Victor Stinnera47082312012-10-04 02:19:54 +020014084 if (arg->flags & F_ALT)
14085 dtoa_flags = Py_DTSF_ALT;
14086 else
14087 dtoa_flags = 0;
14088 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014089 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014090 return -1;
14091 len = strlen(p);
14092 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014093 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014094 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014095 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014096 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014097 }
14098 else
14099 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014100 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014101 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014102}
14103
Victor Stinnerd0880d52012-04-27 23:40:13 +020014104/* formatlong() emulates the format codes d, u, o, x and X, and
14105 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14106 * Python's regular ints.
14107 * Return value: a new PyUnicodeObject*, or NULL if error.
14108 * The output string is of the form
14109 * "-"? ("0x" | "0X")? digit+
14110 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14111 * set in flags. The case of hex digits will be correct,
14112 * There will be at least prec digits, zero-filled on the left if
14113 * necessary to get that many.
14114 * val object to be converted
14115 * flags bitmask of format flags; only F_ALT is looked at
14116 * prec minimum number of digits; 0-fill on left if needed
14117 * type a character in [duoxX]; u acts the same as d
14118 *
14119 * CAUTION: o, x and X conversions on regular ints can never
14120 * produce a '-' sign, but can for Python's unbounded ints.
14121 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014122PyObject *
14123_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014124{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014125 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014126 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014127 Py_ssize_t i;
14128 int sign; /* 1 if '-', else 0 */
14129 int len; /* number of characters */
14130 Py_ssize_t llen;
14131 int numdigits; /* len == numnondigits + numdigits */
14132 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014133
Victor Stinnerd0880d52012-04-27 23:40:13 +020014134 /* Avoid exceeding SSIZE_T_MAX */
14135 if (prec > INT_MAX-3) {
14136 PyErr_SetString(PyExc_OverflowError,
14137 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014138 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014139 }
14140
14141 assert(PyLong_Check(val));
14142
14143 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014144 default:
14145 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014146 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014147 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014148 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014149 /* int and int subclasses should print numerically when a numeric */
14150 /* format code is used (see issue18780) */
14151 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014152 break;
14153 case 'o':
14154 numnondigits = 2;
14155 result = PyNumber_ToBase(val, 8);
14156 break;
14157 case 'x':
14158 case 'X':
14159 numnondigits = 2;
14160 result = PyNumber_ToBase(val, 16);
14161 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014162 }
14163 if (!result)
14164 return NULL;
14165
14166 assert(unicode_modifiable(result));
14167 assert(PyUnicode_IS_READY(result));
14168 assert(PyUnicode_IS_ASCII(result));
14169
14170 /* To modify the string in-place, there can only be one reference. */
14171 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014172 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014173 PyErr_BadInternalCall();
14174 return NULL;
14175 }
14176 buf = PyUnicode_DATA(result);
14177 llen = PyUnicode_GET_LENGTH(result);
14178 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014179 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014180 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014181 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014182 return NULL;
14183 }
14184 len = (int)llen;
14185 sign = buf[0] == '-';
14186 numnondigits += sign;
14187 numdigits = len - numnondigits;
14188 assert(numdigits > 0);
14189
14190 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014191 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014192 (type == 'o' || type == 'x' || type == 'X'))) {
14193 assert(buf[sign] == '0');
14194 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14195 buf[sign+1] == 'o');
14196 numnondigits -= 2;
14197 buf += 2;
14198 len -= 2;
14199 if (sign)
14200 buf[0] = '-';
14201 assert(len == numnondigits + numdigits);
14202 assert(numdigits > 0);
14203 }
14204
14205 /* Fill with leading zeroes to meet minimum width. */
14206 if (prec > numdigits) {
14207 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14208 numnondigits + prec);
14209 char *b1;
14210 if (!r1) {
14211 Py_DECREF(result);
14212 return NULL;
14213 }
14214 b1 = PyBytes_AS_STRING(r1);
14215 for (i = 0; i < numnondigits; ++i)
14216 *b1++ = *buf++;
14217 for (i = 0; i < prec - numdigits; i++)
14218 *b1++ = '0';
14219 for (i = 0; i < numdigits; i++)
14220 *b1++ = *buf++;
14221 *b1 = '\0';
14222 Py_DECREF(result);
14223 result = r1;
14224 buf = PyBytes_AS_STRING(result);
14225 len = numnondigits + prec;
14226 }
14227
14228 /* Fix up case for hex conversions. */
14229 if (type == 'X') {
14230 /* Need to convert all lower case letters to upper case.
14231 and need to convert 0x to 0X (and -0x to -0X). */
14232 for (i = 0; i < len; i++)
14233 if (buf[i] >= 'a' && buf[i] <= 'x')
14234 buf[i] -= 'a'-'A';
14235 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014236 if (!PyUnicode_Check(result)
14237 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014238 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014239 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014240 Py_DECREF(result);
14241 result = unicode;
14242 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014243 else if (len != PyUnicode_GET_LENGTH(result)) {
14244 if (PyUnicode_Resize(&result, len) < 0)
14245 Py_CLEAR(result);
14246 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014247 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014248}
14249
Ethan Furmandf3ed242014-01-05 06:50:30 -080014250/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014251 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014252 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014253 * -1 and raise an exception on error */
14254static int
Victor Stinnera47082312012-10-04 02:19:54 +020014255mainformatlong(PyObject *v,
14256 struct unicode_format_arg_t *arg,
14257 PyObject **p_output,
14258 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014259{
14260 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014261 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014262
14263 if (!PyNumber_Check(v))
14264 goto wrongtype;
14265
Ethan Furman9ab74802014-03-21 06:38:46 -070014266 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014267 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014268 if (type == 'o' || type == 'x' || type == 'X') {
14269 iobj = PyNumber_Index(v);
14270 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014271 if (PyErr_ExceptionMatches(PyExc_TypeError))
14272 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014273 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014274 }
14275 }
14276 else {
14277 iobj = PyNumber_Long(v);
14278 if (iobj == NULL ) {
14279 if (PyErr_ExceptionMatches(PyExc_TypeError))
14280 goto wrongtype;
14281 return -1;
14282 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014283 }
14284 assert(PyLong_Check(iobj));
14285 }
14286 else {
14287 iobj = v;
14288 Py_INCREF(iobj);
14289 }
14290
14291 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014292 && arg->width == -1 && arg->prec == -1
14293 && !(arg->flags & (F_SIGN | F_BLANK))
14294 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014295 {
14296 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014297 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014298 int base;
14299
Victor Stinnera47082312012-10-04 02:19:54 +020014300 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014301 {
14302 default:
14303 assert(0 && "'type' not in [diuoxX]");
14304 case 'd':
14305 case 'i':
14306 case 'u':
14307 base = 10;
14308 break;
14309 case 'o':
14310 base = 8;
14311 break;
14312 case 'x':
14313 case 'X':
14314 base = 16;
14315 break;
14316 }
14317
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014318 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14319 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014320 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014321 }
14322 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014323 return 1;
14324 }
14325
Ethan Furmanb95b5612015-01-23 20:05:18 -080014326 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014327 Py_DECREF(iobj);
14328 if (res == NULL)
14329 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014330 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014331 return 0;
14332
14333wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014334 switch(type)
14335 {
14336 case 'o':
14337 case 'x':
14338 case 'X':
14339 PyErr_Format(PyExc_TypeError,
14340 "%%%c format: an integer is required, "
14341 "not %.200s",
14342 type, Py_TYPE(v)->tp_name);
14343 break;
14344 default:
14345 PyErr_Format(PyExc_TypeError,
14346 "%%%c format: a number is required, "
14347 "not %.200s",
14348 type, Py_TYPE(v)->tp_name);
14349 break;
14350 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014351 return -1;
14352}
14353
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014354static Py_UCS4
14355formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014356{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014357 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014358 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014359 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014360 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014361 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014362 goto onError;
14363 }
14364 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014365 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014366 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014367 /* make sure number is a type of integer */
14368 if (!PyLong_Check(v)) {
14369 iobj = PyNumber_Index(v);
14370 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014371 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014372 }
14373 v = iobj;
14374 Py_DECREF(iobj);
14375 }
14376 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014377 x = PyLong_AsLong(v);
14378 if (x == -1 && PyErr_Occurred())
14379 goto onError;
14380
Victor Stinner8faf8212011-12-08 22:14:11 +010014381 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014382 PyErr_SetString(PyExc_OverflowError,
14383 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014384 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014385 }
14386
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014387 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014388 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014389
Benjamin Peterson29060642009-01-31 22:14:21 +000014390 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014391 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014392 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014393 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014394}
14395
Victor Stinnera47082312012-10-04 02:19:54 +020014396/* Parse options of an argument: flags, width, precision.
14397 Handle also "%(name)" syntax.
14398
14399 Return 0 if the argument has been formatted into arg->str.
14400 Return 1 if the argument has been written into ctx->writer,
14401 Raise an exception and return -1 on error. */
14402static int
14403unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14404 struct unicode_format_arg_t *arg)
14405{
14406#define FORMAT_READ(ctx) \
14407 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14408
14409 PyObject *v;
14410
Victor Stinnera47082312012-10-04 02:19:54 +020014411 if (arg->ch == '(') {
14412 /* Get argument value from a dictionary. Example: "%(name)s". */
14413 Py_ssize_t keystart;
14414 Py_ssize_t keylen;
14415 PyObject *key;
14416 int pcount = 1;
14417
14418 if (ctx->dict == NULL) {
14419 PyErr_SetString(PyExc_TypeError,
14420 "format requires a mapping");
14421 return -1;
14422 }
14423 ++ctx->fmtpos;
14424 --ctx->fmtcnt;
14425 keystart = ctx->fmtpos;
14426 /* Skip over balanced parentheses */
14427 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14428 arg->ch = FORMAT_READ(ctx);
14429 if (arg->ch == ')')
14430 --pcount;
14431 else if (arg->ch == '(')
14432 ++pcount;
14433 ctx->fmtpos++;
14434 }
14435 keylen = ctx->fmtpos - keystart - 1;
14436 if (ctx->fmtcnt < 0 || pcount > 0) {
14437 PyErr_SetString(PyExc_ValueError,
14438 "incomplete format key");
14439 return -1;
14440 }
14441 key = PyUnicode_Substring(ctx->fmtstr,
14442 keystart, keystart + keylen);
14443 if (key == NULL)
14444 return -1;
14445 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014446 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014447 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014448 }
14449 ctx->args = PyObject_GetItem(ctx->dict, key);
14450 Py_DECREF(key);
14451 if (ctx->args == NULL)
14452 return -1;
14453 ctx->args_owned = 1;
14454 ctx->arglen = -1;
14455 ctx->argidx = -2;
14456 }
14457
14458 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014459 while (--ctx->fmtcnt >= 0) {
14460 arg->ch = FORMAT_READ(ctx);
14461 ctx->fmtpos++;
14462 switch (arg->ch) {
14463 case '-': arg->flags |= F_LJUST; continue;
14464 case '+': arg->flags |= F_SIGN; continue;
14465 case ' ': arg->flags |= F_BLANK; continue;
14466 case '#': arg->flags |= F_ALT; continue;
14467 case '0': arg->flags |= F_ZERO; continue;
14468 }
14469 break;
14470 }
14471
14472 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014473 if (arg->ch == '*') {
14474 v = unicode_format_getnextarg(ctx);
14475 if (v == NULL)
14476 return -1;
14477 if (!PyLong_Check(v)) {
14478 PyErr_SetString(PyExc_TypeError,
14479 "* wants int");
14480 return -1;
14481 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014482 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014483 if (arg->width == -1 && PyErr_Occurred())
14484 return -1;
14485 if (arg->width < 0) {
14486 arg->flags |= F_LJUST;
14487 arg->width = -arg->width;
14488 }
14489 if (--ctx->fmtcnt >= 0) {
14490 arg->ch = FORMAT_READ(ctx);
14491 ctx->fmtpos++;
14492 }
14493 }
14494 else if (arg->ch >= '0' && arg->ch <= '9') {
14495 arg->width = arg->ch - '0';
14496 while (--ctx->fmtcnt >= 0) {
14497 arg->ch = FORMAT_READ(ctx);
14498 ctx->fmtpos++;
14499 if (arg->ch < '0' || arg->ch > '9')
14500 break;
14501 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14502 mixing signed and unsigned comparison. Since arg->ch is between
14503 '0' and '9', casting to int is safe. */
14504 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14505 PyErr_SetString(PyExc_ValueError,
14506 "width too big");
14507 return -1;
14508 }
14509 arg->width = arg->width*10 + (arg->ch - '0');
14510 }
14511 }
14512
14513 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014514 if (arg->ch == '.') {
14515 arg->prec = 0;
14516 if (--ctx->fmtcnt >= 0) {
14517 arg->ch = FORMAT_READ(ctx);
14518 ctx->fmtpos++;
14519 }
14520 if (arg->ch == '*') {
14521 v = unicode_format_getnextarg(ctx);
14522 if (v == NULL)
14523 return -1;
14524 if (!PyLong_Check(v)) {
14525 PyErr_SetString(PyExc_TypeError,
14526 "* wants int");
14527 return -1;
14528 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014529 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014530 if (arg->prec == -1 && PyErr_Occurred())
14531 return -1;
14532 if (arg->prec < 0)
14533 arg->prec = 0;
14534 if (--ctx->fmtcnt >= 0) {
14535 arg->ch = FORMAT_READ(ctx);
14536 ctx->fmtpos++;
14537 }
14538 }
14539 else if (arg->ch >= '0' && arg->ch <= '9') {
14540 arg->prec = arg->ch - '0';
14541 while (--ctx->fmtcnt >= 0) {
14542 arg->ch = FORMAT_READ(ctx);
14543 ctx->fmtpos++;
14544 if (arg->ch < '0' || arg->ch > '9')
14545 break;
14546 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14547 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014548 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014549 return -1;
14550 }
14551 arg->prec = arg->prec*10 + (arg->ch - '0');
14552 }
14553 }
14554 }
14555
14556 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14557 if (ctx->fmtcnt >= 0) {
14558 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14559 if (--ctx->fmtcnt >= 0) {
14560 arg->ch = FORMAT_READ(ctx);
14561 ctx->fmtpos++;
14562 }
14563 }
14564 }
14565 if (ctx->fmtcnt < 0) {
14566 PyErr_SetString(PyExc_ValueError,
14567 "incomplete format");
14568 return -1;
14569 }
14570 return 0;
14571
14572#undef FORMAT_READ
14573}
14574
14575/* Format one argument. Supported conversion specifiers:
14576
14577 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014578 - "i", "d", "u": int or float
14579 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014580 - "e", "E", "f", "F", "g", "G": float
14581 - "c": int or str (1 character)
14582
Victor Stinner8dbd4212012-12-04 09:30:24 +010014583 When possible, the output is written directly into the Unicode writer
14584 (ctx->writer). A string is created when padding is required.
14585
Victor Stinnera47082312012-10-04 02:19:54 +020014586 Return 0 if the argument has been formatted into *p_str,
14587 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014588 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014589static int
14590unicode_format_arg_format(struct unicode_formatter_t *ctx,
14591 struct unicode_format_arg_t *arg,
14592 PyObject **p_str)
14593{
14594 PyObject *v;
14595 _PyUnicodeWriter *writer = &ctx->writer;
14596
14597 if (ctx->fmtcnt == 0)
14598 ctx->writer.overallocate = 0;
14599
14600 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014601 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014602 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014603 return 1;
14604 }
14605
14606 v = unicode_format_getnextarg(ctx);
14607 if (v == NULL)
14608 return -1;
14609
Victor Stinnera47082312012-10-04 02:19:54 +020014610
14611 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014612 case 's':
14613 case 'r':
14614 case 'a':
14615 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14616 /* Fast path */
14617 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14618 return -1;
14619 return 1;
14620 }
14621
14622 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14623 *p_str = v;
14624 Py_INCREF(*p_str);
14625 }
14626 else {
14627 if (arg->ch == 's')
14628 *p_str = PyObject_Str(v);
14629 else if (arg->ch == 'r')
14630 *p_str = PyObject_Repr(v);
14631 else
14632 *p_str = PyObject_ASCII(v);
14633 }
14634 break;
14635
14636 case 'i':
14637 case 'd':
14638 case 'u':
14639 case 'o':
14640 case 'x':
14641 case 'X':
14642 {
14643 int ret = mainformatlong(v, arg, p_str, writer);
14644 if (ret != 0)
14645 return ret;
14646 arg->sign = 1;
14647 break;
14648 }
14649
14650 case 'e':
14651 case 'E':
14652 case 'f':
14653 case 'F':
14654 case 'g':
14655 case 'G':
14656 if (arg->width == -1 && arg->prec == -1
14657 && !(arg->flags & (F_SIGN | F_BLANK)))
14658 {
14659 /* Fast path */
14660 if (formatfloat(v, arg, NULL, writer) == -1)
14661 return -1;
14662 return 1;
14663 }
14664
14665 arg->sign = 1;
14666 if (formatfloat(v, arg, p_str, NULL) == -1)
14667 return -1;
14668 break;
14669
14670 case 'c':
14671 {
14672 Py_UCS4 ch = formatchar(v);
14673 if (ch == (Py_UCS4) -1)
14674 return -1;
14675 if (arg->width == -1 && arg->prec == -1) {
14676 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014677 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014678 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014679 return 1;
14680 }
14681 *p_str = PyUnicode_FromOrdinal(ch);
14682 break;
14683 }
14684
14685 default:
14686 PyErr_Format(PyExc_ValueError,
14687 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014688 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014689 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14690 (int)arg->ch,
14691 ctx->fmtpos - 1);
14692 return -1;
14693 }
14694 if (*p_str == NULL)
14695 return -1;
14696 assert (PyUnicode_Check(*p_str));
14697 return 0;
14698}
14699
14700static int
14701unicode_format_arg_output(struct unicode_formatter_t *ctx,
14702 struct unicode_format_arg_t *arg,
14703 PyObject *str)
14704{
14705 Py_ssize_t len;
14706 enum PyUnicode_Kind kind;
14707 void *pbuf;
14708 Py_ssize_t pindex;
14709 Py_UCS4 signchar;
14710 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014711 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014712 Py_ssize_t sublen;
14713 _PyUnicodeWriter *writer = &ctx->writer;
14714 Py_UCS4 fill;
14715
14716 fill = ' ';
14717 if (arg->sign && arg->flags & F_ZERO)
14718 fill = '0';
14719
14720 if (PyUnicode_READY(str) == -1)
14721 return -1;
14722
14723 len = PyUnicode_GET_LENGTH(str);
14724 if ((arg->width == -1 || arg->width <= len)
14725 && (arg->prec == -1 || arg->prec >= len)
14726 && !(arg->flags & (F_SIGN | F_BLANK)))
14727 {
14728 /* Fast path */
14729 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14730 return -1;
14731 return 0;
14732 }
14733
14734 /* Truncate the string for "s", "r" and "a" formats
14735 if the precision is set */
14736 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14737 if (arg->prec >= 0 && len > arg->prec)
14738 len = arg->prec;
14739 }
14740
14741 /* Adjust sign and width */
14742 kind = PyUnicode_KIND(str);
14743 pbuf = PyUnicode_DATA(str);
14744 pindex = 0;
14745 signchar = '\0';
14746 if (arg->sign) {
14747 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14748 if (ch == '-' || ch == '+') {
14749 signchar = ch;
14750 len--;
14751 pindex++;
14752 }
14753 else if (arg->flags & F_SIGN)
14754 signchar = '+';
14755 else if (arg->flags & F_BLANK)
14756 signchar = ' ';
14757 else
14758 arg->sign = 0;
14759 }
14760 if (arg->width < len)
14761 arg->width = len;
14762
14763 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014764 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014765 if (!(arg->flags & F_LJUST)) {
14766 if (arg->sign) {
14767 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014768 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014769 }
14770 else {
14771 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014772 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014773 }
14774 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014775 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14776 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014777 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014778 }
14779
Victor Stinnera47082312012-10-04 02:19:54 +020014780 buflen = arg->width;
14781 if (arg->sign && len == arg->width)
14782 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014783 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014784 return -1;
14785
14786 /* Write the sign if needed */
14787 if (arg->sign) {
14788 if (fill != ' ') {
14789 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14790 writer->pos += 1;
14791 }
14792 if (arg->width > len)
14793 arg->width--;
14794 }
14795
14796 /* Write the numeric prefix for "x", "X" and "o" formats
14797 if the alternate form is used.
14798 For example, write "0x" for the "%#x" format. */
14799 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14800 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14801 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14802 if (fill != ' ') {
14803 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14804 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14805 writer->pos += 2;
14806 pindex += 2;
14807 }
14808 arg->width -= 2;
14809 if (arg->width < 0)
14810 arg->width = 0;
14811 len -= 2;
14812 }
14813
14814 /* Pad left with the fill character if needed */
14815 if (arg->width > len && !(arg->flags & F_LJUST)) {
14816 sublen = arg->width - len;
14817 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14818 writer->pos += sublen;
14819 arg->width = len;
14820 }
14821
14822 /* If padding with spaces: write sign if needed and/or numeric prefix if
14823 the alternate form is used */
14824 if (fill == ' ') {
14825 if (arg->sign) {
14826 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14827 writer->pos += 1;
14828 }
14829 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14830 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14831 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14832 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14833 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14834 writer->pos += 2;
14835 pindex += 2;
14836 }
14837 }
14838
14839 /* Write characters */
14840 if (len) {
14841 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14842 str, pindex, len);
14843 writer->pos += len;
14844 }
14845
14846 /* Pad right with the fill character if needed */
14847 if (arg->width > len) {
14848 sublen = arg->width - len;
14849 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14850 writer->pos += sublen;
14851 }
14852 return 0;
14853}
14854
14855/* Helper of PyUnicode_Format(): format one arg.
14856 Return 0 on success, raise an exception and return -1 on error. */
14857static int
14858unicode_format_arg(struct unicode_formatter_t *ctx)
14859{
14860 struct unicode_format_arg_t arg;
14861 PyObject *str;
14862 int ret;
14863
Victor Stinner8dbd4212012-12-04 09:30:24 +010014864 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14865 arg.flags = 0;
14866 arg.width = -1;
14867 arg.prec = -1;
14868 arg.sign = 0;
14869 str = NULL;
14870
Victor Stinnera47082312012-10-04 02:19:54 +020014871 ret = unicode_format_arg_parse(ctx, &arg);
14872 if (ret == -1)
14873 return -1;
14874
14875 ret = unicode_format_arg_format(ctx, &arg, &str);
14876 if (ret == -1)
14877 return -1;
14878
14879 if (ret != 1) {
14880 ret = unicode_format_arg_output(ctx, &arg, str);
14881 Py_DECREF(str);
14882 if (ret == -1)
14883 return -1;
14884 }
14885
14886 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14887 PyErr_SetString(PyExc_TypeError,
14888 "not all arguments converted during string formatting");
14889 return -1;
14890 }
14891 return 0;
14892}
14893
Alexander Belopolsky40018472011-02-26 01:02:56 +000014894PyObject *
14895PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014896{
Victor Stinnera47082312012-10-04 02:19:54 +020014897 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014898
Guido van Rossumd57fd912000-03-10 22:53:23 +000014899 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014900 PyErr_BadInternalCall();
14901 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014902 }
Victor Stinnera47082312012-10-04 02:19:54 +020014903
14904 ctx.fmtstr = PyUnicode_FromObject(format);
14905 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014906 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014907 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14908 Py_DECREF(ctx.fmtstr);
14909 return NULL;
14910 }
14911 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14912 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14913 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14914 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014915
Victor Stinner8f674cc2013-04-17 23:02:17 +020014916 _PyUnicodeWriter_Init(&ctx.writer);
14917 ctx.writer.min_length = ctx.fmtcnt + 100;
14918 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014919
Guido van Rossumd57fd912000-03-10 22:53:23 +000014920 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014921 ctx.arglen = PyTuple_Size(args);
14922 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014923 }
14924 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014925 ctx.arglen = -1;
14926 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014927 }
Victor Stinnera47082312012-10-04 02:19:54 +020014928 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014929 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014930 ctx.dict = args;
14931 else
14932 ctx.dict = NULL;
14933 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014934
Victor Stinnera47082312012-10-04 02:19:54 +020014935 while (--ctx.fmtcnt >= 0) {
14936 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014937 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014938
14939 nonfmtpos = ctx.fmtpos++;
14940 while (ctx.fmtcnt >= 0 &&
14941 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14942 ctx.fmtpos++;
14943 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014944 }
Victor Stinnera47082312012-10-04 02:19:54 +020014945 if (ctx.fmtcnt < 0) {
14946 ctx.fmtpos--;
14947 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014948 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014949
Victor Stinnercfc4c132013-04-03 01:48:39 +020014950 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14951 nonfmtpos, ctx.fmtpos) < 0)
14952 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014953 }
14954 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014955 ctx.fmtpos++;
14956 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014957 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014958 }
14959 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014960
Victor Stinnera47082312012-10-04 02:19:54 +020014961 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014962 PyErr_SetString(PyExc_TypeError,
14963 "not all arguments converted during string formatting");
14964 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014965 }
14966
Victor Stinnera47082312012-10-04 02:19:54 +020014967 if (ctx.args_owned) {
14968 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014969 }
Victor Stinnera47082312012-10-04 02:19:54 +020014970 Py_DECREF(ctx.fmtstr);
14971 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014972
Benjamin Peterson29060642009-01-31 22:14:21 +000014973 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014974 Py_DECREF(ctx.fmtstr);
14975 _PyUnicodeWriter_Dealloc(&ctx.writer);
14976 if (ctx.args_owned) {
14977 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014978 }
14979 return NULL;
14980}
14981
Jeremy Hylton938ace62002-07-17 16:30:39 +000014982static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014983unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14984
Tim Peters6d6c1a32001-08-02 04:15:00 +000014985static PyObject *
14986unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14987{
Benjamin Peterson29060642009-01-31 22:14:21 +000014988 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014989 static char *kwlist[] = {"object", "encoding", "errors", 0};
14990 char *encoding = NULL;
14991 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014992
Benjamin Peterson14339b62009-01-31 16:36:08 +000014993 if (type != &PyUnicode_Type)
14994 return unicode_subtype_new(type, args, kwds);
14995 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014996 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014997 return NULL;
14998 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014999 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015000 if (encoding == NULL && errors == NULL)
15001 return PyObject_Str(x);
15002 else
Benjamin Peterson29060642009-01-31 22:14:21 +000015003 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000015004}
15005
Guido van Rossume023fe02001-08-30 03:12:59 +000015006static PyObject *
15007unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15008{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015009 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015010 Py_ssize_t length, char_size;
15011 int share_wstr, share_utf8;
15012 unsigned int kind;
15013 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000015014
Benjamin Peterson14339b62009-01-31 16:36:08 +000015015 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015016
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015017 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015018 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015019 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015020 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050015021 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060015022 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015023 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060015024 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015025
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015026 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015027 if (self == NULL) {
15028 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015029 return NULL;
15030 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015031 kind = PyUnicode_KIND(unicode);
15032 length = PyUnicode_GET_LENGTH(unicode);
15033
15034 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015035#ifdef Py_DEBUG
15036 _PyUnicode_HASH(self) = -1;
15037#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015038 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015039#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015040 _PyUnicode_STATE(self).interned = 0;
15041 _PyUnicode_STATE(self).kind = kind;
15042 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015043 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015044 _PyUnicode_STATE(self).ready = 1;
15045 _PyUnicode_WSTR(self) = NULL;
15046 _PyUnicode_UTF8_LENGTH(self) = 0;
15047 _PyUnicode_UTF8(self) = NULL;
15048 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015049 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015050
15051 share_utf8 = 0;
15052 share_wstr = 0;
15053 if (kind == PyUnicode_1BYTE_KIND) {
15054 char_size = 1;
15055 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15056 share_utf8 = 1;
15057 }
15058 else if (kind == PyUnicode_2BYTE_KIND) {
15059 char_size = 2;
15060 if (sizeof(wchar_t) == 2)
15061 share_wstr = 1;
15062 }
15063 else {
15064 assert(kind == PyUnicode_4BYTE_KIND);
15065 char_size = 4;
15066 if (sizeof(wchar_t) == 4)
15067 share_wstr = 1;
15068 }
15069
15070 /* Ensure we won't overflow the length. */
15071 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15072 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015073 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015074 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015075 data = PyObject_MALLOC((length + 1) * char_size);
15076 if (data == NULL) {
15077 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015078 goto onError;
15079 }
15080
Victor Stinnerc3c74152011-10-02 20:39:55 +020015081 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015082 if (share_utf8) {
15083 _PyUnicode_UTF8_LENGTH(self) = length;
15084 _PyUnicode_UTF8(self) = data;
15085 }
15086 if (share_wstr) {
15087 _PyUnicode_WSTR_LENGTH(self) = length;
15088 _PyUnicode_WSTR(self) = (wchar_t *)data;
15089 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015090
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015091 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015092 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015093 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015094#ifdef Py_DEBUG
15095 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15096#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015097 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015098 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015099
15100onError:
15101 Py_DECREF(unicode);
15102 Py_DECREF(self);
15103 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015104}
15105
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015106PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015107"str(object='') -> str\n\
15108str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015109\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015110Create a new string object from the given object. If encoding or\n\
15111errors is specified, then the object must expose a data buffer\n\
15112that will be decoded using the given encoding and error handler.\n\
15113Otherwise, returns the result of object.__str__() (if defined)\n\
15114or repr(object).\n\
15115encoding defaults to sys.getdefaultencoding().\n\
15116errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015117
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015118static PyObject *unicode_iter(PyObject *seq);
15119
Guido van Rossumd57fd912000-03-10 22:53:23 +000015120PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015121 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015122 "str", /* tp_name */
15123 sizeof(PyUnicodeObject), /* tp_size */
15124 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015125 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015126 (destructor)unicode_dealloc, /* tp_dealloc */
15127 0, /* tp_print */
15128 0, /* tp_getattr */
15129 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015130 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015131 unicode_repr, /* tp_repr */
15132 &unicode_as_number, /* tp_as_number */
15133 &unicode_as_sequence, /* tp_as_sequence */
15134 &unicode_as_mapping, /* tp_as_mapping */
15135 (hashfunc) unicode_hash, /* tp_hash*/
15136 0, /* tp_call*/
15137 (reprfunc) unicode_str, /* tp_str */
15138 PyObject_GenericGetAttr, /* tp_getattro */
15139 0, /* tp_setattro */
15140 0, /* tp_as_buffer */
15141 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015142 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015143 unicode_doc, /* tp_doc */
15144 0, /* tp_traverse */
15145 0, /* tp_clear */
15146 PyUnicode_RichCompare, /* tp_richcompare */
15147 0, /* tp_weaklistoffset */
15148 unicode_iter, /* tp_iter */
15149 0, /* tp_iternext */
15150 unicode_methods, /* tp_methods */
15151 0, /* tp_members */
15152 0, /* tp_getset */
15153 &PyBaseObject_Type, /* tp_base */
15154 0, /* tp_dict */
15155 0, /* tp_descr_get */
15156 0, /* tp_descr_set */
15157 0, /* tp_dictoffset */
15158 0, /* tp_init */
15159 0, /* tp_alloc */
15160 unicode_new, /* tp_new */
15161 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015162};
15163
15164/* Initialize the Unicode implementation */
15165
Victor Stinner3a50e702011-10-18 21:21:00 +020015166int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015167{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015168 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015169 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015170 0x000A, /* LINE FEED */
15171 0x000D, /* CARRIAGE RETURN */
15172 0x001C, /* FILE SEPARATOR */
15173 0x001D, /* GROUP SEPARATOR */
15174 0x001E, /* RECORD SEPARATOR */
15175 0x0085, /* NEXT LINE */
15176 0x2028, /* LINE SEPARATOR */
15177 0x2029, /* PARAGRAPH SEPARATOR */
15178 };
15179
Fred Drakee4315f52000-05-09 19:53:39 +000015180 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015181 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015182 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015183 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015184 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015185
Guido van Rossumcacfc072002-05-24 19:01:59 +000015186 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015187 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015188
15189 /* initialize the linebreak bloom filter */
15190 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015191 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015192 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015193
Christian Heimes26532f72013-07-20 14:57:16 +020015194 if (PyType_Ready(&EncodingMapType) < 0)
15195 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015196
Benjamin Petersonc4311282012-10-30 23:21:10 -040015197 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15198 Py_FatalError("Can't initialize field name iterator type");
15199
15200 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15201 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015202
Victor Stinner3a50e702011-10-18 21:21:00 +020015203 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015204}
15205
15206/* Finalize the Unicode implementation */
15207
Christian Heimesa156e092008-02-16 07:38:31 +000015208int
15209PyUnicode_ClearFreeList(void)
15210{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015211 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015212}
15213
Guido van Rossumd57fd912000-03-10 22:53:23 +000015214void
Thomas Wouters78890102000-07-22 19:25:51 +000015215_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015216{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015217 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015218
Serhiy Storchaka05997252013-01-26 12:14:02 +020015219 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015220
Serhiy Storchaka05997252013-01-26 12:14:02 +020015221 for (i = 0; i < 256; i++)
15222 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015223 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015224 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015225}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015226
Walter Dörwald16807132007-05-25 13:52:07 +000015227void
15228PyUnicode_InternInPlace(PyObject **p)
15229{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015230 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015231 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015232#ifdef Py_DEBUG
15233 assert(s != NULL);
15234 assert(_PyUnicode_CHECK(s));
15235#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015236 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015237 return;
15238#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015239 /* If it's a subclass, we don't really know what putting
15240 it in the interned dict might do. */
15241 if (!PyUnicode_CheckExact(s))
15242 return;
15243 if (PyUnicode_CHECK_INTERNED(s))
15244 return;
15245 if (interned == NULL) {
15246 interned = PyDict_New();
15247 if (interned == NULL) {
15248 PyErr_Clear(); /* Don't leave an exception */
15249 return;
15250 }
15251 }
15252 /* It might be that the GetItem call fails even
15253 though the key is present in the dictionary,
15254 namely when this happens during a stack overflow. */
15255 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015256 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015257 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015258
Victor Stinnerf0335102013-04-14 19:13:03 +020015259 if (t) {
15260 Py_INCREF(t);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +020015261 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015262 return;
15263 }
Walter Dörwald16807132007-05-25 13:52:07 +000015264
Benjamin Peterson14339b62009-01-31 16:36:08 +000015265 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015266 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015267 PyErr_Clear();
15268 PyThreadState_GET()->recursion_critical = 0;
15269 return;
15270 }
15271 PyThreadState_GET()->recursion_critical = 0;
15272 /* The two references in interned are not counted by refcnt.
15273 The deallocator will take care of this */
15274 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015275 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015276}
15277
15278void
15279PyUnicode_InternImmortal(PyObject **p)
15280{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015281 PyUnicode_InternInPlace(p);
15282 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015283 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015284 Py_INCREF(*p);
15285 }
Walter Dörwald16807132007-05-25 13:52:07 +000015286}
15287
15288PyObject *
15289PyUnicode_InternFromString(const char *cp)
15290{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015291 PyObject *s = PyUnicode_FromString(cp);
15292 if (s == NULL)
15293 return NULL;
15294 PyUnicode_InternInPlace(&s);
15295 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015296}
15297
Alexander Belopolsky40018472011-02-26 01:02:56 +000015298void
15299_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015300{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015301 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015302 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015303 Py_ssize_t i, n;
15304 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015305
Benjamin Peterson14339b62009-01-31 16:36:08 +000015306 if (interned == NULL || !PyDict_Check(interned))
15307 return;
15308 keys = PyDict_Keys(interned);
15309 if (keys == NULL || !PyList_Check(keys)) {
15310 PyErr_Clear();
15311 return;
15312 }
Walter Dörwald16807132007-05-25 13:52:07 +000015313
Benjamin Peterson14339b62009-01-31 16:36:08 +000015314 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15315 detector, interned unicode strings are not forcibly deallocated;
15316 rather, we give them their stolen references back, and then clear
15317 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015318
Benjamin Peterson14339b62009-01-31 16:36:08 +000015319 n = PyList_GET_SIZE(keys);
15320 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015321 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015322 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015323 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015324 if (PyUnicode_READY(s) == -1) {
15325 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015326 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015327 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015328 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015329 case SSTATE_NOT_INTERNED:
15330 /* XXX Shouldn't happen */
15331 break;
15332 case SSTATE_INTERNED_IMMORTAL:
15333 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015334 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015335 break;
15336 case SSTATE_INTERNED_MORTAL:
15337 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015338 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015339 break;
15340 default:
15341 Py_FatalError("Inconsistent interned string state.");
15342 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015343 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015344 }
15345 fprintf(stderr, "total size of all interned strings: "
15346 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15347 "mortal/immortal\n", mortal_size, immortal_size);
15348 Py_DECREF(keys);
15349 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015350 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015351}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015352
15353
15354/********************* Unicode Iterator **************************/
15355
15356typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015357 PyObject_HEAD
15358 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015359 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015360} unicodeiterobject;
15361
15362static void
15363unicodeiter_dealloc(unicodeiterobject *it)
15364{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015365 _PyObject_GC_UNTRACK(it);
15366 Py_XDECREF(it->it_seq);
15367 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015368}
15369
15370static int
15371unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15372{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015373 Py_VISIT(it->it_seq);
15374 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015375}
15376
15377static PyObject *
15378unicodeiter_next(unicodeiterobject *it)
15379{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015380 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015381
Benjamin Peterson14339b62009-01-31 16:36:08 +000015382 assert(it != NULL);
15383 seq = it->it_seq;
15384 if (seq == NULL)
15385 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015386 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015387
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015388 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15389 int kind = PyUnicode_KIND(seq);
15390 void *data = PyUnicode_DATA(seq);
15391 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15392 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015393 if (item != NULL)
15394 ++it->it_index;
15395 return item;
15396 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015397
Benjamin Peterson14339b62009-01-31 16:36:08 +000015398 Py_DECREF(seq);
15399 it->it_seq = NULL;
15400 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015401}
15402
15403static PyObject *
15404unicodeiter_len(unicodeiterobject *it)
15405{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015406 Py_ssize_t len = 0;
15407 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015408 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015409 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015410}
15411
15412PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15413
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015414static PyObject *
15415unicodeiter_reduce(unicodeiterobject *it)
15416{
15417 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015418 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015419 it->it_seq, it->it_index);
15420 } else {
15421 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15422 if (u == NULL)
15423 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015424 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015425 }
15426}
15427
15428PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15429
15430static PyObject *
15431unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15432{
15433 Py_ssize_t index = PyLong_AsSsize_t(state);
15434 if (index == -1 && PyErr_Occurred())
15435 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015436 if (it->it_seq != NULL) {
15437 if (index < 0)
15438 index = 0;
15439 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15440 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15441 it->it_index = index;
15442 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015443 Py_RETURN_NONE;
15444}
15445
15446PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15447
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015448static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015449 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015450 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015451 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15452 reduce_doc},
15453 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15454 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015455 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015456};
15457
15458PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015459 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15460 "str_iterator", /* tp_name */
15461 sizeof(unicodeiterobject), /* tp_basicsize */
15462 0, /* tp_itemsize */
15463 /* methods */
15464 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15465 0, /* tp_print */
15466 0, /* tp_getattr */
15467 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015468 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015469 0, /* tp_repr */
15470 0, /* tp_as_number */
15471 0, /* tp_as_sequence */
15472 0, /* tp_as_mapping */
15473 0, /* tp_hash */
15474 0, /* tp_call */
15475 0, /* tp_str */
15476 PyObject_GenericGetAttr, /* tp_getattro */
15477 0, /* tp_setattro */
15478 0, /* tp_as_buffer */
15479 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15480 0, /* tp_doc */
15481 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15482 0, /* tp_clear */
15483 0, /* tp_richcompare */
15484 0, /* tp_weaklistoffset */
15485 PyObject_SelfIter, /* tp_iter */
15486 (iternextfunc)unicodeiter_next, /* tp_iternext */
15487 unicodeiter_methods, /* tp_methods */
15488 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015489};
15490
15491static PyObject *
15492unicode_iter(PyObject *seq)
15493{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015494 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015495
Benjamin Peterson14339b62009-01-31 16:36:08 +000015496 if (!PyUnicode_Check(seq)) {
15497 PyErr_BadInternalCall();
15498 return NULL;
15499 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015500 if (PyUnicode_READY(seq) == -1)
15501 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015502 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15503 if (it == NULL)
15504 return NULL;
15505 it->it_index = 0;
15506 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015507 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015508 _PyObject_GC_TRACK(it);
15509 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015510}
15511
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015512
15513size_t
15514Py_UNICODE_strlen(const Py_UNICODE *u)
15515{
15516 int res = 0;
15517 while(*u++)
15518 res++;
15519 return res;
15520}
15521
15522Py_UNICODE*
15523Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15524{
15525 Py_UNICODE *u = s1;
15526 while ((*u++ = *s2++));
15527 return s1;
15528}
15529
15530Py_UNICODE*
15531Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15532{
15533 Py_UNICODE *u = s1;
15534 while ((*u++ = *s2++))
15535 if (n-- == 0)
15536 break;
15537 return s1;
15538}
15539
15540Py_UNICODE*
15541Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15542{
15543 Py_UNICODE *u1 = s1;
15544 u1 += Py_UNICODE_strlen(u1);
15545 Py_UNICODE_strcpy(u1, s2);
15546 return s1;
15547}
15548
15549int
15550Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15551{
15552 while (*s1 && *s2 && *s1 == *s2)
15553 s1++, s2++;
15554 if (*s1 && *s2)
15555 return (*s1 < *s2) ? -1 : +1;
15556 if (*s1)
15557 return 1;
15558 if (*s2)
15559 return -1;
15560 return 0;
15561}
15562
15563int
15564Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15565{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015566 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015567 for (; n != 0; n--) {
15568 u1 = *s1;
15569 u2 = *s2;
15570 if (u1 != u2)
15571 return (u1 < u2) ? -1 : +1;
15572 if (u1 == '\0')
15573 return 0;
15574 s1++;
15575 s2++;
15576 }
15577 return 0;
15578}
15579
15580Py_UNICODE*
15581Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15582{
15583 const Py_UNICODE *p;
15584 for (p = s; *p; p++)
15585 if (*p == c)
15586 return (Py_UNICODE*)p;
15587 return NULL;
15588}
15589
15590Py_UNICODE*
15591Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15592{
15593 const Py_UNICODE *p;
15594 p = s + Py_UNICODE_strlen(s);
15595 while (p != s) {
15596 p--;
15597 if (*p == c)
15598 return (Py_UNICODE*)p;
15599 }
15600 return NULL;
15601}
Victor Stinner331ea922010-08-10 16:37:20 +000015602
Victor Stinner71133ff2010-09-01 23:43:53 +000015603Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015604PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015605{
Victor Stinner577db2c2011-10-11 22:12:48 +020015606 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015607 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015608
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015609 if (!PyUnicode_Check(unicode)) {
15610 PyErr_BadArgument();
15611 return NULL;
15612 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015613 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015614 if (u == NULL)
15615 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015616 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015617 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015618 PyErr_NoMemory();
15619 return NULL;
15620 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015621 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015622 size *= sizeof(Py_UNICODE);
15623 copy = PyMem_Malloc(size);
15624 if (copy == NULL) {
15625 PyErr_NoMemory();
15626 return NULL;
15627 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015628 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015629 return copy;
15630}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015631
Georg Brandl66c221e2010-10-14 07:04:07 +000015632/* A _string module, to export formatter_parser and formatter_field_name_split
15633 to the string.Formatter class implemented in Python. */
15634
15635static PyMethodDef _string_methods[] = {
15636 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15637 METH_O, PyDoc_STR("split the argument as a field name")},
15638 {"formatter_parser", (PyCFunction) formatter_parser,
15639 METH_O, PyDoc_STR("parse the argument as a format string")},
15640 {NULL, NULL}
15641};
15642
15643static struct PyModuleDef _string_module = {
15644 PyModuleDef_HEAD_INIT,
15645 "_string",
15646 PyDoc_STR("string helper module"),
15647 0,
15648 _string_methods,
15649 NULL,
15650 NULL,
15651 NULL,
15652 NULL
15653};
15654
15655PyMODINIT_FUNC
15656PyInit__string(void)
15657{
15658 return PyModule_Create(&_string_module);
15659}
15660
15661
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015662#ifdef __cplusplus
15663}
15664#endif